diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..3ed31756 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,83 @@ +name: CI + +# Disabled: GitHub Actions does not run on this account, so every push produced a failed +# run and a notification. Left in the repo rather than deleted because it still documents +# what a full check is, and it is one edit away from working again for anyone who forks. +# +# Everything below now runs locally instead — `./build.sh --lint` covers build-and-test +# and browser-extension, and `./build.sh --artifacts` covers publish. Re-enable by +# restoring the push/pull_request triggers: +# +# on: +# push: +# branches: [main] +# pull_request: +# workflow_dispatch: +on: + workflow_dispatch: + +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Restore + run: dotnet restore VRCVideoCacher.sln + + # The tree builds warning-free today; -warnaserror keeps it that way rather than + # letting warnings accumulate until nobody reads them. + - name: Build + run: dotnet build VRCVideoCacher.sln -c Debug --no-restore -warnaserror + + - name: Test + run: dotnet test VRCVideoCacher.sln -c Debug --no-build --verbosity normal + + browser-extension: + # chrome/ and firefox/ each have to contain their own copy of the shared files, so they + # can silently diverge when a fix lands in only one. This is the cheap guard against that. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check shared extension files + run: ./BrowserExtension/build.sh --check + + - name: Check locales + run: python3 scripts/lint-locales.py + + publish: + # PublishTrimmed only takes effect on publish, so build-and-test above never exercises + # it. This job is what would catch the trimmer removing something that only reflection + # reaches — a failure mode that cannot reproduce in a Debug build. + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + rid: [win-x64, linux-x64] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Publish ${{ matrix.rid }} + run: > + dotnet publish VRCVideoCacher/VRCVideoCacher.csproj + -c Release -r ${{ matrix.rid }} + -o out/${{ matrix.rid }} + + - name: Package Zip Archive + run: | + cd out/${{ matrix.rid }} + zip -r ../../VRCVideoCacher-${{ matrix.rid }}.zip . + + - uses: actions/upload-artifact@v4 + with: + name: VRCVideoCacher-${{ matrix.rid }}.zip + path: VRCVideoCacher-${{ matrix.rid }}.zip + retention-days: 7 diff --git a/.gitignore b/.gitignore index d81726ba..bd5bad1f 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,11 @@ nul /Build/linux-x64/VRCVideoCacher.pdb /Build/linux-x64/yt-dlp-stub.exe /Build/win-x64/VRCVideoCacher.pdb -notepad.md \ No newline at end of file +notepad.md +output_linux_release/ +output_steam_linux/ +output_win_release/ +VRCVideoCacher-*-x64.zip +# Browser extension packages (produced by BrowserExtension/build.sh) +/dist/ +/out/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..f98c12c3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,180 @@ +# AGENTS.md + +Fork of [codeyumx/VRCVideoCacherPlus](https://github.com/codeyumx/VRCVideoCacherPlus) +(itself a fork of EllyVR/VRCVideoCacher). .NET 10, Avalonia 12, EmbedIO, EF Core + SQLite, +Serilog. `upstream` remote points at codeyumx — keep merges from it possible. + +## Build, check, release + +There is no `dotnet` on the host; it lives in a distrobox container. + +```bash +distrobox enter arch -- dotnet build VRCVideoCacher.sln -warnaserror +``` + +`build.sh` is the pipeline. Actions run in this order no matter what order they are +passed, any failure aborts the rest, and every dotnet call carries `-warnaserror`: + +``` +bump lint build artifacts stop deploy start commit push release +``` + +```bash +./build.sh --lint # locales, extension, strict compile, tests +./build.sh --build --stop --deploy --start # or --restart for the stop/start pair +./build.sh --all --dry-run # rehearse the whole release +``` + +Always `--lint` before committing. + +**GitHub Actions does not run on this account.** `.github/workflows/ci.yml` is +disabled (`workflow_dispatch` only) because every push produced a failed run and a +notification. Its work happens locally instead — `--lint` is the build-and-test and +browser-extension jobs, `--artifacts` is the publish job. Do not re-enable the +triggers. Running the workflow under `act` was considered and rejected: it wants a +container runtime and a runner image to do what amounts to two `dotnet publish` calls. + +**A release is always exactly four assets**: `VRCVideoCacher-win-x64.zip`, +`VRCVideoCacher-linux-x64.zip`, the Chrome `.crx` and the Firefox `.xpi`. `--release` +implies `--artifacts` so it builds them rather than trusting what is in `dist/`, and +both check the set is complete — the `.crx` is silently skipped when `npx` is missing, +which would otherwise ship a release with no Chrome download. The extension `.zip` +byproducts stay in `dist/` and are deliberately not attached. + +`--artifacts` is also the only step that publishes Release/trimmed/single-file, so it +is the only one that exercises the trimmer. A Debug build cannot reproduce the trimmer +dropping something that only reflection reaches. + +`dist/` is shared between `build.sh` and `BrowserExtension/build.sh`; neither may +`rm -rf` it, only its own outputs. + +**Never stop, deploy to, or restart the app while the user has it running** unless +they asked for it in this session. Compiling and linting are always fine. + +## Traps this codebase keeps setting + +**The config file is shared with upstream VRCVideoCacher.** There is no separate +`PlusConfig.json` and no nested `Plus` block. Running plain VRCVideoCacher strips +keys it does not know, so every Plus setting must survive a round-trip through a +config that lost it — default sensibly, never assume presence. + +**Localization fails silently.** English is the fallback, so a missing key renders +English and an empty one renders nothing. Add every new key to all eight +`Languages/*.loc.json`, then run `scripts/lint-locales.py`. Keys are often built at +runtime (`"SkipReasonTooLong|{0:F0}|{1}"`), so grep before assuming one is dead. + +**`System.Text.Json` is source-generated.** A new serialized type needs a +`[JsonSerializable]` entry in `Utils/AppJsonContext.cs` or it fails at runtime, not +at compile time. No Newtonsoft anywhere. + +**Exit code 0 does not mean success.** `ss -K` prints its header to stdout and +`SOCK_DESTROY answers: Operation not permitted` to stderr, then exits 0 — that is how +severing claimed success for years while doing nothing. Classify from the actual +output, and report "not permitted" as itself rather than as failure or success. + +**`.NET` will not follow an HTTPS→HTTP redirect.** PyPyDance downgrades, so the +redirect has to be followed manually with a bounded hop count. + +**Background loops must observe `Program.ShutdownToken`.** `Main` signals shutdown +and then force-exits; a loop that did not link its token is killed mid-step. Link, +do not replace: `CancellationTokenSource.CreateLinkedTokenSource(Program.ShutdownToken)`. + +**Never block the UI thread.** Refresh loops use `PeriodicTimer` + `Task.Run` and +marshal only the finished result back. `DispatcherTimer` doing real work freezes the +window, and so does a synchronous `WaitForExit` on an elevation prompt. + +**Use `ProcessStartInfo.ArgumentList`, never `Arguments`.** Install paths routinely +contain spaces (a Steam library on an external drive), and string interpolation +splits them into two arguments. + +**Anything running elevated is a one-shot helper.** No UI, no config writes, no +background work; re-validate every argument (parse addresses as `IPAddress`) because +it runs as root. See `LaunchArgs.IsPrivilegedHelper`. + +**`TimeSpan` normalizes instead of throwing.** `99:99` silently becomes 1h40m — +validate parsed fields explicitly. + +**`yt-dlp-stub.exe` rebuilds non-deterministically.** It shows up dirty after any +build with identical content. `git checkout` it rather than committing the churn. + +**Do not chain a check onto a build with `&&`.** `dotnet build && grep ...` tests the +grep, not the build. Use an explicit `if ... then ... else ... fi`. + +**Sandbox live testing.** `XDG_CONFIG_HOME=/tmp/vvc-sandbox` keeps the user's real +config and cache database untouched. + +## Telling the user something + +Pick the quietest thing that does the job. In rough order of intrusiveness: + +| Want | Use | +| --- | --- | +| Diagnostics, background progress | `Log.Debug` / `Log.Information` — Logs tab | +| Something degraded but recoverable | `Log.Warning` | +| A short result next to the thing it concerns | tab-local `StatusMessage` + `StatusMessageColor` | +| Persistent app-wide state | `MainWindowViewModel.StatusText` (status bar) | +| The user has to decide | `PopupWindow.CreateConfirm` | +| Broadcast news | MOTD banner | + +**`Log.Error` is not just a log line — it opens a modal.** `UiLogSink` shows a +`PopupWindow` for anything at Error or above (when `ErrorPopups` is on), with +identical messages suppressed for a minute. Reserve it for "the thing you asked for +did not happen". Anything routine that fails — a CDN retry, a missing optional tool — +is `Warning` or `Debug`, or you are throwing a dialog at somebody in VR. + +**Status bar** is `MainWindowViewModel.StatusText` (left) and `CacheStatusText` +(right), bound in `MainWindow.axaml`. It is for standing state — "server running", +cache size — not transient results. It survives a tab switch, so anything written +there stays until something else overwrites it. + +**Tab-local status** is the `StatusMessage` / `StatusMessageColor` pair that +`ActiveConnectionsViewModel`, `SettingsViewModel` and `HistoryViewModel` each carry, +usually behind a small `SetStatus(message, colorHex)`. This is the default for +per-action feedback. Existing colours: `#81C784` success, `#FFB74D` pending or +unsaved, and red for failure. + +**Dialogs** are `Views/PopupWindow`. Message only: +`await new PopupWindow(text).ShowDialog(owner)`. Confirmation: + +```csharp +var dialog = PopupWindow.CreateConfirm(message, Localizer.Get("Yes"), Localizer.Get("No")); +dialog.Title = Localizer.Get("ConfirmClearCacheTitle"); +await dialog.ShowDialog(owner); +if (dialog.Confirmed) { ... } +``` + +`SetFolderHint(label, path)` adds a clickable path, for "put the file here" errors. +There is no text-prompt dialog — add a field to the relevant view instead of +inventing one. + +Every one of these takes a `Localizer.Get` key, never a literal. Owner windows can be +null during startup: `App.MainWindow` is null until the UI exists, and force-unwrapping +it in a log sink once took the whole application down over a log line. + +## Style + +Match upstream — this fork should read like the same project. + +- File-scoped namespaces (enforced as a warning by `.editorconfig`), 4 spaces, `var` + where the type is obvious. +- Serilog structured logging with named holes and a trailing period: + `Log.Information("Added new default rule '{RuleName}'.", rule.Name)`. Never + interpolate into the template. `Log.Debug` for diagnostics, `Warning` for degraded + behaviour, `Error` only when something the user asked for did not happen. +- Comments explain *why*, especially the non-obvious constraint or the bug that made + the code look like this. Do not narrate what the line already says. +- User-facing strings are always localization keys, never literals. +- Tests are xUnit, named as a sentence describing the guarantee + (`NoticeTextNamesTheFileTheOldSettingsAreActuallyIn`), and async rather than + blocking on a task (xUnit1031). + +### UX + +- Never surprise the user with a privileged prompt. Elevation is opt-in per call + site: an explicit button may prompt, an automatic setting toggle may not. +- Report honestly. Degraded outcomes get their own state and their own message — + "needs privileges", "not supported here" and "failed" are three different things + and the UI says which. +- Destructive or outward-facing actions confirm first, and say exactly what will + happen ("Delete all {0} cached videos? This cannot be undone."). +- The app runs alongside VR. Nothing may block, freeze the window, or steal focus. diff --git a/BrowserExtension/README.md b/BrowserExtension/README.md index ac6b6134..a2f57ed0 100644 --- a/BrowserExtension/README.md +++ b/BrowserExtension/README.md @@ -1,29 +1,46 @@ # VRCVideoCacher Cookies Exporter -Sends your YouTube cookies to VRCVideoCacher (`http://localhost:9696/youtube-cookies`) +Sends your YouTube cookies to VRCVideoCacher (`http://127.0.0.1:9696/api/youtube-cookies`) in Netscape format so yt-dlp can use them. Pushes automatically every time a -youtube.com tab finishes loading, or on demand by clicking the toolbar icon. +youtube.com tab finishes loading (when the "share automatically" toggle is on), on demand +from the toolbar popup, or when the app itself asks for a refresh. -`chrome/` and `firefox/` each hold a self-contained extension (same `background.js`, -browser-specific `manifest.json`). +## Layout -## Load unpacked (for testing) +`chrome/` and `firefox/` are each a self-contained, load-unpacked-able extension. Four +files are byte-identical between them: -**Chrome:** `chrome://extensions` → Developer mode → Load unpacked → pick `chrome/`. + cookies.js i18n.js popup.js popup.html -**Firefox:** `about:debugging` → This Firefox → Load Temporary Add-on → pick -`firefox/manifest.json`. +They have to physically exist in both directories, which makes it easy to fix something in +one copy and forget the other. `build.sh --check` fails if they drift, and CI runs it. -## Package for upload +Two files are deliberately per-browser: -Chrome Web Store wants a `.zip` with `manifest.json` at the root: +| File | Chrome | Firefox | +| --- | --- | --- | +| `manifest.json` | MV3 | MV2 | +| `background.js` | service worker, `importScripts("cookies.js")` | background scripts, loaded via the manifest | -```sh -cd chrome && zip -r ../chrome-extension.zip . && cd .. -``` +### A note on Manifest V2 -Firefox (AMO) the same: +The Firefox extension is still MV2. Firefox continues to support it, but it is on a +deprecation path, and Firefox's MV3 is not the same shape as Chrome's — it uses event +pages with `background.scripts`, not a service worker — so the two manifests will still +differ after a migration. Worth doing, but it needs testing in an actual Firefox profile. + +## Build ```sh -cd firefox && zip -r ../firefox-extension.zip . && cd .. +./build.sh # verify shared files, then package both into dist/ +./build.sh --check # verify only (what CI runs) ``` + +`dist/` is generated and gitignored. Packaged zips are not committed: the previous ones +had gone stale against the source, and were being bundled *inside* newly built packages. + +## Load unpacked (for testing) + +**Chrome:** [`chrome://extensions`](chrome://extensions) → Developer mode → Load unpacked → pick `chrome/`. + +**Firefox:** [`about:debugging`](about:debugging) → This Firefox → Load Temporary Add-on → pick `firefox/manifest.json`. Temporary add-ons are removed when Firefox closes. For permanent unsigned installation in Firefox Developer Edition / Nightly, set both [`xpinstall.signatures.required`](about:config#xpinstall.signatures.required) and [`extensions.langpacks.signatures.required`](about:config#extensions.langpacks.signatures.required) to `false` in [`about:config`](about:config). diff --git a/BrowserExtension/build.sh b/BrowserExtension/build.sh new file mode 100755 index 00000000..c93fca19 --- /dev/null +++ b/BrowserExtension/build.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Packages the browser extensions, and verifies the files shared between them have not +# drifted apart. +# +# ./build.sh check shared files, then build both zips into dist/ +# ./build.sh --check check only, no packaging (this is what CI runs) +# +# chrome/ and firefox/ are separate load-unpacked targets, so the shared files have to +# physically exist in both. That makes silent divergence easy — a fix applied to one copy +# and not the other — which is what the check below exists to catch. +set -euo pipefail + +cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Identical in both. background.js and manifest.json are intentionally per-browser: +# Chrome is MV3 with a service worker, Firefox is MV2 with background scripts. +SHARED_FILES=(cookies.js i18n.js popup.js popup.html) + +CHECK_ONLY=false +[ "${1:-}" = "--check" ] && CHECK_ONLY=true + +echo "=== Checking shared files ===" +drift=0 +for file in "${SHARED_FILES[@]}"; do + if ! diff -q "chrome/${file}" "firefox/${file}" >/dev/null 2>&1; then + echo "DRIFT: chrome/${file} and firefox/${file} differ" >&2 + diff -u "chrome/${file}" "firefox/${file}" >&2 || true + drift=1 + fi +done + +if [ "$drift" -ne 0 ]; then + echo "Shared extension files have diverged. Reconcile them before packaging." >&2 + exit 1 +fi +echo "All ${#SHARED_FILES[@]} shared files match." + +# Manifests must not disagree about the version. +chrome_version=$(grep -oE '"version"[[:space:]]*:[[:space:]]*"[^"]+"' chrome/manifest.json | head -1 | grep -oE '[0-9][^"]*') +firefox_version=$(grep -oE '"version"[[:space:]]*:[[:space:]]*"[^"]+"' firefox/manifest.json | head -1 | grep -oE '[0-9][^"]*') +if [ "$chrome_version" != "$firefox_version" ]; then + echo "Manifest version mismatch: chrome=${chrome_version} firefox=${firefox_version}" >&2 + exit 1 +fi +echo "Manifest version: ${chrome_version}" + +if [ "$CHECK_ONLY" = true ]; then + exit 0 +fi + +command -v zip >/dev/null || { echo "zip is not installed" >&2; exit 1; } + +# Shared with the application's release artifacts, so only this script's own outputs may +# be cleared here. `rm -rf "$DIST_DIR"` would delete the VRCVideoCacher-*.zip files that +# ../build.sh --artifacts puts in the same directory, and whichever ran second would win. +DIST_DIR="$(pwd)/../dist" +echo "=== Packaging ===" +mkdir -p "$DIST_DIR" +rm -f "${DIST_DIR}"/VRCVideoCacherPlusPlus-*.zip \ + "${DIST_DIR}"/VRCVideoCacherPlusPlus-*.xpi \ + "${DIST_DIR}"/VRCVideoCacherPlusPlus-*.crx +for browser in chrome firefox; do + out="${DIST_DIR}/VRCVideoCacherPlusPlus-${browser}-${chrome_version}.zip" + (cd "$browser" && zip -qr "$out" . -x '.*') + echo " dist/$(basename "$out")" +done + +# Copy Firefox zip to xpi +cp "${DIST_DIR}/VRCVideoCacherPlusPlus-firefox-${chrome_version}.zip" "${DIST_DIR}/VRCVideoCacherPlusPlus-firefox-${chrome_version}.xpi" +echo " dist/VRCVideoCacherPlusPlus-firefox-${chrome_version}.xpi" + +# Build Chrome CRX +if command -v npx >/dev/null; then + npx -y crx3 chrome -p chrome.pem -o "${DIST_DIR}/VRCVideoCacherPlusPlus-chrome-${chrome_version}.crx" + echo " dist/VRCVideoCacherPlusPlus-chrome-${chrome_version}.crx" +else + echo "WARNING: npx not found, skipping CRX packaging" >&2 +fi + +# The .zip files stay in dist/ as byproducts — .xpi is a copy of the Firefox zip and the +# .crx is built from chrome/ — but ../build.sh --release attaches only the four real +# assets, so a release does not list the same extension twice in two formats. +echo "=== Done ===" diff --git a/BrowserExtension/chrome.pem b/BrowserExtension/chrome.pem new file mode 100644 index 00000000..e8517c8e --- /dev/null +++ b/BrowserExtension/chrome.pem @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQC1wY5WSl2+61Dc +F6017QOMikrUKsLoTM0ttVC8T/ftYkxX2SrVB4JUZCb+okq3NIh6UoQhwA0jlIl+ +iKWZyhIc+/tmg/y4rAiojxeI9hZCCF4WMY/EpC0ODZZieySUBgE11B1U/dcRX3DZ +zRir5lbZzjDZKh2VoFaEsE0NkuJrAjvVfAYHBfzHAtGM+68U4O0RpyP7uibOKnex +gnpZ0mbLjCPx6vyCdeEm6XtllHCp1X+C9K/aO0V2gTZrgol9ypvwnQz1nyXL5S+Z +d3N5gX7AYotgOx3N3zJn7vtevbuTH3BkfcfEn94807ifNtprzVYVvCD72nzxJYph +JIS5cORCFRssQf3x6VwElN/zyjnmkUvKL2BecDxaJw7GvSYxsQNkG9ahJ0dVESvz +Xgk+Nc7GwbhwGZsIkLsyK4wD4Bu7rB/Jogow1pBv0hDua1l3nQw16HjD4lSqJDH1 +tEYASA+cwWWpNKDBGGMOH/AJKwXwab7e0qac9NqymWvaxSKwH+VgWb/HPEMYT2t8 +xP+bw1lZiRgvViQpcMG2eKwuiAad/lbQs9Vs9qaMd1cu5Op4FQjOW0GlLfEAI/9a +JPShdK52iSrGlg/kiPQWpDDYE2SF/Ei/iEEFhtohr5TnCQhHw73aTyv61l9nkk6B +Ylul9ZMi5X47o6yzSXzuGsKN8qMZ3QIDAQABAoICABzp1RRKET6xXXQduhq1gRaG +21+EC+x7ZzppuRWz3Ptg40coT2WDI8r8Aa4JMDyTuVBINyfNTunFk9fSshFUcWw1 +86i7v2S7TUdPOA28JA9OGHWMXdQIz/gH1lAFSezYRbID88SU+vUTCzdCprWV12Qf +pmqthfZLAuhpyWAq6STfvpf3+ld8rtkTzDUSxqfaHixsO8+sLccnP1I4MPGABIVF +3mP6H0A7s10G0G/43LFPutCgzya2vhabeIZCxk+B/yuYODsMna0hYOCXfYGrRXgi +VQyyasvYwUKCZG+OXDwLyMvbrH9NdUOU5K5DQhzbFeIwQsj92VldQPWyIwEDAfRy +AsFMWS9kRdLrZErHkVseoP1hfcUM3w6/BH8lUI45HywsL7GDv7gmn6vHYb8uInDE +QxlOsMcc2O8MSZMvvaooVW3oeTmY6+jW7hG/iguqgS75iO2L2rF8L5WDdWs20O4T +oAz/Bld4zrErprD7EdkxGAJI0tmCNriWpLjyPL1xo6TfC9WAS+lQMkmOke0jnQJm +EoN2PSq6JqRoRL4k+SAeVvo0I/0FJSJ0Ej0d+u9rkNrox/cTJpqDY7g6MnyqQWJj +Jwf+S1NJHGpWo6apOoOn3BkQJu7tj0djVBQ56hlv/maqEKhckgdAw0Ew10QGXjXB +uDgl3YOOO0zH0E1BhS9BAoIBAQD10DijDiQJQEJrqVIJresprfo2sE79fIjhuYxh +Jmh6wMShAZxqj8+ZPbSsJR2sM2VuaH+TBGbsEUgmBfdgSEkF+vSevb0qgiMnKc6R ++j/9V6iReWWKz8M3jc01ft5oi43GuVtEc4S3ifJsRF+QdjTH760Rs76XSetZTGY8 +W2SkB3Z56wtupHSHiAOrsOGUdfVI/Kq24Y65xbcs45e3ZZXGIG43uJwa9Mh4EfR9 +Rou6I4IHIWIdMEDFVJPKvPZRz+5j26H8H2bulpW/XLfj/RZiQrvwAeBDXMcUYHNh +S9b3OEvruU282C2UtS6j9+PQ6hqAW3RjGQ2/NbG++sqB1/AhAoIBAQC9ScPxxicZ +An+sLFnugsHJUZ4QQctXS0BLk4U7lNXBWwkuWJSIoS25cr89bN+UaIQ86LITJwVM +Hdqeu44hcIR9BitD7LJ7CyZm/EY550XBDg5lf+/75dyzOsMxGWZzL+kZ+lAyBoAJ +VFOeKeKaKRX7+JXIiHA1m8720WqqAmUMe38Ej3yhveIvZgCMeMK3EU86q7FkbD0N +tEUoXw2YZ0Bj8V8OdOp3SNOfGGkKwlM0UzUumLVqgo655WjimprNEn/VOXUJPX5j +6+Zz5k0sV7YQ2h+hbi3VZDXxWGMOW0E+2sVklPT93pkigVJZNg1dXVzqbAR0Nlnn +d/1iTDZc+qI9AoIBABrHyKPbEon/ej0IgWuUix5LWgtDQhfTzYXqFSUwbgmRntp7 +tnLVoCRt2JU4pfbw0ogo0l1OCXiGmXmrBLx0o6AHK0dwHH/ZFcNahqrYvMf5GOBg +fXOWFwqiZE0DuW9iZNvVrd/TRg5I9SRefprahf2SWySmlIkfAIkGDc1dl6VXOs0l +kmVHfXqWku/NoYXvI/4DqQWrpUUQCVjWotzUMHEZb2iasEcvi/eo3R4Y5XguDiiA +tpO/gg79m+xmkd9v6+TtNMSnFyu/NClZDJ/GHv4tjxQi4C/2l6ncqDVdcdoVRBA2 +bAW695xP8PjkNOm515FMZW22eQzv6KGJ6S4kPIECggEBALsz6/z+OwaqCPiPeHXB +jcP72zY6y87OlozoHdk6LlknHqJeaq/hr+X7jRVDyq7s2vOeMxdr/Po1gFSCK2P4 +8p7vbfSkcDPuaBFsKEv15W+z5hsN95sJz0bWs9qoQ0FiPcg6XfvLn+8aHgSLaheK +0Lo9NG16OndaW8qQfEwdSDCbJpitC9aug7bay2ohuHjzPodI7Izj21HlWow9zaVP +YEg3nAohKQ3F0b1DmAdS/pT+QdeOocTv0BYbw6pwuu5cAF8xjwUPcyOBV46CUwqq +yF5MSwINhHjJveutvXGiYJm4JYZ/Jvi4oHyWp4mhQoB26IDTSWhhpHKeodMIiq9U +FQUCggEAGI2XQ2oHjpwcjHG35tri+8DYIZ0DR6BKCnGzXIrGbVmBrJKON/xQNHi1 +U8nQ33XId5zcJ7y3qf93hwxZYxPsd5V4TO/GvulTLZ7KukNJRX2fRED1mX3RaeLh +5OTlz4hYM2JXXLPa3iZqr3rP3gecfMTdWP/0wTroZvyc+djopAsYNacynVJB0cRy +Na1g3hXC/tqPCePVbx4ybMpuEa6ZnocTwtefAMik8m2ZxA5phj/hjhklRLJoTz3M +XTx0k1UNpcCMmTQH9RDbGCm46YBqK9BUhMJuJcpEjZETNRKHy1EGwsVuwM7fxzKI +zgGQa3rOM2tkqzO8kpg6OWp6qsfiig== +-----END PRIVATE KEY----- diff --git a/BrowserExtension/firefox/manifest.json b/BrowserExtension/firefox/manifest.json index d079b505..c9061fca 100644 --- a/BrowserExtension/firefox/manifest.json +++ b/BrowserExtension/firefox/manifest.json @@ -20,6 +20,11 @@ "default_popup": "popup.html" }, "browser_specific_settings": { - "gecko": { "id": "vrcvideocacher-cookies@local" } + "gecko": { + "id": "vrcvideocacher-cookies@local", + "data_collection_permissions": { + "required": ["none"] + } + } } } diff --git a/README.md b/README.md index 8d367431..d4b1fa8d 100755 --- a/README.md +++ b/README.md @@ -1,143 +1,242 @@ -# VRCVideoCacherPlus +# VRCVideoCacherPlusPlus + +Caches VRChat videos locally so they play instantly, and gives you control over where +each URL is allowed to go. + +A fork of [VRCVideoCacherPlus](https://github.com/codeyumx/VRCVideoCacherPlus), itself a +fork of [EllyVR/VRCVideoCacher](https://github.com/EllyVR/VRCVideoCacher). **Language:** **English** | [日本語](./README_ja-JP.md) | [Magyar](./README_hu-HU.md) | [한국어](./README_ko-KR.md) | [Português do Brasil](./README_pt-BR.md) -### Download +> The translated READMEs are inherited from upstream and describe the original +> VRCVideoCacher. They have not been updated for this fork. -- [Windows — VRCVideoCacher.exe](https://github.com/codeyumx/VRCVideoCacherPlus/releases/latest/download/VRCVideoCacher.exe) -- [Linux — VRCVideoCacher](https://github.com/codeyumx/VRCVideoCacherPlus/releases/latest/download/VRCVideoCacher) +![Dashboard](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/Dashboard%20Tab.png) -**Install the original VRCVideoCacher cookie extension** (default — use these): -- [Chrome Extension](https://chromewebstore.google.com/detail/vrcvideocacher-cookies-ex/kfgelknbegappcajiflgfbjbdpbpokge) -- [Firefox Extension](https://addons.mozilla.org/en-US/firefox/addon/vrcvideocachercookiesexporter) +## Download -The VRCVideoCacherPlus extensions ([BrowserExtension/](BrowserExtension/)) are in early testing and should send cookies. You can choose: manual send & copy, automatic sharing, and/or app-triggered cookie refresh. They're not on the extension stores yet, so install them unpacked. Unpacked extensions don't update automatically: after pulling a new version, reload the extension yourself. +| | | +| --- | --- | +| Windows | [VRCVideoCacher-win-x64.zip](https://github.com/Bluscream/VRCVideoCacherPlusPlus/releases/latest/download/VRCVideoCacher-win-x64.zip) | +| Linux | [VRCVideoCacher-linux-x64.zip](https://github.com/Bluscream/VRCVideoCacherPlusPlus/releases/latest/download/VRCVideoCacher-linux-x64.zip) | -
-How to install the unpacked extension (Chrome / Firefox) +Unzip anywhere and run it. It has no installer and writes only to its config directory. + +### Cookie extension + +YouTube blocks requests it thinks come from a bot. The extension hands your existing +YouTube session to the app so playback keeps working. **Install the original +VRCVideoCacher extension** — it is signed and published, and it is what most people want: + +- [Chrome Web Store](https://chromewebstore.google.com/detail/vrcvideocacher-cookies-ex/kfgelknbegappcajiflgfbjbdpbpokge) +- [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/vrcvideocachercookiesexporter) + +This repo also ships its own extension, which adds automatic sharing and lets the app +ask for a cookie refresh on demand. It is **not** published to either store, so it has +to be side-loaded — every release includes a `.crx` and a `.xpi`. -Download or clone this repo so you have the `BrowserExtension/` folder locally. +
+Side-loading the PlusPlus extension -**Chrome (and Chromium-based browsers like Edge, Brave):** -1. Open `chrome://extensions` -2. Enable **Developer mode** (top right) -3. Click **Load unpacked** and select the `BrowserExtension/chrome/` folder OR drag and drop the `BrowserExtension/chrome/` into the extensions window +**Chrome / Edge / Brave** — open [`chrome://extensions`](chrome://extensions), turn on +**Developer mode**, then drag the `.crx` onto the page. Loading `BrowserExtension/chrome/` +with **Load unpacked** works too if you have the repo cloned. -**Firefox:** -1. Open `about:debugging#/runtime/this-firefox` -2. Click **Load Temporary Add-on…** and select `BrowserExtension/firefox/manifest.json` -3. Note: temporary add-ons are removed when Firefox closes and must be re-loaded each time. For a persistent install, use [Firefox Developer Edition or Nightly](https://www.mozilla.org/firefox/channel/desktop/) with `xpinstall.signatures.required` set to `false` in `about:config`, zip the `BrowserExtension/firefox/` folder contents, and install the zip via `about:addons` +**Firefox** — release Firefox refuses unsigned add-ons, and the `.xpi` is unsigned. +Either load it temporarily (`about:debugging#/runtime/this-firefox` → **Load Temporary +Add-on…** → pick `BrowserExtension/firefox/manifest.json`, which is dropped when Firefox +closes), or use [Developer Edition or Nightly](https://www.mozilla.org/firefox/channel/desktop/) +with `xpinstall.signatures.required` set to `false` in `about:config` and install the +`.xpi` from `about:addons`.
---- +## What this fork adds + +**Regex URI rules.** Every video URL is matched against an ordered rule list, and the +first match decides what happens: `Cache`, `Direct`, `Redirect`, `Rewrite` or `Block`. +Patterns are real regex with capture substitution (`$1`, `$2`) and tokens like +`{url.domain}` and `{url.path}`. The Rules tab has a live matcher that shows which rule +a URL hits and what it becomes, before you commit anything. + +![Rules](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/Rules%20Tab.png) + +![Editing a rule](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/Edit%20Rule%20Window.png) -VRCVideoCacherPlus helps VRChat videos play. Sometimes, YouTube blocks or throttles videos when a user client does not provide cookies. This app gives YouTube the cookies while you play VRChat so that videos play smoothly and in high definition. This app also downloads videos intelligently if you turn that setting on, so that videos you play often (e.g. VRDancing) don't need to download from the internet again. You can manage the video cache, change the background download speed, and delay the video download (so that you're not downloading two video files or more at the same time). -VRCVideoCacherPlus is based on VRCVideoCacher and adds many improvements, like HLS and streaming playlist (.m3u8) video support. +**Now Playing** reads VRChat's log live and shows what is actually playing — title, +artist, progress — with per-stream controls. -![Main screen](docs/screenshots/main-info.png) -*Main screen — status, cache size, and what the app is doing right now.* +**Active Connections** lists the sockets carrying video right now and can cut a single +stream or all of them. See [the note on privileges](#why-cant-it-always-stop-a-video-that-is-already-playing). -![Download speed and cache delay settings](docs/screenshots/download-settings.png) -*Cache settings — limit background download speed and delay downloads so they don't compete with the video you're watching.* +**Disable Videoplayers** is a single dashboard toggle that blocks all video requests +immediately and closes what it can, for when a world starts playing something you would +rather it did not. -![Automatic cookie refresh with the beta extension](docs/screenshots/cookie-refresh.png) -*Cookies — the beta browser extension can refresh your YouTube cookies automatically, on request from the app.* +**Cache browser and history** show what is stored and what you have watched, with stats +used to decide what to evict when the cache fills — so videos you actually rewatch stay. -### Features +![Cache browser](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/Cache%20Browser.png) -- Pause cache downloads while streaming -- Cache download speed limit -- Download queue & manual downloads -- Cache HLS / streaming-video playlists -- Other improvements -- Builds +**Cloud share links** are rewritten to their direct-download form automatically: Dropbox +`?dl=0` links and Google Drive `/file/d//view` links both work pasted as-is. Mega.nz +does not work and cannot — it is encrypted and JavaScript-only. + +**Smaller things:** download ETA and speed on queued items, a "Download Now" button that +skips the idle delay, video titles in the queue, a tools card tracking `yt-dlp` / `Deno` / +`FFmpeg` versions, an update banner, and a dismissable message-of-the-day. + +![Settings](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/Settings%20Tab.png)
-Details on each feature +Features inherited from VRCVideoCacherPlus + +**Pause cache downloads while streaming** — cache downloads stop while VRChat is +actively requesting streams and resume after a configurable idle period. 0 disables it. -#### Pause cache downloads while streaming +**Cache download speed limit** — cap caching in MB/s so it does not eat your bandwidth. +0 is unlimited. -You can make cache downloads pause automatically when VRChat is playing a streaming video. Set the delay (in seconds) to how long after the stream stops before downloads resume. Set to 0 to disable. +**Manual downloads** — paste YouTube URLs (one per line) into the Downloads tab. Playlist +URLs expand to every video in the playlist. -**Tip:** If you watch long videos or looping content, use the speed limit below instead (or alongside this). +**HLS caching** — finished `.m3u8` and mpegts playlists are re-muxed to MP4 for later +playback. Detection is content-based, so playlists served without a `.m3u8` extension are +still picked up. Live streams (no `#EXT-X-ENDLIST`) are skipped, and there is a +configurable max length. -#### Cache download speed limit +
-You can limit how fast cache downloads run (in MB/s). Set to 0 for unlimited. +## Platform support -**Recommended usage:** Set the pause delay to 300 seconds to cover switching videos or queuing songs, and use the speed limit as a backup for longer playback. +Windows is the tested platform. Linux works — it is what this fork is developed on — but +Resonite patching is Windows-only, and VRChat itself runs under Proton, which changes +where its files live (see [uninstalling](#uninstalling)). SteamVR auto-start is tested on +both. -#### Download queue & manual downloads +## FAQ -You can manually queue videos for caching from the **Downloads** tab. Paste one or more YouTube URLs (one per line) into the text box and click **Add**. YouTube playlists are also supported — paste the playlist URL and all videos in the playlist will be added to the queue automatically. +### How does it work? -#### Cache HLS / streaming-video playlists +It replaces VRChat's `yt-dlp.exe` with a stub that asks this application to resolve the +URL instead. The swap happens at startup and is undone on exit. -Finished HLS streaming playlists (`.m3u8` and mpegts variants like VRDancing's beta mpegts videos) can now be cached as MP4 for later playback. Detection is content-based, so playlists served without a `.m3u8` extension still get picked up. Live streams (no `#EXT-X-ENDLIST`) are skipped, and a max-length cap is configurable in **Cache Settings** (set to 0 for unlimited). +On Windows you may also need codecs: +[VP9](https://apps.microsoft.com/detail/9n4d0msmp0pt) · +[AV1](https://apps.microsoft.com/detail/9mvzqvxjbq9v) · +[AC-3](https://apps.microsoft.com/detail/9nvjqjbdkn97) -**Cloud share URLs:** Dropbox links with `?dl=0` (the default share form) and Google Drive `/file/d//view` links are automatically rewritten to their direct-download form before fetching, so you can paste either form. Mega.nz isn't supported (encrypted, JS-only). Playlists whose segment URLs point to other protected files won't work — the manifest itself plus its segments must be on a directly-fetchable host. +### Are there any risks? -#### Other improvements +From VRChat or EAC — no. From YouTube — possibly; use an alternative Google account for +the cookie extension if you can. -- Update banner — shows a banner when a new version is available -- Better log entries in the log viewer -- Watch history with stats tracking intelligently saves cache space, keeping your favorite videos -- "Download Now" button on queued items — immediately starts downloading a specific item, skipping the idle-wait delay -- Video titles shown in the download queue +### Why can't it always stop a video that is already playing? -#### Builds -##### Windows -Fully user tested on Windows. -##### Linux -App start and basic functionality tested on Linux. -##### Steam App integration -Steam app integration isn't supported yet. SteamVR integration is tested (e.g. starting this app with SteamVR) +Closing a connection that belongs to *another* program is a privileged operation, and +VRChat streaming straight from a CDN is exactly that case. Videos served from this app's +own cache are ours to close and stop instantly; direct streams need permission from the +operating system. -
+Without that permission, blocking still works for everything new — the video already +midway through simply plays to the end. The app tells you which of these happened instead +of claiming success either way. -### Feedback -For code feedback, feature ideas, and bugs, post a GitHub issue. -You can leave general comments and feedback here: [Feedback](https://tally.so/r/kdrM2r) +**Linux** — closing someone else's socket needs the `CAP_NET_ADMIN` capability. Grant it +once and severing works silently from then on, with no password prompt ever: ---- +```bash +sudo setcap cap_net_admin+ep /path/to/VRCVideoCacher +``` -
-FAQ from the EllyVR VRCVideoCacher README +Capabilities live on the file, so **this must be redone after every update**, because the +updater replaces the binary. If you would rather not grant it, the `Sever Connection` +buttons ask for authorisation through your desktop's normal dialog each time (polkit — +KDE, GNOME and the rest all work). -### How does it work? +**Windows** — run as administrator, or accept the UAC prompt when you press +`Sever Connection`. IPv6 connections cannot be closed on Windows at all; it has never +provided an API for it at any privilege level, so those are reported as unsupported +rather than as a permissions problem. -It replaces VRChat's yt-dlp.exe with our own stub yt-dlp, this gets replaced on application startup and is restored on exit. +The automatic **Disable Videoplayers** toggle never prompts for anything. It blocks new +requests and closes what it can, silently. -Auto install missing codecs: [VP9](https://apps.microsoft.com/detail/9n4d0msmp0pt) | [AV1](https://apps.microsoft.com/detail/9mvzqvxjbq9v) | [AC-3](https://apps.microsoft.com/detail/9nvjqjbdkn97) +### Where are the settings stored? -### Are there any risks involved? +`Config.json`, in the same folder the original VRCVideoCacher uses — +`%AppData%\VRCVideoCacher` on Windows, `~/.config/VRCVideoCacher` on Linux. There is one +config file, shared with the original; PlusPlus settings including your rules sit +alongside the normal ones at the top level. -From VRC or EAC? no. +> **Running the original VRCVideoCacher again rewrites `Config.json` and drops every +> setting it does not recognise**, taking your rules back to defaults. The app warns you +> about this once, on first run. -From YouTube/Google? maybe, we strongly recommend you use an alternative Google account if possible. +Coming from an older PlusPlus build, your previous `PlusConfig.json` is left alone and no +longer read. Nothing is migrated automatically — copy anything you want to keep into +`Config.json` yourself. -### How to circumvent YouTube bot detection +### What does it connect to? -In order to fix YouTube videos failing to load, you'll need to install the Chrome or Firefox extension. Visit YouTube, while signed in, at least once while VRCVideoCacher is running, and after VRCVideoCacher has obtained your cookies, the app will send those to YouTube for playing videos. +Beyond the video URL a world asks for: -### Fix YouTube videos sometimes failing to play +| Host | Why | When | +| --- | --- | --- | +| `api.github.com`, `objects.githubusercontent.com` | Update checks and downloads for yt-dlp, Deno, FFmpeg and the app | Startup, then hourly for yt-dlp | +| `dl.deno.land` | Fallback Deno download if GitHub fails | Only on failure | +| `vvc.ellyvr.dev` | Message-of-the-day, from the upstream VRCVideoCacher API | Startup | +| `api.pypy.dance`, `dbapi.vrdancing.club`, `docs.google.com` | Track titles and thumbnails for PyPyDance / VRDancing | When such a video plays | +| `www.youtube.com`, `img.youtube.com` | Titles, thumbnails, and validating your saved cookies | When a YouTube video plays | -> Loading failed. File not found, codec not supported, video resolution too high or insufficient system resources. +Two inherited default rules send a request somewhere you might not expect, because the +URL is rewritten before it is resolved: -YouTube checks system time. Fix: Sync system time, Open Windows Settings -> Time & Language -> Date & Time, under "Additional settings" click "Sync now" +- **niconico links go to `nicovideo.life`**, an unofficial third-party mirror with no + affiliation to this project or to niconico. Playing one tells that mirror what you are + watching. +- **`dmn.moe` links** are rewritten from `/sr/` to `/yt/` and resolved through that site. -
+Both come from upstream. Delete or edit the rules in the Rules tab if you would rather +not use them. + +### YouTube videos fail to play + +Install the cookie extension, then visit YouTube while signed in at least once with this +app running. Once it has your cookies it uses them to resolve videos. + +If you see *"Loading failed. File not found, codec not supported, video resolution too +high or insufficient system resources"*, check your system clock — YouTube rejects +requests with a skewed time. On Windows: **Settings → Time & Language → Date & Time → +Sync now**. + +## Uninstalling + +**Windows** +- If you use VRCX, delete the `VRCVideoCacher` shortcut from `%AppData%\VRCX\startup` +- Delete `%AppData%\VRCVideoCacher` (config and cache) +- Delete `yt-dlp.exe` from `%AppData%\..\LocalLow\VRChat\VRChat\Tools`, then restart VRChat + +**Linux** +- Delete `~/.config/VRCVideoCacher` (config and cache) +- VRChat runs under Proton, so the stub lives in the Steam prefix — delete `yt-dlp.exe` + from `~/.steam/steam/steamapps/compatdata/438100/pfx/drive_c/users/steamuser/AppData/LocalLow/VRChat/VRChat/Tools`, + then restart VRChat + +## Building + +See [AGENTS.md](AGENTS.md) for the full picture. In short: ---- +```bash +./build.sh --lint # locales, extension, strict compile, tests +./build.sh --artifacts # the four release assets into dist/ +./build.sh --help # everything else +``` -## How to uninstall +## Feedback -**Windows:** -- If you have VRCX, delete the startup shortcut "VRCVideoCacher" from `%AppData%\VRCX\startup` -- Delete config and cache from `%AppData%\VRCVideoCacher` -- Delete "yt-dlp.exe" from `%AppData%\..\LocalLow\VRChat\VRChat\Tools`. Restart VRChat. +Bugs and feature ideas: [GitHub issues](https://github.com/Bluscream/VRCVideoCacherPlusPlus/issues). +General comments: [feedback form](https://tally.so/r/kdrM2r). -**Linux:** -- Delete config and cache from `~/.config/VRCVideoCacher` -- VRChat runs under Proton, so delete "yt-dlp.exe" from the Steam compat prefix: `~/.steam/steam/steamapps/compatdata/438100/pfx/drive_c/users/steamuser/AppData/LocalLow/VRChat/VRChat/Tools`. Restart VRChat. +Screenshots and other binary assets live on the [`assets`](https://github.com/Bluscream/VRCVideoCacherPlusPlus/tree/assets) +branch, kept out of the code history. diff --git a/README_hu-HU.md b/README_hu-HU.md index becf366b..07ae49a7 100755 --- a/README_hu-HU.md +++ b/README_hu-HU.md @@ -18,13 +18,13 @@ A VRCVideoCacherPlus bővítmények alfa állapotúak és teszteletlenek — hag A VRCVideoCacherPlus segít a VRChat videók lejátszásában. A YouTube néha blokkolja vagy fojtja a videókat, ha a felhasználó kliense nem ad meg cookie-kat. Ez az alkalmazás átadja a YouTube-nak a cookie-kat, miközben VRChatezel, így a videók simán és nagy felbontásban játszódnak le. Az alkalmazás emellett intelligensen letölti a videókat, ha bekapcsolod ezt a beállítást, így a gyakran lejátszott videókat (pl. VRDancing) nem kell újra letölteni az internetről. Kezelheted a videó-gyorsítótárat, módosíthatod a háttérben futó letöltési sebességet, és késleltetheted a videó letöltését (hogy ne tölts le egyszerre két vagy több videófájlt). A VRCVideoCacherPlus a VRCVideoCacher-en alapul, és számos fejlesztést tartalmaz, mint például a HLS és a streaming lejátszási lista (.m3u8) videók támogatása. -![Főképernyő](docs/screenshots/main-info.png) +![Főképernyő](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/main-info.png) *Főképernyő — állapot, gyorsítótár mérete és az alkalmazás aktuális tevékenysége.* -![Letöltési sebesség és gyorsítótár-késleltetés beállításai](docs/screenshots/download-settings.png) +![Letöltési sebesség és gyorsítótár-késleltetés beállításai](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/download-settings.png) *Gyorsítótár-beállítások — korlátozd a háttérben futó letöltési sebességet, és késleltesd a letöltéseket, hogy ne versenyezzenek az éppen nézett videóval.* -![Automatikus cookie-frissítés a béta bővítménnyel](docs/screenshots/cookie-refresh.png) +![Automatikus cookie-frissítés a béta bővítménnyel](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/cookie-refresh.png) *Cookie-k — a béta böngészőbővítmény az alkalmazás kérésére automatikusan frissítheti a YouTube cookie-jaidat.* ### Funkciók diff --git a/README_ja-JP.md b/README_ja-JP.md index d8608627..06da3b72 100755 --- a/README_ja-JP.md +++ b/README_ja-JP.md @@ -18,13 +18,13 @@ VRCVideoCacherPlus の拡張機能はアルファ版で未テストです。テ VRCVideoCacherPlus は VRChat の動画再生をサポートします。YouTube は、ユーザーのクライアントがクッキーを提供しない場合、動画をブロックまたは制限することがあります。このアプリは VRChat をプレイ中に YouTube へクッキーを渡すことで、動画が高画質でスムーズに再生されるようにします。また、設定をオンにすれば動画をインテリジェントにダウンロードし、よく再生する動画(例: VRDancing)を毎回インターネットからダウンロードし直す必要がなくなります。動画キャッシュの管理、バックグラウンドのダウンロード速度の変更、動画ダウンロードの遅延(複数の動画ファイルを同時にダウンロードしないようにする)が可能です。 VRCVideoCacherPlus は VRCVideoCacher をベースにしており、HLS やストリーミングプレイリスト(.m3u8)動画のサポートなど、多くの改善が加えられています。 -![メイン画面](docs/screenshots/main-info.png) +![メイン画面](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/main-info.png) *メイン画面 — 状態、キャッシュサイズ、アプリの現在の動作。* -![ダウンロード速度とキャッシュ遅延の設定](docs/screenshots/download-settings.png) +![ダウンロード速度とキャッシュ遅延の設定](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/download-settings.png) *キャッシュ設定 — バックグラウンドのダウンロード速度を制限し、視聴中の動画と競合しないようにダウンロードを遅延させます。* -![ベータ拡張機能によるクッキーの自動更新](docs/screenshots/cookie-refresh.png) +![ベータ拡張機能によるクッキーの自動更新](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/cookie-refresh.png) *クッキー — ベータ版のブラウザ拡張機能は、アプリからの要求に応じて YouTube のクッキーを自動で更新できます。* ### 機能 diff --git a/README_ko-KR.md b/README_ko-KR.md index 2371c904..2493589f 100755 --- a/README_ko-KR.md +++ b/README_ko-KR.md @@ -18,13 +18,13 @@ VRCVideoCacherPlus 확장 프로그램은 알파 단계이며 테스트되지 VRCVideoCacherPlus는 VRChat 동영상 재생을 도와줍니다. YouTube는 사용자 클라이언트가 쿠키를 제공하지 않으면 동영상을 차단하거나 제한하는 경우가 있습니다. 이 앱은 VRChat을 플레이하는 동안 YouTube에 쿠키를 전달하여 동영상이 고화질로 부드럽게 재생되도록 합니다. 또한 해당 설정을 켜면 동영상을 지능적으로 다운로드하여 자주 재생하는 동영상(예: VRDancing)을 매번 인터넷에서 다시 다운로드할 필요가 없게 합니다. 동영상 캐시를 관리하고, 백그라운드 다운로드 속도를 변경하며, 동영상 다운로드를 지연시킬 수 있습니다(두 개 이상의 동영상 파일을 동시에 다운로드하지 않도록). VRCVideoCacherPlus는 VRCVideoCacher를 기반으로 하며, HLS 및 스트리밍 재생 목록(.m3u8) 동영상 지원과 같은 여러 개선 사항을 추가했습니다. -![메인 화면](docs/screenshots/main-info.png) +![메인 화면](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/main-info.png) *메인 화면 — 상태, 캐시 크기, 앱이 현재 수행 중인 작업.* -![다운로드 속도 및 캐시 지연 설정](docs/screenshots/download-settings.png) +![다운로드 속도 및 캐시 지연 설정](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/download-settings.png) *캐시 설정 — 백그라운드 다운로드 속도를 제한하고, 시청 중인 동영상과 겹치지 않도록 다운로드를 지연시킵니다.* -![베타 확장 프로그램을 통한 쿠키 자동 갱신](docs/screenshots/cookie-refresh.png) +![베타 확장 프로그램을 통한 쿠키 자동 갱신](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/cookie-refresh.png) *쿠키 — 베타 브라우저 확장 프로그램은 앱의 요청에 따라 YouTube 쿠키를 자동으로 갱신할 수 있습니다.* ### 기능 diff --git a/README_pt-BR.md b/README_pt-BR.md index 81dbe8d4..5eb9a13c 100755 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -18,13 +18,13 @@ As extensões do VRCVideoCacherPlus estão em alfa e não foram testadas — ign O VRCVideoCacherPlus ajuda os vídeos do VRChat a tocarem. Às vezes, o YouTube bloqueia ou limita vídeos quando o cliente do usuário não fornece cookies. Este aplicativo fornece os cookies ao YouTube enquanto você joga VRChat, para que os vídeos toquem de forma fluida e em alta definição. O aplicativo também baixa vídeos de forma inteligente, se você ativar essa configuração, para que os vídeos que você toca com frequência (por exemplo, VRDancing) não precisem ser baixados da internet novamente. Você pode gerenciar o cache de vídeos, alterar a velocidade de download em segundo plano e atrasar o download do vídeo (para não baixar dois ou mais arquivos de vídeo ao mesmo tempo). O VRCVideoCacherPlus é baseado no VRCVideoCacher e adiciona muitas melhorias, como suporte a vídeos HLS e listas de reprodução de streaming (.m3u8). -![Tela principal](docs/screenshots/main-info.png) +![Tela principal](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/main-info.png) *Tela principal — status, tamanho do cache e o que o aplicativo está fazendo no momento.* -![Configurações de velocidade de download e atraso do cache](docs/screenshots/download-settings.png) +![Configurações de velocidade de download e atraso do cache](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/download-settings.png) *Configurações de cache — limite a velocidade de download em segundo plano e atrase os downloads para que não concorram com o vídeo que você está assistindo.* -![Atualização automática de cookies com a extensão beta](docs/screenshots/cookie-refresh.png) +![Atualização automática de cookies com a extensão beta](https://raw.githubusercontent.com/Bluscream/VRCVideoCacherPlusPlus/assets/cookie-refresh.png) *Cookies — a extensão de navegador em beta pode atualizar seus cookies do YouTube automaticamente, a pedido do aplicativo.* ### Recursos diff --git a/VRCVideoCacher.Tests/ConfigSerializationTests.cs b/VRCVideoCacher.Tests/ConfigSerializationTests.cs new file mode 100644 index 00000000..cae32bb3 --- /dev/null +++ b/VRCVideoCacher.Tests/ConfigSerializationTests.cs @@ -0,0 +1,211 @@ +using VRCVideoCacher; +using VRCVideoCacher.Models; +using VRCVideoCacher.Utils; +using Xunit; + +namespace VRCVideoCacher.Tests; + +public class ConfigSerializationTests +{ + private const string LegacyConfigJson = """ + { + "YtdlpWebServerUrl": "http://localhost.youtube.com:9696", + "YtdlpUseCookies": true, + "UseBetaExtension": true, + "YtdlpAutoUpdate": true, + "AutoUpdateVrcVideoCacher": false, + "YtdlpAdditionalArgs": "--retries 3", + "YtdlpDubLanguage": "de", + "CachedAssetPath": "", + "CacheMaxSizeInGb": 10.0, + "CacheHlsPlaylists": true, + "CacheHlsMaxLength": 30, + "CacheOnly": false, + "PreCacheUrls": [], + "PreCacheVideos": ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"], + "PatchResonite": false, + "ResonitePath": "", + "PatchVrChat": true, + "VideoPlayersEnabled": true, + "CloseToTray": true, + "StartMinimized": false, + "StartWithSteamVr": true, + "CookieSetupCompleted": true, + "RedirectVRDancing": false, + "ErrorPopups": true, + "Language": "ja", + "HasShownTrayNotice": true + } + """; + + [Fact] + public void ReadsAConfigWrittenByTheOldSerializer() + { + var config = Json.Deserialize(LegacyConfigJson); + + Assert.NotNull(config); + Assert.Equal("http://localhost.youtube.com:9696", config!.YtdlpWebServerUrl); + Assert.True(config.YtdlpUseCookies); + Assert.True(config.UseBetaExtension); + Assert.False(config.AutoUpdateVrcVideoCacher); + Assert.Equal("--retries 3", config.YtdlpAdditionalArgs); + Assert.Equal("de", config.YtdlpDubLanguage); + Assert.Equal(10f, config.CacheMaxSizeInGb); + Assert.Equal(30, config.CacheHlsMaxLength); + Assert.Equal(["https://www.youtube.com/watch?v=dQw4w9WgXcQ"], config.PreCacheVideos); + Assert.True(config.CookieSetupCompleted); + Assert.Equal("ja", config.Language); + Assert.True(config.HasShownTrayNotice); + } + + [Fact] + public void IgnoresAKeyThatNoLongerExists() + { + var exception = Record.Exception(() => Json.Deserialize(LegacyConfigJson)); + Assert.Null(exception); + } + + [Fact] + public void ConfigSurvivesARoundTrip() + { + var original = Json.Deserialize(LegacyConfigJson)!; + var restored = Json.Deserialize(Json.Serialize(original))!; + + Assert.Equal(original.YtdlpWebServerUrl, restored.YtdlpWebServerUrl); + Assert.Equal(original.CacheMaxSizeInGb, restored.CacheMaxSizeInGb); + Assert.Equal(original.Language, restored.Language); + Assert.Equal(original.PreCacheVideos, restored.PreCacheVideos); + Assert.Equal(original.AutoUpdateVrcVideoCacher, restored.AutoUpdateVrcVideoCacher); + } + + [Fact] + public void ReadsAPlusConfigWrittenByTheOldSerializer() + { + const string json = """ + { + "CacheDownloadRateLimitMBs": 5, + "CacheDownloadIdleSeconds": 30, + "CacheYouTubePreferVp9": true, + "UriRules": [ + { + "Id": "315e410c4f874e68990ce76f4ba9534a", + "Enabled": false, + "Name": "YouTube Music Redirect", + "Pattern": "^https?:\\/\\/music\\.youtube\\.com\\/(?:watch|playlist)?\\?(?:.*?&)?v=([^&]+).*$", + "Action": 2, + "Cache": false, + "MaxResolution": null, + "MaxDurationMinutes": null, + "RedirectTarget": "https://youtube.com/watch?v=$1", + "Integration": null + } + ] + } + """; + + var config = Json.Deserialize(json); + + Assert.NotNull(config); + Assert.Equal(5, config!.CacheDownloadRateLimitMBs); + Assert.Equal(30, config.CacheDownloadIdleSeconds); + Assert.True(config.CacheYouTubePreferVp9); + + var rule = Assert.Single(config.UriRules); + Assert.Equal("315e410c4f874e68990ce76f4ba9534a", rule.Id); + Assert.False(rule.Enabled); + Assert.Equal("YouTube Music Redirect", rule.Name); + Assert.Equal(RuleAction.Redirect, rule.Action); + Assert.Equal("https://youtube.com/watch?v=$1", rule.RedirectTarget); + Assert.Null(rule.MaxResolution); + Assert.Null(rule.Integration); + Assert.Contains(@"music\.youtube\.com", rule.Pattern); + } + + [Fact] + public void DoesNotEscapeUrlsOrRegexPatternsIntoUnreadableText() + { + var config = new ConfigModel + { + UriRules = + [ + new UriRule + { + Name = "Ampersands & plus+signs", + Pattern = @"^https?://x\.com/\?a=1&b=2$", + RedirectTarget = "https://y.com/?a=1&b=2+3" + } + ] + }; + + var json = Json.Serialize(config); + + Assert.Contains("a=1&b=2", json); + Assert.Contains("Ampersands & plus+signs", json); + Assert.DoesNotContain("\\u0026", json); + Assert.DoesNotContain("\\u002B", json); + } + + [Fact] + public void EnumsStayNumericSoExistingFilesKeepWorking() + { + var json = Json.Serialize(new ConfigModel + { + UriRules = [new UriRule { Action = RuleAction.Block }] + }); + + Assert.Contains("\"Action\": 4", json); + } + + [Fact] + public void ToleratesCommentsAndTrailingCommasInAHandEditedFile() + { + const string json = """ + { + // a user's note + "CacheDownloadIdleSeconds": 45, + } + """; + + Assert.Equal(45, Json.Deserialize(json)!.CacheDownloadIdleSeconds); + } + + [Fact] + public void VersionFileRoundTrips() + { + var restored = Json.Deserialize( + Json.Serialize(new VersionJson { Ytdlp = "2026.08.20", Ffmpeg = "7.1.1", Deno = "v2.8.0" }))!; + + Assert.Equal("2026.08.20", restored.Ytdlp); + Assert.Equal("7.1.1", restored.Ffmpeg); + Assert.Equal("v2.8.0", restored.Deno); + } + + [Fact] + public void ReadsAGitHubReleasePayload() + { + const string json = """ + { + "tag_name": "2026.8.21", + "html_url": "https://github.com/codeyumx/VRCVideoCacherPlus/releases/tag/2026.8.21", + "assets": [ + { + "name": "VRCVideoCacher.exe", + "browser_download_url": "https://github.com/.../VRCVideoCacher.exe", + "digest": "sha256:abc" + } + ] + } + """; + + var payload = Json.Deserialize(json); + + Assert.NotNull(payload); + Assert.Equal("2026.8.21", payload!.tag_name); + Assert.Equal("https://github.com/codeyumx/VRCVideoCacherPlus/releases/tag/2026.8.21", payload.html_url); + + var asset = Assert.Single(payload.assets); + Assert.Equal("VRCVideoCacher.exe", asset.name); + Assert.Equal("https://github.com/.../VRCVideoCacher.exe", asset.browser_download_url); + Assert.Equal("sha256:abc", asset.digest); + } +} diff --git a/VRCVideoCacher.Tests/ConnectionSeveringTests.cs b/VRCVideoCacher.Tests/ConnectionSeveringTests.cs new file mode 100644 index 00000000..f8b2dcdb --- /dev/null +++ b/VRCVideoCacher.Tests/ConnectionSeveringTests.cs @@ -0,0 +1,70 @@ +using VRCVideoCacher.Utils; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// `ss` rejects a bare IPv6 literal in a dst filter, and it does so on stderr while still +// exiting 0 — the exact shape of failure that made severing silently do nothing before. +// These pin the one character that fixes it. +public class ConnectionSeveringTests +{ + [Theory] + [InlineData("2001:db8::1", "[2001:db8::1]")] + [InlineData("::1", "[::1]")] + [InlineData("fe80::1ff:fe23:4567:890a", "[fe80::1ff:fe23:4567:890a]")] + public void BracketsIpV6Destinations(string address, string expected) + { + Assert.Equal(expected, ConnectionSevering.FormatSsDestination(address)); + } + + [Theory] + [InlineData("1.2.3.4")] + [InlineData("127.0.0.1")] + [InlineData("172.217.16.142")] + public void LeavesIpV4DestinationsAlone(string address) + { + Assert.Equal(address, ConnectionSevering.FormatSsDestination(address)); + } + + [Fact] + public void LeavesUnparseableInputAlone() + { + // Never reaches ss — the elevated helper drops anything that is not an IP — but the + // formatter must not invent brackets around whatever it is handed. + Assert.Equal("not-an-address", ConnectionSevering.FormatSsDestination("not-an-address")); + } + + [Fact] + public void ParsesTheElevatedSeverCommand() + { + LaunchArgs.SetupArguments("--sever-connections=1.2.3.4,2001:db8::1"); + + Assert.True(LaunchArgs.IsSeverCommand); + Assert.True(LaunchArgs.IsPrivilegedHelper); + Assert.Equal(["1.2.3.4", "2001:db8::1"], LaunchArgs.SeverAddresses); + + LaunchArgs.SeverAddresses = []; + } + + [Fact] + public void ASeverCommandIsNotCarriedIntoRelaunches() + { + // The updater re-emits launch flags. A one-shot privileged command must never be + // among them, or every update would try to elevate. + LaunchArgs.SetupArguments("--sever-connections=1.2.3.4"); + Assert.DoesNotContain(LaunchArgs.BuildArgs(), a => a.Contains("sever")); + LaunchArgs.SeverAddresses = []; + } + + [Fact] + public void CapabilityHintNamesTheRealBinary() + { + var hint = ConnectionSevering.CapabilityHint; + Assert.False(string.IsNullOrWhiteSpace(hint)); + if (OperatingSystem.IsLinux()) + { + Assert.Contains("cap_net_admin", hint); + Assert.Contains(Environment.ProcessPath!, hint); + } + } +} diff --git a/VRCVideoCacher.Tests/DefaultRuleTests.cs b/VRCVideoCacher.Tests/DefaultRuleTests.cs new file mode 100644 index 00000000..1869b767 --- /dev/null +++ b/VRCVideoCacher.Tests/DefaultRuleTests.cs @@ -0,0 +1,123 @@ +using System.Text.RegularExpressions; +using VRCVideoCacher; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// Regression tests for the shipped default rules, run through the same regex construction +// and template expansion the request path uses. +// +// The Dropbox rules in particular: the original pattern was +// ^https?://(?:[a-zA-Z0-9-]+\.)*dropbox\.com/(.*?)(?:\?dl=0)?$ -> ".../$1?dl=1" +// whose lazy group had to expand past the whole query before the anchor could match, so +// the optional ?dl=0 never participated for a link with more than one parameter. Dropbox's +// current share format is "?rlkey=...&st=...&dl=0", which came out as "...&dl=0?dl=1". +public class DefaultRuleTests +{ + private static UriRule Rule(string name) => + DefaultRules.Create().Single(r => r.Name == name); + + /// + /// Applies the enabled Rewrite rules in order, exactly as RuleEngine does. + /// + private static string ApplyRewrites(string url) + { + foreach (var rule in DefaultRules.Create().Where(r => r.Enabled && r.Action == RuleAction.Rewrite)) + { + var match = RuleEngine.GetRegex(rule.Pattern).Match(url); + if (match.Success) + url = RuleEngine.ExpandTemplate(rule.RedirectTarget, url, match); + } + + return url; + } + + [Theory] + // The modern /scl/fi/ share format, which the previous pattern mangled. + [InlineData("https://www.dropbox.com/scl/fi/abc/v.mp4?rlkey=k&st=s&dl=0", + "https://www.dropbox.com/scl/fi/abc/v.mp4?rlkey=k&st=s&dl=1")] + // The older /s/ format, which it handled correctly. + [InlineData("https://www.dropbox.com/s/abc/v.mp4?dl=0", + "https://www.dropbox.com/s/abc/v.mp4?dl=1")] + // Already a direct link: must be left exactly as-is, not given a second query string. + [InlineData("https://www.dropbox.com/s/abc/v.mp4?dl=1", + "https://www.dropbox.com/s/abc/v.mp4?dl=1")] + // raw=1 is also already direct. + [InlineData("https://www.dropbox.com/s/abc/v.mp4?raw=1", + "https://www.dropbox.com/s/abc/v.mp4?raw=1")] + // Bare path with no query at all gets ?dl=1 appended. + [InlineData("https://www.dropbox.com/scl/fi/abc/v.mp4", + "https://www.dropbox.com/scl/fi/abc/v.mp4?dl=1")] + // dl=0 mid-query, with another parameter after it. + [InlineData("https://dropbox.com/s/abc/v.mp4?dl=0&raw=1", + "https://dropbox.com/s/abc/v.mp4?dl=1&raw=1")] + // Not Dropbox: untouched. + [InlineData("https://example.com/s/abc/v.mp4?dl=0", + "https://example.com/s/abc/v.mp4?dl=0")] + public void DropboxRules_ProduceADirectDownloadUrl(string input, string expected) + { + Assert.Equal(expected, ApplyRewrites(input)); + } + + [Theory] + [InlineData("https://drive.google.com/file/d/ABC123/view?usp=sharing", + "https://drive.google.com/uc?export=download&id=ABC123")] + [InlineData("https://drive.google.com/file/d/ABC123", + "https://drive.google.com/uc?export=download&id=ABC123")] + public void GoogleDriveRule_RewritesToDirectDownload(string input, string expected) + { + Assert.Equal(expected, ApplyRewrites(input)); + } + + [Fact] + public void EveryDefaultRuleHasAValidPattern() + { + foreach (var rule in DefaultRules.Create()) + { + var exception = Record.Exception(() => RuleEngine.GetRegex(rule.Pattern)); + Assert.Null(exception); + } + } + + [Fact] + public void DefaultRuleNamesAreUnique() + { + // EnsureDefaultRules tracks seeded defaults by name, so a duplicate name would make + // one of them unseedable. + var names = DefaultRules.Create().Select(r => r.Name).ToList(); + Assert.Equal(names.Count, names.Distinct().Count()); + } + + [Fact] + public void CatchAllRuleIsLastAndMatchesEverything() + { + var rules = DefaultRules.Create(); + var last = rules[^1]; + + Assert.Equal("Everything else", last.Name); + Assert.True(last.Enabled); + Assert.Matches(new Regex(last.Pattern), "https://anything.example/whatever"); + } + + [Fact] + public void BlockRickrollsShipsDisabled() + { + // Block genuinely prevents playback now, so a fresh install must not silently + // refuse specific videos. + Assert.False(Rule("Block Rickrolls").Enabled); + } + + [Fact] + public void YouTubeRuleMatchesItsCommonHostForms() + { + var regex = RuleEngine.GetRegex(Rule("YouTube").Pattern); + + Assert.Matches(regex, "https://www.youtube.com/watch?v=dQw4w9WgXcQ"); + Assert.Matches(regex, "https://youtu.be/dQw4w9WgXcQ"); + Assert.Matches(regex, "https://music.youtube.com/watch?v=dQw4w9WgXcQ"); + Assert.Matches(regex, "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ"); + Assert.DoesNotMatch(regex, "https://notyoutube.com/watch?v=dQw4w9WgXcQ"); + } +} diff --git a/VRCVideoCacher.Tests/HlsManifestTests.cs b/VRCVideoCacher.Tests/HlsManifestTests.cs new file mode 100644 index 00000000..9ca520a0 --- /dev/null +++ b/VRCVideoCacher.Tests/HlsManifestTests.cs @@ -0,0 +1,122 @@ +using VRCVideoCacher.Integrations.Hls; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// The parsed duration and the presence of #EXT-X-ENDLIST are what gate HLS caching: get +// either wrong and yt-dlp is either pointed at a live stream that never ends, or a +// perfectly cacheable video is skipped. +public class HlsManifestTests +{ + private const string CompleteManifest = """ + #EXTM3U + #EXT-X-VERSION:3 + #EXT-X-TARGETDURATION:10 + #EXTINF:9.009, + seg0.ts + #EXTINF:9.009, + seg1.ts + #EXTINF:3.003, + seg2.ts + #EXT-X-ENDLIST + """; + + private const string LiveManifest = """ + #EXTM3U + #EXT-X-VERSION:3 + #EXT-X-MEDIA-SEQUENCE:1740 + #EXTINF:9.009, + seg1740.ts + #EXTINF:9.009, + seg1741.ts + """; + + [Fact] + public void SumsSegmentDurationsAndSeesTheEndList() + { + var (duration, isComplete) = HlsIntegration.ParseMediaPlaylist(CompleteManifest); + + Assert.True(isComplete); + Assert.NotNull(duration); + Assert.Equal(21.021, duration!.Value, precision: 3); + } + + [Fact] + public void ReportsALivePlaylistAsIncomplete() + { + var (duration, isComplete) = HlsIntegration.ParseMediaPlaylist(LiveManifest); + + Assert.False(isComplete); + // A duration is still parsed; it is the completeness flag that gates caching. + Assert.NotNull(duration); + } + + [Fact] + public void ReturnsNoDurationWhenThereAreNoSegments() + { + var (duration, isComplete) = HlsIntegration.ParseMediaPlaylist("#EXTM3U\n#EXT-X-VERSION:3\n"); + + Assert.Null(duration); + Assert.False(isComplete); + } + + [Fact] + public void ParsesDurationsWithAnInvariantDecimalPoint() + { + // Manifests always use '.', so parsing must not follow a comma-decimal culture. + var previous = Thread.CurrentThread.CurrentCulture; + try + { + Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE"); + var (duration, _) = HlsIntegration.ParseMediaPlaylist(CompleteManifest); + Assert.Equal(21.021, duration!.Value, precision: 3); + } + finally + { + Thread.CurrentThread.CurrentCulture = previous; + } + } + + [Fact] + public void HandlesCrLfLineEndings() + { + var (duration, isComplete) = HlsIntegration.ParseMediaPlaylist(CompleteManifest.Replace("\n", "\r\n")); + + Assert.True(isComplete); + Assert.Equal(21.021, duration!.Value, precision: 3); + } + + [Fact] + public void ReadsAnOptionalSessionTitle() + { + const string manifest = """ + #EXTM3U + #EXT-X-SESSION-DATA:DATA-ID="com.apple.hls.title",VALUE="Some Dance Video" + #EXTINF:9.0, + seg0.ts + #EXT-X-ENDLIST + """; + + Assert.Equal("Some Dance Video", HlsIntegration.ParseSessionTitle(manifest)); + } + + [Fact] + public void ReturnsNoTitleWhenTheTagIsAbsent() => + Assert.Null(HlsIntegration.ParseSessionTitle(CompleteManifest)); + + [Theory] + [InlineData("https://cdn.example.com/v/clip.mp4", true)] + [InlineData("https://cdn.example.com/v/clip.WEBM", true)] + [InlineData("https://cdn.example.com/v/thumb.jpg", true)] + [InlineData("https://cdn.example.com/v/clip.m3u8", false)] + [InlineData("https://cdn.example.com/v/stream", false)] + public void LooksObviouslyNotHls_SkipsTheProbeForKnownMediaExtensions(string url, bool expected) => + Assert.Equal(expected, HlsIntegration.LooksObviouslyNotHls(new Uri(url))); + + [Theory] + [InlineData("https://cdn.example.com/v/clip.m3u8", true)] + [InlineData("https://cdn.example.com/v/clip.M3U8", true)] + [InlineData("https://cdn.example.com/v/clip.mp4", false)] + public void CanHandle_FastPathsOnTheM3u8Extension(string url, bool expected) => + Assert.Equal(expected, new HlsIntegration().CanHandle(new Uri(url))); +} diff --git a/VRCVideoCacher.Tests/PyPyDanceTests.cs b/VRCVideoCacher.Tests/PyPyDanceTests.cs new file mode 100644 index 00000000..7cd1f2df --- /dev/null +++ b/VRCVideoCacher.Tests/PyPyDanceTests.cs @@ -0,0 +1,52 @@ +using VRCVideoCacher.Integrations.PyPyDance; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// The cache file is named after the id derived here, so getting it wrong does not fail +// loudly — it makes different videos collide on one file and serves the wrong one back. +public class PyPyDanceTests +{ + [Theory] + [InlineData("http://cdn.pypy.dance/qylu4Ajh6k8.mp4", "qylu4Ajh6k8")] + [InlineData("https://cdn.pypy.dance/fquYjLA_f28.mp4", "fquYjLA_f28")] + [InlineData("http://cdn.pypy.dance/eCN__1XLgng.mp4", "eCN__1XLgng")] + // No extension: the whole segment is the id. + [InlineData("http://cdn.pypy.dance/abc123", "abc123")] + // Only the part before the first dot. + [InlineData("http://cdn.pypy.dance/abc.def.mp4", "abc")] + public void DeriveVideoId_TakesTheCdnFileName(string url, string expected) + { + Assert.Equal(expected, PyPyDanceIntegration.DeriveVideoId(new Uri(url))); + } + + [Fact] + public void DeriveVideoId_RejectsTheUnredirectedApiEndpoint() + { + // The regression this guards: api.pypy.dance answers 302 to a plain-http CDN URL, + // and HttpClient will not follow an https -> http downgrade. The old code read the + // file name off the *original* URL and got "video" — for every single track, so + // they all shared one cache entry. + Assert.Null(PyPyDanceIntegration.DeriveVideoId(new Uri("https://api.pypy.dance/video?id=1"))); + Assert.Null(PyPyDanceIntegration.DeriveVideoId(new Uri("http://api.pypy.dance/video"))); + } + + [Theory] + [InlineData("http://cdn.pypy.dance/")] + [InlineData("http://cdn.pypy.dance")] + public void DeriveVideoId_RejectsAUrlWithNoFileName(string url) + { + Assert.Null(PyPyDanceIntegration.DeriveVideoId(new Uri(url))); + } + + [Theory] + [InlineData("https://api.pypy.dance/video?id=1", true)] + [InlineData("http://api.pypy.dance/video?id=1", true)] + [InlineData("HTTPS://API.PYPY.DANCE/video?id=1", true)] + [InlineData("https://api.pypy.dance/bundle", false)] + [InlineData("https://example.com/video?id=1", false)] + public void CanHandle_MatchesOnlyTheVideoEndpoint(string url, bool expected) + { + Assert.Equal(expected, new PyPyDanceIntegration().CanHandle(new Uri(url))); + } +} diff --git a/VRCVideoCacher.Tests/RuleEngineTests.cs b/VRCVideoCacher.Tests/RuleEngineTests.cs new file mode 100644 index 00000000..3478265d --- /dev/null +++ b/VRCVideoCacher.Tests/RuleEngineTests.cs @@ -0,0 +1,88 @@ +using System.Text.RegularExpressions; +using VRCVideoCacher.Services; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// ExpandTemplate is what turns a matched rule into the URL actually requested, so its +// substitution rules are worth pinning down. GetRegex is the shared compile-and-cache used +// by both the request path and the Rules tab's live matcher. +public class RuleEngineTests +{ + private static Match MatchOf(string pattern, string input) => + RuleEngine.GetRegex(pattern).Match(input); + + [Fact] + public void ExpandTemplate_SubstitutesNumberedGroups() + { + var match = MatchOf(@"^https?://example\.com/(\w+)/(\w+)$", "https://example.com/a/b"); + Assert.Equal("https://cdn.example.com/b-a", RuleEngine.ExpandTemplate("https://cdn.example.com/$2-$1", "https://example.com/a/b", match)); + } + + [Fact] + public void ExpandTemplate_SubstitutesAnUnmatchedOptionalGroupAsEmpty() + { + // The Dropbox rule depends on this: its trailing (&[^#]*)? group usually does not + // participate, and must expand to nothing rather than the literal "${2}". + var match = MatchOf(@"^(a)(b)?$", "a"); + Assert.Equal("a", RuleEngine.ExpandTemplate("${1}${2}", "a", match)); + } + + [Theory] + [InlineData("{url.scheme}", "https")] + [InlineData("{url.host}", "example.com")] + [InlineData("{url.domain}", "example.com")] + [InlineData("{url.path}", "/videos/clip.mp4")] + [InlineData("{url.query}", "?id=7&x=y")] + [InlineData("{url.port}", "443")] + [InlineData("{url.fragment}", "top")] + [InlineData("{url.query.id}", "7")] + [InlineData("{url.query.missing}", "")] + public void ExpandTemplate_SubstitutesUrlTokens(string template, string expected) + { + const string url = "https://example.com/videos/clip.mp4?id=7&x=y#top"; + Assert.Equal(expected, RuleEngine.ExpandTemplate(template, url, MatchOf(".*", url))); + } + + [Fact] + public void ExpandTemplate_ReturnsOriginalUrlForAnEmptyTemplate() + { + const string url = "https://example.com/a"; + Assert.Equal(url, RuleEngine.ExpandTemplate("", url, MatchOf(".*", url))); + } + + [Fact] + public void ExpandTemplate_LeavesTokensAloneForANonAbsoluteUrl() + { + // Nothing to parse, so the host token cannot be resolved — it must not throw. + var exception = Record.Exception(() => RuleEngine.ExpandTemplate("{url.host}", "not a url", MatchOf(".*", "not a url"))); + Assert.Null(exception); + } + + [Fact] + public void GetRegex_ReturnsTheSameInstanceForTheSamePattern() + { + // Caching is the point: the request path compiles every rule for every URL otherwise. + Assert.Same(RuleEngine.GetRegex(@"^https://cached\.example/"), RuleEngine.GetRegex(@"^https://cached\.example/")); + } + + [Fact] + public void GetRegex_IsCaseInsensitiveAndCultureInvariant() + { + var regex = RuleEngine.GetRegex(@"^https://YOUTUBE\.COM/"); + Assert.Matches(regex, "https://youtube.com/watch"); + + // Under a Turkish culture, IgnoreCase without CultureInvariant does not fold I to i, + // so a pattern written in upper case silently stops matching. + var previous = Thread.CurrentThread.CurrentCulture; + try + { + Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("tr-TR"); + Assert.Matches(RuleEngine.GetRegex(@"^https://YOUTUBE\.COM/i"), "https://youtube.com/I"); + } + finally + { + Thread.CurrentThread.CurrentCulture = previous; + } + } +} diff --git a/VRCVideoCacher.Tests/SchemaReconcilerTests.cs b/VRCVideoCacher.Tests/SchemaReconcilerTests.cs new file mode 100644 index 00000000..dbe88656 --- /dev/null +++ b/VRCVideoCacher.Tests/SchemaReconcilerTests.cs @@ -0,0 +1,96 @@ +using Microsoft.EntityFrameworkCore; +using VRCVideoCacher.Database; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// SchemaReconciler backfills columns the EF model declares but the database lacks, because +// EnsureCreated never alters a database that already exists. These run against a real +// temporary SQLite file — the behaviour being tested is entirely about what SQLite does. +public class SchemaReconcilerTests : IDisposable +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"vvc-schema-{Guid.NewGuid():N}.db"); + + private Database.Database CreateContext() => + new(new DbContextOptionsBuilder() + .UseSqlite($"Data Source={_dbPath}") + .Options); + + public void Dispose() + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + foreach (var path in new[] { _dbPath, _dbPath + "-wal", _dbPath + "-shm" }) + { + try { if (File.Exists(path)) File.Delete(path); } + catch { /* best effort */ } + } + } + + private static HashSet ColumnsOf(DbContext db, string table) + { + // EF1002: table names are literals from these tests, not input. +#pragma warning disable EF1002 + return db.Database + .SqlQueryRaw($"SELECT name AS Value FROM pragma_table_info('{table}')") + .AsEnumerable() + .ToHashSet(StringComparer.OrdinalIgnoreCase); +#pragma warning restore EF1002 + } + + [Fact] + public void Run_AddsAColumnMissingFromAnExistingTable() + { + using var db = CreateContext(); + db.Database.EnsureCreated(); + + // Simulate a database created before a property existed. + db.Database.ExecuteSqlRaw("ALTER TABLE VideoInfoCache DROP COLUMN Author"); + Assert.DoesNotContain("Author", ColumnsOf(db, "VideoInfoCache")); + + SchemaReconciler.Run(db); + + Assert.Contains("Author", ColumnsOf(db, "VideoInfoCache")); + } + + [Fact] + public void Run_PreservesExistingRowsWhenBackfilling() + { + using var db = CreateContext(); + db.Database.EnsureCreated(); + db.Database.ExecuteSqlRaw("ALTER TABLE VideoInfoCache DROP COLUMN Author"); + db.Database.ExecuteSqlRaw("INSERT INTO VideoInfoCache (Id, Title, Type) VALUES ('abc', 'Some title', 0)"); + + SchemaReconciler.Run(db); + + var row = db.VideoInfoCache.AsNoTracking().Single(); + Assert.Equal("abc", row.Id); + Assert.Equal("Some title", row.Title); + Assert.Null(row.Author); + } + + [Fact] + public void Run_IsIdempotent() + { + using var db = CreateContext(); + db.Database.EnsureCreated(); + db.Database.ExecuteSqlRaw("ALTER TABLE VideoInfoCache DROP COLUMN Author"); + + SchemaReconciler.Run(db); + var afterFirst = ColumnsOf(db, "VideoInfoCache"); + SchemaReconciler.Run(db); + + Assert.Equal(afterFirst, ColumnsOf(db, "VideoInfoCache")); + } + + [Fact] + public void Run_LeavesAnUpToDateSchemaAlone() + { + using var db = CreateContext(); + db.Database.EnsureCreated(); + var before = ColumnsOf(db, "PlayHistory"); + + SchemaReconciler.Run(db); + + Assert.Equal(before, ColumnsOf(db, "PlayHistory")); + } +} diff --git a/VRCVideoCacher.Tests/SharedConfigMigrationTests.cs b/VRCVideoCacher.Tests/SharedConfigMigrationTests.cs new file mode 100644 index 00000000..3403e35f --- /dev/null +++ b/VRCVideoCacher.Tests/SharedConfigMigrationTests.cs @@ -0,0 +1,134 @@ +using VRCVideoCacher; +using VRCVideoCacher.Models; +using VRCVideoCacher.Utils; +using Xunit; + +namespace VRCVideoCacher.Tests; + +public class SharedConfigMigrationTests +{ + [Fact] + public void PlusSettingsRoundTripInsideTheSharedConfig() + { + var config = new ConfigModel + { + YtdlpDubLanguage = "de", + CacheDownloadRateLimitMBs = 50, + CacheDownloadIdleSeconds = 30, + CacheYouTubePreferVp9 = true, + UriRules = [new UriRule { Name = "Mine", Pattern = "^https://x/", Action = RuleAction.Block }], + SeededDefaultRules = ["Mine"] + }; + + var restored = Json.Deserialize(Json.Serialize(config))!; + + Assert.Equal("de", restored.YtdlpDubLanguage); + Assert.Equal(50, restored.CacheDownloadRateLimitMBs); + Assert.Equal(30, restored.CacheDownloadIdleSeconds); + Assert.True(restored.CacheYouTubePreferVp9); + Assert.Equal(["Mine"], restored.SeededDefaultRules); + + var rule = Assert.Single(restored.UriRules); + Assert.Equal("Mine", rule.Name); + Assert.Equal(RuleAction.Block, rule.Action); + } + + [Fact] + public void PlusSettingsSerialiseAtTopLevel() + { + var json = Json.Serialize(new ConfigModel()); + + Assert.Contains("\"UriRules\": [", json); + Assert.DoesNotContain("\"Plus\":", json); + } + + [Fact] + public void AConfigWrittenByUpstreamLoadsWithDefaultPlusSettings() + { + const string strippedByUpstream = """ + { + "YtdlpWebServerUrl": "http://localhost:9696", + "YtdlpUseCookies": true, + "CacheMaxSizeInGb": 10.0, + "Language": "en" + } + """; + + var config = Json.Deserialize(strippedByUpstream); + + Assert.NotNull(config); + Assert.Equal(30, config!.CacheDownloadIdleSeconds); + + PlusConfigManager.Initialize(config); + Assert.NotEmpty(config.UriRules); + } + + [Fact] + public void TheSharedConfigNoticeFlagDefaultsToUnshown() + { + Assert.False(new ConfigModel().HasShownSharedConfigNotice); + var restored = Json.Deserialize( + Json.Serialize(new ConfigModel { HasShownSharedConfigNotice = true }))!; + Assert.True(restored.HasShownSharedConfigNotice); + } + + [Fact] + public void NoticeTextNamesTheFileTheOldSettingsAreActuallyIn() + { + using var stream = typeof(ConfigModel).Assembly + .GetManifestResourceStream("VRCVideoCacher.Languages.en.loc.json"); + Assert.NotNull(stream); + + using var document = System.Text.Json.JsonDocument.Parse(stream!); + var notice = document.RootElement.GetProperty("SharedConfigNotice").GetString(); + + Assert.NotNull(notice); + // Migrations were removed deliberately, so nothing writes a .bak; the previous + // PlusConfig.json is simply left in place. The message must name that file, not + // a backup that never gets created. + Assert.Contains("PlusConfig.json", notice!); + Assert.DoesNotContain(".bak", notice!); + Assert.Contains("Config.json", notice!); + } + + [Fact] + public void EveryLanguageDefinesTheSameKeysAsEnglish() + { + // English is the fallback, so a key missing from a translation degrades gracefully — + // but it degrades silently, which is how ko.loc.json ended up one key short without + // anyone noticing. Comparing key sets makes that visible at build time. + var assembly = typeof(ConfigModel).Assembly; + + HashSet KeysOf(string resource) + { + using var stream = assembly.GetManifestResourceStream(resource); + using var document = System.Text.Json.JsonDocument.Parse(stream!); + return document.RootElement.EnumerateObject().Select(p => p.Name).ToHashSet(StringComparer.Ordinal); + } + + var english = KeysOf("VRCVideoCacher.Languages.en.loc.json"); + + foreach (var resource in assembly.GetManifestResourceNames() + .Where(n => n.StartsWith("VRCVideoCacher.Languages.") && n.EndsWith(".loc.json"))) + { + var keys = KeysOf(resource); + Assert.True(english.SetEquals(keys), + $"{resource} differs from English: missing [{string.Join(", ", english.Except(keys))}], " + + $"unexpected [{string.Join(", ", keys.Except(english))}]"); + } + } + + [Fact] + public void EveryLanguageHasTheNoticeStrings() + { + foreach (var resource in typeof(ConfigModel).Assembly.GetManifestResourceNames() + .Where(n => n.StartsWith("VRCVideoCacher.Languages.") && n.EndsWith(".loc.json"))) + { + using var stream = typeof(ConfigModel).Assembly.GetManifestResourceStream(resource); + using var document = System.Text.Json.JsonDocument.Parse(stream!); + + Assert.True(document.RootElement.TryGetProperty("SharedConfigNotice", out _), $"{resource} is missing SharedConfigNotice"); + Assert.True(document.RootElement.TryGetProperty("SharedConfigNoticeTitle", out _), $"{resource} is missing SharedConfigNoticeTitle"); + } + } +} diff --git a/VRCVideoCacher.Tests/TerminalFailureTests.cs b/VRCVideoCacher.Tests/TerminalFailureTests.cs new file mode 100644 index 00000000..d6a76852 --- /dev/null +++ b/VRCVideoCacher.Tests/TerminalFailureTests.cs @@ -0,0 +1,47 @@ +using VRCVideoCacher.YTDL; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// Gates every retry in the resolve path. Getting it wrong is costly in both directions: +// too broad and a recoverable video stops being retried, too narrow and a deleted one +// costs four yt-dlp launches while VRChat waits. +public class TerminalFailureTests +{ + [Theory] + [InlineData("ERROR: [youtube] dQw4w9WgXcQ: Video unavailable")] + [InlineData("ERROR: [youtube] abc: Private video. Sign in if you've been granted access to this video")] + [InlineData("ERROR: [youtube] abc: This video has been removed by the uploader")] + [InlineData("ERROR: [youtube] abc: Join this channel to get access to members-only content")] + [InlineData("ERROR: [youtube] abc: This channel does not exist.")] + [InlineData("ERROR: [youtube] abc: This account has been terminated")] + [InlineData("ERROR: [youtube:truncated_id] abc: Incomplete YouTube ID")] + [InlineData("ERROR: Unsupported URL: https://example.com/thing")] + public void RecognisesFailuresNoRetryCanFix(string error) + { + Assert.True(IsTerminal(error), error); + } + + [Theory] + // Format problems are exactly what the non-AVPro and android retries exist for. + [InlineData("ERROR: Requested format is not available. Use --list-formats for a list of available formats")] + // A bot check can succeed on a different client, so it stays retryable. + [InlineData("ERROR: Sign in to confirm you're not a bot")] + [InlineData("ERROR: unable to download video data: HTTP Error 403: Forbidden")] + [InlineData("ERROR: [youtube] abc: Unable to extract player response")] + [InlineData("")] + [InlineData(" ")] + public void LeavesRecoverableFailuresRetryable(string error) + { + Assert.False(IsTerminal(error), error); + } + + [Fact] + public void MatchesRegardlessOfCasing() + { + Assert.True(IsTerminal("error: video UNAVAILABLE")); + Assert.True(IsTerminal("PRIVATE VIDEO")); + } + + private static bool IsTerminal(string error) => VideoId.IsTerminalFailure(error); +} diff --git a/VRCVideoCacher.Tests/VideoFileValidatorTests.cs b/VRCVideoCacher.Tests/VideoFileValidatorTests.cs new file mode 100644 index 00000000..2264bc7d --- /dev/null +++ b/VRCVideoCacher.Tests/VideoFileValidatorTests.cs @@ -0,0 +1,127 @@ +using System.Text; +using VRCVideoCacher.YTDL; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// The validator is what stops an HTML error page served with a 200 from being committed to +// the cache under a .mp4 name and then handed to VRChat on every subsequent play. +public class VideoFileValidatorTests : IDisposable +{ + private readonly List _paths = []; + + private string WriteFile(byte[] content) + { + var path = Path.Combine(Path.GetTempPath(), $"vvc-validator-{Guid.NewGuid():N}.bin"); + File.WriteAllBytes(path, content); + _paths.Add(path); + return path; + } + + private string WriteFile(string content) => WriteFile(Encoding.UTF8.GetBytes(content)); + + /// A body that clears the minimum-size bar, padded with plausible binary. + private string WriteLargeFile(string prefix) + { + var bytes = new byte[VideoFileValidator.MinValidBytes + 1024]; + Encoding.UTF8.GetBytes(prefix).CopyTo(bytes, 0); + return WriteFile(bytes); + } + + public void Dispose() + { + foreach (var path in _paths) + { + try { File.Delete(path); } catch { /* best effort */ } + } + } + + [Fact] + public void RejectsAMissingFile() => + Assert.False(VideoFileValidator.IsLikelyValidVideo(Path.Combine(Path.GetTempPath(), "vvc-does-not-exist"))); + + [Fact] + public void RejectsATinyErrorBody() => + Assert.False(VideoFileValidator.IsLikelyValidVideo(WriteFile("not a video, 166 bytes of nothing"))); + + [Theory] + [InlineData("Error")] + [InlineData("404")] + [InlineData("AccessDenied")] + [InlineData("nope")] + public void RejectsMarkupEvenAboveTheSizeFloor(string markup) => + Assert.False(VideoFileValidator.IsLikelyValidVideo(WriteLargeFile(markup))); + + [Fact] + public void RejectsMarkupPrecededByWhitespaceOrABom() + { + // "\n" must not slip past a naive prefix check. + Assert.False(VideoFileValidator.IsLikelyValidVideo(WriteLargeFile("\n\r\t x"))); + Assert.False(VideoFileValidator.IsLikelyValidVideo(WriteLargeFile(""))); + } + + [Fact] + public void RejectsAJsonErrorEnvelope() => + Assert.False(VideoFileValidator.IsLikelyValidVideo(WriteLargeFile("{\"error\":\"forbidden\",\"code\":403}"))); + + [Fact] + public void AcceptsBinaryAboveTheSizeFloor() + { + // The check is inverted on purpose: real containers start with arbitrary bytes, so + // anything large that is not recognisably markup or a JSON error passes. + var bytes = new byte[VideoFileValidator.MinValidBytes + 1024]; + bytes[0] = 0x00; bytes[1] = 0x00; bytes[2] = 0x00; bytes[3] = 0x20; + bytes[4] = (byte)'f'; bytes[5] = (byte)'t'; bytes[6] = (byte)'y'; bytes[7] = (byte)'p'; + Assert.True(VideoFileValidator.IsLikelyValidVideo(WriteFile(bytes))); + } + + [Fact] + public void TrustsADeclaredVideoContentType() + { + // A binary body that happens to open with something the markup sniff would reject + // still passes when the server explicitly declared it as video. + var path = WriteLargeFile("looks like markup"); + Assert.False(VideoFileValidator.IsLikelyValidVideo(path)); + Assert.True(VideoFileValidator.IsLikelyValidVideo(path, "video/mp4")); + Assert.True(VideoFileValidator.IsLikelyValidVideo(path, "application/mp4")); + } + + [Fact] + public void OnlyRejectsRecognisedMarkupPrefixes() + { + // The check is a deliberately small deny-list, not "anything starting with '<'": + // real containers can begin with arbitrary bytes and must not be thrown away. + Assert.True(VideoFileValidator.IsLikelyValidVideo(WriteLargeFile(" + Assert.True(VideoFileValidator.LooksLikeHlsManifest(WriteFile("whatever"), "application/vnd.apple.mpegurl")); + + [Theory] + [InlineData(null, true)] // absent: let the magic-byte check decide + [InlineData("", true)] + [InlineData("video/mp4", true)] + [InlineData("application/octet-stream", true)] + [InlineData("binary/octet-stream", true)] + [InlineData("text/html", false)] + [InlineData("application/json", false)] + public void IsAcceptableContentType_GatesOnTheDeclaredType(string? contentType, bool expected) => + Assert.Equal(expected, VideoFileValidator.IsAcceptableContentType(contentType)); + + [Fact] + public void TryDelete_NeverThrows() + { + var exception = Record.Exception(() => VideoFileValidator.TryDelete(Path.Combine(Path.GetTempPath(), "vvc-absent"))); + Assert.Null(exception); + } +} diff --git a/VRCVideoCacher.Tests/VideoIdTests.cs b/VRCVideoCacher.Tests/VideoIdTests.cs new file mode 100644 index 00000000..80efd66a --- /dev/null +++ b/VRCVideoCacher.Tests/VideoIdTests.cs @@ -0,0 +1,85 @@ +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; +using VRCVideoCacher.Integrations.YouTube; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// Video id extraction decides the cache file name, so a change here silently invalidates +// every previously cached file for the affected URL shape. +public class VideoIdTests +{ + private static Task ResolveAsync(string url, bool avPro = false) => + new YouTubeIntegration().GetVideoInfo(url, new Uri(url), avPro); + + [Theory] + [InlineData("https://www.youtube.com/watch?v=dQw4w9WgXcQ")] + [InlineData("https://youtube.com/watch?v=dQw4w9WgXcQ&list=PL123")] + [InlineData("https://youtu.be/dQw4w9WgXcQ")] + [InlineData("https://www.youtube.com/embed/dQw4w9WgXcQ")] + [InlineData("https://www.youtube.com/v/dQw4w9WgXcQ")] + [InlineData("https://www.youtube.com/live/dQw4w9WgXcQ")] + [InlineData("https://m.youtube.com/watch?v=dQw4w9WgXcQ")] + [InlineData("https://music.youtube.com/watch?v=dQw4w9WgXcQ")] + [InlineData("https://www.youtube.com/shorts/dQw4w9WgXcQ")] + public async Task ExtractsTheVideoIdFromEveryCommonUrlShape(string url) + { + var info = await ResolveAsync(url); + Assert.NotNull(info); + Assert.Equal("dQw4w9WgXcQ", info!.VideoId); + Assert.Equal(UrlType.YouTube, info.UrlType); + } + + [Fact] + public async Task CanonicalisesToAWatchUrl() + { + // History and the "open source" button must never end up pointing at a playlist. + var info = await ResolveAsync("https://youtube.com/watch?v=dQw4w9WgXcQ&list=PL123"); + Assert.Equal("https://www.youtube.com/watch?v=dQw4w9WgXcQ", info!.VideoUrl); + } + + [Fact] + public async Task PicksTheFormatFromAvPro() + { + const string url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; + + Assert.Equal(DownloadFormat.Webm, (await ResolveAsync(url, avPro: true))!.DownloadFormat); + Assert.Equal(DownloadFormat.MP4, (await ResolveAsync(url, avPro: false))!.DownloadFormat); + } + + [Fact] + public async Task ReturnsNullWhenNoVideoIdIsPresent() => + Assert.Null(await ResolveAsync("https://www.youtube.com/results?search_query=test")); + + [Theory] + [InlineData("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PL123", true)] + [InlineData("https://www.youtube.com/playlist?list=PL123", true)] + [InlineData("https://www.youtube.com/watch?v=dQw4w9WgXcQ", false)] + [InlineData("https://example.com/watch?list=PL123", false)] + [InlineData("not a url", false)] + public void IsYouTubePlaylist_DetectsAListParameterOnAYouTubeHost(string url, bool expected) => + Assert.Equal(expected, VideoId.IsYouTubePlaylist(url)); + + [Fact] + public void HashUrl_IsStableAndFileNameSafe() + { + const string url = "https://cdn.example.com/path/to/video.mp4?token=abc"; + var hash = VideoId.HashUrl(url); + + Assert.Equal(hash, VideoId.HashUrl(url)); + Assert.NotEqual(hash, VideoId.HashUrl(url + "x")); + // Becomes a file name, so base64's /, + and = are stripped. + Assert.DoesNotContain('/', hash); + Assert.DoesNotContain('+', hash); + Assert.DoesNotContain('=', hash); + Assert.True(hash.Length > 0); + } + + [Theory] + [InlineData("https://example.com/a", true)] + [InlineData("http://example.com/a", true)] + [InlineData("relative/path", false)] + [InlineData("", false)] + public void ToUri_AcceptsOnlyAbsoluteUris(string url, bool expected) => + Assert.Equal(expected, VideoId.ToUri(url) != null); +} diff --git a/VRCVideoCacher.Tests/YtdlArgumentTests.cs b/VRCVideoCacher.Tests/YtdlArgumentTests.cs new file mode 100644 index 00000000..ba010498 --- /dev/null +++ b/VRCVideoCacher.Tests/YtdlArgumentTests.cs @@ -0,0 +1,66 @@ +using VRCVideoCacher.YTDL; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// The "additional yt-dlp arguments" setting is one free-form config string, but arguments +// now reach the process through ArgumentList, which needs one token per element. Appending +// the string whole would pass "--retries 3" as a single argument literally named that. +public class YtdlArgumentTests +{ + [Fact] + public void SplitArguments_ReturnsEmpty_ForNullOrBlank() + { + Assert.Empty(YtdlManager.SplitArguments(null)); + Assert.Empty(YtdlManager.SplitArguments("")); + Assert.Empty(YtdlManager.SplitArguments(" \t ")); + } + + [Fact] + public void SplitArguments_SplitsOnWhitespace() + { + Assert.Equal(["--retries", "3", "--no-mtime"], + YtdlManager.SplitArguments("--retries 3 --no-mtime")); + } + + [Fact] + public void SplitArguments_CollapsesRunsOfWhitespace() + { + Assert.Equal(["-a", "-b"], YtdlManager.SplitArguments(" -a \t\t -b ")); + } + + [Fact] + public void SplitArguments_KeepsQuotedValueAsOneToken() + { + Assert.Equal(["--ffmpeg-location", @"C:\Program Files\ffmpeg\bin"], + YtdlManager.SplitArguments(@"--ffmpeg-location ""C:\Program Files\ffmpeg\bin""")); + } + + [Fact] + public void SplitArguments_SupportsSingleQuotes() + { + Assert.Equal(["-f", "bv*[height<=1080]+ba"], + YtdlManager.SplitArguments("-f 'bv*[height<=1080]+ba'")); + } + + [Fact] + public void SplitArguments_JoinsQuotedSectionToAdjacentText() + { + // --key="some value" is one argv entry, not two. + Assert.Equal(["--extractor-args=youtube:player_client=web"], + YtdlManager.SplitArguments(@"--extractor-args=""youtube:player_client=web""")); + } + + [Fact] + public void SplitArguments_TreatsUnterminatedQuoteAsRunningToEnd() + { + Assert.Equal(["-o", "unterminated value"], + YtdlManager.SplitArguments(@"-o ""unterminated value")); + } + + [Fact] + public void SplitArguments_PreservesEmptyQuotedArgument() + { + Assert.Equal(["-f", ""], YtdlManager.SplitArguments(@"-f """"")); + } +} diff --git a/VRCVideoCacher.Tests/YtdlpProgressParserTests.cs b/VRCVideoCacher.Tests/YtdlpProgressParserTests.cs new file mode 100644 index 00000000..0a82093f --- /dev/null +++ b/VRCVideoCacher.Tests/YtdlpProgressParserTests.cs @@ -0,0 +1,135 @@ +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; +using Xunit; + +namespace VRCVideoCacher.Tests; + +// yt-dlp's --newline progress output is the source of the download ETA, so the shapes it +// actually emits — including the "Unknown" ones early in a transfer — need pinning down. +public class YtdlpProgressParserTests +{ + private static DownloadProgress Parse(string line) + { + Assert.True(YtdlpProgressParser.TryParse(line, out var progress), $"failed to parse: {line}"); + return progress; + } + + [Fact] + public void ParsesPercentRateAndEta() + { + var progress = Parse("[download] 45.2% of ~ 12.34MiB at 1.23MiB/s ETA 00:12"); + + Assert.Equal(45.2, progress.Percent, precision: 1); + Assert.Equal(1.23 * 1024 * 1024, progress.BytesPerSecond!.Value, precision: 0); + Assert.Equal(TimeSpan.FromSeconds(12), progress.Eta); + } + + [Fact] + public void ParsesALineWithAFragmentCounter() + { + var progress = Parse("[download] 45.2% of 12.34MiB at 1.23MiB/s ETA 00:12 (frag 10/22)"); + + Assert.Equal(45.2, progress.Percent, precision: 1); + Assert.Equal(TimeSpan.FromSeconds(12), progress.Eta); + } + + [Fact] + public void TreatsUnknownRateAndEtaAsAbsent() + { + // Emitted for the first moments of a transfer. Reporting a made-up estimate here + // would be worse than reporting none. + var progress = Parse("[download] 0.0% of 12.34MiB at Unknown B/s ETA Unknown"); + + Assert.Equal(0.0, progress.Percent); + Assert.Null(progress.BytesPerSecond); + Assert.Null(progress.Eta); + } + + [Fact] + public void ParsesAnHourLongEta() + { + Assert.Equal(new TimeSpan(1, 2, 3), Parse("[download] 5.0% of 4.00GiB at 1.00MiB/s ETA 01:02:03").Eta); + } + + [Fact] + public void ParsesTheCompletionLine() + { + var progress = Parse("[download] 100% of 12.34MiB in 00:05"); + + Assert.Equal(100.0, progress.Percent); + Assert.Null(progress.Eta); + } + + [Theory] + [InlineData("at 512.00B/s", 512d)] + [InlineData("at 1.50KiB/s", 1.5 * 1024)] + [InlineData("at 2.00MiB/s", 2d * 1024 * 1024)] + [InlineData("at 1.00GiB/s", 1024d * 1024 * 1024)] + public void ConvertsBinaryRateUnits(string fragment, double expected) + { + Assert.Equal(expected, Parse($"[download] 10.0% of 1.00GiB {fragment} ETA 00:30").BytesPerSecond!.Value, precision: 0); + } + + [Theory] + [InlineData("[download] Destination: /tmp/video.mp4")] + [InlineData("[info] Writing video metadata")] + [InlineData("")] + public void RejectsLinesWithNoPercentage(string line) + { + Assert.False(YtdlpProgressParser.TryParse(line, out _)); + } + + [Fact] + public void IgnoresANonsensicalEtaRatherThanThrowing() + { + // 99:99 is not a valid minute/second pair; the percentage still parses. + Assert.True(YtdlpProgressParser.TryParse("[download] 10.0% of 1.00GiB at 1.00MiB/s ETA 99:99", out var progress)); + Assert.Equal(10.0, progress.Percent); + Assert.Null(progress.Eta); + } + + [Fact] + public void ParsesInvariantlyUnderACommaDecimalCulture() + { + var previous = Thread.CurrentThread.CurrentCulture; + try + { + Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE"); + Assert.Equal(45.2, Parse("[download] 45.2% of 12.34MiB at 1.23MiB/s ETA 00:12").Percent, precision: 1); + } + finally + { + Thread.CurrentThread.CurrentCulture = previous; + } + } + + [Theory] + [InlineData(0, 45, "45s")] + [InlineData(3, 20, "3m 20s")] + [InlineData(0, 0, "1s")] // never renders "0s" while still downloading + public void FormatsEtaCompactly(int minutes, int seconds, string expected) + { + var progress = new DownloadProgress(50, null, new TimeSpan(0, minutes, seconds)); + Assert.Equal(expected, progress.FormatEta()); + } + + [Fact] + public void FormatsAnHourLongEtaWithHours() + { + Assert.Equal("1h 04m", new DownloadProgress(50, null, new TimeSpan(1, 4, 30)).FormatEta()); + } + + [Fact] + public void FormatsRateAsBytesPerSecond() + { + Assert.Equal("1.50 MB/s", new DownloadProgress(50, 1.5 * 1024 * 1024, null).FormatRate()); + } + + [Fact] + public void ReportsNoRateOrEtaWhenUnknown() + { + var progress = DownloadProgress.AtPercent(50); + Assert.Null(progress.FormatRate()); + Assert.Null(progress.FormatEta()); + } +} diff --git a/VRCVideoCacher/API/APIController.cs b/VRCVideoCacher/API/APIController.cs index 4f37a867..985af610 100644 --- a/VRCVideoCacher/API/APIController.cs +++ b/VRCVideoCacher/API/APIController.cs @@ -1,432 +1,495 @@ -using System.Text; -using EmbedIO; -using EmbedIO.Routing; -using EmbedIO.WebApi; -using VRCVideoCacher.Database; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; -using VRCVideoCacher.YTDL; -using VRCVideoCacher.YTDL.SiteHandlers.Sites; - -namespace VRCVideoCacher.API; - -public class ApiController : WebApiController -{ - // ponytail: fixed local default; this fork takes no remote config from an upstream server. - private const int YoutubePrefetchMaxRetries = 7; - - // Defaults true on process start, so the first app launch asks the extension to push - // fresh cookies. Cleared once valid cookies are received (see ReceiveYoutubeCookies). - private static volatile bool _cookieRefreshRequested = true; - - // Signal the long-poll endpoint waits on, so a UI refresh request wakes the extension - // immediately instead of waiting for its next poll. Swapped out atomically each fire. - private static volatile TaskCompletionSource _refreshSignal = - new(TaskCreationOptions.RunContinuationsAsynchronously); - - // Lets the UI (Cookies panel) ask the new extension to push fresh cookies right now. - public static void RequestCookieRefresh() - { - _cookieRefreshRequested = true; - var pending = Interlocked.Exchange(ref _refreshSignal, - new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); - pending.TrySetResult(); - } - - // We support two extensions: the original EllyVR/upstream one (unchanged) and our new - // one (still in development). App-driven refresh is a NEW-extension-only feature — the - // new extension identifies itself with this header. The old extension never sends it, so - // its behaviour is completely unaffected: it just POSTs cookies on YouTube visits as before. - private const string NewExtensionHeader = "X-VRCVideoCacher-Ext"; - private const string NewExtensionId = "VRCVideoCacherPlus"; - private bool IsNewExtension => - HttpContext.Request.Headers[NewExtensionHeader] == NewExtensionId; - - private static readonly Serilog.ILogger Log = Program.Logger.ForContext(); - private static readonly HttpClient HttpClient = new(new SocketsHttpHandler - { - PooledConnectionLifetime = TimeSpan.FromMinutes(2), - ConnectTimeout = TimeSpan.FromSeconds(10), - }) - { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, - Timeout = TimeSpan.FromSeconds(30), - }; - - // [OLD + NEW EXTENSION] CORS preflight for the youtube-cookies POST. Used by BOTH the - // old/upstream (EllyVR) extension and the new one — do not gate this behind IsNewExtension. - // Chromium's "Private Network Access" (PNA) policy requires a public origin (youtube.com) - // to receive Access-Control-Allow-Private-Network: true before it can POST to localhost. - // Without this OPTIONS handler the preflight is rejected and the extension never sends - // cookies, regardless of which Chromium-based browser the user has the extension in. - [Route(HttpVerbs.Options, "/youtube-cookies")] - public Task ReceiveYoutubeCookiesOptions() - { - ApplyCorsHeaders(); - HttpContext.Response.Headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"; - HttpContext.Response.Headers["Access-Control-Allow-Headers"] = $"Content-Type, {NewExtensionHeader}"; - HttpContext.Response.Headers["Access-Control-Max-Age"] = "86400"; - HttpContext.Response.StatusCode = 204; - return Task.CompletedTask; - } - - // [NEW EXTENSION ONLY] New extension polls this; "1" means the app wants fresh cookies - // pushed (e.g. just started). Only the new extension is answered "1" — anything without - // the header (including the old extension) gets "0", so the old extension is unaffected. - [Route(HttpVerbs.Get, "/youtube-cookies/refresh-needed")] - public async Task CookieRefreshNeeded() - { - ApplyCorsHeaders(); - var needed = _cookieRefreshRequested && IsNewExtension; - await HttpContext.SendStringAsync(needed ? "1" : "0", "text/plain", Encoding.UTF8); - } - - // [NEW EXTENSION ONLY] Long-poll: the new extension holds this open; it returns "1" the - // instant the app requests a refresh, or "0" after a timeout so the connection is - // periodically renewed. This is what makes the UI "Request fresh cookies" button act - // immediately. The old extension never calls this and gets "0" if it somehow does. - [Route(HttpVerbs.Get, "/youtube-cookies/refresh-wait")] - public async Task CookieRefreshWait() - { - ApplyCorsHeaders(); - if (!IsNewExtension) - { - await HttpContext.SendStringAsync("0", "text/plain", Encoding.UTF8); - return; - } - - if (!_cookieRefreshRequested) - { - var signal = _refreshSignal; - using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); - var fired = await Task.WhenAny(signal.Task, Task.Delay(Timeout.Infinite, timeout.Token)); - // signal.Task completing means a refresh was requested; otherwise the delay won. - if (fired != signal.Task) - { - await HttpContext.SendStringAsync("0", "text/plain", Encoding.UTF8); - return; - } - } - - await HttpContext.SendStringAsync("1", "text/plain", Encoding.UTF8); - } - - // [OLD + NEW EXTENSION] The core cookie-receive endpoint. The old/upstream extension POSTs - // here with no special header (its behaviour must stay identical); the new extension POSTs - // the same way plus the X-VRCVideoCacher-Ext header to opt into the refresh-flag lifecycle. - [Route(HttpVerbs.Post, "/youtube-cookies")] - public async Task ReceiveYoutubeCookies() - { - ApplyCorsHeaders(); - - using var reader = new StreamReader(HttpContext.OpenRequestStream(), Encoding.UTF8); - var cookies = await reader.ReadToEndAsync(); - cookies = FilterCookies(cookies); - if (!Program.IsCookiesValid(cookies)) - { - Log.Error("Invalid cookies received, maybe you haven't logged in yet, not saving."); - HttpContext.Response.StatusCode = 400; - await HttpContext.SendStringAsync("Invalid cookies.", "text/plain", Encoding.UTF8); - return; - } - - await File.WriteAllTextAsync(YtdlManager.CookiesPath, cookies); - // Only the new extension participates in the refresh-flag lifecycle; the old - // extension's POST is handled identically to before (it never touches this flag). - if (IsNewExtension) - _cookieRefreshRequested = false; - - HttpContext.Response.StatusCode = 200; - await HttpContext.SendStringAsync("Cookies received.", "text/plain", Encoding.UTF8); - - Log.Information("Received Youtube cookies from browser extension."); - Program.NotifyCookiesUpdated(); - if (!ConfigManager.Config.YtdlpUseCookies) - Log.Warning("Config is NOT set to use cookies from browser extension."); - } - - private void ApplyCorsHeaders() - { - var requestOrigin = HttpContext.Request.Headers["Origin"] ?? string.Empty; - // Always echo back the origin so any browser visiting YouTube can reach us. - // The endpoint only accepts cookies and has no sensitive side-effects on GET, - // so broad CORS is intentional here. - if (!string.IsNullOrEmpty(requestOrigin)) - HttpContext.Response.Headers["Access-Control-Allow-Origin"] = requestOrigin; - - // Required for Chromium's Private Network Access (PNA) policy: allows a - // public origin (youtube.com) to POST to a private address (localhost). - HttpContext.Response.Headers["Access-Control-Allow-Private-Network"] = "true"; - } - - private static string FilterCookies(string cookies) - { - var lines = cookies.Split('\n'); - var filtered = lines.Where(line => - { - var parts = line.Split('\t'); - // Netscape cookie format: domain flag path secure expiration name value - // Skip lines where the cookie name (index 5) starts with "ST-" - // Breaks YT cookie checks otherwise, seems to be a mostly firefox issue. - return parts.Length < 6 || !parts[5].StartsWith("ST-", StringComparison.Ordinal); - }); - return string.Join('\n', filtered); - } - - [Route(HttpVerbs.Get, "/getvideo")] - public async Task GetVideo() - { - // escape double quotes for our own safety - var requestUrl = Request.QueryString["url"]?.Replace("\"", "%22").Trim(); - var avPro = string.Compare(Request.QueryString["avpro"], "true", StringComparison.OrdinalIgnoreCase) == 0; - var source = Request.QueryString["source"]; - - if (string.IsNullOrEmpty(requestUrl)) - { - Log.Warning("No URL provided."); - await HttpContext.SendStringAsync("No URL provided.", "text/plain", Encoding.UTF8); - return; - } - - Log.Information("Request URL: {URL}", requestUrl); - - if (requestUrl.StartsWith("https://eu2.vrdancing.club/weekend/") && ConfigManager.Config.RedirectVRDancing) - { - await HttpContext.SendStringAsync(requestUrl.Replace("eu2", "na2"), "text/plain", Encoding.UTF8); - return; - } - - if (ConfigManager.Config.BlockedUrls.Any(blockedUrl => requestUrl.StartsWith(blockedUrl))) - { - Log.Warning("URL Is Blocked: {URL}", requestUrl); - requestUrl = ConfigManager.Config.BlockRedirect; - } - - if (requestUrl.StartsWith("https://mightygymcdn.nyc3.cdn.digitaloceanspaces.com")) - { - Log.Information("URL Is Mighty Gym: Bypassing."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - return; - } - - // pls no villager - if (requestUrl.StartsWith("https://anime.illumination.media")) - avPro = true; - else if (requestUrl.Contains(".imvrcdn.com") || - (requestUrl.Contains(".illumination.media") && !requestUrl.StartsWith("https://yt.illumination.media"))) - { - Log.Information("URL Is Illumination media: Bypassing."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - return; - } - - // bypass vfi - cinema - if (requestUrl.StartsWith("https://virtualfilm.institute")) - { - Log.Information("URL Is VFI - Cinema: Bypassing."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - return; - } - - var videoInfo = await VideoId.GetVideoId(requestUrl, avPro); - if (videoInfo == null) - { - Log.Information("Failed to get Video Info for URL: {URL}", requestUrl); - return; - } - DatabaseManager.AddPlayHistory(videoInfo); - - if (source == "resonite") - { - Log.Information("Request sent from resonite sending json."); - await HttpContext.SendStringAsync(await VideoId.GetURLResonite(videoInfo.VideoUrl), "text/plain", Encoding.UTF8); - return; - } - - var (isCached, filePath, fileName) = GetCachedFile(videoInfo.VideoId, avPro); - if (isCached) - { - File.SetLastWriteTimeUtc(filePath, DateTime.UtcNow); - DatabaseManager.UpdateVideoWatchStats(videoInfo.VideoId); - var url = $"{ConfigManager.Config.YtdlpWebServerUrl}/{fileName}"; - Log.Information("Responding with Cached URL: {URL}", url); - await HttpContext.SendStringAsync(url, "text/plain", Encoding.UTF8); - return; - } - - if (string.IsNullOrEmpty(videoInfo.VideoId)) - { - Log.Information("Failed to get Video ID: Bypassing."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - return; - } - - if (ConfigManager.Config.CacheOnly) - { - Log.Information("Cache Only Mode Enabled: Bypassing."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - return; - } - - // HLS manifests play natively in AVPro / VRChat's video player — yt-dlp's generic - // extractor would just return the same URL (or fail), so skip the extra process. - // We still queue the download below so it gets cached in the background. - if (videoInfo.UrlType == UrlType.Hls) - { - Log.Information("HLS URL: passing through without yt-dlp resolution."); - await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); - var hlsDuration = DatabaseManager.GetVideoInfoCache(videoInfo.VideoId)?.Duration; - ActiveStreamTracker.RecordActivity(videoInfo.VideoId, hlsDuration); - if (ConfigManager.Config.CacheHlsPlaylists && IsHlsCacheable(videoInfo, hlsDuration)) - VideoDownloader.QueueDownload(videoInfo); - return; - } - - var (response, success) = await VideoId.GetUrl(videoInfo, avPro); - if (!success) - { - Log.Warning("Get URL: {Error}", response); - // only send the error back if it's for YouTube, otherwise let it play the request URL normally - if (videoInfo.UrlType == UrlType.YouTube) - { - HttpContext.Response.StatusCode = 500; - await HttpContext.SendStringAsync(response, "text/plain", Encoding.UTF8); - return; - } - response = string.Empty; - } - - if (videoInfo.UrlType == UrlType.YouTube || - videoInfo.VideoUrl.StartsWith("https://manifest.googlevideo.com") || - videoInfo.VideoUrl.Contains("googlevideo.com")) - { - var isPrefetchSuccessful = await VideoTools.Prefetch(response, YoutubePrefetchMaxRetries); - - if (!isPrefetchSuccessful && avPro) - { - Log.Warning("Prefetch failed with AVPro, retrying without AVPro."); - avPro = false; - (response, success) = await VideoId.GetUrl(videoInfo, avPro); - await VideoTools.Prefetch(response, YoutubePrefetchMaxRetries); - } - } - - Log.Information("Responding with URL: {URL}", response); - await HttpContext.SendStringAsync(response, "text/plain", Encoding.UTF8); - - // Don't attempt to cache if its a livestream - if (videoInfo.VideoId.Equals("live")) - return; - - // Record activity immediately with whatever duration we already have cached, - // so download deferral and queueing are never blocked by a slow yt-dlp call. - var cachedDuration = DatabaseManager.GetVideoInfoCache(videoInfo.VideoId)?.Duration; - ActiveStreamTracker.RecordActivity(videoInfo.VideoId, cachedDuration); - - // If we don't have duration yet for a YouTube video, fetch it in the background - // with a timeout so the tracker gets updated when it's available. - if (videoInfo.UrlType == UrlType.YouTube && cachedDuration is not > 0) - { - _ = Task.Run(async () => - { - try - { - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); - var duration = await VideoId.FetchAndCacheYouTubeMetadataAsync(videoInfo.VideoId) - .WaitAsync(cts.Token); - if (duration is > 0) - ActiveStreamTracker.RecordActivity(videoInfo.VideoId, duration); - } - catch (OperationCanceledException) - { - Log.Warning("Metadata fetch for {VideoId} timed out, using fallback duration.", videoInfo.VideoId); - } - catch (Exception ex) - { - Log.Warning("Background metadata fetch for {VideoId} failed: {Error}", videoInfo.VideoId, ex.Message); - } - }); - } - - // check if file is cached again to handle race condition - (isCached, _, _) = GetCachedFile(videoInfo.VideoId, avPro); - if (!isCached && ( - (videoInfo.UrlType == UrlType.YouTube && ConfigManager.Config.CacheYouTube) || - (videoInfo.UrlType == UrlType.PyPyDance && ConfigManager.Config.CachePyPyDance) || - (videoInfo.UrlType == UrlType.VRDancing && ConfigManager.Config.CacheVrDancing))) - { - VideoDownloader.QueueDownload(videoInfo); - } - } - - // HLS playlists are only cacheable if the probe observed an #EXT-X-ENDLIST and parsed a - // finite duration under the configured max — otherwise yt-dlp may sit on a live stream. - // Raw MPEG-TS streams are progressive single-file downloads: a finite Content-Length is - // the equivalent "this is a complete video, not a live feed" signal. - private static bool IsHlsCacheable(VideoInfo videoInfo, double? cachedDuration) - { - var probe = HlsHandler.TryGetCachedProbe(videoInfo.VideoUrl); - if (probe is null) - { - Log.Information("HLS {VideoId}: skipping cache — probe result unavailable.", videoInfo.VideoId); - return false; - } - if (probe.Value.IsTransportStream) - { - if (probe.Value.ContentLength is not > 0) - { - Log.Information("MPEG-TS {VideoId}: skipping cache — no Content-Length (likely a live stream).", videoInfo.VideoId); - return false; - } - return true; - } - if (!probe.Value.IsComplete) - { - Log.Information("HLS {VideoId}: skipping cache — manifest is live or incomplete (no #EXT-X-ENDLIST).", videoInfo.VideoId); - return false; - } - var duration = probe.Value.Duration ?? cachedDuration; - if (duration is not > 0) - { - Log.Information("HLS {VideoId}: skipping cache — no parsed duration.", videoInfo.VideoId); - return false; - } - var maxMinutes = ConfigManager.Config.CacheHlsMaxLength; - if (maxMinutes > 0 && duration > maxMinutes * 60) - { - Log.Information("HLS {VideoId}: skipping cache — {Min:F1}min exceeds max {Max}min.", - videoInfo.VideoId, duration.Value / 60.0, maxMinutes); - return false; - } - return true; - } - - private static (bool isCached, string filePath, string fileName) GetCachedFile(string videoId, bool avPro) - { - var ext = avPro ? "webm" : "mp4"; - var fileName = $"{videoId}.{ext}"; - var filePath = Path.Join(CacheManager.CachePath, fileName); - var isCached = File.Exists(filePath) && EnsureValidOrEvict(filePath, fileName); - if (avPro && !isCached) - { - // retry with .mp4 - fileName = $"{videoId}.mp4"; - filePath = Path.Join(CacheManager.CachePath, fileName); - isCached = File.Exists(filePath) && EnsureValidOrEvict(filePath, fileName); - } - return (isCached, filePath, fileName); - } - - // If a cache file fails sanity checks (size/magic), drop it so the next play - // re-resolves and re-downloads instead of serving the same broken bytes forever. - private static bool EnsureValidOrEvict(string filePath, string fileName) - { - if (VideoFileValidator.IsLikelyValidVideo(filePath)) - return true; - - Log.Warning("Evicting invalid cache entry {File} on read.", fileName); - try { CacheManager.DeleteCacheItem(fileName); } - catch (Exception ex) { Log.Warning("Failed to evict {File}: {Err}", fileName, ex.Message); } - return false; - } +using System.Text; +using EmbedIO; +using EmbedIO.Routing; +using EmbedIO.WebApi; +using VRCVideoCacher.Database; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using VRCVideoCacher.YTDL; +using VRCVideoCacher.Integrations; +using VRCVideoCacher.Integrations.Hls; + +namespace VRCVideoCacher.API; + +public class ApiController : WebApiController +{ + // ponytail: fixed local default; this fork takes no remote config from an upstream server. + private const int YoutubePrefetchMaxRetries = 7; + + // Defaults true on process start, so the first app launch asks the extension to push + // fresh cookies. Cleared once valid cookies are received (see ReceiveYoutubeCookies). + private static volatile bool _cookieRefreshRequested = true; + + // Signal the long-poll endpoint waits on, so a UI refresh request wakes the extension + // immediately instead of waiting for its next poll. Swapped out atomically each fire. + private static volatile TaskCompletionSource _refreshSignal = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + // Lets the UI (Cookies panel) ask the new extension to push fresh cookies right now. + public static void RequestCookieRefresh() + { + _cookieRefreshRequested = true; + var pending = Interlocked.Exchange(ref _refreshSignal, + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + pending.TrySetResult(); + } + + // We support two extensions: the original EllyVR/upstream one (unchanged) and our new + // one (still in development). App-driven refresh is a NEW-extension-only feature — the + // new extension identifies itself with this header. The old extension never sends it, so + // its behaviour is completely unaffected: it just POSTs cookies on YouTube visits as before. + private const string NewExtensionHeader = "X-VRCVideoCacher-Ext"; + private const string NewExtensionId = "VRCVideoCacherPlus"; + private bool IsNewExtension => + HttpContext.Request.Headers[NewExtensionHeader] == NewExtensionId; + + private static readonly Serilog.ILogger Log = Program.Logger.ForContext(); + + // [OLD + NEW EXTENSION] CORS preflight for the youtube-cookies POST. Used by BOTH the + // old/upstream (EllyVR) extension and the new one — do not gate this behind IsNewExtension. + // Chromium's "Private Network Access" (PNA) policy requires a public origin (youtube.com) + // to receive Access-Control-Allow-Private-Network: true before it can POST to localhost. + // Without this OPTIONS handler the preflight is rejected and the extension never sends + // cookies, regardless of which Chromium-based browser the user has the extension in. + [Route(HttpVerbs.Options, "/youtube-cookies")] + [Route(HttpVerbs.Options, "/youtube-cookies/refresh-wait")] + [Route(HttpVerbs.Options, "/youtube-cookies/refresh-needed")] + public Task ReceiveYoutubeCookiesOptions() + { + ApplyCorsHeaders(); + HttpContext.Response.Headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"; + HttpContext.Response.Headers["Access-Control-Allow-Headers"] = $"Content-Type, {NewExtensionHeader}"; + HttpContext.Response.Headers["Access-Control-Max-Age"] = "86400"; + HttpContext.Response.StatusCode = 204; + return Task.CompletedTask; + } + + // [NEW EXTENSION ONLY] New extension polls this; "1" means the app wants fresh cookies + // pushed (e.g. just started). Only the new extension is answered "1" — anything without + // the header (including the old extension) gets "0", so the old extension is unaffected. + [Route(HttpVerbs.Get, "/youtube-cookies/refresh-needed")] + public async Task CookieRefreshNeeded() + { + ApplyCorsHeaders(); + var needed = _cookieRefreshRequested && IsNewExtension; + await HttpContext.SendStringAsync(needed ? "1" : "0", "text/plain", Encoding.UTF8); + } + + // [NEW EXTENSION ONLY] Long-poll: the new extension holds this open; it returns "1" the + // instant the app requests a refresh, or "0" after a timeout so the connection is + // periodically renewed. This is what makes the UI "Request fresh cookies" button act + // immediately. The old extension never calls this and gets "0" if it somehow does. + [Route(HttpVerbs.Get, "/youtube-cookies/refresh-wait")] + public async Task CookieRefreshWait() + { + ApplyCorsHeaders(); + if (!IsNewExtension) + { + await HttpContext.SendStringAsync("0", "text/plain", Encoding.UTF8); + return; + } + + if (!_cookieRefreshRequested) + { + var signal = _refreshSignal; + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + var fired = await Task.WhenAny(signal.Task, Task.Delay(Timeout.Infinite, timeout.Token)); + // signal.Task completing means a refresh was requested; otherwise the delay won. + if (fired != signal.Task) + { + await HttpContext.SendStringAsync("0", "text/plain", Encoding.UTF8); + return; + } + } + + await HttpContext.SendStringAsync("1", "text/plain", Encoding.UTF8); + } + + // [OLD + NEW EXTENSION] The core cookie-receive endpoint. The old/upstream extension POSTs + // here with no special header (its behaviour must stay identical); the new extension POSTs + // the same way plus the X-VRCVideoCacher-Ext header to opt into the refresh-flag lifecycle. + [Route(HttpVerbs.Post, "/youtube-cookies")] + public async Task ReceiveYoutubeCookies() + { + ApplyCorsHeaders(); + + using var reader = new StreamReader(HttpContext.OpenRequestStream(), Encoding.UTF8); + var cookies = await reader.ReadToEndAsync(); + cookies = FilterCookies(cookies); + if (!Program.IsCookiesValid(cookies)) + { + Log.Error("Invalid cookies received, maybe you haven't logged in yet, not saving."); + HttpContext.Response.StatusCode = 400; + await HttpContext.SendStringAsync("Invalid cookies.", "text/plain", Encoding.UTF8); + return; + } + + await File.WriteAllTextAsync(YtdlManager.CookiesPath, cookies); + // Only the new extension participates in the refresh-flag lifecycle; the old + // extension's POST is handled identically to before (it never touches this flag). + if (IsNewExtension) + _cookieRefreshRequested = false; + + HttpContext.Response.StatusCode = 200; + await HttpContext.SendStringAsync("Cookies received.", "text/plain", Encoding.UTF8); + + Log.Information("Received Youtube cookies from browser extension."); + Program.NotifyCookiesUpdated(); + if (!ConfigManager.Config.YtdlpUseCookies) + Log.Warning("Config is NOT set to use cookies from browser extension."); + } + + // Origins that legitimately talk to the cookie endpoints: a YouTube page (where the + // extension's content script runs) or an extension context. Note that an extension + // holding host_permissions for localhost bypasses CORS entirely, so the extension + // schemes here are belt-and-braces for the ones that don't. + private static readonly string[] AllowedCookieOrigins = + [ + "https://www.youtube.com", + "https://youtube.com", + "https://m.youtube.com", + "https://music.youtube.com", + "https://studio.youtube.com" + ]; + + private static bool IsAllowedCookieOrigin(string origin) => + AllowedCookieOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase) || + origin.StartsWith("chrome-extension://", StringComparison.OrdinalIgnoreCase) || + origin.StartsWith("moz-extension://", StringComparison.OrdinalIgnoreCase); + + private void ApplyCorsHeaders() + { + var requestOrigin = HttpContext.Request.Headers["Origin"] ?? string.Empty; + + // Previously echoed back whatever Origin arrived, so any page the user happened to + // be visiting could POST a cookie file at us and overwrite the real one. Only the + // origins that actually host the extension are answered now. + if (string.IsNullOrEmpty(requestOrigin) || !IsAllowedCookieOrigin(requestOrigin)) + return; + + HttpContext.Response.Headers["Access-Control-Allow-Origin"] = requestOrigin; + HttpContext.Response.Headers["Vary"] = "Origin"; + + // Required for Chromium's Private Network Access (PNA) policy: allows a + // public origin (youtube.com) to POST to a private address (localhost). + HttpContext.Response.Headers["Access-Control-Allow-Private-Network"] = "true"; + } + + private static string FilterCookies(string cookies) + { + var lines = cookies.Split('\n'); + var filtered = lines.Where(line => + { + var parts = line.Split('\t'); + // Netscape cookie format: domain flag path secure expiration name value + // Skip lines where the cookie name (index 5) starts with "ST-" + // Breaks YT cookie checks otherwise, seems to be a mostly firefox issue. + return parts.Length < 6 || !parts[5].StartsWith("ST-", StringComparison.Ordinal); + }); + return string.Join('\n', filtered); + } + + // An empty 200 means "nothing to resolve, play the URL as-is" — which is precisely what + // the Direct and bypass paths want, and precisely wrong for a block: the game happily + // plays a direct .mp4 without any help from us, so an empty body blocks nothing. Only a + // non-2xx makes yt-dlp-stub exit non-zero, which is the signal that actually stops + // playback. Callers that mean "bypass" must keep sending an empty 200. + private async Task SendBlockedAsync(string reason) + { + HttpContext.Response.StatusCode = 403; + await HttpContext.SendStringAsync(reason, "text/plain", Encoding.UTF8); + } + + /// + /// The only legitimate caller of /getvideo is yt-dlp-stub, a plain HTTP client with no + /// browser context. A cross-origin GET from a web page needs no preflight, so without + /// this check any site the user visits could drive the resolver: make the application + /// fetch arbitrary URLs, queue downloads and write into the cache. It could not read + /// the responses, but it would not need to. + /// + /// Sec-Fetch-Site: none means the user typed the URL themselves, which is deliberate + /// and cannot be triggered by a third party, so that case is allowed through. + /// + private bool IsBrowserOriginatedRequest() + { + if (!string.IsNullOrEmpty(HttpContext.Request.Headers["Origin"])) + return true; + + var fetchSite = HttpContext.Request.Headers["Sec-Fetch-Site"]; + return !string.IsNullOrEmpty(fetchSite) && + !string.Equals(fetchSite, "none", StringComparison.OrdinalIgnoreCase); + } + + [Route(HttpVerbs.Get, "/getvideo")] + public async Task GetVideo() + { + if (IsBrowserOriginatedRequest()) + { + Log.Warning("Rejecting browser-originated request to /getvideo."); + HttpContext.Response.StatusCode = 403; + await HttpContext.SendStringAsync("This endpoint is not callable from a browser.", "text/plain", Encoding.UTF8); + return; + } + + // No quote-mangling here any more: yt-dlp arguments go through ArgumentList, so a + // quote in a URL can no longer break out of the command line. The old + // Replace("\"", "%22") was the single guard for the whole application and it also + // corrupted any URL that legitimately contained one. + var requestUrl = Request.QueryString["url"]?.Trim(); + var avPro = string.Compare(Request.QueryString["avpro"], "true", StringComparison.OrdinalIgnoreCase) == 0; + var source = Request.QueryString["source"]; + + if (string.IsNullOrEmpty(requestUrl)) + { + Log.Warning("No URL provided."); + await HttpContext.SendStringAsync("No URL provided.", "text/plain", Encoding.UTF8); + return; + } + + Log.Information("Request URL: {URL}", requestUrl); + + + + // Evaluate URL against Rules Engine + var evalResult = RuleEngine.EvaluateUrl(requestUrl); + if (evalResult.MatchedRule != null) + { + Log.Information("Rule matched '{RuleName}' -> Action: {Action}, FinalURL: '{FinalUrl}'", + evalResult.MatchedRule.Name, evalResult.Action, evalResult.FinalUrl); + + switch (evalResult.Action) + { + case RuleAction.Block: + Log.Warning("URL blocked by rule '{RuleName}': {URL}", evalResult.MatchedRule.Name, requestUrl); + await SendBlockedAsync($"Blocked by VRCVideoCacher rule '{evalResult.MatchedRule.Name}'."); + return; + + case RuleAction.Direct: + ActiveStreamTracker.AssociateUrlInfo(evalResult.FinalUrl, requestUrl, requestUrl, null, null); + Log.Information("URL set to Direct (bypass caching) by rule '{RuleName}': {URL}", evalResult.MatchedRule.Name, evalResult.FinalUrl); + await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); + return; + + case RuleAction.Redirect: + ActiveStreamTracker.AssociateUrlInfo(evalResult.RedirectUrl, requestUrl, requestUrl, null, null); + Log.Information("URL redirected by rule '{RuleName}' to: {RedirectUrl}", evalResult.MatchedRule.Name, evalResult.RedirectUrl); + await HttpContext.SendStringAsync(evalResult.RedirectUrl, "text/plain", Encoding.UTF8); + return; + + case RuleAction.Resolve: + case RuleAction.Rewrite: + default: + requestUrl = evalResult.FinalUrl; + break; + } + } + + var videoInfo = await VideoId.GetVideoId(requestUrl, avPro); + if (videoInfo == null) + { + Log.Information("Failed to get Video Info for URL: {URL}", requestUrl); + return; + } + DatabaseManager.AddPlayHistory(videoInfo); + var dbCache = DatabaseManager.GetVideoInfoCache(videoInfo.VideoId); + + if (source == "resonite") + { + Log.Information("Request sent from resonite sending json."); + await HttpContext.SendStringAsync(await VideoId.GetURLResonite(videoInfo.VideoUrl), "text/plain", Encoding.UTF8); + return; + } + + var (isCached, filePath, fileName) = GetCachedFile(videoInfo.VideoId, avPro); + if (isCached) + { + // LRU bookkeeping only — the file may be open for serving or mid-eviction, and + // failing to stamp it is not a reason to fail the request. + try { File.SetLastWriteTimeUtc(filePath, DateTime.UtcNow); } + catch (Exception ex) { Log.Debug("Could not stamp {File}: {Err}", fileName, ex.Message); } + DatabaseManager.UpdateVideoWatchStats(videoInfo.VideoId); + var url = $"{ConfigManager.Config.YtdlpWebServerUrl}/{fileName}"; + ActiveStreamTracker.AssociateUrlInfo(url, videoInfo.VideoUrl, dbCache?.Title ?? videoInfo.VideoUrl, videoInfo.VideoId, dbCache?.Duration); + Log.Information("Responding with Cached URL: {URL}", url); + await HttpContext.SendStringAsync(url, "text/plain", Encoding.UTF8); + return; + } + + if (string.IsNullOrEmpty(videoInfo.VideoId)) + { + ActiveStreamTracker.AssociateUrlInfo(videoInfo.VideoUrl, videoInfo.VideoUrl, dbCache?.Title ?? videoInfo.VideoUrl, videoInfo.VideoId, dbCache?.Duration); + Log.Information("Failed to get Video ID: Bypassing."); + await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); + return; + } + + if (ConfigManager.Config.CacheOnly) + { + ActiveStreamTracker.AssociateUrlInfo(videoInfo.VideoUrl, videoInfo.VideoUrl, dbCache?.Title ?? videoInfo.VideoUrl, videoInfo.VideoId, dbCache?.Duration); + Log.Information("Cache Only Mode Enabled: Bypassing."); + await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); + return; + } + + // HLS manifests play natively in AVPro / VRChat's video player — yt-dlp's generic + // extractor would just return the same URL (or fail), so skip the extra process. + // We still queue the download below so it gets cached in the background. + if (videoInfo.UrlType == UrlType.Hls) + { + var hlsDuration = DatabaseManager.GetVideoInfoCache(videoInfo.VideoId)?.Duration; + ActiveStreamTracker.AssociateUrlInfo(videoInfo.VideoUrl, videoInfo.VideoUrl, dbCache?.Title ?? videoInfo.VideoUrl, videoInfo.VideoId, hlsDuration); + Log.Information("HLS URL: passing through without yt-dlp resolution."); + await HttpContext.SendStringAsync(string.Empty, "text/plain", Encoding.UTF8); + ActiveStreamTracker.RecordActivity(videoInfo.VideoId, hlsDuration); + if (ConfigManager.Config.CacheHlsPlaylists && IsHlsCacheable(videoInfo, hlsDuration)) + VideoDownloader.QueueDownload(videoInfo); + return; + } + + var (response, success) = await VideoId.GetUrl(videoInfo, avPro); + if (!success) + { + Log.Warning("Get URL: {Error}", response); + // only send the error back if it's for YouTube, otherwise let it play the request URL normally + if (videoInfo.UrlType == UrlType.YouTube) + { + HttpContext.Response.StatusCode = 500; + await HttpContext.SendStringAsync(response, "text/plain", Encoding.UTF8); + return; + } + response = string.Empty; + } + + // The StartsWith("https://manifest.googlevideo.com") that used to sit here was + // subsumed by the Contains check on the same line. + if (videoInfo.UrlType == UrlType.YouTube || + videoInfo.VideoUrl.Contains("googlevideo.com")) + { + var isPrefetchSuccessful = await VideoTools.Prefetch(response, YoutubePrefetchMaxRetries); + + if (!isPrefetchSuccessful && avPro) + { + Log.Warning("Prefetch failed with AVPro, retrying without AVPro."); + avPro = false; + (response, success) = await VideoId.GetUrl(videoInfo, avPro); + await VideoTools.Prefetch(response, YoutubePrefetchMaxRetries); + } + } + + var cachedDuration = DatabaseManager.GetVideoInfoCache(videoInfo.VideoId)?.Duration; + var finalUrl = string.IsNullOrEmpty(response) ? videoInfo.VideoUrl : response; + ActiveStreamTracker.AssociateUrlInfo(finalUrl, videoInfo.VideoUrl, dbCache?.Title ?? videoInfo.VideoUrl, videoInfo.VideoId, cachedDuration); + Log.Information("Responding with URL: {URL}", response); + await HttpContext.SendStringAsync(response, "text/plain", Encoding.UTF8); + + // Don't attempt to cache if its a livestream + if (videoInfo.VideoId.Equals("live")) + return; + + // Record activity immediately with whatever duration we already have cached, + // so download deferral and queueing are never blocked by a slow yt-dlp call. + ActiveStreamTracker.RecordActivity(videoInfo.VideoId, cachedDuration); + + // Trigger background metadata resolution (fast oEmbed title & duration) + if (videoInfo.UrlType == UrlType.YouTube) + { + _ = Task.Run(async () => + { + try + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + var duration = await VideoId.FetchAndCacheYouTubeMetadataAsync(videoInfo.VideoId) + .WaitAsync(cts.Token); + if (duration is > 0) + ActiveStreamTracker.RecordActivity(videoInfo.VideoId, duration); + } + catch (OperationCanceledException) + { + Log.Warning("Metadata fetch for {VideoId} timed out, using fallback duration.", videoInfo.VideoId); + } + catch (Exception ex) + { + Log.Warning("Background metadata fetch for {VideoId} failed: {Error}", videoInfo.VideoId, ex.Message); + } + }); + } + + // check if file is cached again to handle race condition + (isCached, _, _) = GetCachedFile(videoInfo.VideoId, avPro); + if (!isCached && evalResult.MatchedRule?.Cache == true) + { + VideoDownloader.QueueDownload(videoInfo); + } + } + + // HLS playlists are only cacheable if the probe observed an #EXT-X-ENDLIST and parsed a + // finite duration under the configured max — otherwise yt-dlp may sit on a live stream. + // Raw MPEG-TS streams are progressive single-file downloads: a finite Content-Length is + // the equivalent "this is a complete video, not a live feed" signal. + private static bool IsHlsCacheable(VideoInfo videoInfo, double? cachedDuration) + { + var probe = HlsIntegration.TryGetCachedProbe(videoInfo.VideoUrl); + if (probe is null) + { + Log.Information("HLS {VideoId}: skipping cache — probe result unavailable.", videoInfo.VideoId); + return false; + } + if (probe.Value.IsTransportStream) + { + if (probe.Value.ContentLength is not > 0) + { + Log.Information("MPEG-TS {VideoId}: skipping cache — no Content-Length (likely a live stream).", videoInfo.VideoId); + return false; + } + return true; + } + if (!probe.Value.IsComplete) + { + Log.Information("HLS {VideoId}: skipping cache — manifest is live or incomplete (no #EXT-X-ENDLIST).", videoInfo.VideoId); + return false; + } + var duration = probe.Value.Duration ?? cachedDuration; + if (duration is not > 0) + { + Log.Information("HLS {VideoId}: skipping cache — no parsed duration.", videoInfo.VideoId); + return false; + } + var maxMinutes = ConfigManager.Config.CacheHlsMaxLength; + if (maxMinutes > 0 && duration > maxMinutes * 60) + { + Log.Information("HLS {VideoId}: skipping cache — {Min:F1}min exceeds max {Max}min.", + videoInfo.VideoId, duration.Value / 60.0, maxMinutes); + return false; + } + return true; + } + + private static (bool isCached, string filePath, string fileName) GetCachedFile(string videoId, bool avPro) + { + var ext = avPro ? "webm" : "mp4"; + var fileName = $"{videoId}.{ext}"; + var filePath = Path.Join(CacheManager.CachePath, fileName); + var isCached = File.Exists(filePath) && EnsureValidOrEvict(filePath, fileName); + if (avPro && !isCached) + { + // retry with .mp4 + fileName = $"{videoId}.mp4"; + filePath = Path.Join(CacheManager.CachePath, fileName); + isCached = File.Exists(filePath) && EnsureValidOrEvict(filePath, fileName); + } + return (isCached, filePath, fileName); + } + + // If a cache file fails sanity checks (size/magic), drop it so the next play + // re-resolves and re-downloads instead of serving the same broken bytes forever. + private static bool EnsureValidOrEvict(string filePath, string fileName) + { + if (VideoFileValidator.IsLikelyValidVideo(filePath)) + return true; + + Log.Warning("Evicting invalid cache entry {File} on read.", fileName); + try { CacheManager.DeleteCacheItem(fileName); } + catch (Exception ex) { Log.Warning("Failed to evict {File}: {Err}", fileName, ex.Message); } + return false; + } } \ No newline at end of file diff --git a/VRCVideoCacher/API/LocalStreamRegistry.cs b/VRCVideoCacher/API/LocalStreamRegistry.cs new file mode 100644 index 00000000..d3ccf1a1 --- /dev/null +++ b/VRCVideoCacher/API/LocalStreamRegistry.cs @@ -0,0 +1,136 @@ +using System.Collections.Concurrent; +using EmbedIO; +using Serilog; + +namespace VRCVideoCacher.API; + +/// +/// Tracks the cached-video responses this server is currently streaming, so they can be cut +/// off when video playback is blocked. +/// +/// This is the reliable half of severing: the socket is ours, so closing it needs no +/// privileges and works identically on every platform. +/// +/// EmbedIO gives a module no "request finished" callback when it is not the final handler, +/// so completion cannot be observed directly. The previous version simply never removed +/// anything, which made this an unbounded leak — one retained IHttpContext per video +/// request, for the lifetime of the process, and far worse for HLS where every segment is +/// its own request. Instead, entries are pruned by liveness: once EmbedIO has finished a +/// response it disposes the output stream, so a stream that can no longer be written to is +/// a stream that is done. +/// +public static class LocalStreamRegistry +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(LocalStreamRegistry)); + + private sealed record Entry(IHttpContext Context, string Path, DateTime StartedAt); + + private static readonly ConcurrentDictionary Streams = new(); + + /// + /// Backstop for anything the liveness check somehow misses. No legitimate cached-video + /// response stays open for hours. + /// + private static readonly TimeSpan MaxStreamAge = TimeSpan.FromHours(6); + + public static int Count => Streams.Count; + + public static void Register(IHttpContext context, string path) + { + // Pruning here rather than on a timer keeps the dictionary bounded by the number of + // genuinely concurrent streams, at the cost of a cheap sweep per media request. + Prune(); + Streams[Guid.NewGuid()] = new Entry(context, path, DateTime.UtcNow); + } + + /// + /// Closes every stream currently being served and returns how many were actually live. + /// Entries that had already finished are discarded rather than counted, so the number + /// reported to the user reflects what was really interrupted. + /// + public static int CloseAll() + { + var closed = 0; + + foreach (var key in Streams.Keys.ToList()) + { + if (!Streams.TryRemove(key, out var entry)) + continue; + + if (!IsLive(entry)) + continue; + + if (Close(entry)) + closed++; + } + + return closed; + } + + private static bool Close(Entry entry) + { + try + { + entry.Context.Response.OutputStream.Close(); + return true; + } + catch (Exception ex) + { + // Racing normal completion is expected and not worth surfacing. + Log.Debug("Could not close stream for {Path}: {Error}", entry.Path, ex.Message); + return false; + } + } + + private static void Prune() + { + foreach (var pair in Streams) + { + if (IsLive(pair.Value) && DateTime.UtcNow - pair.Value.StartedAt < MaxStreamAge) + continue; + + Streams.TryRemove(pair.Key, out _); + } + } + + /// + /// A finished response has had its output stream disposed by EmbedIO, which makes it + /// unwritable — and touching a disposed stream throws, which is equally conclusive. + /// + private static bool IsLive(Entry entry) + { + try + { + return entry.Context.Response.OutputStream.CanWrite; + } + catch + { + return false; + } + } +} + +/// +/// Registers cached-video responses with as they start. +/// Passes every request straight through — it observes, it does not serve. +/// +public class ActiveStreamModule : WebModuleBase +{ + private static readonly string[] MediaExtensions = [".mp4", ".webm", ".m3u8", ".ts"]; + + public ActiveStreamModule() : base("/") + { + } + + public override bool IsFinalHandler => false; + + protected override Task OnRequestAsync(IHttpContext context) + { + var path = context.Request.Url.AbsolutePath; + + if (MediaExtensions.Any(ext => path.EndsWith(ext, StringComparison.OrdinalIgnoreCase))) + LocalStreamRegistry.Register(context, path); + + return Task.CompletedTask; + } +} diff --git a/VRCVideoCacher/API/WebServer.cs b/VRCVideoCacher/API/WebServer.cs index cb14ffe6..ca79caed 100644 --- a/VRCVideoCacher/API/WebServer.cs +++ b/VRCVideoCacher/API/WebServer.cs @@ -21,8 +21,6 @@ public static void Init() _server = CreateWebServer(ConfigManager.Config.YtdlpWebServerUrl); - // RunAsync returns a long-running task that completes when the server stops. - // Fire-and-forget, but observe faults so port-in-use errors get logged. _server.RunAsync().ContinueWith(t => { if (t.IsFaulted) @@ -50,13 +48,12 @@ private static EmbedIO.WebServer CreateWebServer(string url) var server = new EmbedIO.WebServer(o => o .WithUrlPrefixes(urls) .WithMode(HttpListenerMode.EmbedIO)) - // First, we will configure our web server by adding Modules. + .WithModule(new ActiveStreamModule()) .WithWebApi("/api", m => m .WithController()) .WithStaticFolder("/", CacheManager.CachePath, true, m => m .WithContentCaching(true)); - // Listen for state changes. server.StateChanged += (_, e) => $"WebServer State: {e.NewState}".Info(); server.OnUnhandledException += OnUnhandledException; server.OnHttpException += OnHttpException; @@ -87,4 +84,4 @@ private static Task OnUnhandledException(IHttpContext context, Exception excepti Log.Information(exception, "OnUnhandledException Error Occured"); return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/VRCVideoCacher/AdminWarningWindowPain.cs b/VRCVideoCacher/AdminWarningWindowPain.cs new file mode 100644 index 00000000..1f9d54a5 --- /dev/null +++ b/VRCVideoCacher/AdminWarningWindowPain.cs @@ -0,0 +1,39 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; + +namespace VRCVideoCacher; + +public class AdminWarningWindowPain : Window +{ + public AdminWarningWindowPain(string error) + { + var okButton = + new Button + { + Content = "OK", + HorizontalAlignment = HorizontalAlignment.Right, + Width = 80, + }; + okButton.Click += (_, _) => this.Close(); + + Title = "VRCVideoCacher"; + Width = 400; + SizeToContent = SizeToContent.Height; + WindowStartupLocation = WindowStartupLocation.CenterScreen; + Content = new StackPanel + { + Margin = new Thickness(20), + Children = + { + new TextBlock + { + Text = error, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, + Margin = new Thickness(0, 0, 0, 20) + }, + okButton + } + }; + } +} \ No newline at end of file diff --git a/VRCVideoCacher/App.axaml b/VRCVideoCacher/App.axaml index 0b3b276d..9484a9ed 100644 --- a/VRCVideoCacher/App.axaml +++ b/VRCVideoCacher/App.axaml @@ -6,6 +6,7 @@ RequestedThemeVariant="Dark"> + diff --git a/VRCVideoCacher/App.axaml.cs b/VRCVideoCacher/App.axaml.cs index c1c4bc73..dbe9669a 100644 --- a/VRCVideoCacher/App.axaml.cs +++ b/VRCVideoCacher/App.axaml.cs @@ -1,274 +1,298 @@ -using System.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices; -using Avalonia; -using Avalonia.Controls; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Markup.Xaml; -using Avalonia.Threading; -using Jeek.Avalonia.Localization; -using VRCVideoCacher.Languages; -using VRCVideoCacher.Utils; -using VRCVideoCacher.ViewModels; -using VRCVideoCacher.Views; - -namespace VRCVideoCacher; - -public partial class App : Application -{ - private TrayIcon? _trayIcon; - public static MainWindow? MainWindow; - - public override void Initialize() - { - AvaloniaXamlLoader.Load(this); - } - - private static async void OnMainWindowOpened(object? sender, EventArgs e) - { - if (MainWindow == null) - return; - - MainWindow.Opened -= OnMainWindowOpened; - - if (!ConfigManager.Config.StartMinimized) - return; - - // Let Avalonia finish the initial open/layout/render work first. - await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render); - - // Then minimize/hide on the next UI turn. - await Dispatcher.UIThread.InvokeAsync(() => - { - if (ConfigManager.Config.CloseToTray) - MainWindow.Hide(); - else - MainWindow.WindowState = WindowState.Minimized; - }, DispatcherPriority.Background); - } - - [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "DataValidators is safe to access at startup")] - public override void OnFrameworkInitializationCompleted() - { - InitializeLocalization(); - - if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - var mainVm = new MainWindowViewModel(); - MainWindow = new MainWindow - { - DataContext = mainVm - }; - - desktop.MainWindow = MainWindow; - desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; - - // Check for updates and show banner if available - _ = CheckForUpdatesAsync(mainVm); - - // Check if a previous session had a DNS connection failure - mainVm.CheckDnsFailure(); - - // Set up tray icon - SetupTrayIcon(desktop); - - // Handle window closing - minimize to tray instead, but allow OS/programmatic closes - MainWindow.Closing += (_, e) => - { - if (!ConfigManager.Config.CloseToTray || _isExiting || e.IsProgrammatic) - return; - - e.Cancel = true; - HideToTray(); - }; - - // Minimize at startup if needed - MainWindow.Opened += OnMainWindowOpened; - - // Allow the app to exit cleanly on OS shutdown/logoff - desktop.ShutdownRequested += (_, _) => - { - _isExiting = true; - _trayIcon?.Dispose(); - _trayIcon = null; - }; - } - - base.OnFrameworkInitializationCompleted(); - } - - private void InitializeLocalization() - { - var localizer = new EmbeddedJsonLocalizer(); - Localizer.SetLocalizer(localizer); - - var configLang = ConfigManager.Config.Language; - var lang = string.IsNullOrEmpty(configLang) ? "en" : configLang; - Localizer.Language = lang; - } - - private static async Task CheckForUpdatesAsync(MainWindowViewModel vm) - { - var update = await Updater.CheckForUpdates(); - if (update != null) - { - await Dispatcher.UIThread.InvokeAsync(() => vm.ShowUpdate(update)); - } - } - - private bool _isExiting; - private IClassicDesktopStyleApplicationLifetime? _desktop; - private NativeMenuItem? _showItem; - private NativeMenuItem? _openCacheItem; - private NativeMenuItem? _exitItem; - - // Win32 message constants for close interception - private const uint WmClose = 0x0010; - private const uint WmSysCommand = 0x0112; - private const int ScClose = 0xF060; - - private IntPtr Win32WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, ref bool handled) - { - // User clicked the title-bar X button (generates SC_CLOSE before WM_CLOSE). - // Marking as handled suppresses the subsequent WM_CLOSE, so the Closing - // event never fires for a normal user-initiated close on Windows. - if (ConfigManager.Config.CloseToTray && - msg == WmSysCommand && - (wParam.ToInt32() & 0xFFF0) == ScClose) - { - HideToTray(); - handled = true; - return IntPtr.Zero; - } - - // Raw WM_CLOSE arriving here means it came from an external source - // (taskkill, Task Manager) — a user close via SC_CLOSE would have been - // caught above and never reached this point. - if (msg == WmClose && !_isExiting) - { - _isExiting = true; - _trayIcon?.Dispose(); - _trayIcon = null; - _desktop?.Shutdown(); - handled = true; - } - - return IntPtr.Zero; - } - - private void SetupTrayIcon(IClassicDesktopStyleApplicationLifetime desktop) - { - _desktop = desktop; - - // On Windows, hook WndProc to distinguish a user clicking X (SC_CLOSE) - // from an external kill signal (raw WM_CLOSE from taskkill/Task Manager). - if (OperatingSystem.IsWindows()) - Win32Properties.AddWndProcHookCallback(MainWindow!, Win32WndProc); - - // On Linux, SIGTERM bypasses the Closing event entirely. Intercept it - // and route through desktop.Shutdown() so the tray icon is disposed and - // Avalonia state is cleaned up properly before the process exits. - if (OperatingSystem.IsLinux()) - { - PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => - { - ctx.Cancel = true; // suppress default immediate-kill behaviour - Dispatcher.UIThread.Post(() => - { - _isExiting = true; - _trayIcon?.Dispose(); - _trayIcon = null; - _desktop?.Shutdown(); - }); - }); - - //Pressing X on window does not remove the tray nor stop the console process - MainWindow!.Closing += (_, _) => - { - if (ConfigManager.Config.CloseToTray || _isExiting) - return; - - _isExiting = true; - _trayIcon?.Dispose(); - _trayIcon = null; - _desktop?.Shutdown(); - }; - } - - _showItem = new NativeMenuItem(Localizer.Get("TrayShow")); - _showItem.Click += (_, _) => ShowMainWindow(); - - _openCacheItem = new NativeMenuItem(Localizer.Get("TrayOpenCacheFolder")); - _openCacheItem.Click += (_, _) => OpenCacheFolder(); - - _exitItem = new NativeMenuItem(Localizer.Get("TrayExit")); - _exitItem.Click += (_, _) => - { - _isExiting = true; - desktop.Shutdown(); - }; - - Localizer.LanguageChanged += (_, _) => - { - if (_showItem != null) _showItem.Header = Localizer.Get("TrayShow"); - if (_openCacheItem != null) _openCacheItem.Header = Localizer.Get("TrayOpenCacheFolder"); - if (_exitItem != null) _exitItem.Header = Localizer.Get("TrayExit"); - }; - - var menu = new NativeMenu - { - _showItem, - new NativeMenuItemSeparator(), - _openCacheItem, - new NativeMenuItemSeparator(), - _exitItem - }; - - _trayIcon = new TrayIcon - { - ToolTipText = "VRCVideoCacherPlus", - Icon = new WindowIcon(Avalonia.Platform.AssetLoader.Open(new Uri("avares://VRCVideoCacher/Assets/icon.ico"))), - Menu = menu, - IsVisible = true - }; - - _trayIcon.Clicked += (_, _) => ShowMainWindow(); - } - - private async void HideToTray() - { - if (!ConfigManager.Config.HasShownTrayNotice && MainWindow != null) - { - ConfigManager.Config.HasShownTrayNotice = true; - ConfigManager.TrySaveConfig(); - - var notice = new PopupWindow( - Localizer.Get("TrayMinimizeNotice")); - await notice.ShowDialog(MainWindow); - } - - MainWindow?.Hide(); - } - - private void ShowMainWindow() - { - if (MainWindow != null) - { - MainWindow.Show(); - MainWindow.WindowState = WindowState.Normal; - MainWindow.Activate(); - } - } - - private void OpenCacheFolder() - { - var cachePath = CacheManager.CachePath; - if (OperatingSystem.IsWindows()) - { - System.Diagnostics.Process.Start("explorer.exe", cachePath); - } - else if (OperatingSystem.IsLinux()) - { - System.Diagnostics.Process.Start("xdg-open", cachePath); - } - } -} +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Avalonia.Threading; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Languages; +using VRCVideoCacher.Utils; +using VRCVideoCacher.ViewModels; +using VRCVideoCacher.Views; + +namespace VRCVideoCacher; + +public partial class App : Application +{ + private TrayIcon? _trayIcon; + public static MainWindow? MainWindow; + + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + private static async void OnMainWindowOpened(object? sender, EventArgs e) + { + if (MainWindow == null) + return; + + MainWindow.Opened -= OnMainWindowOpened; + + if (!ConfigManager.Config.StartMinimized) + return; + + // Let Avalonia finish the initial open/layout/render work first. + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render); + + // Then minimize/hide on the next UI turn. + await Dispatcher.UIThread.InvokeAsync(() => + { + if (ConfigManager.Config.CloseToTray) + MainWindow.Hide(); + else + MainWindow.WindowState = WindowState.Minimized; + }, DispatcherPriority.Background); + } + + [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "DataValidators is safe to access at startup")] + public override void OnFrameworkInitializationCompleted() + { + InitializeLocalization(); + + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + var mainVm = new MainWindowViewModel(); + MainWindow = new MainWindow + { + DataContext = mainVm + }; + + desktop.MainWindow = MainWindow; + desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; + + // Check for updates and show banner if available + _ = CheckForUpdatesAsync(mainVm); + + // Check if a previous session had a DNS connection failure + mainVm.CheckDnsFailure(); + + // Set up tray icon + SetupTrayIcon(desktop); + + // Handle window closing - minimize to tray instead, but allow OS/programmatic closes + MainWindow.Closing += (_, e) => + { + if (!ConfigManager.Config.CloseToTray || _isExiting || e.IsProgrammatic) + return; + + e.Cancel = true; + HideToTray(); + }; + + // Minimize at startup if needed + MainWindow.Opened += OnMainWindowOpened; + + // Allow the app to exit cleanly on OS shutdown/logoff + desktop.ShutdownRequested += (_, _) => + { + _isExiting = true; + _trayIcon?.Dispose(); + _trayIcon = null; + + // Stops the background polling that the Active Connections and Now Playing + // tabs start when first opened. + (MainWindow?.DataContext as MainWindowViewModel)?.Dispose(); + }; + } + + base.OnFrameworkInitializationCompleted(); + } + + private void InitializeLocalization() + { + var localizer = new EmbeddedJsonLocalizer(); + Localizer.SetLocalizer(localizer); + + var configLang = ConfigManager.Config.Language; + var lang = string.IsNullOrEmpty(configLang) ? "en" : configLang; + + // The config can name a language we no longer ship. The localizer falls back on its + // own now, but correcting it here keeps Localizer.Language consistent with what is + // actually rendered, so the Settings dropdown doesn't show a blank selection. + if (!Localizer.Languages.Contains(lang)) + { + ConfigManager.Config.Language = lang = "en"; + ConfigManager.TrySaveConfig(); + } + + Localizer.Language = lang; + } + + private static async Task CheckForUpdatesAsync(MainWindowViewModel vm) + { + var update = await Updater.CheckForUpdates(); + if (update != null) + { + await Dispatcher.UIThread.InvokeAsync(() => vm.ShowUpdate(update)); + } + } + + private bool _isExiting; + private IClassicDesktopStyleApplicationLifetime? _desktop; + private NativeMenuItem? _showItem; + private NativeMenuItem? _videoPlayersItem; + private NativeMenuItem? _openCacheItem; + private NativeMenuItem? _exitItem; + + // Win32 message constants for close interception + private const uint WmClose = 0x0010; + private const uint WmSysCommand = 0x0112; + private const int ScClose = 0xF060; + + private IntPtr Win32WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + // User clicked the title-bar X button (generates SC_CLOSE before WM_CLOSE). + // Marking as handled suppresses the subsequent WM_CLOSE, so the Closing + // event never fires for a normal user-initiated close on Windows. + if (ConfigManager.Config.CloseToTray && + msg == WmSysCommand && + (wParam.ToInt32() & 0xFFF0) == ScClose) + { + HideToTray(); + handled = true; + return IntPtr.Zero; + } + + // Raw WM_CLOSE arriving here means it came from an external source + // (taskkill, Task Manager) — a user close via SC_CLOSE would have been + // caught above and never reached this point. + if (msg == WmClose && !_isExiting) + { + _isExiting = true; + _trayIcon?.Dispose(); + _trayIcon = null; + _desktop?.Shutdown(); + handled = true; + } + + return IntPtr.Zero; + } + + private void SetupTrayIcon(IClassicDesktopStyleApplicationLifetime desktop) + { + _desktop = desktop; + + // On Windows, hook WndProc to distinguish a user clicking X (SC_CLOSE) + // from an external kill signal (raw WM_CLOSE from taskkill/Task Manager). + if (OperatingSystem.IsWindows()) + Win32Properties.AddWndProcHookCallback(MainWindow!, Win32WndProc); + + // On Linux, SIGTERM bypasses the Closing event entirely. Intercept it + // and route through desktop.Shutdown() so the tray icon is disposed and + // Avalonia state is cleaned up properly before the process exits. + if (OperatingSystem.IsLinux()) + { + PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => + { + ctx.Cancel = true; // suppress default immediate-kill behaviour + Dispatcher.UIThread.Post(() => + { + _isExiting = true; + _trayIcon?.Dispose(); + _trayIcon = null; + _desktop?.Shutdown(); + }); + }); + + //Pressing X on window does not remove the tray nor stop the console process + MainWindow!.Closing += (_, _) => + { + if (ConfigManager.Config.CloseToTray || _isExiting) + return; + + _isExiting = true; + _trayIcon?.Dispose(); + _trayIcon = null; + _desktop?.Shutdown(); + }; + } + + _showItem = new NativeMenuItem(Localizer.Get("Show")); + _showItem.Click += (_, _) => ShowMainWindow(); + + _videoPlayersItem = new NativeMenuItem(); + _videoPlayersItem.Click += (_, _) => ConfigManager.SetVideoPlayersEnabled(!ConfigManager.Config.VideoPlayersEnabled); + UpdateVideoPlayersTrayHeader(); + + _openCacheItem = new NativeMenuItem(Localizer.Get("TrayOpenCacheFolder")); + _openCacheItem.Click += (_, _) => OpenCacheFolder(); + + _exitItem = new NativeMenuItem(Localizer.Get("TrayExit")); + _exitItem.Click += (_, _) => + { + _isExiting = true; + desktop.Shutdown(); + }; + + Localizer.LanguageChanged += (_, _) => + { + if (_showItem != null) _showItem.Header = Localizer.Get("Show"); + if (_openCacheItem != null) _openCacheItem.Header = Localizer.Get("TrayOpenCacheFolder"); + if (_exitItem != null) _exitItem.Header = Localizer.Get("TrayExit"); + UpdateVideoPlayersTrayHeader(); + }; + + ConfigManager.OnConfigChanged += UpdateVideoPlayersTrayHeader; + + var menu = new NativeMenu + { + _showItem, + new NativeMenuItemSeparator(), + _videoPlayersItem, + new NativeMenuItemSeparator(), + _openCacheItem, + new NativeMenuItemSeparator(), + _exitItem + }; + + _trayIcon = new TrayIcon + { + ToolTipText = "VRCVideoCacherPlus", + Icon = new WindowIcon(Avalonia.Platform.AssetLoader.Open(new Uri("avares://VRCVideoCacher/Assets/icon.ico"))), + Menu = menu, + IsVisible = true + }; + + _trayIcon.Clicked += (_, _) => ShowMainWindow(); + } + + private void UpdateVideoPlayersTrayHeader() + { + Dispatcher.UIThread.Post(() => + { + if (_videoPlayersItem == null) return; + var enabled = ConfigManager.Config.VideoPlayersEnabled; + var actionText = enabled ? Localizer.Get("Disable") : Localizer.Get("Enable"); + _videoPlayersItem.Header = $"{actionText} {Localizer.Get("VideoPlayers")}"; + }); + } + + private async void HideToTray() + { + if (!ConfigManager.Config.HasShownTrayNotice && MainWindow != null) + { + ConfigManager.Config.HasShownTrayNotice = true; + ConfigManager.TrySaveConfig(); + + var notice = new PopupWindow( + Localizer.Get("TrayMinimizeNotice")); + await notice.ShowDialog(MainWindow); + } + + MainWindow?.Hide(); + } + + private void ShowMainWindow() + { + if (MainWindow != null) + { + MainWindow.Show(); + MainWindow.WindowState = WindowState.Normal; + MainWindow.Activate(); + } + } + + private void OpenCacheFolder() => OpenUrl.OpenFolder(CacheManager.CachePath); +} diff --git a/VRCVideoCacher/CacheManager.cs b/VRCVideoCacher/CacheManager.cs index 0ef27adc..13d0ad36 100644 --- a/VRCVideoCacher/CacheManager.cs +++ b/VRCVideoCacher/CacheManager.cs @@ -33,7 +33,23 @@ static CacheManager() CachePath = Path.Join(Program.CurrentProcessPath, ConfigManager.Config.CachedAssetPath); Log.Debug("Using cache path {CachePath}", CachePath); - BuildCache(); + + // Re-check the size budget whenever the config changes. ConfigManager used to call + // TryFlushCache directly at the end of its own initialiser, which re-entered this + // type before CachePath had been assigned. + ConfigManager.OnConfigChanged += TryFlushCache; + + // A failure in here surfaces as a TypeInitializationException from whatever + // happened to touch CacheManager first, which is close to undebuggable. An + // unreadable cache directory should degrade to an empty index, not that. + try + { + BuildCache(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to index the cache directory {CachePath}", CachePath); + } } private static string GetSystemCacheFolder() @@ -53,6 +69,15 @@ public static void Init() TryFlushCache(); } + // The only file names this directory ever owns are ".mp4" and ".webm". + // Anything else in there belongs to someone else — the web server writes index.html into + // it, and users put things in it — so it must not be treated as a cache entry, validated + // as a video, or deleted. + private static readonly string[] CacheFileExtensions = [".mp4", ".webm"]; + + private static bool IsCacheFile(string fileName) => + CacheFileExtensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase); + private static void BuildCache() { CachedAssets.Clear(); @@ -66,6 +91,13 @@ private static void BuildCache() if (file.StartsWith("_tempVideo.", StringComparison.Ordinal)) continue; + // Previously every file here was validated as a video and deleted if it failed, + // which meant index.html was destroyed and recreated on every single launch — + // with a "Removed invalid cache entry" warning each time — and anything a user + // had put in the folder was deleted without asking. + if (!IsCacheFile(file)) + continue; + // Self-heal: if a previous session committed a tiny error body or otherwise // corrupt file into the cache, drop it so we re-download instead of serving // 166-byte garbage to VRChat forever. @@ -83,7 +115,53 @@ private static void BuildCache() continue; } - AddToCache(file); + // Index without flushing per file: AddToCache calls TryFlushCache, which walks + // and sorts the whole dictionary, so using it here made startup quadratic in + // the number of cached videos. One flush at the end does the same job. + IndexCacheFile(file); + } + + TryFlushCache(); + } + + private static readonly ConcurrentDictionary PinnedFiles = new(); + + /// + /// Protects a cache file from eviction while it is being written or published. Dispose + /// the returned handle when done. + /// + /// Needed because a file can be evicted the instant it is added: LRU orders by mtime, + /// and a bulk pre-cache entry carries the timestamp from its manifest, which may be + /// years old — so it arrives as the least-recently-used thing in the cache and + /// AddToCache's own flush would delete what was just downloaded. + /// + public static IDisposable PinFile(string fileName) + { + PinnedFiles.AddOrUpdate(fileName, 1, static (_, count) => count + 1); + return new Pin(fileName); + } + + private sealed class Pin(string fileName) : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + return; + + while (PinnedFiles.TryGetValue(fileName, out var count)) + { + if (count <= 1) + { + if (PinnedFiles.TryRemove(new KeyValuePair(fileName, count))) + return; + } + else if (PinnedFiles.TryUpdate(fileName, count - 1, count)) + { + return; + } + } } } @@ -109,19 +187,43 @@ public static void TryFlushCache() if (cacheSize < maxCacheSize) break; + if (PinnedFiles.ContainsKey(kvp.Value.FileName)) + { + Log.Debug("Not evicting {FileName}: currently in use.", kvp.Value.FileName); + continue; + } + var videoId = Path.GetFileNameWithoutExtension(kvp.Value.FileName); var filePath = Path.Join(CachePath, kvp.Value.FileName); if (File.Exists(filePath)) { - File.Delete(filePath); - cacheSize -= kvp.Value.Size; + // A cache file can be open for serving or being written by the downloader. + // ClearCache already tolerated that; eviction did not, and the exception + // propagated out through AddToCache into the download-completion path. + try + { + File.Delete(filePath); + cacheSize -= kvp.Value.Size; + } + catch (Exception ex) + { + Log.Warning("Could not evict {FileName}: {Error}", kvp.Value.FileName, ex.Message); + continue; + } // delete thumbnail if not in recent history if (recentPlayHistory.All(h => h.Id != videoId)) { var thumbnailPath = ThumbnailManager.GetThumbnailPath(videoId); - if (File.Exists(thumbnailPath)) - File.Delete(thumbnailPath); + try + { + if (File.Exists(thumbnailPath)) + File.Delete(thumbnailPath); + } + catch (Exception ex) + { + Log.Debug("Could not delete thumbnail {Path}: {Error}", thumbnailPath, ex.Message); + } } } CachedAssets.TryRemove(kvp.Key, out _); @@ -129,10 +231,24 @@ public static void TryFlushCache() } public static void AddToCache(string fileName) + { + if (!IndexCacheFile(fileName)) + return; + + OnCacheChanged?.Invoke(fileName, CacheChangeType.Added); + TryFlushCache(); + } + + /// + /// Records a file's size and timestamp in the index. Returns false if it has gone. + /// Split out from so bulk indexing can skip the per-file + /// event and size-budget check. + /// + private static bool IndexCacheFile(string fileName) { var filePath = Path.Join(CachePath, fileName); if (!File.Exists(filePath)) - return; + return false; var fileInfo = new FileInfo(filePath); var videoCache = new VideoCache @@ -145,9 +261,7 @@ public static void AddToCache(string fileName) var existingCache = CachedAssets.GetOrAdd(videoCache.FileName, videoCache); existingCache.Size = fileInfo.Length; existingCache.LastModified = fileInfo.LastWriteTimeUtc; - - OnCacheChanged?.Invoke(fileName, CacheChangeType.Added); - TryFlushCache(); + return true; } private static long GetCacheSize() @@ -175,7 +289,18 @@ public static void DeleteCacheItem(string fileName) if (!File.Exists(filePath)) return; - File.Delete(filePath); + try + { + File.Delete(filePath); + } + catch (Exception ex) + { + // Reached from the request path via EnsureValidOrEvict, where the file may + // still be open. Leave the entry in place and try again on the next read. + Log.Warning("Could not delete cached video {FileName}: {Error}", fileName, ex.Message); + return; + } + CachedAssets.TryRemove(fileName, out _); OnCacheChanged?.Invoke(fileName, CacheChangeType.Removed); Log.Information("Deleted cached video: {FileName}", fileName); diff --git a/VRCVideoCacher/ConfigManager.cs b/VRCVideoCacher/ConfigManager.cs index 08a1b0eb..6563a48b 100755 --- a/VRCVideoCacher/ConfigManager.cs +++ b/VRCVideoCacher/ConfigManager.cs @@ -1,7 +1,8 @@ using System.Globalization; +using System.Linq; using Jeek.Avalonia.Localization; -using Newtonsoft.Json; using Serilog; +using VRCVideoCacher.Models; using VRCVideoCacher.Utils; // ReSharper disable FieldCanBeMadeReadOnly.Global @@ -27,7 +28,7 @@ static ConfigManager() try { if (File.Exists(ConfigFilePath)) - newConfig = JsonConvert.DeserializeObject(File.ReadAllText(ConfigFilePath)); + newConfig = Json.Deserialize(File.ReadAllText(ConfigFilePath)); if (newConfig != null) Config = newConfig; } @@ -54,22 +55,72 @@ static ConfigManager() if (Config.YtdlpWebServerUrl.EndsWith('/')) Config.YtdlpWebServerUrl = Config.YtdlpWebServerUrl.TrimEnd('/'); + // Repairs and seeds the rule list. Called with the instance rather than reaching + // for ConfigManager.Config: PlusConfigManager has no static state of its own, so + // there is no initialiser to re-enter here. + PlusConfigManager.Initialize(Config); + Log.Information("Loaded config."); TrySaveConfig(); } public static void TrySaveConfig() { - var newConfig = JsonConvert.SerializeObject(Config, Formatting.Indented); + var newConfig = Json.Serialize(Config); var oldConfig = File.Exists(ConfigFilePath) ? File.ReadAllText(ConfigFilePath) : string.Empty; if (newConfig == oldConfig) return; Log.Information("Config changed, saving..."); - File.WriteAllText(ConfigFilePath, newConfig); + AtomicFile.WriteAllText(ConfigFilePath, newConfig); Log.Information("Config saved."); + OnConfigChanged?.Invoke(); - CacheManager.TryFlushCache(); + } + + public static void SetVideoPlayersEnabled(bool enabled) + { + Config.VideoPlayersEnabled = enabled; + + var rule = Config.UriRules.FirstOrDefault(r => r.Name == "Block all Videos"); + if (!enabled) + { + if (rule == null) + { + rule = new UriRule + { + Name = "Block all Videos", + Pattern = ".*", + Action = RuleAction.Block, + Enabled = true + }; + Config.UriRules.Insert(0, rule); + } + else + { + rule.Enabled = true; + Config.UriRules.Remove(rule); + Config.UriRules.Insert(0, rule); + } + } + else + { + if (rule != null) + { + rule.Enabled = false; + } + } + + TrySaveConfig(); + + if (!enabled) + { + // Fire-and-forget: severing spawns subprocesses and must not block whoever + // toggled the setting. Outcome is reported through the log. + // No elevation here: this fires from a settings toggle, and a polkit/UAC + // dialog nobody asked for is worse than a connection that keeps playing. + _ = Utils.ConnectionSevering.SeverAllAsync(); + } } private static bool GetUserConfirmation(string prompt, bool defaultValue) @@ -93,17 +144,6 @@ private static void FirstRunConsole() } else { - Config.CacheYouTube = GetUserConfirmation("Would you like to cache/download Youtube videos?", true); - if (Config.CacheYouTube) - { - var maxResolution = GetUserConfirmation("Would you like to cache/download Youtube videos in 4k?", true); - Config.CacheYouTubeMaxResolution = maxResolution ? 2160 : 1080; - } - - var vrDancingPyPyChoice = GetUserConfirmation("Would you like to cache/download VRDancing & PyPyDance videos?", true); - Config.CacheVrDancing = vrDancingPyPyChoice; - Config.CachePyPyDance = vrDancingPyPyChoice; - Config.PatchResonite = GetUserConfirmation("Would you like to enable Resonite support?", false); } @@ -144,17 +184,9 @@ public class ConfigModel // Caching public string CachedAssetPath = ""; public float CacheMaxSizeInGb = 10f; - public bool CacheYouTube = true; - public int CacheYouTubeMaxResolution = 1080; - public int CacheYouTubeMaxLength = 120; - public bool CachePyPyDance = true; - public bool CacheVrDancing = true; public bool CacheHlsPlaylists = true; public int CacheHlsMaxLength = 30; public bool CacheOnly = false; - // Cache Rules - public string[] BlockedUrls = ["https://na2.vrdancing.club/sampleurl.mp4"]; - public string BlockRedirect = "https://www.youtube.com/watch?v=byv2bKekeWQ"; // URLs of JSON manifests listing direct file downloads to mirror into the cache. public string[] PreCacheUrls = []; // Video URLs (YouTube, VRDancing, ...) resolved through the normal download path @@ -167,11 +199,11 @@ public class ConfigModel public bool PatchVrChat = true; // Video Cacher + public bool VideoPlayersEnabled = true; public bool CloseToTray = true; public bool StartMinimized = false; public bool StartWithSteamVr = true; public bool CookieSetupCompleted = false; - public bool RedirectVRDancing = false; public bool ErrorPopups = true; // Localization @@ -179,4 +211,15 @@ public class ConfigModel // UI state public bool HasShownTrayNotice = false; + public bool HasShownSharedConfigNotice = false; + public string DismissedMotdHash = string.Empty; + + // PlusPlus settings (flattened) + public int CacheDownloadRateLimitMBs = 0; // 0 = unlimited + public int CacheDownloadIdleSeconds = 30; // 0 = disabled + public bool CacheYouTubePreferVp9 = true; // VP9+aac in mp4 instead of h264+aac + public List UriRules = DefaultRules.Create(); + public List SeededDefaultRules = []; + + public static List GetDefaultRules() => DefaultRules.Create(); } diff --git a/VRCVideoCacher/Controls/MarkdownText.cs b/VRCVideoCacher/Controls/MarkdownText.cs new file mode 100644 index 00000000..b28bc5d2 --- /dev/null +++ b/VRCVideoCacher/Controls/MarkdownText.cs @@ -0,0 +1,88 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using Avalonia.Layout; +using Avalonia.Media; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.Controls; + +/// +/// Attached property that renders a small markdown subset into a 's inlines, +/// so remote text (the MOTD) can carry clickable links: +/// +/// <TextBlock controls:MarkdownText.Text="{Binding Motd}" /> +/// +/// Parsing — and URL validation — lives in ; this only builds the +/// visual tree. Do not also set TextBlock.Text on the same control: Text and +/// Inlines are mutually exclusive. +/// +public static class MarkdownText +{ + public static readonly AttachedProperty TextProperty = + AvaloniaProperty.RegisterAttached("Text", typeof(MarkdownText)); + + public static void SetText(TextBlock target, string? value) => target.SetValue(TextProperty, value); + public static string? GetText(TextBlock target) => target.GetValue(TextProperty); + + static MarkdownText() + { + TextProperty.Changed.AddClassHandler((textBlock, args) => + Render(textBlock, args.NewValue.GetValueOrDefault())); + } + + private static void Render(TextBlock textBlock, string? markdown) + { + var inlines = textBlock.Inlines; + if (inlines is null) + return; + + inlines.Clear(); + + foreach (var span in MarkdownInlineParser.Parse(markdown)) + { + if (span.LineBreak) + { + inlines.Add(new LineBreak()); + continue; + } + + inlines.Add(span.Url is null ? BuildRun(span) : BuildLink(textBlock, span)); + } + } + + private static Run BuildRun(MarkdownSpan span) => new(span.Text) + { + FontWeight = span.Bold ? FontWeight.Bold : FontWeight.Normal, + FontStyle = span.Italic ? FontStyle.Italic : FontStyle.Normal, + }; + + /// + /// A link is a real so it gets the themed hover, focus and hand + /// cursor for free — hosted in an so it flows with the text. + /// + /// NavigateUri is deliberately NOT set: that would open the URL through Avalonia's launcher + /// and bypass , which is what enforces the http/https allowlist. + /// + private static InlineUIContainer BuildLink(TextBlock textBlock, MarkdownSpan span) + { + var url = span.Url!; + var button = new HyperlinkButton + { + Content = span.Text, + Padding = new Thickness(0), + MinWidth = 0, + MinHeight = 0, + Background = Brushes.Transparent, + BorderThickness = new Thickness(0), + VerticalAlignment = VerticalAlignment.Center, + FontWeight = span.Bold ? FontWeight.Bold : textBlock.FontWeight, + FontStyle = span.Italic ? FontStyle.Italic : FontStyle.Normal, + }; + + // Show where the link actually goes — the text is author-controlled and need not match the URL. + ToolTip.SetTip(button, url); + button.Click += (_, _) => OpenUrl.Open(url); + return new InlineUIContainer(button); + } +} diff --git a/VRCVideoCacher/Database/Database.cs b/VRCVideoCacher/Database/Database.cs index 3e8cd676..613861b9 100644 --- a/VRCVideoCacher/Database/Database.cs +++ b/VRCVideoCacher/Database/Database.cs @@ -23,7 +23,10 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { Directory.CreateDirectory(CacheDir); optionsBuilder.UseSqlite($"Data Source={DbPath}"); +#if DEBUG + // See DatabaseManager: logs parameter values, so debug builds only. optionsBuilder.EnableSensitiveDataLogging(); +#endif } } diff --git a/VRCVideoCacher/Database/DatabaseManager.cs b/VRCVideoCacher/Database/DatabaseManager.cs index 3451223d..db268373 100755 --- a/VRCVideoCacher/Database/DatabaseManager.cs +++ b/VRCVideoCacher/Database/DatabaseManager.cs @@ -18,10 +18,14 @@ static DatabaseManager() { Directory.CreateDirectory(Database.CacheDir); - var options = new DbContextOptionsBuilder() - .UseSqlite($"Data Source={Database.DbPath}") - .EnableSensitiveDataLogging() - .Options; + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite($"Data Source={Database.DbPath}"); +#if DEBUG + // Puts parameter values — watch history URLs and video ids — into the log output. + // Useful while developing, not something to ship enabled. + optionsBuilder = optionsBuilder.EnableSensitiveDataLogging(); +#endif + var options = optionsBuilder.Options; _contextFactory = new PooledDbContextFactory(options); @@ -39,6 +43,21 @@ DownloadFormat INTEGER NOT NULL ) """); + // A queue entry is identified by (VideoId, DownloadFormat), but nothing enforced + // that — AddPendingDownload checked for an existing row and then inserted, so two + // callers racing both saw "absent" and both inserted. Collapse any duplicates an + // existing database already accumulated, keeping the earliest, then constrain it. + db.Database.ExecuteSqlRaw(""" + DELETE FROM vvc_PendingDownloads + WHERE Key NOT IN ( + SELECT MIN(Key) FROM vvc_PendingDownloads GROUP BY VideoId, DownloadFormat + ) + """); + db.Database.ExecuteSqlRaw(""" + CREATE UNIQUE INDEX IF NOT EXISTS ux_vvc_PendingDownloads_Video + ON vvc_PendingDownloads (VideoId, DownloadFormat) + """); + db.Database.ExecuteSqlRaw(""" CREATE TABLE IF NOT EXISTS vvc_VideoWatchStats ( VideoId TEXT PRIMARY KEY NOT NULL, @@ -55,6 +74,11 @@ CREATE TABLE IF NOT EXISTS vvc_VRDancingTitles ( Instructor TEXT NOT NULL DEFAULT '' ) """); + + // TODO: Remove later - EnsureCreated above builds the schema only for a database that does not yet + // exist, and there are no migrations, so a property added to an existing entity + // would be missing for every current user until they deleted their database. + SchemaReconciler.Run(db); } public static string? GetLatestHistoryUrl(string videoId) @@ -159,6 +183,10 @@ public static void AddVideoInfoCache(VideoInfoCache videoInfoCache) db.VideoInfoCache.Add(videoInfoCache); } db.SaveChanges(); + if (!string.IsNullOrEmpty(videoInfoCache.Title)) + { + YTDL.ActiveStreamTracker.AssociateUrlInfo(videoInfoCache.Id, videoInfoCache.Id, videoInfoCache.Title, videoInfoCache.Id, videoInfoCache.Duration); + } OnVideoInfoCacheUpdated?.Invoke(); } @@ -228,22 +256,18 @@ public static void UpdateVideoWatchStats(string videoId) if (string.IsNullOrEmpty(videoId)) return; using var db = _contextFactory.CreateDbContext(); - var stats = db.VideoWatchStats.Find(videoId); - if (stats != null) - { - stats.WatchCount++; - stats.LastWatchedAt = DateTime.UtcNow; - } - else - { - db.VideoWatchStats.Add(new VideoWatchStats - { - VideoId = videoId, - WatchCount = 1, - LastWatchedAt = DateTime.UtcNow - }); - } - db.SaveChanges(); + + // Single atomic upsert rather than read-modify-write. Two plays landing at once + // previously either lost an increment (both read the same count) or collided on the + // primary key. The DateTime goes through a parameter so the provider writes it in + // the same text format EF reads back. + db.Database.ExecuteSqlRaw(""" + INSERT INTO vvc_VideoWatchStats (VideoId, LastWatchedAt, WatchCount) + VALUES ({0}, {1}, 1) + ON CONFLICT(VideoId) DO UPDATE SET + WatchCount = WatchCount + 1, + LastWatchedAt = excluded.LastWatchedAt + """, videoId, DateTime.UtcNow); } public static Dictionary GetAllVideoWatchStats() @@ -267,20 +291,24 @@ public static int GetPlayHistoryCount() public static void AddPendingDownload(VideoInfo videoInfo) { using var db = _contextFactory.CreateDbContext(); - var exists = db.PendingDownloads.Any(p => - p.VideoId == videoInfo.VideoId && p.DownloadFormat == videoInfo.DownloadFormat); - if (exists) return; - db.PendingDownloads.Add(new PendingDownload - { - QueuedAt = DateTime.UtcNow, - VideoUrl = videoInfo.VideoUrl, - VideoId = videoInfo.VideoId, - UrlType = videoInfo.UrlType, - DownloadFormat = videoInfo.DownloadFormat - }); - db.SaveChanges(); - OnPendingDownloadsChanged?.Invoke(); + // Insert-or-ignore against the unique (VideoId, DownloadFormat) index, rather than + // Any() followed by Add — two callers racing both saw "not present" and both + // inserted, so the same video was downloaded twice. The row count tells us whether + // anything was actually queued, so the UI is not notified for a no-op. + var inserted = db.Database.ExecuteSqlRaw(""" + INSERT INTO vvc_PendingDownloads (QueuedAt, VideoUrl, VideoId, UrlType, DownloadFormat) + VALUES ({0}, {1}, {2}, {3}, {4}) + ON CONFLICT (VideoId, DownloadFormat) DO NOTHING + """, + DateTime.UtcNow, + videoInfo.VideoUrl, + videoInfo.VideoId, + (int)videoInfo.UrlType, + (int)videoInfo.DownloadFormat); + + if (inserted > 0) + OnPendingDownloadsChanged?.Invoke(); } public static void RemovePendingDownload(string videoId, DownloadFormat format) diff --git a/VRCVideoCacher/Database/SchemaReconciler.cs b/VRCVideoCacher/Database/SchemaReconciler.cs new file mode 100644 index 00000000..29e0acaa --- /dev/null +++ b/VRCVideoCacher/Database/SchemaReconciler.cs @@ -0,0 +1,103 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Serilog; + +namespace VRCVideoCacher.Database; + +/// +/// TODO: Remove later - Schema reconciler backfills missing database columns. +/// +/// Adds columns that the EF model declares but the database on disk is missing. +/// +/// This exists because the schema is created with EnsureCreated() and there are no +/// migrations. EnsureCreated only ever creates a database that is absent — it never touches +/// one that already exists — so a property added to History or VideoInfoCache would simply +/// not exist for anybody who had already run the application, and the first query touching +/// it would fail at runtime with "no such column" rather than at startup. +/// +/// Only ever adds columns. It will not drop, rename or retype anything, so it cannot lose +/// data; a change that needs more than an added column still needs real migrations, which +/// remain the proper long-term answer. +/// +public static class SchemaReconciler +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(SchemaReconciler)); + + public static void Run(DbContext db) + { + foreach (var entityType in db.Model.GetEntityTypes()) + { + var tableName = entityType.GetTableName(); + if (string.IsNullOrEmpty(tableName) || !TableExists(db, tableName)) + continue; + + var existingColumns = GetColumns(db, tableName); + var storeObject = StoreObjectIdentifier.Table(tableName, entityType.GetSchema()); + + foreach (var property in entityType.GetProperties()) + { + var columnName = property.GetColumnName(storeObject); + if (string.IsNullOrEmpty(columnName) || existingColumns.Contains(columnName)) + continue; + + AddColumn(db, tableName, columnName, property); + } + } + } + + private static void AddColumn(DbContext db, string tableName, string columnName, IProperty property) + { + var columnType = property.GetColumnType() ?? "TEXT"; + + // SQLite can only add a column that is nullable or has a constant default, so a + // non-nullable one needs a type-appropriate filler for the existing rows. + var nullability = property.IsNullable ? "NULL" : $"NOT NULL DEFAULT {DefaultLiteralFor(columnType)}"; + + try + { + // EF1002: DDL cannot take bound parameters for identifiers. Every value here + // comes from the compiled EF model — table names, column names and store types + // are all compile-time constants of this assembly, never user input. +#pragma warning disable EF1002 + db.Database.ExecuteSqlRaw($"ALTER TABLE \"{tableName}\" ADD COLUMN \"{columnName}\" {columnType} {nullability}"); +#pragma warning restore EF1002 + Log.Information("Added missing column {Table}.{Column} ({Type}).", tableName, columnName, columnType); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to add missing column {Table}.{Column}.", tableName, columnName); + } + } + + private static string DefaultLiteralFor(string columnType) + { + var type = columnType.ToUpperInvariant(); + if (type.Contains("INT") || type.Contains("REAL") || type.Contains("NUMERIC") || + type.Contains("DOUBLE") || type.Contains("FLOAT") || type.Contains("DECIMAL")) + return "0"; + + if (type.Contains("BLOB")) + return "x''"; + + return "''"; + } + + private static bool TableExists(DbContext db, string tableName) => + db.Database + .SqlQueryRaw( + "SELECT name AS Value FROM sqlite_master WHERE type = 'table' AND name = {0}", tableName) + .AsEnumerable() + .Any(); + + private static HashSet GetColumns(DbContext db, string tableName) + { + // EF1002: pragma_table_info does not accept a bound parameter for the table name. + // tableName comes from the compiled EF model, and quotes are escaped regardless. +#pragma warning disable EF1002 + return db.Database + .SqlQueryRaw($"SELECT name AS Value FROM pragma_table_info('{tableName.Replace("'", "''")}')") + .AsEnumerable() + .ToHashSet(StringComparer.OrdinalIgnoreCase); +#pragma warning restore EF1002 + } +} diff --git a/VRCVideoCacher/FileTools.cs b/VRCVideoCacher/FileTools.cs index e8e45208..2df8471f 100644 --- a/VRCVideoCacher/FileTools.cs +++ b/VRCVideoCacher/FileTools.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Globalization; using System.Runtime.Versioning; using Serilog; @@ -9,7 +9,7 @@ namespace VRCVideoCacher; public class FileTools { private static readonly ILogger Log = Program.Logger.ForContext(); - private static readonly string? YtdlPathVrc; + public static readonly string? YtdlPathVrc; private static readonly string? BackupPathVrc; private static readonly string? YtdlPathReso; private static readonly string? BackupPathReso; @@ -63,15 +63,18 @@ static FileTools() { throw new NotImplementedException("Unknown platform"); } - var vrcPath = Path.Join(localLowPath, "VRChat/VRChat/Tools/yt-dlp.exe"); - if (!File.Exists(vrcPath)) + if (!string.IsNullOrEmpty(localLowPath)) { - Log.Warning("YT-DLP not found at expected VRChat path: {Path}", vrcPath); - } - else - { - YtdlPathVrc = vrcPath; - BackupPathVrc = $"{vrcPath}.bkp"; + var vrcPath = Path.Join(localLowPath, "VRChat/VRChat/Tools/yt-dlp.exe"); + if (!File.Exists(vrcPath)) + { + Log.Warning("YT-DLP not found at expected VRChat path: {Path}", vrcPath); + } + else + { + YtdlPathVrc = vrcPath; + BackupPathVrc = $"{vrcPath}.bkp"; + } } } @@ -180,18 +183,36 @@ public static void MarkFileExecutable(string path) } } - public static void BackupAllYtdl() + /// + /// Brings the on-disk yt-dlp stubs in line with the current PatchVrChat and + /// PatchResonite settings: patches what is enabled, restores what is not. + /// + /// Replaces a patch-only pass that never undid anything, so turning a toggle off left + /// the game patched until the user happened to quit the application cleanly — and let + /// the Settings screen apply the change immediately rather than deferring it to the + /// next launch with no indication that it had. + /// + public static void ApplyPatchSettings() { if (ConfigManager.Config.PatchVrChat) { if (!BackupAndReplaceYtdl(YtdlPathVrc, BackupPathVrc)) - Log.Error("Can't find VRC data, it may not be installed. {Path}", YtdlPathVrc); + Log.Warning("Can't find VRC data, it may not be installed. {Path}", YtdlPathVrc); } + else + { + RestoreYtdl(YtdlPathVrc, BackupPathVrc); + } + if (ConfigManager.Config.PatchResonite) { if (!BackupAndReplaceYtdl(YtdlPathReso, BackupPathReso)) Log.Warning("Can't find Resonite data, it may not be installed. {Path}", YtdlPathReso); } + else + { + RestoreYtdl(YtdlPathReso, BackupPathReso); + } } public static void RestoreAllYtdl() @@ -208,31 +229,54 @@ private static bool BackupAndReplaceYtdl(string? ytdlPath, string? backupPath) { return false; } - if (File.Exists(ytdlPath)) + + try { - var hash = Program.ComputeBinaryContentHash(File.ReadAllBytes(ytdlPath)); - if (hash == Program.YtdlpHash) + if (File.Exists(ytdlPath)) + { + var hash = Program.ComputeBinaryContentHash(File.ReadAllBytes(ytdlPath)); + if (hash == Program.YtdlpHash) + { + Log.Information("YT-DLP is already patched."); + return true; + } + if (File.Exists(backupPath)) + { + try + { + File.SetAttributes(backupPath, FileAttributes.Normal); + File.Delete(backupPath); + } + catch + { + // ignore permission issue on backup + } + } + File.Move(ytdlPath, backupPath); + Log.Information("Backed up YT-DLP."); + } + using var stream = Program.GetYtDlpStub(); + using var fileStream = File.Create(ytdlPath); + stream.CopyTo(fileStream); + fileStream.Close(); + try { - Log.Information("YT-DLP is already patched."); - return true; + var attr = File.GetAttributes(ytdlPath); + attr |= FileAttributes.ReadOnly; + File.SetAttributes(ytdlPath, attr); } - if (File.Exists(backupPath)) + catch { - File.SetAttributes(backupPath, FileAttributes.Normal); - File.Delete(backupPath); + // ignore attribute set failure on locked files } - File.Move(ytdlPath, backupPath); - Log.Information("Backed up YT-DLP."); + Log.Information("Patched YT-DLP."); + return true; + } + catch (Exception ex) + { + Log.Warning(ex, "Unable to patch YT-DLP at {Path} (file or directory may be read-only/locked)", ytdlPath); + return false; } - using var stream = Program.GetYtDlpStub(); - using var fileStream = File.Create(ytdlPath); - stream.CopyTo(fileStream); - fileStream.Close(); - var attr = File.GetAttributes(ytdlPath); - attr |= FileAttributes.ReadOnly; - File.SetAttributes(ytdlPath, attr); - Log.Information("Patched YT-DLP."); - return true; } private static void RestoreYtdl(string? ytdlPath, string? backupPath) @@ -242,16 +286,23 @@ private static void RestoreYtdl(string? ytdlPath, string? backupPath) !File.Exists(backupPath)) return; - Log.Information("Restoring yt-dlp..."); - if (File.Exists(ytdlPath)) + try + { + Log.Information("Restoring yt-dlp..."); + if (File.Exists(ytdlPath)) + { + File.SetAttributes(ytdlPath, FileAttributes.Normal); + File.Delete(ytdlPath); + } + File.Move(backupPath, ytdlPath); + var attr = File.GetAttributes(ytdlPath); + attr &= ~FileAttributes.ReadOnly; + File.SetAttributes(ytdlPath, attr); + Log.Information("Restored YT-DLP."); + } + catch (Exception ex) { - File.SetAttributes(ytdlPath, FileAttributes.Normal); - File.Delete(ytdlPath); + Log.Warning(ex, "Failed to restore yt-dlp at {Path}", ytdlPath); } - File.Move(backupPath, ytdlPath); - var attr = File.GetAttributes(ytdlPath); - attr &= ~FileAttributes.ReadOnly; - File.SetAttributes(ytdlPath, attr); - Log.Information("Restored YT-DLP."); } } \ No newline at end of file diff --git a/VRCVideoCacher/Integrations/Generic/GenericIntegration.cs b/VRCVideoCacher/Integrations/Generic/GenericIntegration.cs new file mode 100644 index 00000000..e545e6bd --- /dev/null +++ b/VRCVideoCacher/Integrations/Generic/GenericIntegration.cs @@ -0,0 +1,28 @@ +using Serilog; +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.Integrations.Generic; + +/// +/// The fallback for any URL nothing else claims: hash the URL for a stable cache id and let +/// yt-dlp's generic extractor deal with the rest. Must stay last in the registry. +/// +public class GenericIntegration : Integration +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + + public override bool CanHandle(Uri uri) => true; + + public override Task GetVideoInfo(string url, Uri uri, bool avPro) + { + Log.Information("No specific integration for URL, using generic: {URL}", url); + return Task.FromResult(new VideoInfo + { + VideoUrl = url, + VideoId = VideoId.HashUrl(url), + UrlType = UrlType.Other, + DownloadFormat = DownloadFormat.MP4 + }); + } +} diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/HlsHandler.cs b/VRCVideoCacher/Integrations/Hls/HlsIntegration.cs similarity index 88% rename from VRCVideoCacher/YTDL/SiteHandlers/Sites/HlsHandler.cs rename to VRCVideoCacher/Integrations/Hls/HlsIntegration.cs index 7afb2ecb..a738dd34 100644 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/HlsHandler.cs +++ b/VRCVideoCacher/Integrations/Hls/HlsIntegration.cs @@ -4,23 +4,28 @@ using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; using VRCVideoCacher.Models; +using VRCVideoCacher.Utils; +using VRCVideoCacher.YTDL; -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; +namespace VRCVideoCacher.Integrations.Hls; /// /// Handles HLS manifests regardless of URL shape. Detection is content-based: /// a GET on the URL is inspected for an HLS content-type or a #EXTM3U body /// prefix. Probe results are memoized briefly so GetVideoInfo doesn't refetch. /// -public class HlsHandler : ISiteHandler +public class HlsIntegration : Integration { - private static readonly ILogger Log = Program.Logger.ForContext(); + private static readonly ILogger Log = Program.Logger.ForContext(); private static readonly HttpClient HttpClient = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2), ConnectTimeout = TimeSpan.FromSeconds(3), AllowAutoRedirect = true, + // Probes whatever URL a world hands us, and follows redirects while doing it, so + // the address guard belongs at connect time where it also covers those redirects. + ConnectCallback = UrlPolicy.GuardedConnectAsync, }) { DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, @@ -63,7 +68,7 @@ private static string ProbeKey(string url) catch { return url; } } - public bool CanHandle(Uri uri) + public override bool CanHandle(Uri uri) { // Fast path: explicit .m3u8 extension — skip the probe entirely. return uri.AbsolutePath.EndsWith(".m3u8", StringComparison.OrdinalIgnoreCase); @@ -112,7 +117,7 @@ public static (double? Duration, bool IsComplete, bool IsTransportStream, long? private static TimeSpan EffectiveTtl(ProbeResult result) => (result.IsHls || result.IsTransportStream) ? ProbeTtl : NegativeProbeTtl; - public async Task GetVideoInfo(string url, Uri uri, bool avPro) + public override async Task GetVideoInfo(string url, Uri uri, bool avPro) { // Hash the path-only form so signed CDN URLs (rotating query tokens per play) // resolve to a stable videoId — otherwise the cached MP4 is never re-served. @@ -180,46 +185,13 @@ private static TimeSpan EffectiveTtl(ProbeResult result) => return null; } - public List GetYtdlpArguments(Uri uri, bool avPro) => []; - // Share-URL rewriting is opt-in: this rewriter sees *every* URL (content detection - // happens later), so the Dropbox/GDrive rewrites would change behavior for plain MP4 - // shares too. Gating on CacheHlsPlaylists keeps the default install unaffected. - public Task RewriteUrl(string url, Uri uri) => - Task.FromResult(ConfigManager.Config.CacheHlsPlaylists ? RewriteShareUrl(url, uri) : url); - - /// - /// Rewrites common cloud-host share URLs to their direct-download form so the probe - /// and yt-dlp see the actual file body instead of an HTML preview page. Applies to - /// the request URL only — segment URLs inside an HLS manifest aren't touched. - /// - public static string RewriteShareUrl(string url, Uri uri) - { - var host = uri.Host.ToLowerInvariant(); - - // Dropbox: dl=0 (preview page) → dl=1 (direct download). Also covers - // www.dropbox.com/s/... and dropbox.com/scl/fi/... share URLs. - if (host == "dropbox.com" || host.EndsWith(".dropbox.com")) - { - var q = uri.Query; - if (q.Contains("dl=0")) - return url.Replace("dl=0", "dl=1"); - if (string.IsNullOrEmpty(q)) - return url + "?dl=1"; - if (!q.Contains("dl=1") && !q.Contains("raw=1")) - return url + "&dl=1"; - } - - // Google Drive: /file/d//view → /uc?export=download&id= - if (host == "drive.google.com") - { - var m = System.Text.RegularExpressions.Regex.Match(uri.AbsolutePath, @"^/file/d/([^/]+)"); - if (m.Success) - return $"https://drive.google.com/uc?export=download&id={m.Groups[1].Value}"; - } - - return url; - } + // Share-URL rewriting used to live here as well as in the default rules, gated on + // CacheHlsPlaylists — a flag with nothing to do with Dropbox or Google Drive. Two + // implementations of the same behaviour, reachable under different conditions, is one + // too many: the rules engine is the user-visible, user-editable place for it, so the + // "Dropbox Share Rewrite", "Dropbox Direct Download" and "Google Drive File Rewrite" + // default rules are now the only implementation. private static async Task ProbeCached(string url) { @@ -269,6 +241,12 @@ private static async Task Probe(string url, int depth) return new ProbeResult(false, null, false, null); } + if (!UrlPolicy.IsFetchableWebUrl(url)) + { + Log.Debug("Skipping HLS probe for non-web URL {URL}", url); + return new ProbeResult(false, null, false, null); + } + try { using var req = new HttpRequestMessage(HttpMethod.Get, url); @@ -371,7 +349,7 @@ private static async Task Probe(string url, int depth) return (ms.ToArray(), truncated); } - private static (double? Duration, bool IsComplete) ParseMediaPlaylist(string body) + internal static (double? Duration, bool IsComplete) ParseMediaPlaylist(string body) { double total = 0; var any = false; @@ -396,7 +374,7 @@ private static (double? Duration, bool IsComplete) ParseMediaPlaylist(string bod /// Parses an optional title out of #EXT-X-SESSION-DATA tags carrying /// DATA-ID="com.apple.hls.title" (rare but standard per RFC 8216 §4.3.4.4). /// - private static string? ParseSessionTitle(string body) + internal static string? ParseSessionTitle(string body) { foreach (var rawLine in body.Split('\n')) { diff --git a/VRCVideoCacher/Integrations/Integration.cs b/VRCVideoCacher/Integrations/Integration.cs new file mode 100644 index 00000000..fa56e108 --- /dev/null +++ b/VRCVideoCacher/Integrations/Integration.cs @@ -0,0 +1,46 @@ +using VRCVideoCacher.Models; + +namespace VRCVideoCacher.Integrations; + +/// +/// Site-specific handling that a URL rule cannot express. +/// +/// The Rules tab already covers matching, rewriting, redirecting and blocking by pattern, +/// and that is the right tool whenever a regex is enough. An Integration exists for what +/// comes after: deriving a stable video id that names the cached file, canonicalising a URL +/// so history and the cache agree, calling a site's own API for a title, and choosing the +/// yt-dlp format arguments that site needs. +/// +/// If a site needs none of that, it needs a rule, not a class here. +/// +public abstract class Integration +{ + /// + /// The identifier a rule's Integration field binds to, letting a rule force a URL + /// through this integration regardless of what says. Null means + /// it is not selectable from a rule and is reached only by CanHandle. + /// + /// These names are persisted in the user's rule list: renaming one silently detaches + /// every saved rule that referenced it. + /// + public virtual string? Name => null; + + /// + /// Whether this integration claims the URL on shape alone. Must not touch the network — + /// it is called for every integration on every request. + /// + public abstract bool CanHandle(Uri uri); + + /// + /// Establishes the cache identity for a URL: the video id that names the cached file, + /// the canonical URL to record, the type, and the container to download. Returns null + /// when the URL turns out not to point at anything playable. + /// + public abstract Task GetVideoInfo(string url, Uri uri, bool avPro); + + /// + /// Extra yt-dlp arguments for this site — format selection, client impersonation. + /// One argv token per element, never pre-quoted; see YtdlManager.GenerateYtdlArgs. + /// + public virtual List GetYtdlpArguments(Uri uri, bool avPro) => []; +} diff --git a/VRCVideoCacher/Integrations/IntegrationRegistry.cs b/VRCVideoCacher/Integrations/IntegrationRegistry.cs new file mode 100644 index 00000000..e03347d7 --- /dev/null +++ b/VRCVideoCacher/Integrations/IntegrationRegistry.cs @@ -0,0 +1,128 @@ +using VRCVideoCacher.Integrations.Generic; +using VRCVideoCacher.Integrations.Hls; +using VRCVideoCacher.Integrations.PyPyDance; +using VRCVideoCacher.Integrations.Rewriters; +using VRCVideoCacher.Integrations.VRDancing; +using VRCVideoCacher.Integrations.YouTube; +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.Integrations; + +/// +/// Every integration and rewriter, and the order they are consulted in. +/// +/// Adding a site means adding a class in its own folder and one line here. +/// +public static class IntegrationRegistry +{ + private static readonly List Integrations = + [ + new YouTubeIntegration(), + new PyPyDanceIntegration(), + new VRDancingIntegration(), + new HlsIntegration(), + // Claims everything, so it must stay last. + new GenericIntegration(), + ]; + + /// + /// Run in order before any integration sees the URL, each seeing the previous one's + /// output. + /// + /// Cloud share-link rewriting (Dropbox, Google Drive) is deliberately absent: it lives + /// in the default rules, where the user can see and change it. + /// + private static readonly List Rewriters = + [ + new NicoVideoRewriter(), // nicovideo.jp / nico.ms → nicovideo.life + new YtsRewriter(), // dmn.moe /sr/ → /yt/ + new ThirdPartyYouTubeRewriter(), // follow redirects to the real YouTube URL + ]; + + public static async Task ApplyRewrites(string url) + { + foreach (var rewriter in Rewriters) + { + var uri = VideoId.ToUri(url); + if (uri == null) + return url; + + url = await rewriter.RewriteAsync(url, uri); + } + + return url; + } + + /// + /// Picks the integration for a URL. A rule naming one wins over shape matching, which + /// is how a rule forces an otherwise-unrecognised host through a specific integration. + /// + public static Integration? Resolve(Uri uri, UriRule? matchedRule = null) + { + if (matchedRule != null && !string.IsNullOrEmpty(matchedRule.Integration)) + { + var named = Integrations.FirstOrDefault(i => i.Name == matchedRule.Integration); + if (named != null) + return named; + } + + return Integrations.FirstOrDefault(i => i.CanHandle(uri)); + } + + /// + /// Like , but when only the generic fallback would match it runs + /// a content probe to detect HLS manifests served under arbitrary URLs — no .m3u8 + /// extension, unknown host. + /// + public static async Task ResolveAsync(string url, Uri uri, UriRule? matchedRule = null) + { + var integration = Resolve(uri, matchedRule); + + if (integration is not null and not GenericIntegration) + return integration; + + // Skip the probe for URLs that clearly aren't HLS (plain .mp4, images, etc). + if (HlsIntegration.LooksObviouslyNotHls(uri)) + return integration; + + // Skip it entirely when HLS caching is off — detection is only worth the up-to-5s + // GET if we are going to do something with the answer. Checked per call, not + // memoised, so enabling the setting takes effect on the next play. + if (!ConfigManager.Config.CacheHlsPlaylists) + return integration; + + // True for HLS manifests and for raw progressive MPEG-TS; both route through + // HlsIntegration, which exposes the distinction via TryGetCachedProbe. + if (await HlsIntegration.LooksLikeStreamable(url)) + return Integrations.OfType().First(); + + return integration; + } + + /// + /// Returns the integration that produced a , identified by its + /// . + /// + /// Preferred over re-resolving from the URL once a VideoInfo exists: GetVideoInfo + /// canonicalises as it goes — a /shorts/ link and a bare video id both come back as + /// /watch?v=... — so re-running rule evaluation against the new form can pick a + /// different integration than the one that created the record. + /// + public static Integration? ResolveByUrlType(UrlType urlType) => urlType switch + { + UrlType.YouTube => Integrations.OfType().FirstOrDefault(), + UrlType.PyPyDance => Integrations.OfType().FirstOrDefault(), + UrlType.VRDancing => Integrations.OfType().FirstOrDefault(), + UrlType.Hls => Integrations.OfType().FirstOrDefault(), + _ => Integrations.OfType().FirstOrDefault(), + }; + + /// Whether anything other than the generic fallback claims this URL. + public static bool HasSpecificIntegration(Uri uri) => + Integrations.Any(i => i is not GenericIntegration && i.CanHandle(uri)); + + /// Names selectable from a rule's Integration field. + public static IReadOnlyList AvailableIntegrationNames() => + Integrations.Select(i => i.Name).Where(n => !string.IsNullOrEmpty(n)).ToList()!; +} diff --git a/VRCVideoCacher/Services/PyPyDanceAPIService.cs b/VRCVideoCacher/Integrations/PyPyDance/PyPyDanceApiService.cs similarity index 97% rename from VRCVideoCacher/Services/PyPyDanceAPIService.cs rename to VRCVideoCacher/Integrations/PyPyDance/PyPyDanceApiService.cs index fba9fa39..9e805ee7 100644 --- a/VRCVideoCacher/Services/PyPyDanceAPIService.cs +++ b/VRCVideoCacher/Integrations/PyPyDance/PyPyDanceApiService.cs @@ -4,8 +4,9 @@ using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; using VRCVideoCacher.Models; +using VRCVideoCacher.Services; -namespace VRCVideoCacher.Services; +namespace VRCVideoCacher.Integrations.PyPyDance; internal class PyPyDanceBundle { diff --git a/VRCVideoCacher/Integrations/PyPyDance/PyPyDanceIntegration.cs b/VRCVideoCacher/Integrations/PyPyDance/PyPyDanceIntegration.cs new file mode 100644 index 00000000..5bfb5b80 --- /dev/null +++ b/VRCVideoCacher/Integrations/PyPyDance/PyPyDanceIntegration.cs @@ -0,0 +1,142 @@ +using System.Web; +using Serilog; +using VRCVideoCacher.Models; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.Integrations.PyPyDance; + +/// +/// api.pypy.dance/video redirects to the real file. The cache id comes from that final +/// file name, while the song id in the original query drives the metadata lookup. +/// +public class PyPyDanceIntegration : Integration +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + private static readonly string[] Prefixes = ["http://api.pypy.dance/video", "https://api.pypy.dance/video"]; + + private const int MaxRedirects = 5; + + // Redirects are followed by hand because HttpClient will not do this one. + // + // api.pypy.dance/video?id=N answers 302 to a plain-http CDN URL, and .NET refuses to + // auto-follow an https -> http redirect: it stops and returns the 302 with RequestUri + // still pointing at the original request. Reading the file name off that gave "video" + // as the id for *every* PyPyDance video, so they all collided on a single cache entry — + // the first one downloaded was then served for all of them. + // + // Upgrading the target to https is not an option: cdn.pypy.dance answers 525 there + // (its own TLS is misconfigured) and only serves the file over http. The address guard + // still applies, and the hop count is bounded. + private static readonly HttpClient RedirectClient = new(new SocketsHttpHandler + { + AllowAutoRedirect = false, + ConnectTimeout = TimeSpan.FromSeconds(10), + ConnectCallback = UrlPolicy.GuardedConnectAsync, + }) + { + DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, + Timeout = TimeSpan.FromSeconds(20) + }; + + public override string Name => "PyPyDance"; + + public override bool CanHandle(Uri uri) => + Prefixes.Any(prefix => uri.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); + + /// + /// The cache id is the CDN file's base name, which is the YouTube id the track came + /// from. Returns null when the URL has no usable file name — notably the un-redirected + /// "/video" endpoint itself, which must never become an id. + /// + internal static string? DeriveVideoId(Uri finalUri) + { + var fileName = Path.GetFileName(finalUri.LocalPath); + if (string.IsNullOrEmpty(fileName)) + return null; + + var videoId = !fileName.Contains('.') ? fileName : fileName.Split('.')[0]; + + // "video" is the API endpoint's own path segment: seeing it means the redirect was + // not followed, and using it would collide every track onto one cache file. + if (string.IsNullOrEmpty(videoId) || videoId is "." or ".." or "video") + return null; + + return videoId; + } + + private static async Task ResolveFinalUrlAsync(string url) + { + var current = new Uri(url); + + for (var hop = 0; hop <= MaxRedirects; hop++) + { + using var request = new HttpRequestMessage(HttpMethod.Head, current); + using var response = await RedirectClient.SendAsync(request); + + var location = response.Headers.Location; + if (location == null) + { + if (!response.IsSuccessStatusCode) + { + Log.Error("PyPyDance URL {URL} returned {Status} with no redirect.", current, response.StatusCode); + return null; + } + + return current; + } + + var next = location.IsAbsoluteUri ? location : new Uri(current, location); + if (!UrlPolicy.IsFetchableWebUrl(next)) + { + Log.Warning("PyPyDance redirected to a non-web URL: {URL}", next); + return null; + } + + current = next; + } + + Log.Warning("PyPyDance redirect chain for {URL} exceeded {Max} hops.", url, MaxRedirects); + return null; + } + + public override async Task GetVideoInfo(string url, Uri uri, bool avPro) + { + try + { + var finalUri = await ResolveFinalUrlAsync(url); + if (finalUri == null) + return null; + + var videoId = DeriveVideoId(finalUri); + if (videoId == null) + { + Log.Error("Could not derive a video ID from the resolved PypyDance URL: {URL}", finalUri); + return null; + } + + var videoUrl = finalUri.ToString(); + + var query = HttpUtility.ParseQueryString(uri.Query); + if (!int.TryParse(query.Get("id"), out var songId)) + { + Log.Error("Failed to get video ID from PypyDance URL: {URL}", url); + return null; + } + + _ = Task.Run(async () => await PyPyDanceApiService.DownloadMetadata(songId, videoId)); + + return new VideoInfo + { + VideoUrl = videoUrl, + VideoId = videoId, + UrlType = UrlType.PyPyDance, + DownloadFormat = DownloadFormat.MP4 + }; + } + catch (Exception ex) + { + Log.Error("Failed to get video ID from PypyDance URL {URL}: {Error}", url, ex.Message); + return null; + } + } +} diff --git a/VRCVideoCacher/Integrations/Rewriters/NicoVideoRewriter.cs b/VRCVideoCacher/Integrations/Rewriters/NicoVideoRewriter.cs new file mode 100644 index 00000000..29f3f7a6 --- /dev/null +++ b/VRCVideoCacher/Integrations/Rewriters/NicoVideoRewriter.cs @@ -0,0 +1,42 @@ +using System.Text.RegularExpressions; +using Serilog; + +namespace VRCVideoCacher.Integrations.Rewriters; + +/// +/// Redirects niconico links to nicovideo.life, a third-party mirror that yt-dlp can +/// actually resolve. +/// +/// That mirror is unofficial and unaffiliated with this project or with niconico, so +/// playing a niconico link tells it what is being watched. Documented under "What does it +/// connect to?" in the README; inherited from upstream VRCVideoCacher. +/// +public class NicoVideoRewriter : UrlRewriter +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + + private const string MirrorHost = "nicovideo.life"; + + // Full nicovideo/niconico watch URLs, and the nico.ms short form. + private static readonly Regex WatchUrl = new(@"^(https?)://(live|www)\.nicovideo\.jp/watch/(.+)$", RegexOptions.Compiled); + private static readonly Regex ShortUrl = new(@"^(https?)://nico\.ms/(.+)$", RegexOptions.Compiled); + + public override Task RewriteAsync(string url, Uri uri) + { + if (!uri.Host.EndsWith("nicovideo.jp") && !uri.Host.EndsWith("nico.ms")) + return Task.FromResult(url); + + var (match, idGroup) = new[] + { + (WatchUrl.Match(url), 3), + (ShortUrl.Match(url), 2), + }.FirstOrDefault(candidate => candidate.Item1.Success); + + if (match?.Success != true) + return Task.FromResult(url); + + var rewritten = $"https://www.{MirrorHost}/watch/{match.Groups[idGroup].Value}"; + Log.Information("Incompatible URL, passing to third-party resolver {Host}: {URL}", MirrorHost, rewritten); + return Task.FromResult(rewritten); + } +} diff --git a/VRCVideoCacher/Integrations/Rewriters/ThirdPartyYouTubeRewriter.cs b/VRCVideoCacher/Integrations/Rewriters/ThirdPartyYouTubeRewriter.cs new file mode 100644 index 00000000..d8c137c5 --- /dev/null +++ b/VRCVideoCacher/Integrations/Rewriters/ThirdPartyYouTubeRewriter.cs @@ -0,0 +1,94 @@ +using Serilog; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.Integrations.Rewriters; + +/// +/// Follows redirect chains from third-party YouTube front-ends (dmn.moe, u2b.cx and +/// friends) until the destination is something an integration recognises. +/// +/// This is the case a Rewrite rule cannot express: where the real URL is only discoverable +/// by asking the server, not by pattern-matching the one we were given. +/// +public class ThirdPartyYouTubeRewriter : UrlRewriter +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + + private const int MaxHops = 5; + + // AllowAutoRedirect=false so each hop can be inspected and the walk stopped as soon as + // the destination is a URL an integration recognises. + private static readonly HttpClient NoAutoRedirectClient = new(new SocketsHttpHandler + { + AllowAutoRedirect = false, + ConnectTimeout = TimeSpan.FromSeconds(10), + // Walks redirect chains for URLs chosen by whoever is in the instance. + ConnectCallback = UrlPolicy.GuardedConnectAsync, + }) + { + DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, + Timeout = TimeSpan.FromSeconds(20) + }; + + public override async Task RewriteAsync(string url, Uri uri) + { + if (IntegrationRegistry.HasSpecificIntegration(uri)) + return url; + + var current = url; + + try + { + for (var hop = 0; hop < MaxHops; hop++) + { + using var request = new HttpRequestMessage(HttpMethod.Head, current); + using var response = await NoAutoRedirectClient.SendAsync(request); + + var location = response.Headers.Location; + if (location == null) + break; + + // Resolve relative redirects against the current URL + var next = location.IsAbsoluteUri ? location.ToString() : new Uri(new Uri(current), location).ToString(); + + if (!Uri.TryCreate(next, UriKind.Absolute, out var nextUri)) + break; + + // A Location header can name any scheme it likes; only http(s) is ever a + // video we could go on to fetch. + if (!UrlPolicy.IsFetchableWebUrl(nextUri)) + { + Log.Warning("Stopping redirect chain at non-web URL {Url}", next); + break; + } + + // Stop as soon as the redirect target is something we handle specifically. + if (IntegrationRegistry.HasSpecificIntegration(nextUri)) + { + Log.Information("Resolved redirect: {URL} -> {Resolved}", url, next); + return next; + } + + current = next; + + var status = (int)response.StatusCode; + if (status is < 300 or >= 400) + break; + } + } + catch (HttpRequestException ex) + { + Log.Warning(ex, "Failed to follow redirects for {URL}, returning original", url); + return url; + } + + if (current != url) + { + Log.Information("Resolved redirect: {URL} -> {Resolved}", url, current); + if (Uri.TryCreate(current, UriKind.Absolute, out var finalUri) && !IntegrationRegistry.HasSpecificIntegration(finalUri)) + Log.Warning("Resolved URL has no specific integration, will use generic: {URL}", current); + } + + return current; + } +} diff --git a/VRCVideoCacher/Integrations/Rewriters/YtsRewriter.cs b/VRCVideoCacher/Integrations/Rewriters/YtsRewriter.cs new file mode 100644 index 00000000..2019cba5 --- /dev/null +++ b/VRCVideoCacher/Integrations/Rewriters/YtsRewriter.cs @@ -0,0 +1,25 @@ +using Serilog; + +namespace VRCVideoCacher.Integrations.Rewriters; + +/// +/// dmn.moe serves its player under /sr/ and the resolvable stream under /yt/. +/// +public class YtsRewriter : UrlRewriter +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + + private const string Host = "https://dmn.moe"; + + public override Task RewriteAsync(string url, Uri uri) + { + if (!url.StartsWith(Host, StringComparison.OrdinalIgnoreCase)) + return Task.FromResult(url); + + var rewritten = url.Replace("/sr/", "/yt/"); + if (rewritten != url) + Log.Information("YTS URL detected, modified to: {URL}", rewritten); + + return Task.FromResult(rewritten); + } +} diff --git a/VRCVideoCacher/Integrations/UrlRewriter.cs b/VRCVideoCacher/Integrations/UrlRewriter.cs new file mode 100644 index 00000000..03b939c5 --- /dev/null +++ b/VRCVideoCacher/Integrations/UrlRewriter.cs @@ -0,0 +1,22 @@ +namespace VRCVideoCacher.Integrations; + +/// +/// Rewrites a URL before any looks at it. +/// +/// Deliberately not an Integration. Rewriting is a different job: these have no video id to +/// derive, no format arguments to supply and nothing to resolve. Under the single interface +/// this replaced, every rewriter still had to implement CanHandle (returning false) and +/// GetVideoInfo (returning null) purely to satisfy it — three classes carrying two dead +/// members each, and nothing preventing a fourth from implementing them by accident. +/// +/// Prefer a Rewrite rule in the Rules tab wherever a regex suffices. A class here is for +/// rewrites that genuinely need code — following a redirect chain, for instance. +/// +public abstract class UrlRewriter +{ + /// + /// Returns the rewritten URL, or the original when this rewriter does not apply. + /// Rewriters run in order, each seeing the previous one's output. + /// + public abstract Task RewriteAsync(string url, Uri uri); +} diff --git a/VRCVideoCacher/Services/VRDancingAPIService.cs b/VRCVideoCacher/Integrations/VRDancing/VRDancingApiService.cs similarity index 91% rename from VRCVideoCacher/Services/VRDancingAPIService.cs rename to VRCVideoCacher/Integrations/VRDancing/VRDancingApiService.cs index 14d67f22..c54f10f1 100644 --- a/VRCVideoCacher/Services/VRDancingAPIService.cs +++ b/VRCVideoCacher/Integrations/VRDancing/VRDancingApiService.cs @@ -1,15 +1,16 @@ -using Newtonsoft.Json; -using Serilog; +using Serilog; +using VRCVideoCacher.Utils; using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; using VRCVideoCacher.Models; +using VRCVideoCacher.Services; -namespace VRCVideoCacher.Services; +namespace VRCVideoCacher.Integrations.VRDancing; -public class VRDancingAPIService +public class VRDancingApiService { private const string VRDancingAPIBaseURL = "https://dbapi.vrdancing.club/"; - private static readonly ILogger Logger = Program.Logger.ForContext(); + private static readonly ILogger Logger = Program.Logger.ForContext(); private static readonly HttpClient HttpClient = new() { BaseAddress = new Uri(VRDancingAPIBaseURL), @@ -28,7 +29,7 @@ public class VRDancingAPIService (int)req.StatusCode, code, str.Length > 200 ? str[..200] : str); return null; } - return JsonConvert.DeserializeObject(str); + return Json.Deserialize(str); } public static async Task DownloadMetadata(string code, string videoId) diff --git a/VRCVideoCacher/Integrations/VRDancing/VRDancingIntegration.cs b/VRCVideoCacher/Integrations/VRDancing/VRDancingIntegration.cs new file mode 100644 index 00000000..5b945c7e --- /dev/null +++ b/VRCVideoCacher/Integrations/VRDancing/VRDancingIntegration.cs @@ -0,0 +1,39 @@ +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.Integrations.VRDancing; + +/// +/// VRDancing serves each track from a regional host under a short code. The code drives the +/// metadata lookup; the cache id is a hash of the URL, since there is no id in it to use. +/// +public class VRDancingIntegration : Integration +{ + private static readonly string[] Prefixes = + [ + "https://na2.vrdancing.club", + "https://eu2.vrdancing.club", + "https://mpegts-beta.vrdancing.club" + ]; + + public override string Name => "VRDancing"; + + public override bool CanHandle(Uri uri) => + Prefixes.Any(prefix => uri.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); + + public override Task GetVideoInfo(string url, Uri uri, bool avPro) + { + var code = url.TrimEnd('/').Split('/').Last(); + var videoId = VideoId.HashUrl(url); + + _ = Task.Run(async () => await VRDancingApiService.DownloadMetadata(code, videoId)); + + return Task.FromResult(new VideoInfo + { + VideoUrl = url, + VideoId = videoId, + UrlType = UrlType.VRDancing, + DownloadFormat = DownloadFormat.MP4 + }); + } +} diff --git a/VRCVideoCacher/Services/VRDancingSheetService.cs b/VRCVideoCacher/Integrations/VRDancing/VRDancingSheetService.cs similarity index 91% rename from VRCVideoCacher/Services/VRDancingSheetService.cs rename to VRCVideoCacher/Integrations/VRDancing/VRDancingSheetService.cs index ec1337e3..80b0c31b 100644 --- a/VRCVideoCacher/Services/VRDancingSheetService.cs +++ b/VRCVideoCacher/Integrations/VRDancing/VRDancingSheetService.cs @@ -2,7 +2,7 @@ using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; -namespace VRCVideoCacher.Services; +namespace VRCVideoCacher.Integrations.VRDancing; public static class VRDancingSheetService { @@ -29,21 +29,31 @@ public static void StartBackgroundSync() { _ = Task.Run(async () => { - while (true) + var token = Program.ShutdownToken; + while (!token.IsCancellationRequested) { try { if (IsStale()) await SyncOnceAsync(); + + await Task.Delay(SyncInterval, token); + } + catch (OperationCanceledException) + { + // Shutting down. + return; } catch (Exception ex) { Logger.Warning(ex, "VRDancing sheet sync failed"); - } - await Task.Delay(SyncInterval); + // Still wait out the interval after a failure, or a persistent error + // turns this into a hot loop. + try { await Task.Delay(SyncInterval, token); } + catch (OperationCanceledException) { return; } + } } - // ReSharper disable once FunctionNeverReturns }); } diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/YouTubeHandler.cs b/VRCVideoCacher/Integrations/YouTube/YouTubeIntegration.cs similarity index 64% rename from VRCVideoCacher/YTDL/SiteHandlers/Sites/YouTubeHandler.cs rename to VRCVideoCacher/Integrations/YouTube/YouTubeIntegration.cs index 9fc471d0..7cbd2844 100644 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/YouTubeHandler.cs +++ b/VRCVideoCacher/Integrations/YouTube/YouTubeIntegration.cs @@ -1,81 +1,82 @@ -using System.Text.RegularExpressions; -using Serilog; -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class YouTubeHandler : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - private static readonly string[] Hosts = ["youtube.com", "youtu.be", "www.youtube.com", "m.youtube.com", "music.youtube.com"]; - private static readonly Regex IdRegex = new(@"(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|live\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})"); - private static readonly Regex BareIdRegex = new(@"^\/(?=[a-zA-Z0-9_-]*[\d_A-Z-])[a-zA-Z0-9_-]{11}$"); - private const string AVProFormat = "(mp4/best)[height<=?1080][height>=?64][width>=?64]"; - private const string UnityPlayerFormat = "(mp4/best)[vcodec!=av01][vcodec!=vp9.2][height<=?1080][height>=?64][width>=?64][protocol^=http]"; - - public bool CanHandle(Uri uri) => Hosts.Contains(uri.Host); - - public Task GetVideoInfo(string url, Uri uri, bool avPro) - { - string? videoId = null; - - var match = IdRegex.Match(url); - if (match.Success) - videoId = match.Groups[1].Value; - else if (uri.AbsolutePath.StartsWith("/shorts/")) - videoId = uri.AbsolutePath.Split('/')[^1]; - else if (uri.AbsolutePath.TrimEnd('/').EndsWith("/live")) - videoId = "live"; - else if (BareIdRegex.IsMatch(uri.AbsolutePath)) - videoId = uri.AbsolutePath.TrimStart('/'); - - if (string.IsNullOrEmpty(videoId)) - { - Log.Warning("Failed to parse video ID from YouTube URL: {URL}", url); - return Task.FromResult(null); - } - - videoId = videoId.Length > 11 ? videoId[..11] : videoId; - - // Persist a canonical single-video URL so history/buttons never link to a playlist. - var canonicalUrl = $"https://www.youtube.com/watch?v={videoId}"; - - return Task.FromResult(new VideoInfo - { - VideoUrl = canonicalUrl, - VideoId = videoId, - UrlType = UrlType.YouTube, - DownloadFormat = avPro ? DownloadFormat.Webm : DownloadFormat.MP4 - }); - } - - public List GetYtdlpArguments(Uri uri, bool avPro) - { - var args = new List - { - }; - - if (avPro) - { - // Using the Safari impersonation with the web client gets us the muxed m3u8's that aren't normally available otherwise. - // These are the only streams that are compatible with AVPro currently due to WMF being unmaintained. - args.Add("--impersonate=\"safari\""); - args.Add("--extractor-args=\"youtube:player_client=web\""); - - // AVPro - var lang = ConfigManager.Config.YtdlpDubLanguage; - // If dub language is set, attempt to fetch, else use defaults. - args.Add(!string.IsNullOrEmpty(lang) - ? $"-f \"[language={lang}]/{AVProFormat}\"" - : $"-f \"{AVProFormat}\""); - } - else - { - // Unity Player - args.Add($"-f \"{UnityPlayerFormat}\""); - } - - return args; - } - -} \ No newline at end of file +using System.Text.RegularExpressions; +using Serilog; +using VRCVideoCacher.Models; + +namespace VRCVideoCacher.Integrations.YouTube; + +public class YouTubeIntegration : Integration +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + + private static readonly string[] Hosts = ["youtube.com", "youtu.be", "www.youtube.com", "m.youtube.com", "music.youtube.com"]; + private static readonly Regex IdRegex = new(@"(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|live\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})"); + private static readonly Regex BareIdRegex = new(@"^\/(?=[a-zA-Z0-9_-]*[\d_A-Z-])[a-zA-Z0-9_-]{11}$"); + + private const string AVProFormat = "(mp4/best)[height<=?1080][height>=?64][width>=?64]"; + private const string UnityPlayerFormat = "(mp4/best)[vcodec!=av01][vcodec!=vp9.2][height<=?1080][height>=?64][width>=?64][protocol^=http]"; + + public override string Name => "YouTube"; + + public override bool CanHandle(Uri uri) => Hosts.Contains(uri.Host); + + public override Task GetVideoInfo(string url, Uri uri, bool avPro) + { + string? videoId = null; + + var match = IdRegex.Match(url); + if (match.Success) + videoId = match.Groups[1].Value; + else if (uri.AbsolutePath.StartsWith("/shorts/")) + videoId = uri.AbsolutePath.Split('/')[^1]; + else if (uri.AbsolutePath.TrimEnd('/').EndsWith("/live")) + videoId = "live"; + else if (BareIdRegex.IsMatch(uri.AbsolutePath)) + videoId = uri.AbsolutePath.TrimStart('/'); + + if (string.IsNullOrEmpty(videoId)) + { + Log.Warning("Failed to parse video ID from YouTube URL: {URL}", url); + return Task.FromResult(null); + } + + videoId = videoId.Length > 11 ? videoId[..11] : videoId; + + // Persist a canonical single-video URL so history/buttons never link to a playlist. + var canonicalUrl = $"https://www.youtube.com/watch?v={videoId}"; + + return Task.FromResult(new VideoInfo + { + VideoUrl = canonicalUrl, + VideoId = videoId, + UrlType = UrlType.YouTube, + DownloadFormat = avPro ? DownloadFormat.Webm : DownloadFormat.MP4 + }); + } + + public override List GetYtdlpArguments(Uri uri, bool avPro) + { + var args = new List(); + + if (avPro) + { + // Safari impersonation with the web client is what surfaces the muxed m3u8 + // streams, which are currently the only ones AVPro can play — WMF is unmaintained. + args.Add("--impersonate"); + args.Add("safari"); + args.Add("--extractor-args"); + args.Add("youtube:player_client=web"); + + var lang = ConfigManager.Config.YtdlpDubLanguage; + args.Add("-f"); + args.Add(!string.IsNullOrEmpty(lang) ? $"[language={lang}]/{AVProFormat}" : AVProFormat); + } + else + { + // Unity Player + args.Add("-f"); + args.Add(UnityPlayerFormat); + } + + return args; + } +} diff --git a/VRCVideoCacher/Services/YouTubeMetadataService.cs b/VRCVideoCacher/Integrations/YouTube/YouTubeMetadataService.cs similarity index 53% rename from VRCVideoCacher/Services/YouTubeMetadataService.cs rename to VRCVideoCacher/Integrations/YouTube/YouTubeMetadataService.cs index b3285bb7..e92e22ad 100644 --- a/VRCVideoCacher/Services/YouTubeMetadataService.cs +++ b/VRCVideoCacher/Integrations/YouTube/YouTubeMetadataService.cs @@ -2,14 +2,17 @@ using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; using VRCVideoCacher.Models; +using VRCVideoCacher.Services; -namespace VRCVideoCacher.Services; +namespace VRCVideoCacher.Integrations.YouTube; public static class YouTubeMetadataService { + private static readonly Serilog.ILogger Log = Program.Logger.ForContext(typeof(YouTubeMetadataService)); + private static readonly HttpClient HttpClient = new() { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, + DefaultRequestHeaders = { { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" } }, Timeout = TimeSpan.FromSeconds(10) }; @@ -20,18 +23,27 @@ public static class YouTubeMetadataService try { - var url = $"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={videoId}&format=json"; - var response = await HttpClient.GetStringAsync(url); + // The watch URL is a parameter *value* and has to be escaped as one. Unescaped, + // its "?v=" started a new parameter of the outer query, so YouTube saw + // url=https://www.youtube.com/watch with no video id and answered 404 — and the + // catch below swallowed it, so titles never resolved through this path at all. + var target = Uri.EscapeDataString($"https://www.youtube.com/watch?v={videoId}"); + var response = await HttpClient.GetStringAsync($"https://www.youtube.com/oembed?url={target}&format=json"); using var doc = JsonDocument.Parse(response); if (!doc.RootElement.TryGetProperty("title", out var titleElement)) return null; var title = titleElement.GetString(); - doc.RootElement.TryGetProperty("author_name", out var authorElement); - var author = authorElement.GetString(); - if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(author)) + if (string.IsNullOrEmpty(title)) return null; + // author_name is optional in the oEmbed response, and a missing one is no + // reason to throw away a perfectly good title. Reading it unconditionally also + // threw on the default JsonElement when the property was absent. + var author = doc.RootElement.TryGetProperty("author_name", out var authorElement) + ? authorElement.GetString() + : null; + var videoInfo = new VideoInfoCache { Id = videoId, @@ -42,9 +54,11 @@ public static class YouTubeMetadataService DatabaseManager.AddVideoInfoCache(videoInfo); return videoInfo; } - catch + catch (Exception ex) { - // Silently fail - we'll just show the video ID + // Non-fatal: the UI falls back to showing the video ID. Logged at debug so the + // next breakage here isn't invisible the way this one was. + Log.Debug("oEmbed lookup failed for {VideoId}: {Error}", videoId, ex.Message); } return null; diff --git a/VRCVideoCacher/Languages/EmbeddedJsonLocalizer.cs b/VRCVideoCacher/Languages/EmbeddedJsonLocalizer.cs index 2e0d0e75..d341dd2e 100644 --- a/VRCVideoCacher/Languages/EmbeddedJsonLocalizer.cs +++ b/VRCVideoCacher/Languages/EmbeddedJsonLocalizer.cs @@ -1,69 +1,119 @@ -using System.Collections.Frozen; -using System.Reflection; -using Jeek.Avalonia.Localization; -using Newtonsoft.Json.Linq; - -namespace VRCVideoCacher.Languages; - -public class EmbeddedJsonLocalizer : BaseLocalizer -{ - private FrozenDictionary _languageStrings = new Dictionary().ToFrozenDictionary(); - - private const string prefix = "VRCVideoCacher.Languages."; - private const string suffix = ".loc.json"; - - public EmbeddedJsonLocalizer() - { - Reload(); - OnLanguageChanged(); - FireLanguageChanged(); - } - - public override void Reload() - { - var assembly = Assembly.GetExecutingAssembly(); - var resources = assembly.GetManifestResourceNames() - .Where(r => r.StartsWith(prefix) && r.EndsWith(suffix)) - .ToList(); - - foreach (var resourceName in resources) - { - var langId = resourceName[prefix.Length..^suffix.Length]; - _languages.Add(langId); - } - - ValidateLanguage(); - _hasLoaded = true; - UpdateDisplayLanguages(); - } - - protected override void OnLanguageChanged() - { - var assembly = Assembly.GetExecutingAssembly(); - var resourceName = assembly.GetManifestResourceNames() - .First(r => r.Equals($"{prefix}{_language}{suffix}")); - - using var stream = assembly.GetManifestResourceStream(resourceName)!; - using var reader = new StreamReader(stream); - var json = JObject.Parse(reader.ReadToEnd()); - - _languageStrings = json.Properties() - .ToDictionary(k => k.Name, v => v.Value?.ToString() ?? v.Name) - .ToFrozenDictionary(); - } - - public override string Get(string key) - { - if (!_hasLoaded) - { - Reload(); - } - - if (_languageStrings?.TryGetValue(key, out string? value) == true) - { - return value; - } - - return base.Language + ":" + key; - } -} +using System.Collections.Frozen; +using System.Reflection; +using System.Text.Json; +using Jeek.Avalonia.Localization; + +namespace VRCVideoCacher.Languages; + +public class EmbeddedJsonLocalizer : BaseLocalizer +{ + private const string Prefix = "VRCVideoCacher.Languages."; + private const string Suffix = ".loc.json"; + private const string FallbackLanguageCode = "en"; + + private static readonly Serilog.ILogger Log = Program.Logger.ForContext(); + + private FrozenDictionary _languageStrings = FrozenDictionary.Empty; + + // English stays loaded alongside the active language so that a key missing from a + // translation renders real text instead of surfacing the raw "ru:SomeKey" marker. + private FrozenDictionary _fallbackStrings = FrozenDictionary.Empty; + + public EmbeddedJsonLocalizer() + { + Reload(); + OnLanguageChanged(); + FireLanguageChanged(); + } + + public override void Reload() + { + foreach (var resourceName in GetLanguageResourceNames()) + { + var langId = resourceName[Prefix.Length..^Suffix.Length]; + // Guard against duplicates: Get() calls Reload() whenever _hasLoaded is false, + // so this can run more than once over the same resource list. + if (!_languages.Contains(langId)) + _languages.Add(langId); + } + + _fallbackStrings = LoadLanguage(FallbackLanguageCode) ?? FrozenDictionary.Empty; + + ValidateLanguage(); + _hasLoaded = true; + UpdateDisplayLanguages(); + } + + protected override void OnLanguageChanged() + { + // A config naming a language we no longer ship — hand-edited, or a translation + // dropped between releases — used to reach .First() here and throw + // InvalidOperationException out of App.InitializeLocalization, killing the app + // before the window ever appeared. Fall back to English instead. + var strings = LoadLanguage(_language); + if (strings == null) + { + Log.Warning("No embedded strings for language '{Language}'; falling back to '{Fallback}'.", + _language, FallbackLanguageCode); + strings = _fallbackStrings; + } + + _languageStrings = strings; + } + + public override string Get(string key) + { + if (!_hasLoaded) + { + Reload(); + } + + if (_languageStrings.TryGetValue(key, out var value)) + return value; + + // Untranslated key: show the English text rather than ":" at the user. + if (_fallbackStrings.TryGetValue(key, out var fallback)) + { + Log.Debug("Missing '{Language}' translation for key '{Key}'; using English.", _language, key); + return fallback; + } + + return key; + } + + private static IEnumerable GetLanguageResourceNames() => + Assembly.GetExecutingAssembly() + .GetManifestResourceNames() + .Where(r => r.StartsWith(Prefix, StringComparison.Ordinal) && + r.EndsWith(Suffix, StringComparison.Ordinal)); + + /// + /// Loads one embedded language file, or null when there is no resource for it. + /// + private static FrozenDictionary? LoadLanguage(string? languageId) + { + if (string.IsNullOrEmpty(languageId)) + return null; + + try + { + var assembly = Assembly.GetExecutingAssembly(); + using var stream = assembly.GetManifestResourceStream($"{Prefix}{languageId}{Suffix}"); + if (stream == null) + return null; + + using var document = JsonDocument.Parse(stream); + return document.RootElement + .EnumerateObject() + // A non-string value would be a mistake in the file; fall back to the key + // so the UI shows something identifiable rather than throwing. + .ToDictionary(p => p.Name, p => p.Value.GetString() ?? p.Name) + .ToFrozenDictionary(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to parse embedded language file for '{Language}'.", languageId); + return null; + } + } +} diff --git a/VRCVideoCacher/Languages/en.loc.json b/VRCVideoCacher/Languages/en.loc.json old mode 100755 new mode 100644 index c2e57ca5..038f9694 --- a/VRCVideoCacher/Languages/en.loc.json +++ b/VRCVideoCacher/Languages/en.loc.json @@ -1,25 +1,13 @@ { "Dashboard": "Dashboard", + "NowPlaying": "Now Playing", + "ActiveConnections": "Active Connections", "Settings": "Settings", "CacheBrowser": "Cache Browser", "Downloads": "Downloads", "History": "History", "Logs": "Logs", "About": "About", - "PreCacheVideos": "Pre-cached Videos", - "PreCacheVideosHint": "Video URLs downloaded at startup if not already cached. You can paste several at once, separated by commas, spaces or new lines.", - "CookiesExpired": "Login cookie expired", - "CookiesExpireToday": "Login cookie expires today", - "CookiesExpireInDaysFormat": "Login cookie expires in {0} days", - "Stats": "Stats", - "CacheHitRate": "Cache Hit Rate", - "BandwidthSaved": "Bandwidth Saved", - "CacheHits": "Cache Hits", - "TotalPlays": "Total Plays", - "MostReplayed": "Most Replayed", - "NoLongerCached": "No longer cached", - "BytesSavedCaveatFormat": "Excludes {0} cache hits on videos that have since been removed from the cache, so the real figure is higher.", - "Refresh": "Refresh", "Save": "Save", "Reset": "Reset", @@ -35,7 +23,6 @@ "Done": "Done", "Language": "Language", "General": "General", - "ToggleHostTooltip": "Toggle using YouTube domain for localhost cache", "ServerStatus": "Server Status", "Cache": "Cache", @@ -53,7 +40,6 @@ "Expired": "Expired", "Unknown": "Unknown", "ServerRunning": "Server running", - "ServerSettings": "Server Settings", "WebServerUrl": "Web Server URL", "DownloadSettings": "Download Settings", @@ -64,13 +50,8 @@ "CacheSettings": "Cache Settings", "CachePathLabel": "Cache Path (leave empty for default)", "MaxCacheSizeLabel": "Max Cache Size in GB (0 = unlimited)", - "CacheYouTubeVideos": "Cache YouTube Videos", - "MaxYouTubeResolution": "Max YouTube Resolution", - "PreferVp9ForCache": "Prefer VP9 for cached videos (MP4)", - "PreferVp9ForCacheTooltip": "Saves 20–50% storage for cached YouTube videos with no quality loss. Works on all platforms including Quest. Safe to enable for most users.", + "MaxResolution": "Max Resolution", "MaxVideoLength": "Max Video Length (minutes)", - "CachePyPyDanceVideos": "Cache PyPyDance Videos", - "CacheVRDancingVideos": "Cache VRDancing Videos", "CacheHlsPlaylists": "Cache HLS Videos (.m3u8 / mpegts)", "OnlyServeCachedVideos": "Only Serve Cached Videos", "CacheDownloadIdleSeconds": "Pause cache downloads while streaming (seconds)", @@ -83,19 +64,14 @@ "CloseToTray": "Close to Tray", "StartMinimized": "Start Minimized", "StartWithSteamVr": "Start with SteamVR", - "ErrorPopups": "Error Popups", - "BlockedUrls": "Blocked URLs", - "BlockedUrlRedirect": "Blocked URL Redirect", "SettingsSaved": "Settings saved!", + "SettingsSavedRestartRequired": "Saved — restart VRCVideoCacher for the new cache folder to take effect", "SettingsReset": "Settings reset to last saved values.", "SettingsUnsavedChanges": "You have unsaved changes.", - "RedirectVRDancing": "Redirect EU VRDancing to NA", - "OpenFolder": "Open Folder", "DeleteAllCache": "Delete All Cache", "SearchVideosWatermark": "Search videos...", "VideosCountFormat": "{0} of {1} videos", - "DownloadQueue": "Download Queue", "ClearQueue": "Clear Queue", "CurrentDownload": "Current Download", @@ -118,7 +94,7 @@ "SkipReasonBotCheck": "YouTube bot-check — install the browser extension: github.com/clienthax/VRCVideoCacherBrowserExtension and use an alternative YouTube account", "SkipReasonVideoUnavailable": "Video unavailable", "SkipReasonPrivateVideo": "Video is private", - + "SkipReasonStalled": "Download stalled — no data received", "LogViewer": "Log Viewer", "ExportLogs": "Export Logs", "ClearLogs": "Clear Logs", @@ -128,9 +104,7 @@ "Warning": "Warning", "Error": "Error", "AutoScroll": "Auto-scroll", - "EntriesCountFormat": "{0} entries", - "CookieSetupTitle": "YouTube Cookie Extension Setup", "CookieSetupSubtitle": "Fix YouTube bot detection errors", "CookieSetupStep1Header": "Step 1: Select your browser", @@ -166,6 +140,9 @@ "CookiesStatusPresent": "Cookies present (not yet verified)", "CookiesStatusWorking": "Cookies are working with YouTube!", "CookiesStatusExpired": "Cookies expired or rejected by YouTube", + "CookiesExpired": "Cookies have expired", + "CookiesExpireToday": "Cookies expire today", + "CookiesExpireInDaysFormat": "Expires in {0} days", "CookiesRefreshHeader": "Refreshing cookies", "CookiesHelpLegacy": "With the standard extension, cookies are sent when you open YouTube in your browser with the extension installed. You can also paste them manually below.", "CookiesHelpBeta": "\"Request fresh cookies\" pulls a fresh set instantly — no need to open the extension or enable automatic sharing. You can also click \"Send cookies\" in the extension or paste them below.", @@ -180,24 +157,58 @@ "AddHostsEntry": "Add Hosts Entry", "OpenChromeWebStore": "Open Chrome Web Store", "OpenFirefoxAddons": "Open Firefox Add-ons", - "DontShowThisAgain": "Don't show this again", - "TrayShow": "Show", + "Show": "Show", "TrayOpenCacheFolder": "Open Cache Folder", "TrayExit": "Exit", "TrayMinimizeNotice": "VRCVideoCacher is still running in the background. Click the tray icon to reopen it.", - "VRCVideoCacherPlus": "VRCVideoCacherPlus", "Updates": "Updates", "AutoUpdateVRCVideoCacher": "Auto-update VRCVideoCacher", - "CreatedBy": "Created By", "ReportAnIssue": "Report an Issue", "OpenIssueOnGitHub": "Open an issue on GitHub", - "JoinOurDiscord": "Join our Discord to report an issue", "RedownloadUtils": "Redownload Utils", "OpenUtilsFolder": "Open Utils Folder", "RedownloadingUtils": "Redownloading utils...", "RedownloadComplete": "Utils redownloaded successfully!", - "RedownloadFailed": "Redownload failed. Check logs for details." + "RedownloadFailed": "Redownload failed. Check logs for details.", + "PreCacheVideos": "Pre-cached Videos", + "PreCacheVideosHint": "Video URLs downloaded at startup if not already cached. You can paste several at once, separated by commas, spaces or new lines.", + "Rules": "Rules", + "AddRule": "Add Rule", + "RuleName": "Rule Name", + "RegexPattern": "Regex Pattern", + "Action": "Action", + "RedirectTarget": "Redirect Target URL", + "RewriteTarget": "Target Rewrite Pattern / URL", + "Enabled": "Enabled", + "Tools": "Tools", + "VideoPlayers": "Video Players", + "Disable": "Disable", + "Enable": "Enable", + "RulesManagedViaRulesTabNote": "Domain caching, resolution caps, redirects, and URL rewrites are managed via the Rules tab.", + "TestUrlPlaceholder": "Test URL...", + "UnsavedRulesMessage": "You have unsaved changes in your rules. Do you want to save or discard your changes before leaving?", + "Discard": "Discard", + "ResetToDefaults": "Defaults", + "ConfirmResetDefaultsMessage": "Are you sure you want to reset all rules to factory defaults? Any custom rules will be replaced.", + "EditRuleTitle": "Edit Rule", + "AddRuleTitle": "Add Rule", + "PatternCannotBeEmpty": "Pattern cannot be empty.", + "InvalidRegex": "Invalid regex: {0}", + "UpdateAvailable": "Version {0} is available!", + "UpdateDownloading": "Downloading update...", + "UpdateFailed": "Update failed. Check the logs and try again.", + "SkipReasonInvalidDownload": "Downloaded file failed validation", + "SkipReasonTruncated": "Download was incomplete", + "DownloadTimeRemaining": "{0} left", + "SharedConfigNoticeTitle": "Settings are now shared", + "SharedConfigNotice": "VRCVideoCacherPlusPlus keeps its settings in the same Config.json as the original VRCVideoCacher, rather than a separate file.\n\nIf you run the original VRCVideoCacher (or the Plus version), it will rewrite that file and drop the PlusPlus settings — including your URL rules. They would go back to defaults.\n\nIf you are coming from an older PlusPlus build, your previous settings are still in PlusConfig.json in the same folder. That file is no longer read, but it is left in place so you can copy anything you want back out of it.", + "SeverSucceeded": "Stopped {0} connection(s).", + "SeverNeedsPrivileges": "Cached videos were stopped. Closing VRChat's direct connections needs administrator/root, so a video already streaming will keep playing until it ends.", + "SeverUnsupported": "This platform has no way to close VRChat's direct connections.", + "SeverFailed": "Failed to close connections. See the log for details.", + "SeverNothingToDo": "Nothing to stop.", + "AddressCopied": "Address copied to clipboard." } diff --git a/VRCVideoCacher/Languages/hu.loc.json b/VRCVideoCacher/Languages/hu.loc.json old mode 100755 new mode 100644 index 1cd428e0..cbf18ef2 --- a/VRCVideoCacher/Languages/hu.loc.json +++ b/VRCVideoCacher/Languages/hu.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "Főoldal", + "NowPlaying": "Most játszott", + "ActiveConnections": "Aktív kapcsolatok", "Settings": "Beállítások", "CacheBrowser": "Gyorsítótár Böngésző", "Downloads": "Letöltések", "History": "Előzmények", "Logs": "Naplók", "About": "Rólunk", - "PreCacheVideos": "Előre gyorsítótárazott videók", - "PreCacheVideosHint": "Indításkor letöltött videó-URL-ek, ha még nincsenek a gyorsítótárban. Egyszerre többet is beilleszthetsz, vesszővel, szóközzel vagy sortöréssel elválasztva.", - "CookiesExpired": "A bejelentkezési süti lejárt", - "CookiesExpireToday": "A bejelentkezési süti ma lejár", - "CookiesExpireInDaysFormat": "A bejelentkezési süti {0} nap múlva lejár", - "Stats": "Statisztika", - "CacheHitRate": "Gyorsítótár-találati arány", - "BandwidthSaved": "Megtakarított sávszélesség", - "CacheHits": "Gyorsítótár-találatok", - "TotalPlays": "Összes lejátszás", - "MostReplayed": "Legtöbbször újranézett", - "NoLongerCached": "Már nincs a gyorsítótárban", - "BytesSavedCaveatFormat": "Nem tartalmaz {0} találatot olyan videókon, amelyek azóta törlődtek a gyorsítótárból, így a valós érték magasabb.", "Refresh": "Frissítés", "Save": "Mentés", "Reset": "Visszaállítás", @@ -54,7 +43,6 @@ "ServerSettings": "Szerver Beállítások", "WebServerUrl": "Web Szerver URL", "DownloadSettings": "Beállítások Letöltése", - "YtdlpPathGlobalLabel": "yt-dlp a PATH környezeti változóból", "UseYouTubeCookies": "YouTube Sütik Használata (böngésző kiegészítő szükséges)", "AutoUpdateUtils": "Automatikus frissítés segédprogramoknak (yt-dlp, FFmpeg és Deno)", "AdditionalYtdlpArgs": "Kiegészítő yt-dlp Paraméterek", @@ -62,13 +50,8 @@ "CacheSettings": "Gyorsítótár Beállítások", "CachePathLabel": "Gyorsítótár Útvonal (hagyd üresen az alapértelmezett értékhez)", "MaxCacheSizeLabel": "Maximális Gyorsítótár Méret GB-ban (0 = korlátlan)", - "CacheYouTubeVideos": "YouTube Videók Gyorsítótárazása", - "MaxYouTubeResolution": "Maximális YouTube Felbontás", - "PreferVp9ForCache": "VP9 előnyben részesítése gyorsítótárazott videókhoz (MP4)", - "PreferVp9ForCacheTooltip": "20–50%-kal csökkenti a gyorsítótárazott YouTube-videók tárhelyét minőségromlás nélkül. Minden platformon működik, beleértve a Questet is. A legtöbb felhasználónak biztonságosan engedélyezhető.", + "MaxResolution": "Maximális felbontás", "MaxVideoLength": "Maximális Videó Hossza (perc)", - "CachePyPyDanceVideos": "PyPyDance Videók Gyorsítótár", - "CacheVRDancingVideos": "VRDancing Videók Gyorsítótár", "CacheHlsPlaylists": "HLS Videók Gyorsítótár (.m3u8 / mpegts)", "OnlyServeCachedVideos": "Csak Gyorsítótárazott Videókat Szolgáljon Ki", "CacheDownloadIdleSeconds": "Gyorsítótár letöltés szüneteltetése streamelés közben (másodperc)", @@ -81,13 +64,10 @@ "CloseToTray": "Tálcára Csukás", "StartMinimized": "Indítás Minimalizálva", "StartWithSteamVr": "Indítsd el az alkalmazást a SteamVR segítségével", - "ErrorPopups": "Hiba felugró ablakok", - "BlockedUrls": "Letiltott Linkek", - "BlockedUrlRedirect": "Blokkolt Link Átirányítás", "SettingsSaved": "Beállítások Mentve!", + "SettingsSavedRestartRequired": "Mentve — indítsd újra a VRCVideoCachert az új gyorsítótár mappához", "SettingsReset": "Beállítások visszaállnak az utoljára mentett értékekre.", "SettingsUnsavedChanges": "Vannak mentetlen változások.", - "RedirectVRDancing": "EU VRDancing átirányítása NA-ra", "OpenFolder": "Mappa Megnyitás", "DeleteAllCache": "Összes gyorsítótár Törlése", "SearchVideosWatermark": "Videók Keresése...", @@ -114,6 +94,7 @@ "SkipReasonBotCheck": "YouTube bot-ellenőrzés — telepítse a böngészőbővítményt: github.com/clienthax/VRCVideoCacherBrowserExtension és használjon alternatív YouTube fiókot", "SkipReasonVideoUnavailable": "A videó nem elérhető", "SkipReasonPrivateVideo": "A videó privát", + "SkipReasonStalled": "A letöltés elakadt — nem érkezett adat", "LogViewer": "Napló Néző", "ExportLogs": "Napló Exportálás", "ClearLogs": "Naplók Törlése", @@ -141,6 +122,10 @@ "OpenYouTube": "YouTube Megnyitása", "OpenYouTubeWith": "Megnyitás ezzel...", "CookieSetupStep3Note": "Megjegyzés: A sütik fogadását követően eltávolíthatod a bővítményt. Ha bejelentkezve újra böngészed a YouTube-ot, a sütik érvényüket veszthetik. A beállítás után fontold meg a YouTube sűtik törlését a böngésződből, vagy hagyd telepítve a bővítményt.", + "PasteCookiesManually": "Sütik beillesztése kézzel", + "SaveCookies": "Sütik mentése", + "ManualCookiesWrongFormat": "Hibás formátum — másold és illeszd be a sütiket pontosan úgy, ahogy a bővítmény adta (Sütik vágólapra másolása).", + "ManualCookiesExpired": "Ezek a sütik lejártak. Jelentkezz be újra a YouTube-ra, és másolj friss sütiket.", "CookieSetupStep4Header": "4. Lépés: localhost.youtube.com (Opcionális)", "CookieSetupStep4Desc": "A localhost.youtube.com bejegyzés hozzáadása a hosts fájlhoz lehetővé teszi a VRCVideoCacher számára, hogy a YouTube domain használatával tárolt videókat szolgáltasson, ami javítja a kompatibilitást a VRChat videolejátszójával.", "CookieSetupStep4Note": "Ehhez rendszergazdai jogosultság szükséges. Ezt a lépést kihagyhatod, és később a Főoldalon konfigurálhatod.", @@ -148,6 +133,23 @@ "CookieSetupCompleteDesc": "YouTube sütik beérkeztek. A bot-felismerési hibák többé nem jelennek meg.", "CookiesReceived": "Sütik megérkeztek!", "WaitingForCookies": "Várakozás a sütikre.", + "CookiesVerifyNow": "Ellenőrzés most", + "CookiesStatusDisabled": "A YouTube sütik le vannak tiltva", + "CookiesStatusVerifying": "Sütik ellenőrzése...", + "CookiesStatusMissing": "Nem található érvényes süti", + "CookiesStatusPresent": "Sütik jelen vannak (még nincsenek ellenőrizve)", + "CookiesStatusWorking": "A sütik működnek a YouTube-bal!", + "CookiesStatusExpired": "Lejárt vagy elutasított YouTube sütik", + "CookiesExpired": "A sütik lejártak", + "CookiesExpireToday": "A sütik ma lejárnak", + "CookiesExpireInDaysFormat": "Lejár {0} nap múlva", + "CookiesRefreshHeader": "Sütik frissítése", + "CookiesHelpLegacy": "A szokásos bővítménnyel a sütik akkor kerülnek elküldésre, amikor megnyitod a YouTube-ot a böngésződben a telepített bővítménnyel. Az alábbiakban kézzel is beillesztheted őket.", + "CookiesHelpBeta": "A \"Friss sütik kérése\" azonnal lekér egy friss készletet — nem kell megnyitnod a bővítményt, sem engedélyezned az automatikus megosztást. Kattinthatsz a bővítmény \"Sütik küldése\" gombjára is, vagy beillesztheted őket alább.", + "UseBetaExtension": "Béta bővítmény használata", + "UseBetaExtensionTooltip": "Csak akkor engedélyezd, ha telepítetted a Béta böngészőbővítményt. Feloldja az alkalmazás által indított azonnali süti-frissítést. A legtöbb felhasználó a szokásos bővítményt használja, és kikapcsolva kell hagynia ezt.", + "CookiesRequestRefresh": "Friss sütik kérése", + "CookiesRequestRefreshTooltip": "Megkéri a bővítményt, hogy azonnal küldjön friss sütiket. Csak annyi kell, hogy a böngésző nyitva legyen a telepített bővítménnyel és bejelentkezve a YouTube-ra — az automatikus megosztásnak nem kell bekapcsolva lennie.", "CookiesDisabledWarning": "A \"YouTube Sütik Használata\" jelenleg ki van kapcsolva. Kérjük, lépj a Beállításokba, és engedélyezd először.", "HostsActive": "localhost.youtube.com aktív", "NotConfigured": "Nincs konfigurálva", @@ -156,7 +158,7 @@ "OpenChromeWebStore": "Chrome Web Áruház Megnyítás", "OpenFirefoxAddons": "Firefox Addonok Megnyítás", "DontShowThisAgain": "Ne mutasd ezt újra", - "TrayShow": "Megjelenítés", + "Show": "Megjelenítés", "TrayOpenCacheFolder": "Gyorsítótár Mappa Megnyitása", "TrayExit": "Kilépés", "TrayMinimizeNotice": "A VRCVideoCacher még mindig fut a háttérben. Kattintson a tálcaikonra az újranyitáshoz.", @@ -166,28 +168,47 @@ "CreatedBy": "Készítette", "ReportAnIssue": "Hiba Jelentése", "OpenIssueOnGitHub": "Nyisd meg a probléma részt a GitHubon", - "JoinOurDiscord": "Csatlakozz a Discordunkhoz, hogy jelentsd a problémákat", "RedownloadUtils": "Segédprogramok Újraletöltése", + "OpenUtilsFolder": "Segédprogramok Mappa Megnyitása", "RedownloadingUtils": "Segédprogramok újraletöltése...", "RedownloadComplete": "A segédprogramok újraletöltése sikeres volt!", "RedownloadFailed": "Az újraletöltés sikertelen. A részletekért ellenőrizd a naplókat.", - "OpenUtilsFolder": "Segédprogramok Mappa Megnyitása", - "SaveCookies": "Sütik mentése", - "PasteCookiesManually": "Sütik beillesztése kézzel", - "ManualCookiesWrongFormat": "Hibás formátum — másold és illeszd be a sütiket pontosan úgy, ahogy a bővítmény adta (Sütik vágólapra másolása).", - "ManualCookiesExpired": "Ezek a sütik lejártak. Jelentkezz be újra a YouTube-ra, és másolj friss sütiket.", - "CookiesVerifyNow": "Ellenőrzés most", - "CookiesStatusDisabled": "A YouTube sütik le vannak tiltva", - "CookiesStatusVerifying": "Sütik ellenőrzése...", - "CookiesStatusMissing": "Nem található érvényes süti", - "CookiesStatusPresent": "Sütik jelen vannak (még nincsenek ellenőrizve)", - "CookiesStatusWorking": "A sütik működnek a YouTube-bal!", - "CookiesStatusExpired": "A sütik lejártak, vagy a YouTube elutasította őket", - "CookiesRefreshHeader": "Sütik frissítése", - "CookiesHelpLegacy": "A szokásos bővítménnyel a sütik akkor kerülnek elküldésre, amikor megnyitod a YouTube-ot a böngésződben a telepített bővítménnyel. Az alábbiakban kézzel is beillesztheted őket.", - "CookiesHelpBeta": "A \"Friss sütik kérése\" azonnal lekér egy friss készletet — nem kell megnyitnod a bővítményt, sem engedélyezned az automatikus megosztást. Kattinthatsz a bővítmény \"Sütik küldése\" gombjára is, vagy beillesztheted őket alább.", - "UseBetaExtension": "Béta bővítmény használata", - "UseBetaExtensionTooltip": "Csak akkor engedélyezd, ha telepítetted a Béta böngészőbővítményt. Feloldja az alkalmazás által indított azonnali süti-frissítést. A legtöbb felhasználó a szokásos bővítményt használja, és kikapcsolva kell hagynia ezt.", - "CookiesRequestRefresh": "Friss sütik kérése", - "CookiesRequestRefreshTooltip": "Megkéri a bővítményt, hogy azonnal küldjön friss sütiket. Csak annyi kell, hogy a böngésző nyitva legyen a telepített bővítménnyel és bejelentkezve a YouTube-ra — az automatikus megosztásnak nem kell bekapcsolva lennie." + "PreCacheVideos": "Előre gyorsítótárazott videók", + "PreCacheVideosHint": "Indításkor letöltött videó URL-ek, ha még nincsenek gyorsítótárazva. Többet is beilleszthet egyszerre, vesszővel, szóközökkel vagy új sorokkal elválasztva.", + "Rules": "Szabályok", + "AddRule": "Szabály hozzáadása", + "RuleName": "Szabály neve", + "RegexPattern": "Regex minta", + "Action": "Művelet", + "RedirectTarget": "Átirányítási cél URL", + "RewriteTarget": "Átirányítási / Átírási cél minta vagy URL", + "Enabled": "Engedélyezve", + "Tools": "Ezközök", + "VideoPlayers": "Videolejátszók", + "Disable": "Letiltás", + "Enable": "Engedélyezés", + "RulesManagedViaRulesTabNote": "A tartomány-gyorsítótárazás, felbontási korlátok, átirányítások és URL-átírások a Szabályok lapon kezelhetők.", + "TestUrlPlaceholder": "Teszt URL...", + "UnsavedRulesMessage": "Mentetlen szabálymódosításai vannak. Szeretné menteni vagy elvetni a módosításokat kilépés előtt?", + "Discard": "Elvetés", + "ResetToDefaults": "Alapértelmezések", + "ConfirmResetDefaultsMessage": "Biztosan visszaállítja az összes szabályt a gyári alapértelmezésekre? Az egyedi szabályok felülíródnak.", + "EditRuleTitle": "Szabály szerkesztése", + "AddRuleTitle": "Szabály hozzáadása", + "PatternCannotBeEmpty": "A minta nem lehet üres.", + "InvalidRegex": "Érvénytelen reguláris kifejezés: {0}", + "UpdateAvailable": "A(z) {0} verzió elérhető!", + "UpdateDownloading": "Frissítés letöltése...", + "UpdateFailed": "A frissítés sikertelen. Ellenőrizd a naplót, és próbáld újra.", + "SkipReasonInvalidDownload": "A letöltött fájl nem ment át az ellenőrzésen", + "SkipReasonTruncated": "A letöltés hiányos volt", + "DownloadTimeRemaining": "{0} van hátra", + "SharedConfigNoticeTitle": "A beállítások mostantól közösek", + "SharedConfigNotice": "A VRCVideoCacherPlusPlus a beállításait ugyanabban a Config.json fájlban tárolja, mint az eredeti VRCVideoCacher, nem külön fájlban.\n\nHa futtatod az eredeti VRCVideoCachert (vagy a Plus verziót), az felülírja ezt a fájlt, és eltávolítja a PlusPlus beállításokat – beleértve az URL-szabályaidat is. Ezek visszaállnának az alapértelmezettre.\n\nHa régebbi PlusPlus verzióról váltasz, a korábbi beállításaid továbbra is megtalálhatók a PlusConfig.json fájlban ugyanabban a mappában. Ezt a fájlt már nem olvassuk be, de a helyén hagyjuk, hogy bármit átmásolhass belőle.", + "SeverSucceeded": "{0} kapcsolat leállítva.", + "SeverNeedsPrivileges": "A gyorsítótárazott videók leálltak. A VRChat közvetlen kapcsolatainak lezárásához rendszergazda/root jogosultság kell, így a már futó stream a végéig játszódik.", + "SeverUnsupported": "Ezen a platformon nem lehet lezárni a VRChat közvetlen kapcsolatait.", + "SeverFailed": "A kapcsolatok lezárása sikertelen. Részletek a naplóban.", + "SeverNothingToDo": "Nincs mit leállítani.", + "AddressCopied": "A cím a vágólapra másolva." } diff --git a/VRCVideoCacher/Languages/it.loc.json b/VRCVideoCacher/Languages/it.loc.json index d7aecd97..5083518c 100755 --- a/VRCVideoCacher/Languages/it.loc.json +++ b/VRCVideoCacher/Languages/it.loc.json @@ -1,41 +1,28 @@ { "Dashboard": "Dashboard", + "NowPlaying": "In riproduzione", + "ActiveConnections": "Connessioni attive", "Settings": "Impostazioni", "CacheBrowser": "Sfoglia Cache", "Downloads": "Download", "History": "Cronologia", "Logs": "Logs", "About": "Informazioni", - "PreCacheVideos": "Video pre-memorizzati", - "PreCacheVideosHint": "URL di video scaricati all'avvio se non già in cache. Puoi incollarne diversi insieme, separati da virgole, spazi o a capo.", - "CookiesExpired": "Cookie di accesso scaduto", - "CookiesExpireToday": "Il cookie di accesso scade oggi", - "CookiesExpireInDaysFormat": "Il cookie di accesso scade tra {0} giorni", - "Stats": "Statistiche", - "CacheHitRate": "Percentuale di hit della cache", - "BandwidthSaved": "Banda risparmiata", - "CacheHits": "Hit della cache", - "TotalPlays": "Riproduzioni totali", - "MostReplayed": "Più riprodotti", - "NoLongerCached": "Non più in cache", - "BytesSavedCaveatFormat": "Esclude {0} hit su video successivamente rimossi dalla cache, quindi il valore reale è superiore.", - "Refresh": "Aggiorna", "Save": "Salva", "Reset": "Ripristina", "Add": "Aggiungi", "Delete": "Elimina", "Cancel": "Annulla", - "Yes": "Sì", + "Yes": "Yes", "No": "No", - "ConfirmClearCacheTitle": "Svuotare la cache?", - "ConfirmClearCacheFormat": "Eliminare tutti i {0} video in cache? Questa azione non può essere annullata.", + "ConfirmClearCacheTitle": "Clear cache?", + "ConfirmClearCacheFormat": "Delete all {0} cached videos? This cannot be undone.", "Back": "Indietro", "Next": "Avanti", "Done": "Fatto", "Language": "Lingua", "General": "Generale", - "ToggleHostTooltip": "Usa il dominio YouTube per la cache di localhost", "ServerStatus": "Stato del Server", "Cache": "Cache", @@ -53,72 +40,61 @@ "Expired": "Scaduti", "Unknown": "Sconosciuto", "ServerRunning": "Server in esecuzione", - "ServerSettings": "Impostazioni Server", "WebServerUrl": "URL Web Server", "DownloadSettings": "Impostazioni Download", "UseYouTubeCookies": "Usa Cookie YouTube (richiede estensione browser)", "AutoUpdateUtils": "Aggiornamento automatico Utility (yt-dlp, FFmpeg e Deno)", "AdditionalYtdlpArgs": "Argomenti aggiuntivi yt-dlp", - "PreferredDubLanguage": "Lingua doppiaggio preferita (es. 'de' per Tedesco)", + "PreferredDubLanguage": "Lingua doppiaggio preferita (es. 'it' per Italiano)", "CacheSettings": "Impostazioni Cache", "CachePathLabel": "Percorso Cache (lascia vuoto per il predefinito)", "MaxCacheSizeLabel": "Dimensione Max Cache in GB (0 = illimitata)", - "CacheYouTubeVideos": "Cache Video YouTube", - "MaxYouTubeResolution": "Risoluzione Max YouTube", - "PreferVp9ForCache": "Preferisci VP9 per i video in cache (MP4)", - "PreferVp9ForCacheTooltip": "Risparmia il 20–50% di spazio per i video YouTube in cache senza perdita di qualità. Funziona su tutte le piattaforme, incluso Quest. Sicuro da abilitare per la maggior parte degli utenti.", + "MaxResolution": "Risoluzione massima", "MaxVideoLength": "Lunghezza Max Video (minuti)", - "CachePyPyDanceVideos": "Cache Video PyPyDance", - "CacheVRDancingVideos": "Cache Video VRDancing", - "CacheHlsPlaylists": "Cache Video HLS (.m3u8 / mpegts)", + "CacheHlsPlaylists": "Cache HLS Videos (.m3u8 / mpegts)", "OnlyServeCachedVideos": "Servi solo video in cache", - "CacheDownloadIdleSeconds": "Sospendi i download in cache durante lo streaming (secondi)", - "CacheDownloadIdleSecondsTooltip": "Sospende i download in cache mentre VRChat richiede attivamente gli URL di stream, e riprende dopo questo numero di secondi di inattività. Imposta a 0 per disattivare. Consigliato: 120–300. Usa il limite di velocità qui sotto per i video lunghi.", - "CacheDownloadRateLimit": "Limite Velocità Download Cache (MB/s)", - "CacheDownloadRateLimitTooltip": "Limita la velocità di download durante la memorizzazione in cache dei video. Utile per evitare che i download in cache occupino tutta la banda. Imposta a 0 per illimitato.", + "CacheDownloadIdleSeconds": "Pause cache downloads while streaming (seconds)", + "CacheDownloadIdleSecondsTooltip": "Pause cache downloads when VRChat is actively requesting stream URLs, and resume after this many seconds of inactivity. Set to 0 to disable. Recommended: 120–300. Use the speed limit below for long videos.", + "CacheDownloadRateLimit": "Cache Download Speed Limit (MB/s)", + "CacheDownloadRateLimitTooltip": "Limit download speed when caching videos. Useful to prevent cache downloads from using all your bandwidth. Set to 0 for unlimited.", "GamePatching": "Patch dei Giochi", "PatchVRChat": "Patch VRChat", "PatchResonite": "Patch Resonite", "CloseToTray": "Riduci nella barra delle applicazioni", "StartMinimized": "Avvia minimizzato", "StartWithSteamVr": "Avvia con SteamVR", - "ErrorPopups": "Popup di errore", - "BlockedUrls": "URL Bloccati", - "BlockedUrlRedirect": "Reindirizzamento URL bloccati", "SettingsSaved": "Impostazioni salvate!", + "SettingsSavedRestartRequired": "Salvato — riavvia VRCVideoCacher per applicare la nuova cartella cache", "SettingsReset": "Impostazioni ripristinate ai valori salvati l'ultima volta.", "SettingsUnsavedChanges": "Hai modifiche non salvate.", - "RedirectVRDancing": "Reindirizza EU VRDancing a NA", - "OpenFolder": "Apri Cartella", "DeleteAllCache": "Elimina tutta la cache", "SearchVideosWatermark": "Cerca video...", "VideosCountFormat": "{0} di {1} video", - "DownloadQueue": "Coda Download", "ClearQueue": "Svuota Coda", "CurrentDownload": "Download in corso", "NoActiveDownload": "Nessun download attivo", "AddManualDownload": "Aggiungi Download Manuale", - "EnterVideoUrl": "Inserisci URL video (separati da virgola, riga o spazio)...", + "EnterVideoUrl": "Inserisci URL video...", "QueuedDownloads": "Download in coda", "QueueIsEmpty": "La coda è vuota", - "DownloadSkipped": "Saltato: {0} — {1}", - "DownloadFailed": "Download non riuscito: {0}", - "DownloadCompleted": "Scaricato: {0}", - "SkipReasonLiveStream": "Il video è una diretta streaming", - "SkipReasonTooLong": "Video troppo lungo ({0}min > limite di {1}min)", - "SkipReasonNoMetadata": "Impossibile recuperare i metadati del video", - "SkipReasonParseFailed": "Impossibile analizzare le informazioni del video", - "SkipReasonUnsupportedUrl": "Tipo di URL non supportato", - "SkipReasonFileExists": "Già in cache", - "SkipReasonFileNotFound": "File scaricato non trovato", - "SkipReasonFormatUnavailable": "Nessuno stream corrispondente al formato/risoluzione configurati", - "SkipReasonBotCheck": "Verifica bot di YouTube — installa l'estensione del browser: github.com/clienthax/VRCVideoCacherBrowserExtension e usa un account YouTube alternativo", - "SkipReasonVideoUnavailable": "Video non disponibile", - "SkipReasonPrivateVideo": "Il video è privato", - + "DownloadSkipped": "Skipped: {0} — {1}", + "DownloadFailed": "Failed to download: {0}", + "DownloadCompleted": "Downloaded: {0}", + "SkipReasonLiveStream": "Video is a live stream", + "SkipReasonTooLong": "Video too long ({0}min > {1}min limit)", + "SkipReasonNoMetadata": "Could not fetch video metadata", + "SkipReasonParseFailed": "Could not parse video info", + "SkipReasonUnsupportedUrl": "Unsupported URL type", + "SkipReasonFileExists": "Already cached", + "SkipReasonFileNotFound": "Downloaded file not found", + "SkipReasonFormatUnavailable": "No matching stream for the configured format/resolution", + "SkipReasonBotCheck": "YouTube bot-check — install the browser extension: github.com/clienthax/VRCVideoCacherBrowserExtension and use an alternative YouTube account", + "SkipReasonVideoUnavailable": "Video unavailable", + "SkipReasonPrivateVideo": "Video is private", + "SkipReasonStalled": "Download bloccato — nessun dato ricevuto", "LogViewer": "Visualizzatore Logs", "ExportLogs": "Esporta Logs", "ClearLogs": "Svuota Logs", @@ -128,9 +104,7 @@ "Warning": "Avviso", "Error": "Errore", "AutoScroll": "Scorrimento automatico", - "EntriesCountFormat": "{0} voci", - "CookieSetupTitle": "Configurazione Estensione Cookie YouTube", "CookieSetupSubtitle": "Risolvi gli errori di rilevamento bot di YouTube", "CookieSetupStep1Header": "Passaggio 1: Seleziona il tuo browser", @@ -145,13 +119,13 @@ "CookieSetupStep2AccountWarning": "Si consiglia di usare un account secondario (burner account).", "CookieSetupStep3Header": "Passaggio 3: Vai su YouTube", "CookieSetupStep3Desc": "Apri YouTube nel tuo browser e assicurati di aver effettuato l'accesso. L'estensione invierà automaticamente i tuoi cookie a VRCVideoCacher.", - "OpenYouTube": "Apri YouTube (browser predefinito)", - "OpenYouTubeWith": "Apri con...", + "OpenYouTube": "Apri YouTube", + "OpenYouTubeWith": "Open with...", "CookieSetupStep3Note": "Nota: Puoi disinstallare l'estensione dopo aver ricevuto i cookie. Se navighi di nuovo su YouTube mentre sei loggato, i cookie potrebbero essere invalidati. Considera di eliminare i cookie di YouTube dal browser dopo la configurazione o mantieni l'estensione installata.", - "PasteCookiesManually": "Incolla i cookie manualmente", - "SaveCookies": "Salva cookie", - "ManualCookiesWrongFormat": "Formato errato — copia e incolla i cookie esattamente come forniti dall'estensione (Copia cookie negli appunti).", - "ManualCookiesExpired": "Questi cookie sono scaduti. Accedi di nuovo a YouTube e copia cookie aggiornati.", + "PasteCookiesManually": "Paste cookies manually", + "SaveCookies": "Save cookies", + "ManualCookiesWrongFormat": "Wrong format — copy and paste the cookies exactly as given by the extension (Copy cookies to clipboard).", + "ManualCookiesExpired": "These cookies are expired. Log in to YouTube again and copy fresh cookies.", "CookieSetupStep4Header": "Passaggio 4: localhost.youtube.com (Opzionale)", "CookieSetupStep4Desc": "Aggiungere una voce al file hosts per localhost.youtube.com permette a VRCVideoCacher di servire i video in cache usando il dominio YouTube, migliorando la compatibilità con il player video di VRChat.", "CookieSetupStep4Note": "Questo richiede permessi di amministratore. Puoi saltare questo passaggio e configurarlo più tardi dalla Dashboard.", @@ -159,45 +133,82 @@ "CookieSetupCompleteDesc": "I cookie di YouTube sono stati ricevuti. Non dovresti più vedere errori di rilevamento bot.", "CookiesReceived": "Cookie ricevuti!", "WaitingForCookies": "In attesa dei cookie...", - "CookiesVerifyNow": "Verifica ora", - "CookiesStatusDisabled": "I cookie di YouTube sono disattivati", - "CookiesStatusVerifying": "Verifica dei cookie in corso...", - "CookiesStatusMissing": "Nessun cookie valido trovato", - "CookiesStatusPresent": "Cookie presenti (non ancora verificati)", - "CookiesStatusWorking": "I cookie funzionano con YouTube!", + "CookiesVerifyNow": "Verify now", + "CookiesStatusDisabled": "YouTube cookies are disabled", + "CookiesStatusVerifying": "Checking cookies...", + "CookiesStatusMissing": "No valid cookies found", + "CookiesStatusPresent": "Cookies present (not yet verified)", + "CookiesStatusWorking": "Cookies are working with YouTube!", "CookiesStatusExpired": "Cookie scaduti o rifiutati da YouTube", - "CookiesRefreshHeader": "Aggiornamento dei cookie", - "CookiesHelpLegacy": "Con l'estensione standard, i cookie vengono inviati quando apri YouTube nel browser con l'estensione installata. Puoi anche incollarli manualmente qui sotto.", - "CookiesHelpBeta": "\"Richiedi cookie aggiornati\" recupera immediatamente un nuovo set — senza bisogno di aprire l'estensione o abilitare la condivisione automatica. Puoi anche cliccare \"Invia cookie\" nell'estensione o incollarli qui sotto.", - "UseBetaExtension": "Usa l'estensione Beta", - "UseBetaExtensionTooltip": "Abilita questa opzione solo se hai installato l'estensione Beta del browser. Sblocca l'aggiornamento istantaneo dei cookie attivato dall'app. La maggior parte degli utenti usa l'estensione standard e dovrebbe lasciarla disattivata.", - "CookiesRequestRefresh": "Richiedi cookie aggiornati", - "CookiesRequestRefreshTooltip": "Chiede all'estensione di inviare immediatamente cookie aggiornati. Il browser deve solo essere aperto con l'estensione installata e con l'accesso a YouTube — la condivisione automatica non deve essere attiva.", - "CookiesDisabledWarning": "\"Usa Cookie YouTube\" è attualmente disattivato. Vai su Impostazioni e abilitalo prima.", + "CookiesExpired": "I cookie sono scaduti", + "CookiesExpireToday": "I cookie scadono oggi", + "CookiesExpireInDaysFormat": "Scade tra {0} giorni", + "CookiesRefreshHeader": "Refreshing cookies", + "CookiesHelpLegacy": "With the standard extension, cookies are sent when you open YouTube in your browser with the extension installed. You can also paste them manually below.", + "CookiesHelpBeta": "\"Request fresh cookies\" pulls a fresh set instantly — no need to open the extension or enable automatic sharing. You can also click \"Send cookies\" in the extension or paste them below.", + "UseBetaExtension": "Use Beta extension", + "UseBetaExtensionTooltip": "Enable this only if you installed the Beta browser extension. It unlocks app-triggered instant cookie refresh. Most users run the standard extension and should leave this off.", + "CookiesRequestRefresh": "Request fresh cookies", + "CookiesRequestRefreshTooltip": "Asks the extension to send fresh cookies immediately. The browser just needs to be open with the extension installed and logged into YouTube — automatic sharing does not need to be on.", + "CookiesDisabledWarning": "\"Use YouTube Cookies\" is currently disabled. Please go to Settings and enable it first.", "HostsActive": "localhost.youtube.com è attivo", "NotConfigured": "Non configurato", "RemoveEntry": "Rimuovi Voce", "AddHostsEntry": "Aggiungi Voce Hosts", "OpenChromeWebStore": "Apri Chrome Web Store", "OpenFirefoxAddons": "Apri Firefox Add-ons", - "DontShowThisAgain": "Non mostrare più questo messaggio", - "TrayShow": "Mostra", + "Show": "Mostra", "TrayOpenCacheFolder": "Apri cartella Cache", "TrayExit": "Esci", - "TrayMinimizeNotice": "VRCVideoCacher è ancora in esecuzione in background. Clicca sull'icona nella barra delle applicazioni per riaprirlo.", - + "TrayMinimizeNotice": "VRCVideoCacher is still running in the background. Click the tray icon to reopen it.", "VRCVideoCacherPlus": "VRCVideoCacherPlus", "Updates": "Aggiornamenti", "AutoUpdateVRCVideoCacher": "Aggiornamento automatico VRCVideoCacher", - "CreatedBy": "Creato da", "ReportAnIssue": "Segnala un problema", "OpenIssueOnGitHub": "Apri una segnalazione su GitHub", - "JoinOurDiscord": "Unisciti al nostro Discord per segnalare un problema", - "RedownloadUtils": "Riscarica Utility", - "OpenUtilsFolder": "Apri cartella Utility", - "RedownloadingUtils": "Riscaricamento delle utility in corso...", - "RedownloadComplete": "Utility riscaricate con successo!", - "RedownloadFailed": "Riscaricamento non riuscito. Controlla i log per i dettagli." + "RedownloadUtils": "Redownload Utils", + "OpenUtilsFolder": "Open Utils Folder", + "RedownloadingUtils": "Redownloading utils...", + "RedownloadComplete": "Utils redownloaded successfully!", + "RedownloadFailed": "Redownload failed. Check logs for details.", + "PreCacheVideos": "Video pre-memorizzati nella cache", + "PreCacheVideosHint": "URL video scaricati all’avvio se non già memorizzati nella cache. Puoi incollarne diversi contemporaneamente, separati da virgole, spazi o nuove righe.", + "Rules": "Regole", + "AddRule": "Aggiungi regola", + "RuleName": "Nome regola", + "RegexPattern": "Pattern Regex", + "Action": "Azione", + "RedirectTarget": "URL di reindirizzamento di destinazione", + "RewriteTarget": "Pattern di riscrittura / URL di destinazione", + "Enabled": "Abilitato", + "Tools": "Strumenti", + "VideoPlayers": "Lettori video", + "Disable": "Disattiva", + "Enable": "Attiva", + "RulesManagedViaRulesTabNote": "La memorizzazione nella cache dei domini, i limiti di risoluzione, i reindirizzamenti e le riscritture sono gestiti tramite la scheda Regole.", + "TestUrlPlaceholder": "URL di prova...", + "UnsavedRulesMessage": "Hai modifiche non salvate nelle tue regole. Vuoi salvare o scartare le modifiche prima di uscire?", + "Discard": "Scarta", + "ResetToDefaults": "Impostazioni predefinite", + "ConfirmResetDefaultsMessage": "Sei sicuro di voler ripristinare tutte le regole ai valori predefiniti di fabbrica? Le regole personalizzate verranno sostituite.", + "EditRuleTitle": "Modifica regola", + "AddRuleTitle": "Aggiungi regola", + "PatternCannotBeEmpty": "Il pattern non può essere vuoto.", + "InvalidRegex": "Regex non valida: {0}", + "UpdateAvailable": "La versione {0} è disponibile!", + "UpdateDownloading": "Download dell'aggiornamento...", + "UpdateFailed": "Aggiornamento non riuscito. Controlla i log e riprova.", + "SkipReasonInvalidDownload": "Il file scaricato non ha superato la validazione", + "SkipReasonTruncated": "Il download è incompleto", + "DownloadTimeRemaining": "{0} rimanenti", + "SharedConfigNoticeTitle": "Le impostazioni sono ora condivise", + "SharedConfigNotice": "VRCVideoCacherPlusPlus salva le impostazioni nello stesso Config.json del VRCVideoCacher originale, invece che in un file separato.\n\nSe esegui il VRCVideoCacher originale (o la versione Plus), riscriverà quel file eliminando le impostazioni PlusPlus, incluse le tue regole URL, che torneranno ai valori predefiniti.\n\nSe arrivi da una versione PlusPlus precedente, le tue impostazioni sono ancora in PlusConfig.json nella stessa cartella. Quel file non viene più letto, ma resta al suo posto per poterne recuperare ciò che vuoi.", + "SeverSucceeded": "Interrotte {0} connessioni.", + "SeverNeedsPrivileges": "I video in cache sono stati fermati. Chiudere le connessioni dirette di VRChat richiede privilegi di amministratore/root, quindi un video già in streaming continuerà fino alla fine.", + "SeverUnsupported": "Questa piattaforma non permette di chiudere le connessioni dirette di VRChat.", + "SeverFailed": "Impossibile chiudere le connessioni. Consulta il log.", + "SeverNothingToDo": "Niente da interrompere.", + "AddressCopied": "Indirizzo copiato negli appunti." } diff --git a/VRCVideoCacher/Languages/ja.loc.json b/VRCVideoCacher/Languages/ja.loc.json old mode 100755 new mode 100644 index f05eea89..c8033863 --- a/VRCVideoCacher/Languages/ja.loc.json +++ b/VRCVideoCacher/Languages/ja.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "ダッシュボード", + "NowPlaying": "再生中", + "ActiveConnections": "アクティブな接続", "Settings": "設定", "CacheBrowser": "キャッシュブラウザー", "Downloads": "ダウンロード", "History": "履歴", "Logs": "ログ", "About": "バージョン情報", - "PreCacheVideos": "事前キャッシュする動画", - "PreCacheVideosHint": "未キャッシュの場合、起動時にダウンロードする動画URL。 カンマ・スペース・改行で区切って複数まとめて貼り付けできます。", - "CookiesExpired": "ログインCookieの有効期限が切れました", - "CookiesExpireToday": "ログインCookieは本日期限切れになります", - "CookiesExpireInDaysFormat": "ログインCookieは {0} 日後に期限切れになります", - "Stats": "統計", - "CacheHitRate": "キャッシュヒット率", - "BandwidthSaved": "節約した通信量", - "CacheHits": "キャッシュヒット数", - "TotalPlays": "総再生回数", - "MostReplayed": "再生回数の多い動画", - "NoLongerCached": "キャッシュにありません", - "BytesSavedCaveatFormat": "キャッシュから削除された動画への {0} 回のヒットは含まれていないため、実際の値はこれより大きくなります。", "Refresh": "更新", "Save": "保存", "Reset": "リセット", @@ -61,13 +50,8 @@ "CacheSettings": "キャッシュの設定", "CachePathLabel": "キャッシュのパス (空白で既定を使用)", "MaxCacheSizeLabel": "キャッシュの最大サイズ (GB 単位、0 = 無制限)", - "CacheYouTubeVideos": "YouTube の動画をキャッシュする", - "MaxYouTubeResolution": "YouTube の最大解像度", - "PreferVp9ForCache": "キャッシュ動画にVP9を優先する (MP4)", - "PreferVp9ForCacheTooltip": "画質を落とさずにキャッシュされたYouTube動画のストレージを20〜50%節約できます。Questを含む全プラットフォームで動作します。ほとんどのユーザーは有効にして問題ありません。", + "MaxResolution": "最大解像度", "MaxVideoLength": "最大の動画の長さ (分単位)", - "CachePyPyDanceVideos": "PyPyDance の動画をキャッシュする", - "CacheVRDancingVideos": "VRDancing の動画をキャッシュする", "CacheHlsPlaylists": "HLS 動画をキャッシュする (.m3u8 / mpegts)", "OnlyServeCachedVideos": "キャッシュされた動画のみを配信する", "CacheDownloadIdleSeconds": "ストリーミング中はキャッシュダウンロードを一時停止(秒)", @@ -80,13 +64,10 @@ "CloseToTray": "タスクトレイに収納する", "StartMinimized": "最小化して起動する", "StartWithSteamVr": "SteamVR と同時に起動する", - "ErrorPopups": "エラーポップアップ", - "BlockedUrls": "ブロックする URL", - "BlockedUrlRedirect": "ブロックした URL のリダイレクト", "SettingsSaved": "設定を保存しました!", + "SettingsSavedRestartRequired": "保存しました — 新しいキャッシュフォルダーを適用するには VRCVideoCacher を再起動してください", "SettingsReset": "設定は最後に保存された値にリセットされます。", "SettingsUnsavedChanges": "保存していない変更があります。", - "RedirectVRDancing": "EU の VRDancing を NA にリダイレクト", "OpenFolder": "フォルダーを開く", "DeleteAllCache": "すべてのキャッシュを削除", "SearchVideosWatermark": "動画を検索...", @@ -113,6 +94,7 @@ "SkipReasonBotCheck": "YouTubeのBot確認 — 拡張機能をインストールしてください: github.com/clienthax/VRCVideoCacherBrowserExtension また、別のYouTubeアカウントを使用してください", "SkipReasonVideoUnavailable": "動画は利用できません", "SkipReasonPrivateVideo": "非公開動画です", + "SkipReasonStalled": "ダウンロードが停止しました — データを受信できません", "LogViewer": "ログビューアー", "ExportLogs": "ログをエクスポート", "ClearLogs": "ログを消去", @@ -140,6 +122,10 @@ "OpenYouTube": "YouTube を開く", "OpenYouTubeWith": "次で開く...", "CookieSetupStep3Note": "注意: Cookie を受信後は、拡張機能をアンインストールできます。ただし、ログインした状態で YouTube を再度閲覧すると Cookie が無効になる可能性があります。設定後にブラウザーから YouTube の Cookie を削除するか、拡張機能をインストールしたままにすることをご検討ください。", + "PasteCookiesManually": "Cookie を手動で貼り付け", + "SaveCookies": "Cookie を保存", + "ManualCookiesWrongFormat": "形式が正しくありません — 拡張機能から提供されたとおりに Cookie をコピーして貼り付けてください(Cookie をクリップボードにコピー)。", + "ManualCookiesExpired": "この Cookie は期限切れです。YouTube に再度ログインして、新しい Cookie をコピーしてください。", "CookieSetupStep4Header": "ステップ 4: localhost.youtube.com (任意)", "CookieSetupStep4Desc": "hosts エントリに localhost.youtube.com を追加すると、VRCVideoCacher は YouTube ドメインを使用してキャッシュされた動画を提供できるようになり、VRChat の動画プレーヤーとの互換性が向上します。", "CookieSetupStep4Note": "この機能は管理者権限が必要です。この手順をスキップして、後でダッシュボードから設定することもできます。", @@ -147,6 +133,23 @@ "CookieSetupCompleteDesc": "YouTube の Cookie を受信しました。ボット検出によるエラーは表示されなくなります。", "CookiesReceived": "Cookie を受信しました!", "WaitingForCookies": "Cookie を待機中...", + "CookiesVerifyNow": "今すぐ確認", + "CookiesStatusDisabled": "YouTube の Cookie は無効です", + "CookiesStatusVerifying": "Cookie を確認中...", + "CookiesStatusMissing": "有効な Cookie が見つかりません", + "CookiesStatusPresent": "Cookie あり(未検証)", + "CookiesStatusWorking": "Cookie は YouTube で正常に動作しています!", + "CookiesStatusExpired": "YouTubeクッキーの期限が切れているか、拒否されました", + "CookiesExpired": "クッキーの期限が切れています", + "CookiesExpireToday": "クッキーの期限は本日までです", + "CookiesExpireInDaysFormat": "あと {0} 日で期限切れ", + "CookiesRefreshHeader": "Cookie の更新", + "CookiesHelpLegacy": "標準の拡張機能では、拡張機能をインストールしたブラウザーで YouTube を開くと Cookie が送信されます。以下に手動で貼り付けることもできます。", + "CookiesHelpBeta": "\"新しい Cookie をリクエスト\" を押すと、新しい Cookie をすぐに取得できます — 拡張機能を開いたり自動共有を有効にする必要はありません。拡張機能の\"Cookie を送信\"をクリックするか、以下に貼り付けることもできます。", + "UseBetaExtension": "ベータ版拡張機能を使用", + "UseBetaExtensionTooltip": "ベータ版のブラウザー拡張機能をインストールした場合のみ有効にしてください。アプリからの即時 Cookie 更新が使えるようになります。ほとんどのユーザーは標準の拡張機能を使用しており、これはオフのままにしてください。", + "CookiesRequestRefresh": "新しい Cookie をリクエスト", + "CookiesRequestRefreshTooltip": "拡張機能に新しい Cookie をすぐに送信するよう依頼します。拡張機能をインストールして YouTube にログインした状態でブラウザーを開いておくだけでよく — 自動共有を有効にする必要はありません。", "CookiesDisabledWarning": "「YouTube の Cookie を使用する」が現在無効になっています。設定に移動して、まず有効にしてください。", "HostsActive": "localhost.youtube.com は有効です", "NotConfigured": "未構成", @@ -155,7 +158,7 @@ "OpenChromeWebStore": "Chrome ウェブストアを開く", "OpenFirefoxAddons": "Firefox Add-ons を開く", "DontShowThisAgain": "今後表示しない", - "TrayShow": "表示", + "Show": "表示", "TrayOpenCacheFolder": "キャッシュフォルダーを開く", "TrayExit": "終了", "TrayMinimizeNotice": "VRCVideoCacher はバックグラウンドで引き続き実行されています。タスクトレイのアイコンをクリックして再度表示してください。", @@ -165,28 +168,47 @@ "CreatedBy": "開発者:", "ReportAnIssue": "問題を報告", "OpenIssueOnGitHub": "GitHub の Issue を開く", - "JoinOurDiscord": "Discord に参加して問題を報告", "RedownloadUtils": "ユーティリティを再ダウンロード", + "OpenUtilsFolder": "ユーティリティフォルダーを開く", "RedownloadingUtils": "ユーティリティを再ダウンロード中...", "RedownloadComplete": "ユーティリティの再ダウンロードが完了しました!", "RedownloadFailed": "再ダウンロードに失敗しました。詳細はログを確認してください。", - "OpenUtilsFolder": "ユーティリティフォルダーを開く", - "SaveCookies": "Cookie を保存", - "PasteCookiesManually": "Cookie を手動で貼り付け", - "ManualCookiesWrongFormat": "形式が正しくありません — 拡張機能から提供されたとおりに Cookie をコピーして貼り付けてください(Cookie をクリップボードにコピー)。", - "ManualCookiesExpired": "この Cookie は期限切れです。YouTube に再度ログインして、新しい Cookie をコピーしてください。", - "CookiesVerifyNow": "今すぐ確認", - "CookiesStatusDisabled": "YouTube の Cookie は無効です", - "CookiesStatusVerifying": "Cookie を確認中...", - "CookiesStatusMissing": "有効な Cookie が見つかりません", - "CookiesStatusPresent": "Cookie あり(未検証)", - "CookiesStatusWorking": "Cookie は YouTube で正常に動作しています!", - "CookiesStatusExpired": "Cookie が期限切れ、または YouTube に拒否されました", - "CookiesRefreshHeader": "Cookie の更新", - "CookiesHelpLegacy": "標準の拡張機能では、拡張機能をインストールしたブラウザーで YouTube を開くと Cookie が送信されます。以下に手動で貼り付けることもできます。", - "CookiesHelpBeta": "\"新しい Cookie をリクエスト\" を押すと、新しい Cookie をすぐに取得できます — 拡張機能を開いたり自動共有を有効にする必要はありません。拡張機能の\"Cookie を送信\"をクリックするか、以下に貼り付けることもできます。", - "UseBetaExtension": "ベータ版拡張機能を使用", - "UseBetaExtensionTooltip": "ベータ版のブラウザー拡張機能をインストールした場合のみ有効にしてください。アプリからの即時 Cookie 更新が使えるようになります。ほとんどのユーザーは標準の拡張機能を使用しており、これはオフのままにしてください。", - "CookiesRequestRefresh": "新しい Cookie をリクエスト", - "CookiesRequestRefreshTooltip": "拡張機能に新しい Cookie をすぐに送信するよう依頼します。拡張機能をインストールして YouTube にログインした状態でブラウザーを開いておくだけでよく — 自動共有を有効にする必要はありません。" + "PreCacheVideos": "事前キャッシュ動画", + "PreCacheVideosHint": "まだキャッシュされていない場合、起動時にダウンロードされる動画URL。カンマ、スペース、改行で区切って複数同時に貼り付けることができます。", + "Rules": "ルール", + "AddRule": "ルールを追加", + "RuleName": "ルール名", + "RegexPattern": "正規表現パターン", + "Action": "アクション", + "RedirectTarget": "リダイレクト先URL", + "RewriteTarget": "書き換え先のパターン / URL", + "Enabled": "有効", + "Tools": "ツール", + "VideoPlayers": "動画プレイヤー", + "Disable": "無効化", + "Enable": "有効化", + "RulesManagedViaRulesTabNote": "ドメインキャッシュ、解像度上限、リダイレクト、URL書き換えは「ルール」タブで管理されます。", + "TestUrlPlaceholder": "テストURL...", + "UnsavedRulesMessage": "保存されていないルールの変更があります。離れる前に変更を保存または破棄しますか?", + "Discard": "破棄", + "ResetToDefaults": "デフォルト", + "ConfirmResetDefaultsMessage": "すべてのルールを工場出荷時のデフォルトにリセットしますか?カスタムルールは上書きされます。", + "EditRuleTitle": "ルールを編集", + "AddRuleTitle": "ルールを追加", + "PatternCannotBeEmpty": "パターンを空にはできません。", + "InvalidRegex": "正規表現が無効です: {0}", + "UpdateAvailable": "バージョン {0} が利用可能です!", + "UpdateDownloading": "更新をダウンロード中...", + "UpdateFailed": "更新に失敗しました。ログを確認して再試行してください。", + "SkipReasonInvalidDownload": "ダウンロードしたファイルの検証に失敗しました", + "SkipReasonTruncated": "ダウンロードが不完全でした", + "DownloadTimeRemaining": "残り {0}", + "SharedConfigNoticeTitle": "設定が共有されるようになりました", + "SharedConfigNotice": "VRCVideoCacherPlusPlus は、専用ファイルではなくオリジナルの VRCVideoCacher と同じ Config.json に設定を保存します。\n\nオリジナルの VRCVideoCacher(または Plus 版)を実行すると、そのファイルが書き換えられ、URL ルールを含む PlusPlus の設定が削除され、既定値に戻ります。\n\n以前の PlusPlus からの移行であれば、以前の設定は同じフォルダーの PlusConfig.json に残っています。このファイルはもう読み込まれませんが、必要な内容を取り出せるようそのまま残してあります。", + "SeverSucceeded": "{0} 件の接続を停止しました。", + "SeverNeedsPrivileges": "キャッシュ済み動画は停止しました。VRChat の直接接続を切断するには管理者/root 権限が必要なため、再生中のストリームは最後まで続きます。", + "SeverUnsupported": "このプラットフォームでは VRChat の直接接続を切断できません。", + "SeverFailed": "接続の切断に失敗しました。詳細はログを確認してください。", + "SeverNothingToDo": "停止する対象がありません。", + "AddressCopied": "アドレスをクリップボードにコピーしました。" } diff --git a/VRCVideoCacher/Languages/ko.loc.json b/VRCVideoCacher/Languages/ko.loc.json old mode 100755 new mode 100644 index 780c60b2..2d2b0c2c --- a/VRCVideoCacher/Languages/ko.loc.json +++ b/VRCVideoCacher/Languages/ko.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "대시보드", + "NowPlaying": "현재 재생 중", + "ActiveConnections": "활성 연결", "Settings": "설정", "CacheBrowser": "캐시 브라우저", "Downloads": "다운로드", "History": "기록", "Logs": "로그", "About": "정보", - "PreCacheVideos": "미리 캐시할 동영상", - "PreCacheVideosHint": "캐시에 없으면 시작할 때 다운로드할 동영상 URL입니다. 쉼표, 공백 또는 줄바꿈으로 구분해 여러 개를 한 번에 붙여넣을 수 있습니다.", - "CookiesExpired": "로그인 쿠키가 만료되었습니다", - "CookiesExpireToday": "로그인 쿠키가 오늘 만료됩니다", - "CookiesExpireInDaysFormat": "로그인 쿠키가 {0}일 후 만료됩니다", - "Stats": "통계", - "CacheHitRate": "캐시 적중률", - "BandwidthSaved": "절약한 대역폭", - "CacheHits": "캐시 적중", - "TotalPlays": "총 재생 수", - "MostReplayed": "가장 많이 재생됨", - "NoLongerCached": "캐시에 없음", - "BytesSavedCaveatFormat": "캐시에서 삭제된 동영상의 적중 {0}회는 제외되어 실제 값은 더 높습니다.", "Refresh": "새로고침", "Save": "저장", "Reset": "재설정", @@ -61,13 +50,8 @@ "CacheSettings": "캐시 설정", "CachePathLabel": "캐시 경로 (비워두면 기본값 사용)", "MaxCacheSizeLabel": "최대 캐시 크기 (단위: GB, 0 = 무제한)", - "CacheYouTubeVideos": "YouTube 동영상 캐시", - "MaxYouTubeResolution": "YouTube 최대 해상도", - "PreferVp9ForCache": "캐시 동영상에 VP9 우선 사용 (MP4)", - "PreferVp9ForCacheTooltip": "화질 저하 없이 캐시된 YouTube 동영상 저장 공간을 20~50% 절약합니다. Quest를 포함한 모든 플랫폼에서 작동합니다. 대부분의 사용자에게 안전하게 활성화할 수 있습니다.", + "MaxResolution": "최대 해상도", "MaxVideoLength": "최대 영상 길이 (분)", - "CachePyPyDanceVideos": "PyPyDance 동영상 캐시", - "CacheVRDancingVideos": "VRDancing 동영상 캐시", "CacheHlsPlaylists": "HLS 동영상 캐시 (.m3u8 / mpegts)", "OnlyServeCachedVideos": "캐시된 동영상만 제공", "CacheDownloadIdleSeconds": "스트리밍 중 캐시 다운로드 일시정지 (초)", @@ -80,13 +64,10 @@ "CloseToTray": "닫을 때 트레이로 최소화", "StartMinimized": "최소화된 상태로 시작", "StartWithSteamVr": "SteamVR로 앱 실행", - "ErrorPopups": "오류 팝업", - "BlockedUrls": "차단된 URL", - "BlockedUrlRedirect": "차단된 URL 리디렉션", "SettingsSaved": "설정이 저장되었습니다!", + "SettingsSavedRestartRequired": "저장됨 — 새 캐시 폴더를 적용하려면 VRCVideoCacher를 다시 시작하세요", "SettingsReset": "설정이 마지막 저장된 상태로 재설정되었습니다.", "SettingsUnsavedChanges": "저장되지 않은 변경 사항이 있습니다.", - "RedirectVRDancing": "EU VRDancing을 NA로 리디렉션", "OpenFolder": "폴더 열기", "DeleteAllCache": "모든 캐시 삭제", "SearchVideosWatermark": "동영상 검색...", @@ -113,6 +94,7 @@ "SkipReasonBotCheck": "YouTube 봇 확인 — 브라우저 확장 프로그램을 설치하세요: github.com/clienthax/VRCVideoCacherBrowserExtension 그리고 대체 YouTube 계정을 사용하세요", "SkipReasonVideoUnavailable": "동영상을 사용할 수 없습니다", "SkipReasonPrivateVideo": "비공개 동영상입니다", + "SkipReasonStalled": "다운로드가 중단됨 — 데이터를 수신하지 못했습니다", "LogViewer": "로그 뷰어", "ExportLogs": "로그 내보내기", "ClearLogs": "로그 지우기", @@ -140,6 +122,10 @@ "OpenYouTube": "YouTube 열기", "OpenYouTubeWith": "다음으로 열기...", "CookieSetupStep3Note": "안내: 쿠키를 가져온 후에 확장을 제거할 수 있습니다. 로그인된 상태로 YouTube를 이용하면 쿠키가 무효화될 수 있습니다. 설정 후 브라우저에서 YouTube 쿠키를 삭제하거나 확장을 설치된 상태로 두세요.", + "PasteCookiesManually": "쿠키 수동 붙여넣기", + "SaveCookies": "쿠키 저장", + "ManualCookiesWrongFormat": "형식이 잘못됨 — 확장 프로그램이 제공한 그대로 쿠키를 복사하여 붙여넣으세요 (쿠키를 클립보드에 복사).", + "ManualCookiesExpired": "이 쿠키는 만료되었습니다. YouTube에 다시 로그인하여 새 쿠키를 복사하세요.", "CookieSetupStep4Header": "4단계: localhost.youtube.com (선택)", "CookieSetupStep4Desc": "hosts 파일에 localhost.youtube.com 항목을 추가하면 VRCVideoCacher가 YouTube 도메인을 통해 캐시된 동영상을 제공할 수 있어 VRChat의 동영상 플레이어와의 호환성이 개선됩니다.", "CookieSetupStep4Note": "이 작업엔 관리자 권한이 필요합니다. 이 단계를 건너뛰고 나중에 대시보드에서 설정할 수 있습니다.", @@ -147,6 +133,23 @@ "CookieSetupCompleteDesc": "YouTube 쿠키를 가져왔습니다. 봇 감지 오류가 더 이상 표시되지 않을 것입니다.", "CookiesReceived": "쿠기를 가져왔습니다!", "WaitingForCookies": "쿠키를 기다리는 중...", + "CookiesVerifyNow": "지금 확인", + "CookiesStatusDisabled": "YouTube 쿠키가 비활성화되었습니다", + "CookiesStatusVerifying": "쿠키 확인 중...", + "CookiesStatusMissing": "유효한 쿠키를 찾을 수 없음", + "CookiesStatusPresent": "쿠키 있음 (아직 검증되지 않음)", + "CookiesStatusWorking": "쿠키가 YouTube에서 정상 작동 중입니다!", + "CookiesStatusExpired": "YouTube 쿠키가 만료되었거나 거부되었습니다", + "CookiesExpired": "쿠키가 만료되었습니다", + "CookiesExpireToday": "쿠키가 오늘 만료됩니다", + "CookiesExpireInDaysFormat": "{0}일 후 만료", + "CookiesRefreshHeader": "쿠키 새로고침", + "CookiesHelpLegacy": "기본 확장 프로그램을 사용하면 확장이 설치된 브라우저에서 YouTube를 열 때 쿠키가 전송됩니다. 아래에서 수동으로 붙여넣을 수도 있습니다.", + "CookiesHelpBeta": "\"새 쿠키 요청\"을 누르면 새 쿠키를 즉시 가져옵니다 — 확장을 열거나 자동 공유를 켜지 않아도 됩니다. 확장의 \"쿠키 보내기\"를 클릭하거나 아래에 붙여넣을 수도 있습니다.", + "UseBetaExtension": "베타 확장 사용", + "UseBetaExtensionTooltip": "베타 브라우저 확장을 설치한 경우에만 활성화하세요. 앱이 트리거하는 즉시 쿠키 새로고침을 사용할 수 있게 됩니다. 대부분의 사용자는 기본 확장을 사용하므로 꿔두지 않는 것이 좋습니다.", + "CookiesRequestRefresh": "새 쿠키 요청", + "CookiesRequestRefreshTooltip": "확장에 새 쿠키를 즉시 보내도록 요청합니다. 확장이 설치되고 YouTube에 로그인된 상태로 브라우저를 열어두기만 하면 됩니다 — 자동 공유를 켜지 않아도 됩니다.", "CookiesDisabledWarning": "\"YouTube 쿠키 사용\"이 현재 비활성화되어 있습니다. 설정으로 이동하여 먼저 활성화해 주세요.", "HostsActive": "localhost.youtube.com이 활성 상태입니다", "NotConfigured": "설정되지 않음", @@ -155,7 +158,7 @@ "OpenChromeWebStore": "Chrome 웹 스토어 열기", "OpenFirefoxAddons": "Firefox용 부가 기능 열기", "DontShowThisAgain": "다시 보지 않기", - "TrayShow": "표시", + "Show": "표시", "TrayOpenCacheFolder": "캐시 폴더 열기", "TrayExit": "종료", "TrayMinimizeNotice": "VRCVideoCacher가 백그라운드에서 계속 실행 중입니다. 트레이 아이콘을 클릭하여 다시 여세요.", @@ -165,28 +168,47 @@ "CreatedBy": "제작자: ", "ReportAnIssue": "문제 보고", "OpenIssueOnGitHub": "GitHub에서 Issue 열기", - "JoinOurDiscord": "Discord 서버에 참여하고 문제 보고하기", "RedownloadUtils": "유틸리티 다시 다운로드", + "OpenUtilsFolder": "유틸리티 폴더 열기", "RedownloadingUtils": "유틸리티 다시 다운로드 중...", "RedownloadComplete": "유틸리티를 성공적으로 다시 다운로드했습니다!", "RedownloadFailed": "다시 다운로드에 실패했습니다. 자세한 내용은 로그를 확인하세요.", - "OpenUtilsFolder": "유틸리티 폴더 열기", - "SaveCookies": "쿠키 저장", - "PasteCookiesManually": "쿠키 수동 붙여넣기", - "ManualCookiesWrongFormat": "형식이 잘못됨 — 확장 프로그램이 제공한 그대로 쿠키를 복사하여 붙여넣으세요 (쿠키를 클립보드에 복사).", - "ManualCookiesExpired": "이 쿠키는 만료되었습니다. YouTube에 다시 로그인하여 새 쿠키를 복사하세요.", - "CookiesVerifyNow": "지금 확인", - "CookiesStatusDisabled": "YouTube 쿠키가 비활성화되었습니다", - "CookiesStatusVerifying": "쿠키 확인 중...", - "CookiesStatusMissing": "유효한 쿠키를 찾을 수 없음", - "CookiesStatusPresent": "쿠키 있음 (아직 검증되지 않음)", - "CookiesStatusWorking": "쿠키가 YouTube에서 정상 작동 중입니다!", - "CookiesStatusExpired": "쿠키가 만료되었거나 YouTube에서 거부됨", - "CookiesRefreshHeader": "쿠키 새로고침", - "CookiesHelpLegacy": "기본 확장 프로그램을 사용하면 확장이 설치된 브라우저에서 YouTube를 열 때 쿠키가 전송됩니다. 아래에서 수동으로 붙여넣을 수도 있습니다.", - "CookiesHelpBeta": "\"새 쿠키 요청\"을 누르면 새 쿠키를 즉시 가져옵니다 — 확장을 열거나 자동 공유를 켜지 않아도 됩니다. 확장의 \"쿠키 보내기\"를 클릭하거나 아래에 붙여넣을 수도 있습니다.", - "UseBetaExtension": "베타 확장 사용", - "UseBetaExtensionTooltip": "베타 브라우저 확장을 설치한 경우에만 활성화하세요. 앱이 트리거하는 즉시 쿠키 새로고침을 사용할 수 있게 됩니다. 대부분의 사용자는 기본 확장을 사용하므로 꿔두지 않는 것이 좋습니다.", - "CookiesRequestRefresh": "새 쿠키 요청", - "CookiesRequestRefreshTooltip": "확장에 새 쿠키를 즉시 보내도록 요청합니다. 확장이 설치되고 YouTube에 로그인된 상태로 브라우저를 열어두기만 하면 됩니다 — 자동 공유를 켜지 않아도 됩니다." + "PreCacheVideos": "사전 캐시된 비디오", + "PreCacheVideosHint": "캐시되지 않은 경우 시작 시 다운로드되는 비디오 URL입니다. 쉼표, 공백 또는 줄바꿈으로 구분하여 여러 개를 한 번에 붙여넣을 수 있습니다.", + "Rules": "규칙", + "AddRule": "규칙 추가", + "RuleName": "규칙 이름", + "RegexPattern": "정규식 패턴", + "Action": "동작", + "RedirectTarget": "리디렉션 대상 URL", + "RewriteTarget": "대상 재작성 패턴 / URL", + "Enabled": "활성화됨", + "Tools": "도구", + "VideoPlayers": "비디오 플레이어", + "Disable": "비활성화", + "Enable": "활성화", + "RulesManagedViaRulesTabNote": "도메인 캐싱, 해상도 제한, 리디렉션 및 URL 재작성은 규칙 탭에서 관리됩니다.", + "TestUrlPlaceholder": "테스트 URL...", + "UnsavedRulesMessage": "저장되지 않은 규칙 변경 사항이 있습니다. 나가기 전에 변경 사항을 저장하거나 취소하시겠습니까?", + "Discard": "취소", + "ResetToDefaults": "기본값", + "ConfirmResetDefaultsMessage": "모든 규칙을 공장 기본값으로 재설정하시겠습니까? 사용자 지정 규칙이 대체됩니다.", + "EditRuleTitle": "규칙 편집", + "AddRuleTitle": "규칙 추가", + "PatternCannotBeEmpty": "패턴은 비워 둘 수 없습니다.", + "InvalidRegex": "잘못된 정규식: {0}", + "UpdateAvailable": "버전 {0}을(를) 사용할 수 있습니다!", + "UpdateDownloading": "업데이트 다운로드 중...", + "UpdateFailed": "업데이트에 실패했습니다. 로그를 확인한 후 다시 시도하세요.", + "SkipReasonInvalidDownload": "다운로드한 파일이 검증에 실패했습니다", + "SkipReasonTruncated": "다운로드가 완료되지 않았습니다", + "DownloadTimeRemaining": "{0} 남음", + "SharedConfigNoticeTitle": "설정이 이제 공유됩니다", + "SharedConfigNotice": "VRCVideoCacherPlusPlus는 별도 파일 대신 원본 VRCVideoCacher와 동일한 Config.json에 설정을 저장합니다.\n\n원본 VRCVideoCacher(또는 Plus 버전)를 실행하면 해당 파일을 덮어써서 URL 규칙을 포함한 PlusPlus 설정이 제거되고 기본값으로 돌아갑니다.\n\n이전 PlusPlus 버전에서 넘어왔다면 이전 설정은 같은 폴더의 PlusConfig.json에 그대로 있습니다. 이 파일은 더 이상 읽지 않지만, 필요한 내용을 옮길 수 있도록 남겨 둡니다.", + "SeverSucceeded": "{0}개의 연결을 중지했습니다.", + "SeverNeedsPrivileges": "캐시된 영상은 중지되었습니다. VRChat의 직접 연결을 끊으려면 관리자/root 권한이 필요하므로 이미 재생 중인 스트림은 끝까지 계속됩니다.", + "SeverUnsupported": "이 플랫폼에서는 VRChat의 직접 연결을 끊을 수 없습니다.", + "SeverFailed": "연결을 끊지 못했습니다. 자세한 내용은 로그를 확인하세요.", + "SeverNothingToDo": "중지할 항목이 없습니다.", + "AddressCopied": "주소를 클립보드에 복사했습니다." } diff --git a/VRCVideoCacher/Languages/pt.loc.json b/VRCVideoCacher/Languages/pt.loc.json old mode 100755 new mode 100644 index aed516bc..03acef06 --- a/VRCVideoCacher/Languages/pt.loc.json +++ b/VRCVideoCacher/Languages/pt.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "Painel", + "NowPlaying": "Reproduzindo agora", + "ActiveConnections": "Conexões ativas", "Settings": "Preferências", "CacheBrowser": "Navegador em Cachê", "Downloads": "Transferências", "History": "Histórico", "Logs": "Registros", "About": "Sobre", - "PreCacheVideos": "Vídeos pré-armazenados", - "PreCacheVideosHint": "URLs de vídeos baixados na inicialização se ainda não estiverem em cache. Você pode colar vários de uma vez, separados por vírgulas, espaços ou quebras de linha.", - "CookiesExpired": "Cookie de login expirado", - "CookiesExpireToday": "O cookie de login expira hoje", - "CookiesExpireInDaysFormat": "O cookie de login expira em {0} dias", - "Stats": "Estatísticas", - "CacheHitRate": "Taxa de acerto do cache", - "BandwidthSaved": "Banda economizada", - "CacheHits": "Acertos de cache", - "TotalPlays": "Reproduções totais", - "MostReplayed": "Mais reproduzidos", - "NoLongerCached": "Não está mais em cache", - "BytesSavedCaveatFormat": "Exclui {0} acertos em vídeos removidos do cache desde então, portanto o valor real é maior.", "Refresh": "Atualizar", "Save": "Salvar", "Reset": "Redefinir", @@ -61,13 +50,8 @@ "CacheSettings": "Preferências de cachê", "CachePathLabel": "Diretório do cachê (deixe em branco para padrão)", "MaxCacheSizeLabel": "Tamanho máximo de cachê em GB (0 = ilimitado)", - "CacheYouTubeVideos": "Salvar vídeos do YouTube em cachê", - "MaxYouTubeResolution": "Resolução máxima do YouTube", - "PreferVp9ForCache": "Priorizar VP9 para vídeos em cachê (MP4)", - "PreferVp9ForCacheTooltip": "Economiza 20–50% de espaço de armazenamento para vídeos do YouTube em cachê sem perda de qualidade. Funciona em todas as plataformas, incluindo Quest. Seguro para a maioria dos usuários.", + "MaxResolution": "Resolução máxima", "MaxVideoLength": "Duração máxima do vídeo (minutos)", - "CachePyPyDanceVideos": "Salvar vídeos do PyPyDance em cachê", - "CacheVRDancingVideos": "Salvar vídeos do VRDancing em cachê", "CacheHlsPlaylists": "Salvar vídeos HLS em cachê (.m3u8 / mpegts)", "OnlyServeCachedVideos": "Reproduzir apenas vídeos armazenados em cachê", "CacheDownloadIdleSeconds": "Pausar downloads de cachê durante o streaming (segundos)", @@ -77,18 +61,13 @@ "GamePatching": "Patch do Jogo", "PatchVRChat": "Patch para VRChat", "PatchResonite": "Patch para Resonite", - "Updates": "Atualizações", - "AutoUpdateVRCVideoCacher": "Atualizar automaticamente VRCVideoCacher", "CloseToTray": "Fechar para bandeja", "StartMinimized": "Iniciar minimizado", "StartWithSteamVr": "Iniciar com o SteamVR", - "ErrorPopups": "Pop-ups de erro", - "BlockedUrls": "URLs bloqueadas", - "BlockedUrlRedirect": "Destino de redirecionamento de URLs bloqueadas", "SettingsSaved": "Preferências salvas!", + "SettingsSavedRestartRequired": "Salvo — reinicie o VRCVideoCacher para aplicar a nova pasta de cache", "SettingsReset": "Preferências redefinidas para os últimos valores salvos.", "SettingsUnsavedChanges": "Você tem mudanças não salvas.", - "RedirectVRDancing": "Redirecionar VRDancing Europeu para Norte-Americano", "OpenFolder": "Abrir pasta", "DeleteAllCache": "Esvaziar o cachê", "SearchVideosWatermark": "Procurar vídeos...", @@ -115,6 +94,7 @@ "SkipReasonBotCheck": "Verificação de bot do YouTube — instale a extensão do navegador: github.com/clienthax/VRCVideoCacherBrowserExtension e use uma conta alternativa do YouTube", "SkipReasonVideoUnavailable": "Vídeo indisponível", "SkipReasonPrivateVideo": "O vídeo é privado", + "SkipReasonStalled": "Download travado — nenhum dado recebido", "LogViewer": "Visualizador de registros", "ExportLogs": "Exportar registros", "ClearLogs": "Limpar registros", @@ -142,6 +122,10 @@ "OpenYouTube": "Abrir YouTube", "OpenYouTubeWith": "Abrir com...", "CookieSetupStep3Note": "Atenção: Você pode desinstalar a extensão assim que os cookies forem recebidos. Se você navegar o YouTube novamente enquanto estiver logado, os cookies podem acabar expirando. Você pode excluir os cookies do YouTube do seu navegador após a configuração ou manter a extensão instalada.", + "PasteCookiesManually": "Colar cookies manualmente", + "SaveCookies": "Salvar cookies", + "ManualCookiesWrongFormat": "Formato incorreto — copie e cole os cookies exatamente como fornecidos pela extensão (Copiar cookies para a área de transferência).", + "ManualCookiesExpired": "Estes cookies expiraram. Faça login no YouTube novamente e copie cookies novos.", "CookieSetupStep4Header": "Passo 4: localhost.youtube.com (opcional)", "CookieSetupStep4Desc": "Adicionar localhost.youtube.com à lista de hosts permite que o VRCVideoCacher reproduza videos em cachê usando o domínio do YouTube, o que melhora a compatibilidade com os video players do VRChat.", "CookieSetupStep4Note": "Esta ação requer permissão do administrador. Você pode pular esta etapa e configurá-la mais tarde pelo Painel.", @@ -149,6 +133,23 @@ "CookieSetupCompleteDesc": "Cookies do YouTube recebidos. Você não deverá mais ver erros de detecção de bots do YouTube.", "CookiesReceived": "Cookies recebidos!", "WaitingForCookies": "Esperando pelos cookies...", + "CookiesVerifyNow": "Verificar agora", + "CookiesStatusDisabled": "Os cookies do YouTube estão desativados", + "CookiesStatusVerifying": "Verificando cookies...", + "CookiesStatusMissing": "Nenhum cookie válido encontrado", + "CookiesStatusPresent": "Cookies presentes (ainda não verificados)", + "CookiesStatusWorking": "Os cookies estão funcionando com o YouTube!", + "CookiesStatusExpired": "Cookies expirados ou rejeitados pelo YouTube", + "CookiesExpired": "Os cookies expiraram", + "CookiesExpireToday": "Os cookies expiram hoje", + "CookiesExpireInDaysFormat": "Expira em {0} dias", + "CookiesRefreshHeader": "Atualizando cookies", + "CookiesHelpLegacy": "Com a extensão padrão, os cookies são enviados quando você abre o YouTube no seu navegador com a extensão instalada. Você também pode colá-los manualmente abaixo.", + "CookiesHelpBeta": "\"Solicitar cookies novos\" obtém um novo conjunto instantaneamente — sem precisar abrir a extensão ou ativar o compartilhamento automático. Você também pode clicar em \"Enviar cookies\" na extensão ou colá-los abaixo.", + "UseBetaExtension": "Usar extensão Beta", + "UseBetaExtensionTooltip": "Ative isto apenas se você instalou a extensão de navegador Beta. Ela desbloqueia a atualização instantânea de cookies acionada pelo aplicativo. A maioria dos usuários usa a extensão padrão e deve deixar isto desativado.", + "CookiesRequestRefresh": "Solicitar cookies novos", + "CookiesRequestRefreshTooltip": "Pede para a extensão enviar cookies novos imediatamente. Basta que o navegador esteja aberto com a extensão instalada e logado no YouTube — o compartilhamento automático não precisa estar ativado.", "CookiesDisabledWarning": "\"Usar cookies do YouTube\" está atualmente desativado. Por favor, vá para as Configurações e ative-o primeiro.", "HostsActive": "localhost.youtube.com está ativo", "NotConfigured": "Não configurado", @@ -157,36 +158,57 @@ "OpenChromeWebStore": "Abrir Chrome Web Store", "OpenFirefoxAddons": "Abrir Add-ons do Firefox", "DontShowThisAgain": "Não mostrar novamente", - "TrayShow": "Mostrar", + "Show": "Mostrar", "TrayOpenCacheFolder": "Abrir pasta de cachê", "TrayExit": "Encerrar", "TrayMinimizeNotice": "VRCVideoCacher ainda está sendo executado em segundo plano. Clique no ícone da bandeja para reabri-lo.", "VRCVideoCacherPlus": "VRCVideoCacherPlus", + "Updates": "Atualizações", + "AutoUpdateVRCVideoCacher": "Atualizar automaticamente VRCVideoCacher", "CreatedBy": "Criado por", "ReportAnIssue": "Reportar um problema", "OpenIssueOnGitHub": "Abrir uma solicitação no GitHub", - "JoinOurDiscord": "Entre em nosso Discord para reportar um problema", "RedownloadUtils": "Baixar Ferramentas Novamente", + "OpenUtilsFolder": "Abrir pasta de ferramentas", "RedownloadingUtils": "Baixando ferramentas novamente...", "RedownloadComplete": "Ferramentas baixadas novamente com sucesso!", "RedownloadFailed": "Falha ao baixar novamente. Verifique os registros para detalhes.", - "OpenUtilsFolder": "Abrir pasta de ferramentas", - "SaveCookies": "Salvar cookies", - "PasteCookiesManually": "Colar cookies manualmente", - "ManualCookiesWrongFormat": "Formato incorreto — copie e cole os cookies exatamente como fornecidos pela extensão (Copiar cookies para a área de transferência).", - "ManualCookiesExpired": "Estes cookies expiraram. Faça login no YouTube novamente e copie cookies novos.", - "CookiesVerifyNow": "Verificar agora", - "CookiesStatusDisabled": "Os cookies do YouTube estão desativados", - "CookiesStatusVerifying": "Verificando cookies...", - "CookiesStatusMissing": "Nenhum cookie válido encontrado", - "CookiesStatusPresent": "Cookies presentes (ainda não verificados)", - "CookiesStatusWorking": "Os cookies estão funcionando com o YouTube!", - "CookiesStatusExpired": "Cookies expirados ou rejeitados pelo YouTube", - "CookiesRefreshHeader": "Atualizando cookies", - "CookiesHelpLegacy": "Com a extensão padrão, os cookies são enviados quando você abre o YouTube no seu navegador com a extensão instalada. Você também pode colá-los manualmente abaixo.", - "CookiesHelpBeta": "\"Solicitar cookies novos\" obtém um novo conjunto instantaneamente — sem precisar abrir a extensão ou ativar o compartilhamento automático. Você também pode clicar em \"Enviar cookies\" na extensão ou colá-los abaixo.", - "UseBetaExtension": "Usar extensão Beta", - "UseBetaExtensionTooltip": "Ative isto apenas se você instalou a extensão de navegador Beta. Ela desbloqueia a atualização instantânea de cookies acionada pelo aplicativo. A maioria dos usuários usa a extensão padrão e deve deixar isto desativado.", - "CookiesRequestRefresh": "Solicitar cookies novos", - "CookiesRequestRefreshTooltip": "Pede para a extensão enviar cookies novos imediatamente. Basta que o navegador esteja aberto com a extensão instalada e logado no YouTube — o compartilhamento automático não precisa estar ativado." + "PreCacheVideos": "Vídeos pré-carregados no cache", + "PreCacheVideosHint": "URLs de vídeo baixadas na inicialização se ainda não estiverem no cache. Você pode colar várias de uma vez, separadas por vírgulas, espaços ou novas linhas.", + "Rules": "Regras", + "AddRule": "Adicionar regra", + "RuleName": "Nome da regra", + "RegexPattern": "Padrão Regex", + "Action": "Ação", + "RedirectTarget": "URL de destino do redirecionamento", + "RewriteTarget": "Padrão de reescrita / URL de destino", + "Enabled": "Ativado", + "Tools": "Ferramentas", + "VideoPlayers": "Reprodutores de vídeo", + "Disable": "Desativar", + "Enable": "Ativar", + "RulesManagedViaRulesTabNote": "O cache de domínios, limites de resolução, redirecionamentos e reescritas de URL são gerenciados na aba Regras.", + "TestUrlPlaceholder": "URL de teste...", + "UnsavedRulesMessage": "Você tem alterações não salvas nas suas regras. Deseja salvar ou descartar as alterações antes de sair?", + "Discard": "Descartar", + "ResetToDefaults": "Padrões", + "ConfirmResetDefaultsMessage": "Tem certeza de que deseja redefinir todas as regras para os padrões de fábrica? As regras personalizadas serão substituídas.", + "EditRuleTitle": "Editar regra", + "AddRuleTitle": "Adicionar regra", + "PatternCannotBeEmpty": "O padrão não pode ficar vazio.", + "InvalidRegex": "Regex inválida: {0}", + "UpdateAvailable": "A versão {0} está disponível!", + "UpdateDownloading": "Baixando atualização...", + "UpdateFailed": "Falha na atualização. Verifique os logs e tente novamente.", + "SkipReasonInvalidDownload": "O arquivo baixado não passou na validação", + "SkipReasonTruncated": "O download ficou incompleto", + "DownloadTimeRemaining": "faltam {0}", + "SharedConfigNoticeTitle": "As configurações agora são compartilhadas", + "SharedConfigNotice": "O VRCVideoCacherPlusPlus guarda suas configurações no mesmo Config.json do VRCVideoCacher original, em vez de um arquivo separado.\n\nSe você executar o VRCVideoCacher original (ou a versão Plus), ele reescreverá esse arquivo e removerá as configurações do PlusPlus — incluindo suas regras de URL, que voltariam ao padrão.\n\nSe você vem de uma versão anterior do PlusPlus, suas configurações antigas continuam em PlusConfig.json na mesma pasta. Esse arquivo não é mais lido, mas fica no lugar para você recuperar o que quiser.", + "SeverSucceeded": "{0} conexão(ões) interrompida(s).", + "SeverNeedsPrivileges": "Os vídeos em cache foram parados. Fechar as conexões diretas do VRChat exige administrador/root, então um vídeo já em transmissão continuará até o fim.", + "SeverUnsupported": "Esta plataforma não permite fechar as conexões diretas do VRChat.", + "SeverFailed": "Falha ao fechar as conexões. Veja o log para detalhes.", + "SeverNothingToDo": "Nada para interromper.", + "AddressCopied": "Endereço copiado para a área de transferência." } diff --git a/VRCVideoCacher/Languages/ru.loc.json b/VRCVideoCacher/Languages/ru.loc.json old mode 100755 new mode 100644 index de1ccd0c..00ac885c --- a/VRCVideoCacher/Languages/ru.loc.json +++ b/VRCVideoCacher/Languages/ru.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "Панель управления", + "NowPlaying": "Сейчас играет", + "ActiveConnections": "Активные соединения", "Settings": "Настройки", "CacheBrowser": "Кэш браузера", "Downloads": "Загрузки", "History": "История", "Logs": "Логи", "About": "О программе", - "PreCacheVideos": "Предзагружаемые видео", - "PreCacheVideosHint": "Ссылки на видео, загружаемые при запуске, если их ещё нет в кэше. Можно вставить сразу несколько, разделяя запятыми, пробелами или переносами строк.", - "CookiesExpired": "Cookie входа истёк", - "CookiesExpireToday": "Cookie входа истекает сегодня", - "CookiesExpireInDaysFormat": "Cookie входа истекает через {0} дн.", - "Stats": "Статистика", - "CacheHitRate": "Доля попаданий в кэш", - "BandwidthSaved": "Сэкономлено трафика", - "CacheHits": "Попадания в кэш", - "TotalPlays": "Всего воспроизведений", - "MostReplayed": "Чаще всего повторяли", - "NoLongerCached": "Больше не в кэше", - "BytesSavedCaveatFormat": "Не учтено {0} попаданий по видео, уже удалённым из кэша, поэтому реальное значение выше.", "Refresh": "Обновить", "Save": "Сохранить", "Reset": "Сбросить", @@ -61,13 +50,8 @@ "CacheSettings": "Настройки кэша", "CachePathLabel": "Путь к кэшу (Оставьте пустым для значения по умолчанию)", "MaxCacheSizeLabel": "Максимальный размер Кэша в Гб (0 = неограниченно)", - "CacheYouTubeVideos": "Кэширования видео YouTube", - "MaxYouTubeResolution": "Максимальное Разрешение YouTube", - "PreferVp9ForCache": "Предпочитать VP9 для кэшированных видео (MP4)", - "PreferVp9ForCacheTooltip": "Экономит 20–50% места для кэшированных видео YouTube без потери качества. Работает на всех платформах, включая Quest. Большинству пользователей можно смело включить.", + "MaxResolution": "Максимальное разрешение", "MaxVideoLength": "Максимальная длина Видео (В минутах)", - "CachePyPyDanceVideos": "Кэшировать PyPyDance Видео", - "CacheVRDancingVideos": "Кэшировать VrDancing Видео", "CacheHlsPlaylists": "Кэшировать HLS Видео (.m3u8 / mpegts)", "OnlyServeCachedVideos": "Только Серверныйе Кэшированные видео", "CacheDownloadIdleSeconds": "Приостановить загрузку кэша во время стриминга (секунды)", @@ -77,18 +61,13 @@ "GamePatching": "Патч Игры", "PatchVRChat": "Патч VrChat", "PatchResonite": "Патч Resonite", - "Updates": "Обновления", - "AutoUpdateVRCVideoCacher": "Автообновления VRCVideoCacher", "CloseToTray": "Закрыть в Трей", "StartMinimized": "Запускать Свёрнутым", "StartWithSteamVr": "Запустить приложение с помощью SteamVR", - "ErrorPopups": "Всплывающие окна ошибок", - "BlockedUrls": "Заблокированный URL", - "BlockedUrlRedirect": "Перенаправление заблокированного URL", "SettingsSaved": "Настройки сохранены!", + "SettingsSavedRestartRequired": "Сохранено — перезапустите VRCVideoCacher, чтобы применить новую папку кэша", "SettingsReset": "Настройки сброшенны до последнего сохранения", "SettingsUnsavedChanges": "У вас есть несохраненные изменения!", - "RedirectVRDancing": "Перенаправить EU VRDancing на NA", "OpenFolder": "Открыть папку..", "DeleteAllCache": "Удалить весь кэш", "SearchVideosWatermark": "Поиск видео...", @@ -115,6 +94,7 @@ "SkipReasonBotCheck": "Проверка YouTube на бота — установите расширение: github.com/clienthax/VRCVideoCacherBrowserExtension и используйте альтернативный аккаунт YouTube", "SkipReasonVideoUnavailable": "Видео недоступно", "SkipReasonPrivateVideo": "Видео является приватным", + "SkipReasonStalled": "Загрузка остановлена — данные не поступают", "LogViewer": "Просмотр логов", "ExportLogs": "Экспортировать логи", "ClearLogs": "Очистить логи", @@ -142,6 +122,10 @@ "OpenYouTube": "Открыть YouTube", "OpenYouTubeWith": "Открыть с помощью...", "CookieSetupStep3Note": "Примечание: расширение можно удалить после получения cookie. Если вы снова войдёте на YouTube, cookie могут стать недействительными. Рекомендуется удалить cookie YouTube из браузера после настройки или оставите расширение установленным.", + "PasteCookiesManually": "Вставить cookie вручную", + "SaveCookies": "Сохранить cookie", + "ManualCookiesWrongFormat": "Неверный формат — скопируйте и вставьте cookie ровно в том виде, в каком их выдало расширение (Копировать cookie в буфер обмена).", + "ManualCookiesExpired": "Эти cookie истекли. Войдите в YouTube снова и скопируйте свежие cookie.", "CookieSetupStep4Header": "Шаг 4-ый: localhost.youtube.com (Оптимально)", "CookieSetupStep4Desc": "Добавление записей для localhost.youtube.com дает VRCVideoCacher раздавать кэшированные видео через домен YouTube, Что улутшает совместимость с видеоплеером VRChat.", "CookieSetupStep4Note": "Это требует права администратора. Вы можете пропустить этот шаг и настроить его позже в Панели управления.", @@ -149,6 +133,23 @@ "CookieSetupCompleteDesc": "YouTube cookies получены. Ошибка обнаружения ботов больше не должны появляться.", "CookiesReceived": "Cookies получены!", "WaitingForCookies": "Ожидание cookie...", + "CookiesVerifyNow": "Проверить сейчас", + "CookiesStatusDisabled": "Cookie YouTube отключены", + "CookiesStatusVerifying": "Проверка cookie...", + "CookiesStatusMissing": "Действительные cookie не найдены", + "CookiesStatusPresent": "Cookie присутствуют (ещё не проверены)", + "CookiesStatusWorking": "Cookie работают с YouTube!", + "CookiesStatusExpired": "Срок действия файлов cookie истек или они отклонены YouTube", + "CookiesExpired": "Срок действия файлов cookie истек", + "CookiesExpireToday": "Срок действия файлов cookie истекает сегодня", + "CookiesExpireInDaysFormat": "Истекает через {0} дн.", + "CookiesRefreshHeader": "Обновление cookie", + "CookiesHelpLegacy": "Со стандартным расширением cookie отправляются, когда вы открываете YouTube в браузере с установленным расширением. Также их можно вставить вручную ниже.", + "CookiesHelpBeta": "\"Запросить свежие cookie\" мгновенно получает новый набор — не нужно открывать расширение или включать автоматический обмен. Также можно нажать \"Отправить cookie\" в расширении или вставить их ниже.", + "UseBetaExtension": "Использовать бета-расширение", + "UseBetaExtensionTooltip": "Включайте только если вы установили бета-расширение браузера. Оно разблокирует мгновенное обновление cookie по запросу приложения. Большинство пользователей используют стандартное расширение и должны оставить это выключенным.", + "CookiesRequestRefresh": "Запросить свежие cookie", + "CookiesRequestRefreshTooltip": "Просит расширение немедленно отправить свежие cookie. Достаточно, чтобы браузер был открыт с установленным расширением и выполнен вход в YouTube — автоматический обмен включать не обязательно.", "CookiesDisabledWarning": "«Использовать YouTube Cookie» в данный момент отключено. Пожалуйста, перейдите в Настройки и сначала включите его.", "HostsActive": "localhost.youtube.com Активна", "NotConfigured": "Не настроено", @@ -157,36 +158,57 @@ "OpenChromeWebStore": "Открыть Chrome Web Store (Chrome Веб магазин)", "OpenFirefoxAddons": "Открыть Firefox Add-ons (FireFox Аддоны)", "DontShowThisAgain": "Не показывать это снова.", - "TrayShow": "Показать", + "Show": "Показать", "TrayOpenCacheFolder": "Открыть папку с кэшом", "TrayExit": "Выход.", "TrayMinimizeNotice": "VRCVideoCacher всё ещё работает в фоновом режиме. Нажмите на значок в трее, чтобы открыть снова.", "VRCVideoCacherPlus": "VRCVideoCacherPlus", + "Updates": "Обновления", + "AutoUpdateVRCVideoCacher": "Автообновления VRCVideoCacher", "CreatedBy": "Авторы", "ReportAnIssue": "Сообщить о проблеме..", "OpenIssueOnGitHub": "Открыть задачу на GitHub", - "JoinOurDiscord": "Присоединиться к нашему Discord серверу, чтобы сообщить о вашей проблеме", "RedownloadUtils": "Перезагрузить утилиты", + "OpenUtilsFolder": "Открыть папку утилит", "RedownloadingUtils": "Повторная загрузка утилит...", "RedownloadComplete": "Утилиты успешно перезагружены!", "RedownloadFailed": "Повторная загрузка не удалась. Подробности смотрите в логах.", - "OpenUtilsFolder": "Открыть папку утилит", - "SaveCookies": "Сохранить cookie", - "PasteCookiesManually": "Вставить cookie вручную", - "ManualCookiesWrongFormat": "Неверный формат — скопируйте и вставьте cookie ровно в том виде, в каком их выдало расширение (Копировать cookie в буфер обмена).", - "ManualCookiesExpired": "Эти cookie истекли. Войдите в YouTube снова и скопируйте свежие cookie.", - "CookiesVerifyNow": "Проверить сейчас", - "CookiesStatusDisabled": "Cookie YouTube отключены", - "CookiesStatusVerifying": "Проверка cookie...", - "CookiesStatusMissing": "Действительные cookie не найдены", - "CookiesStatusPresent": "Cookie присутствуют (ещё не проверены)", - "CookiesStatusWorking": "Cookie работают с YouTube!", - "CookiesStatusExpired": "Cookie истекли или отклонены YouTube", - "CookiesRefreshHeader": "Обновление cookie", - "CookiesHelpLegacy": "Со стандартным расширением cookie отправляются, когда вы открываете YouTube в браузере с установленным расширением. Также их можно вставить вручную ниже.", - "CookiesHelpBeta": "\"Запросить свежие cookie\" мгновенно получает новый набор — не нужно открывать расширение или включать автоматический обмен. Также можно нажать \"Отправить cookie\" в расширении или вставить их ниже.", - "UseBetaExtension": "Использовать бета-расширение", - "UseBetaExtensionTooltip": "Включайте только если вы установили бета-расширение браузера. Оно разблокирует мгновенное обновление cookie по запросу приложения. Большинство пользователей используют стандартное расширение и должны оставить это выключенным.", - "CookiesRequestRefresh": "Запросить свежие cookie", - "CookiesRequestRefreshTooltip": "Просит расширение немедленно отправить свежие cookie. Достаточно, чтобы браузер был открыт с установленным расширением и выполнен вход в YouTube — автоматический обмен включать не обязательно." + "PreCacheVideos": "Предварительно кэшированные видео", + "PreCacheVideosHint": "URL видео, скачиваемые при запуске, если они еще не закэшированы. Можно вставить несколько одновременно, разделив запятыми, пробелами или переводами строк.", + "Rules": "Правила", + "AddRule": "Добавить правило", + "RuleName": "Название правила", + "RegexPattern": "Шаблон Regex", + "Action": "Действие", + "RedirectTarget": "Целевой URL перенаправления", + "RewriteTarget": "Целевой шаблон перезаписи / URL", + "Enabled": "Включено", + "Tools": "Инструменты", + "VideoPlayers": "Видеоплееры", + "Disable": "Отключить", + "Enable": "Включить", + "RulesManagedViaRulesTabNote": "Кэширование доменов, ограничения разрешения, перенаправления и перезапись URL управляются во вкладке Правила.", + "TestUrlPlaceholder": "Тестовый URL...", + "UnsavedRulesMessage": "У вас есть несохраненные изменения правил. Сохранить или отменить изменения перед выходом?", + "Discard": "Отменить", + "ResetToDefaults": "По умолчанию", + "ConfirmResetDefaultsMessage": "Вы уверены, что хотите сбросить все правила до заводских настроек? Пользовательские правила будут заменены.", + "EditRuleTitle": "Изменить правило", + "AddRuleTitle": "Добавить правило", + "PatternCannotBeEmpty": "Шаблон не может быть пустым.", + "InvalidRegex": "Неверное регулярное выражение: {0}", + "UpdateAvailable": "Доступна версия {0}!", + "UpdateDownloading": "Загрузка обновления...", + "UpdateFailed": "Не удалось обновить. Проверьте журнал и повторите попытку.", + "SkipReasonInvalidDownload": "Загруженный файл не прошёл проверку", + "SkipReasonTruncated": "Загрузка не завершена", + "DownloadTimeRemaining": "осталось {0}", + "SharedConfigNoticeTitle": "Настройки теперь общие", + "SharedConfigNotice": "VRCVideoCacherPlusPlus хранит настройки в том же файле Config.json, что и оригинальный VRCVideoCacher, а не в отдельном файле.\n\nЕсли запустить оригинальный VRCVideoCacher (или версию Plus), он перезапишет этот файл и удалит настройки PlusPlus, включая ваши правила URL — они вернутся к значениям по умолчанию.\n\nЕсли вы переходите со старой сборки PlusPlus, прежние настройки остались в PlusConfig.json в той же папке. Этот файл больше не читается, но оставлен на месте, чтобы вы могли перенести из него нужное.", + "SeverSucceeded": "Остановлено соединений: {0}.", + "SeverNeedsPrivileges": "Кэшированные видео остановлены. Для закрытия прямых соединений VRChat нужны права администратора/root, поэтому уже идущая трансляция продолжится до конца.", + "SeverUnsupported": "На этой платформе нельзя закрыть прямые соединения VRChat.", + "SeverFailed": "Не удалось закрыть соединения. Подробности в журнале.", + "SeverNothingToDo": "Нечего останавливать.", + "AddressCopied": "Адрес скопирован в буфер обмена." } diff --git a/VRCVideoCacher/Languages/zh.loc.json b/VRCVideoCacher/Languages/zh.loc.json old mode 100755 new mode 100644 index 0beeaa99..0a02821a --- a/VRCVideoCacher/Languages/zh.loc.json +++ b/VRCVideoCacher/Languages/zh.loc.json @@ -1,24 +1,13 @@ { "Dashboard": "仪表盘", + "NowPlaying": "正在播放", + "ActiveConnections": "活动连接", "Settings": "设置", "CacheBrowser": "缓存浏览器", "Downloads": "下载", "History": "历史记录", "Logs": "日志", "About": "关于", - "PreCacheVideos": "预缓存视频", - "PreCacheVideosHint": "启动时下载的视频链接(若尚未缓存)。 可以一次粘贴多个,使用逗号、空格或换行分隔。", - "CookiesExpired": "登录 Cookie 已过期", - "CookiesExpireToday": "登录 Cookie 今天过期", - "CookiesExpireInDaysFormat": "登录 Cookie 将在 {0} 天后过期", - "Stats": "统计", - "CacheHitRate": "缓存命中率", - "BandwidthSaved": "节省的流量", - "CacheHits": "缓存命中", - "TotalPlays": "总播放次数", - "MostReplayed": "重复播放最多", - "NoLongerCached": "已不在缓存中", - "BytesSavedCaveatFormat": "不包含已从缓存中删除的视频的 {0} 次命中,因此实际数值更高。", "Refresh": "刷新", "Save": "保存", "Reset": "重置", @@ -61,13 +50,8 @@ "CacheSettings": "缓存设置", "CachePathLabel": "缓存路径(留空则使用默认路径)", "MaxCacheSizeLabel": "最大缓存大小(GB)(0 = 无限制)", - "CacheYouTubeVideos": "缓存 YouTube 视频", - "MaxYouTubeResolution": "YouTube 最高分辨率", - "PreferVp9ForCache": "缓存视频优先使用 VP9 (MP4)", - "PreferVp9ForCacheTooltip": "在不损失画质的情况下,为缓存的 YouTube 视频节省 20–50% 的存储空间。支持包括 Quest 在内的所有平台。大多数用户可以安全启用。", + "MaxResolution": "最大分辨率", "MaxVideoLength": "最大视频时长(分钟)", - "CachePyPyDanceVideos": "缓存 PyPyDance 视频", - "CacheVRDancingVideos": "缓存 VRDancing 视频", "CacheHlsPlaylists": "缓存 HLS 视频 (.m3u8 / mpegts)", "OnlyServeCachedVideos": "仅提供已缓存的视频", "CacheDownloadIdleSeconds": "串流时暂停缓存下载(秒)", @@ -80,13 +64,10 @@ "CloseToTray": "关闭到系统托盘", "StartMinimized": "启动时最小化", "StartWithSteamVr": "通过 SteamVR 启动应用", - "ErrorPopups": "错误弹窗", - "BlockedUrls": "屏蔽的 URL", - "BlockedUrlRedirect": "屏蔽 URL 重定向地址", "SettingsSaved": "设置已保存!", + "SettingsSavedRestartRequired": "已保存 — 请重启 VRCVideoCacher 以应用新的缓存文件夹", "SettingsReset": "设置已重置为上次保存的值。", "SettingsUnsavedChanges": "有未保存的设置更改。", - "RedirectVRDancing": "将 EU VRDancing 重定向至 NA", "OpenFolder": "打开文件夹", "DeleteAllCache": "删除全部缓存", "SearchVideosWatermark": "搜索视频...", @@ -113,6 +94,7 @@ "SkipReasonBotCheck": "YouTube 机器人验证 — 请安装浏览器扩展:github.com/clienthax/VRCVideoCacherBrowserExtension 并使用其他 YouTube 账户", "SkipReasonVideoUnavailable": "视频不可用", "SkipReasonPrivateVideo": "视频为私有", + "SkipReasonStalled": "下载停滞 — 未接收到数据", "LogViewer": "日志查看器", "ExportLogs": "导出日志", "ClearLogs": "清除日志", @@ -140,6 +122,10 @@ "OpenYouTube": "打开 YouTube", "OpenYouTubeWith": "打开方式...", "CookieSetupStep3Note": "注意:收到 Cookie 后可以卸载扩展。若在登录状态下再次浏览 YouTube,Cookie 可能会失效。建议设置完成后从浏览器删除 YouTube Cookie,或保留扩展继续使用。", + "PasteCookiesManually": "手动粘贴 Cookie", + "SaveCookies": "保存 Cookie", + "ManualCookiesWrongFormat": "格式错误 — 请按照扩展提供的原样复制并粘贴 Cookie(复制 Cookie 到剪贴板)。", + "ManualCookiesExpired": "这些 Cookie 已过期。请重新登录 YouTube 并复制新的 Cookie。", "CookieSetupStep4Header": "第 4 步:localhost.youtube.com(可选)", "CookieSetupStep4Desc": "为 localhost.youtube.com 添加 hosts 条目后,VRCVideoCacher 可以使用 YouTube 域名提供缓存视频,从而提升与 VRChat 视频播放器的兼容性。", "CookieSetupStep4Note": "此操作需要管理员权限。您可以跳过此步骤,稍后在仪表盘中进行配置。", @@ -147,6 +133,23 @@ "CookieSetupCompleteDesc": "已成功接收 YouTube Cookie,不再出现机器人检测错误。", "CookiesReceived": "已接收 Cookie!", "WaitingForCookies": "等待 Cookie...", + "CookiesVerifyNow": "立即验证", + "CookiesStatusDisabled": "YouTube Cookie 已禁用", + "CookiesStatusVerifying": "正在检查 Cookie...", + "CookiesStatusMissing": "未找到有效的 Cookie", + "CookiesStatusPresent": "存在 Cookie(尚未验证)", + "CookiesStatusWorking": "Cookie 在 YouTube 上正常工作!", + "CookiesStatusExpired": "Cookie 已过期或被 YouTube 拒绝", + "CookiesExpired": "Cookie 已过期", + "CookiesExpireToday": "Cookie 今天到期", + "CookiesExpireInDaysFormat": "{0} 天后过期", + "CookiesRefreshHeader": "刷新 Cookie", + "CookiesHelpLegacy": "使用标准扩展时,当您在安装了扩展的浏览器中打开 YouTube 时会发送 Cookie。您也可以在下方手动粘贴。", + "CookiesHelpBeta": "\"请求新 Cookie\" 会立即获取一组新 Cookie — 无需打开扩展或启用自动共享。您也可以在扩展中点击\"发送 Cookie\",或在下方粘贴。", + "UseBetaExtension": "使用 Beta 扩展", + "UseBetaExtensionTooltip": "仅在您安装了 Beta 浏览器扩展时才启用此选项。它可解锁由应用触发的即时 Cookie 刷新。大多数用户使用标准扩展,应保持此选项关闭。", + "CookiesRequestRefresh": "请求新 Cookie", + "CookiesRequestRefreshTooltip": "请求扩展立即发送新 Cookie。只需浏览器处于打开状态、已安装扩展并登录 YouTube 即可 — 无需开启自动共享。", "CookiesDisabledWarning": "\"使用 YouTube Cookie\" 当前已禁用。请前往设置并先启用此选项。", "HostsActive": "localhost.youtube.com 已激活", "NotConfigured": "未配置", @@ -155,7 +158,7 @@ "OpenChromeWebStore": "打开 Chrome 网上应用店", "OpenFirefoxAddons": "打开 Firefox 附加组件", "DontShowThisAgain": "不再显示", - "TrayShow": "显示", + "Show": "显示", "TrayOpenCacheFolder": "打开缓存文件夹", "TrayExit": "退出", "TrayMinimizeNotice": "VRCVideoCacher 仍在后台运行。点击托盘图标重新打开。", @@ -165,28 +168,47 @@ "CreatedBy": "由以下人员创建", "ReportAnIssue": "报告问题", "OpenIssueOnGitHub": "在 GitHub 上打开问题", - "JoinOurDiscord": "加入我们的 Discord 以报告问题", "RedownloadUtils": "重新下载工具", + "OpenUtilsFolder": "打开工具文件夹", "RedownloadingUtils": "正在重新下载工具...", "RedownloadComplete": "工具重新下载成功!", "RedownloadFailed": "重新下载失败。请查看日志以了解详情。", - "OpenUtilsFolder": "打开工具文件夹", - "SaveCookies": "保存 Cookie", - "PasteCookiesManually": "手动粘贴 Cookie", - "ManualCookiesWrongFormat": "格式错误 — 请按照扩展提供的原样复制并粘贴 Cookie(复制 Cookie 到剪贴板)。", - "ManualCookiesExpired": "这些 Cookie 已过期。请重新登录 YouTube 并复制新的 Cookie。", - "CookiesVerifyNow": "立即验证", - "CookiesStatusDisabled": "YouTube Cookie 已禁用", - "CookiesStatusVerifying": "正在检查 Cookie...", - "CookiesStatusMissing": "未找到有效的 Cookie", - "CookiesStatusPresent": "存在 Cookie(尚未验证)", - "CookiesStatusWorking": "Cookie 在 YouTube 上正常工作!", - "CookiesStatusExpired": "Cookie 已过期或被 YouTube 拒绝", - "CookiesRefreshHeader": "刷新 Cookie", - "CookiesHelpLegacy": "使用标准扩展时,当您在安装了扩展的浏览器中打开 YouTube 时会发送 Cookie。您也可以在下方手动粘贴。", - "CookiesHelpBeta": "\"请求新 Cookie\" 会立即获取一组新 Cookie — 无需打开扩展或启用自动共享。您也可以在扩展中点击\"发送 Cookie\",或在下方粘贴。", - "UseBetaExtension": "使用 Beta 扩展", - "UseBetaExtensionTooltip": "仅在您安装了 Beta 浏览器扩展时才启用此选项。它可解锁由应用触发的即时 Cookie 刷新。大多数用户使用标准扩展,应保持此选项关闭。", - "CookiesRequestRefresh": "请求新 Cookie", - "CookiesRequestRefreshTooltip": "请求扩展立即发送新 Cookie。只需浏览器处于打开状态、已安装扩展并登录 YouTube 即可 — 无需开启自动共享。" + "PreCacheVideos": "预缓存视频", + "PreCacheVideosHint": "启动时下载的视频 URL(如果尚未缓存)。您可以一次粘贴多个,用逗号、空格或换行符分隔。", + "Rules": "规则", + "AddRule": "添加规则", + "RuleName": "规则名称", + "RegexPattern": "正则表达式", + "Action": "操作", + "RedirectTarget": "重定向目标 URL", + "RewriteTarget": "目标重写模式 / URL", + "Enabled": "已启用", + "Tools": "工具", + "VideoPlayers": "视频播放器", + "Disable": "禁用", + "Enable": "启用", + "RulesManagedViaRulesTabNote": "域名缓存、分辨率限制、重定向和 URL 重写均在“规则”选项卡中管理。", + "TestUrlPlaceholder": "测试 URL...", + "UnsavedRulesMessage": "您有未保存的规则更改。在离开之前,要保存还是放弃更改?", + "Discard": "放弃", + "ResetToDefaults": "默认值", + "ConfirmResetDefaultsMessage": "您确定要将所有规则重置为出厂默认设置吗?自定义规则将被替换。", + "EditRuleTitle": "编辑规则", + "AddRuleTitle": "添加规则", + "PatternCannotBeEmpty": "匹配模式不能为空。", + "InvalidRegex": "正则表达式无效:{0}", + "UpdateAvailable": "版本 {0} 可用!", + "UpdateDownloading": "正在下载更新...", + "UpdateFailed": "更新失败。请查看日志后重试。", + "SkipReasonInvalidDownload": "下载的文件未通过校验", + "SkipReasonTruncated": "下载不完整", + "DownloadTimeRemaining": "剩余 {0}", + "SharedConfigNoticeTitle": "设置现已共享", + "SharedConfigNotice": "VRCVideoCacherPlusPlus 将设置保存在与原版 VRCVideoCacher 相同的 Config.json 中,而不是单独的文件。\n\n如果你运行原版 VRCVideoCacher(或 Plus 版本),它会重写该文件并删除 PlusPlus 的设置(包括你的 URL 规则),这些设置将恢复为默认值。\n\n如果你是从旧版 PlusPlus 升级而来,之前的设置仍保存在同一文件夹的 PlusConfig.json 中。该文件已不再读取,但会保留原处,方便你从中取回需要的内容。", + "SeverSucceeded": "已停止 {0} 个连接。", + "SeverNeedsPrivileges": "已停止缓存视频。关闭 VRChat 的直连需要管理员/root 权限,因此正在播放的流会继续到结束。", + "SeverUnsupported": "此平台无法关闭 VRChat 的直连。", + "SeverFailed": "关闭连接失败。详情请查看日志。", + "SeverNothingToDo": "没有可停止的内容。", + "AddressCopied": "地址已复制到剪贴板。" } diff --git a/VRCVideoCacher/Models/DefaultRules.cs b/VRCVideoCacher/Models/DefaultRules.cs new file mode 100644 index 00000000..8bad712b --- /dev/null +++ b/VRCVideoCacher/Models/DefaultRules.cs @@ -0,0 +1,153 @@ +using VRCVideoCacher.Models; + +namespace VRCVideoCacher; + +/// +/// The rule list a fresh installation starts with. +/// +/// Deliberately a plain static class with no state and no static constructor: touching +/// PlusConfigManager reaches through to ConfigManager.Config, whose initialiser reads and +/// writes Config.json in the user's profile. Keeping the defaults here means they can be +/// exercised by tests without any of that happening. +/// +public static class DefaultRules +{ + // Dropbox share links always carry a dl=0 parameter, but not always as the only one: + // the current /scl/fi/ format is "?rlkey=...&st=...&dl=0". Flipping that one parameter + // to dl=1 is what turns the HTML preview page into the actual file, and rlkey must be + // preserved, so the whole query can't just be replaced. + internal const string DropboxForceDownloadPattern = + @"^(https?:\/\/(?:[a-zA-Z0-9-]+\.)*dropbox\.com\/[^#]*[?&])dl=0(&[^#]*)?$"; + internal const string DropboxForceDownloadTarget = "${1}dl=1${2}"; + + // Separate rule for a link that has been trimmed down to a bare path: there is no + // parameter to flip, so dl=1 has to be appended as a new query string. Deliberately + // does not match a URL that already has a query — one that carries dl=1 or raw=1 is + // already a direct link, and one that carries neither is left alone rather than guessed at. + internal const string DropboxAppendDownloadPattern = + @"^(https?:\/\/(?:[a-zA-Z0-9-]+\.)*dropbox\.com\/[^?#]+)$"; + internal const string DropboxAppendDownloadTarget = "${1}?dl=1"; + + // Shipped in earlier versions and wrong: the lazy (.*?) had to expand past the whole + // query before the anchor could match, so the optional (?:\?dl=0)? never participated + // for any link with more than one parameter. The target then appended a second "?", + // producing "...&dl=0?dl=1". Existing installs carry their own copy of the rule list, + // so the corrected default only reaches them via the migration below. + internal const string LegacyDropboxPattern = + @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*dropbox\.com\/(.*?)(?:\?dl=0)?$"; + + public static List Create() + { + return + [ + new UriRule + { + Name = "VRDancing EU to NA Redirect", + Pattern = @"^https?:\/\/eu2\.vrdancing\.club\/weekend\/(.*)$", + Action = RuleAction.Redirect, + RedirectTarget = "https://na2.vrdancing.club/weekend/$1", + Enabled = false + }, + new UriRule + { + Name = "YouTube Music Redirect", + Pattern = @"^https?:\/\/music\.youtube\.com\/(?:watch|playlist)?\?(?:.*?&)?v=([^&]+).*$", + Action = RuleAction.Redirect, + RedirectTarget = "https://youtube.com/watch?v=$1", + Enabled = false + }, + new UriRule + { + Name = "Dropbox Share Rewrite", + Pattern = DropboxForceDownloadPattern, + Action = RuleAction.Rewrite, + RedirectTarget = DropboxForceDownloadTarget, + Enabled = true + }, + new UriRule + { + Name = "Dropbox Direct Download", + Pattern = DropboxAppendDownloadPattern, + Action = RuleAction.Rewrite, + RedirectTarget = DropboxAppendDownloadTarget, + Enabled = true + }, + new UriRule + { + Name = "Google Drive File Rewrite", + Pattern = @"^https?:\/\/drive\.google\.com\/file\/d\/([^\/]+)(?:\/.*)?$", + Action = RuleAction.Rewrite, + RedirectTarget = "https://drive.google.com/uc?export=download&id=$1", + Enabled = true + }, + new UriRule + { + Name = "MightyGym CDN Direct", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*mightygymcdn\.nyc3\.cdn\.digitaloceanspaces\.com(?:[\/?#]|$)", + Action = RuleAction.Direct, + Enabled = true + }, + new UriRule + { + Name = "Illumination Media Direct", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*(?:imvrcdn\.com|illumination\.media)(?:[\/?#]|$)", + Action = RuleAction.Direct, + Enabled = true + }, + new UriRule + { + Name = "Virtual Film Institute Direct", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*virtualfilm\.institute(?:[\/?#]|$)", + Action = RuleAction.Direct, + Enabled = true + }, + new UriRule + { + Name = "Block Rickrolls", + Pattern = @"^https?://(?:www\.)?youtube\.com/watch\?v=(?:dQw4w9WgXcQ|jzmz6K8K4L0|XfELJU1mRMg)", + Action = RuleAction.Block, + // Ships disabled: Block now genuinely prevents playback, and a fresh install + // silently refusing specific videos is a surprise, not a default. Existing + // configs keep whatever the user already has. + Enabled = false + }, + new UriRule + { + Name = "YouTube", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*(?:youtube\.com|youtu\.be|youtube-nocookie\.com)(?:[\/?#]|$)", + Action = RuleAction.Resolve, + Cache = true, + MaxResolution = 1080, + MaxDurationMinutes = 120, + Enabled = true, + Integration = "YouTube" + }, + new UriRule + { + Name = "PyPyDance", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*pypy\.dance(?:[\/?#]|$)", + Action = RuleAction.Resolve, + Cache = true, + Enabled = true, + Integration = "PyPyDance" + }, + new UriRule + { + Name = "VRDancing", + Pattern = @"^https?:\/\/(?:[a-zA-Z0-9-]+\.)*vrdancing\.club(?:[\/?#]|$)", + Action = RuleAction.Resolve, + Cache = true, + Enabled = true, + Integration = "VRDancing" + }, + new UriRule + { + Name = "Everything else", + Pattern = @".*", + Action = RuleAction.Resolve, + Cache = false, + Enabled = true + } + ]; + } +} diff --git a/VRCVideoCacher/Models/DownloadProgress.cs b/VRCVideoCacher/Models/DownloadProgress.cs new file mode 100644 index 00000000..c30f6abc --- /dev/null +++ b/VRCVideoCacher/Models/DownloadProgress.cs @@ -0,0 +1,36 @@ +namespace VRCVideoCacher.Models; + +/// +/// A progress sample for the download currently in flight. +/// +/// Speed and time remaining are both optional, and genuinely unknown often enough to matter: +/// yt-dlp reports "Unknown" for the first moments of a transfer, and a server that sends no +/// Content-Length leaves nothing to measure the remainder against. Callers should show the +/// percentage alone in that case rather than inventing a number. +/// +public readonly record struct DownloadProgress(double Percent, double? BytesPerSecond, TimeSpan? Eta) +{ + public static DownloadProgress AtPercent(double percent) => new(percent, null, null); + + /// + /// "1.2 MB/s", or null when the rate isn't known yet. + /// + public string? FormatRate() => + BytesPerSecond is > 0 ? $"{Utils.CacheStats.FormatSize((long)BytesPerSecond.Value)}/s" : null; + + /// + /// Compact, largest-unit-first time remaining: "45s", "3m 20s", "1h 04m". + /// + public string? FormatEta() + { + if (Eta is not { } eta || eta < TimeSpan.Zero) + return null; + + if (eta.TotalHours >= 1) + return $"{(int)eta.TotalHours}h {eta.Minutes:D2}m"; + + return eta.TotalMinutes >= 1 + ? $"{eta.Minutes}m {eta.Seconds:D2}s" + : $"{Math.Max(eta.Seconds, 1)}s"; + } +} diff --git a/VRCVideoCacher/Models/UriRule.cs b/VRCVideoCacher/Models/UriRule.cs new file mode 100644 index 00000000..d52cf8f4 --- /dev/null +++ b/VRCVideoCacher/Models/UriRule.cs @@ -0,0 +1,88 @@ +using System.Text.Json.Serialization; + +namespace VRCVideoCacher.Models; + +public enum RuleAction +{ + Direct, + Resolve, + Redirect, + Rewrite, + Block +} + +public class UriRule +{ + public string Id { get; set; } = Guid.NewGuid().ToString("N"); + public bool Enabled { get; set; } = true; + public string Name { get; set; } = string.Empty; + public string Pattern { get; set; } = string.Empty; + public RuleAction Action { get; set; } = RuleAction.Resolve; + + // Cache options + public bool Cache { get; set; } = false; + public int? MaxResolution { get; set; } // e.g. 1080 + public int? MaxDurationMinutes { get; set; } // e.g. 120 + + // Redirect / Rewrite action option + public string RedirectTarget { get; set; } = string.Empty; + + // Site Integration Name (YouTube, PyPyDance, VRDancing, etc.) + public string? Integration { get; set; } = null; + + public UriRule Clone() + { + return new UriRule + { + Id = Id, + Enabled = Enabled, + Name = Name, + Pattern = Pattern, + Action = Action, + Cache = Cache, + MaxResolution = MaxResolution, + MaxDurationMinutes = MaxDurationMinutes, + RedirectTarget = RedirectTarget, + Integration = Integration + }; + } + + public string GetActionSummary() + { + switch (Action) + { + case RuleAction.Direct: + return "Direct"; + + case RuleAction.Resolve: + if (Cache) + { + var parts = new List(); + if (MaxResolution.HasValue && MaxResolution.Value > 0) + parts.Add($"<{MaxResolution.Value}p"); + if (MaxDurationMinutes.HasValue && MaxDurationMinutes.Value > 0) + parts.Add($"<{MaxDurationMinutes.Value}m"); + if (parts.Count > 0) + return $"Resolve & Cache ({string.Join(", ", parts)})"; + return "Resolve & Cache"; + } + return "Resolve"; + + case RuleAction.Redirect: + return string.IsNullOrWhiteSpace(RedirectTarget) + ? "Redirect" + : $"Redirect to {RedirectTarget}"; + + case RuleAction.Rewrite: + return string.IsNullOrWhiteSpace(RedirectTarget) + ? "Rewrite" + : $"Rewrite to {RedirectTarget}"; + + case RuleAction.Block: + return "Block"; + + default: + return Action.ToString(); + } + } +} diff --git a/VRCVideoCacher/Models/Versions.cs b/VRCVideoCacher/Models/Versions.cs index 408e880a..8dea80ea 100644 --- a/VRCVideoCacher/Models/Versions.cs +++ b/VRCVideoCacher/Models/Versions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; using Serilog; +using VRCVideoCacher.Utils; namespace VRCVideoCacher.Models; @@ -15,7 +15,7 @@ static Versions() { try { - CurrentVersion = JsonConvert.DeserializeObject(File.ReadAllText(VersionPath)) ?? + CurrentVersion = Json.Deserialize(File.ReadAllText(VersionPath)) ?? new VersionJson(); return; } @@ -30,7 +30,7 @@ static Versions() public static void Save() { - File.WriteAllText(VersionPath, JsonConvert.SerializeObject(CurrentVersion, Formatting.Indented)); + AtomicFile.WriteAllText(VersionPath, Json.Serialize(CurrentVersion)); } } diff --git a/VRCVideoCacher/PlusConfigManager.cs b/VRCVideoCacher/PlusConfigManager.cs index 2617a5a1..580ea84e 100644 --- a/VRCVideoCacher/PlusConfigManager.cs +++ b/VRCVideoCacher/PlusConfigManager.cs @@ -1,98 +1,111 @@ -using Newtonsoft.Json; using Serilog; +using VRCVideoCacher.Models; namespace VRCVideoCacher; /// -/// Manages Plus-specific settings in a separate file so they don't get -/// overwritten when the upstream VRCVideoCacher opens the shared Config.json. +/// The PlusPlus-only settings, and the rule seeding that goes with them. +/// +/// These live as flat top-level fields inside the main ConfigModel. /// -public class PlusConfigManager +public static class PlusConfigManager { - public static PlusConfigModel Config { get; private set; } - private static readonly ILogger Log = Program.Logger.ForContext(); - private static readonly string ConfigFilePath; + private static readonly ILogger Log = Program.Logger.ForContext(typeof(PlusConfigManager)); - public static event Action? OnConfigChanged; + public static ConfigModel Config => ConfigManager.Config; - static PlusConfigManager() + /// Saves config via ConfigManager. + public static void TrySaveConfig() => ConfigManager.TrySaveConfig(); + + public static List GetDefaultRules() => DefaultRules.Create(); + + /// + /// Runs once from ConfigManager's initialiser, after the file is loaded and before it + /// is saved back. + /// + internal static void Initialize(ConfigModel config) { - ConfigFilePath = Path.Join(Program.DataPath, "PlusConfig.json"); - Log.Information("Loading Plus config from {Path}...", ConfigFilePath); + // TODO: Remove later - Migrating/repairing broken Dropbox rule pattern for existing users + MigrateBrokenDefaultRules(config); + EnsureDefaultRules(config); + } - PlusConfigModel? loaded = null; - try - { - if (File.Exists(ConfigFilePath)) - loaded = JsonConvert.DeserializeObject(File.ReadAllText(ConfigFilePath)); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to load Plus config, creating new one..."); - } + /// + /// TODO: Remove later - Repairs default rules that shipped with a broken pattern. + /// + private static void MigrateBrokenDefaultRules(ConfigModel config) + { + if (config.UriRules == null) + return; - if (loaded != null) + foreach (var rule in config.UriRules) { - Config = loaded; - Log.Information("Plus config loaded successfully."); - } - else - { - Log.Information("No Plus config found, creating new one..."); - Config = new PlusConfigModel(); - MigrateFromMainConfig(); - } + if (rule.Pattern != DefaultRules.LegacyDropboxPattern) + continue; - TrySaveConfig(); + Log.Information("Repairing broken default rule '{RuleName}' (Dropbox share rewrite).", rule.Name); + rule.Pattern = DefaultRules.DropboxForceDownloadPattern; + rule.RedirectTarget = DefaultRules.DropboxForceDownloadTarget; + } } + // The catch-all rule stays last; new defaults are inserted above it. + private const string CatchAllRuleName = "Everything else"; + + public static void EnsureDefaultRules() => EnsureDefaultRules(Config); + /// - /// On first run, pull any existing Plus-specific values from the main Config.json - /// so the user doesn't lose their settings. + /// Seeds default rules that this installation has not been offered before. /// - private static void MigrateFromMainConfig() + private static void EnsureDefaultRules(ConfigModel config) { - var configPath = Path.Join(Program.DataPath, "Config.json"); - if (!File.Exists(configPath)) - return; + var defaults = DefaultRules.Create(); - try + if (config.UriRules == null || config.UriRules.Count == 0) { - var json = JsonConvert.DeserializeObject>(File.ReadAllText(configPath)); - if (json == null) - return; - - if (json.TryGetValue("CacheDownloadRateLimitMBs", out var rate)) - Config.CacheDownloadRateLimitMBs = Convert.ToInt32(rate); - if (json.TryGetValue("CacheDownloadIdleSeconds", out var idle)) - Config.CacheDownloadIdleSeconds = Convert.ToInt32(idle); - if (json.TryGetValue("CacheYouTubePreferVp9", out var vp9)) - Config.CacheYouTubePreferVp9 = Convert.ToBoolean(vp9); - Log.Information("Migrated Plus settings from main Config.json."); + config.UriRules = defaults; + config.SeededDefaultRules = defaults.Select(rule => rule.Name).ToList(); + return; } - catch (Exception ex) + + if (config.SeededDefaultRules == null) + config.SeededDefaultRules = []; + + // Upgrading from a version with no seed tracking: everything the user already has + // has evidently been seeded. Anything missing is either a rule they deleted or a + // genuinely new default; both get offered exactly once here, and are then recorded. + if (config.SeededDefaultRules.Count == 0) { - Log.Warning(ex, "Failed to migrate Plus settings from main Config.json, using defaults."); + config.SeededDefaultRules = defaults + .Where(d => config.UriRules.Any(r => r.Name == d.Name || r.Pattern == d.Pattern)) + .Select(d => d.Name) + .ToList(); } - } - public static void TrySaveConfig() - { - var newConfig = JsonConvert.SerializeObject(Config, Formatting.Indented); - var oldConfig = File.Exists(ConfigFilePath) ? File.ReadAllText(ConfigFilePath) : string.Empty; - if (newConfig == oldConfig) - return; + foreach (var defRule in defaults) + { + if (config.SeededDefaultRules.Contains(defRule.Name)) + continue; - Log.Information("Plus config changed, saving..."); - File.WriteAllText(ConfigFilePath, newConfig); - Log.Information("Plus config saved."); - OnConfigChanged?.Invoke(); - } -} + if (config.UriRules.Any(r => r.Name == defRule.Name || r.Pattern == defRule.Pattern)) + { + config.SeededDefaultRules.Add(defRule.Name); + continue; + } -public class PlusConfigModel -{ - public int CacheDownloadRateLimitMBs { get; set; } // 0 = unlimited - public int CacheDownloadIdleSeconds { get; set; } = 30; // 0 = disabled - public bool CacheYouTubePreferVp9 { get; set; } = true; // VP9+aac in mp4 instead of h264+aac + var catchAllIndex = config.UriRules.FindIndex(r => r.Name == CatchAllRuleName); + if (catchAllIndex >= 0) + config.UriRules.Insert(catchAllIndex, defRule); + else + config.UriRules.Add(defRule); + + config.SeededDefaultRules.Add(defRule.Name); + Log.Information("Added new default rule '{RuleName}'.", defRule.Name); + } + + // Defensive: an earlier version could insert the same rule more than once. Keyed on + // a tuple rather than a "Name + \"|\" + Pattern" string, which could collide across + // differently-split name/pattern pairs. + config.UriRules = config.UriRules.DistinctBy(r => (r.Name, r.Pattern)).ToList(); + } } diff --git a/VRCVideoCacher/Program.cs b/VRCVideoCacher/Program.cs index e9c61891..bc62166d 100755 --- a/VRCVideoCacher/Program.cs +++ b/VRCVideoCacher/Program.cs @@ -9,6 +9,7 @@ using Serilog.Templates.Themes; using VRCVideoCacher.API; using VRCVideoCacher.Services; +using VRCVideoCacher.Integrations.VRDancing; using VRCVideoCacher.Utils; using VRCVideoCacher.YTDL; #if STEAMRELEASE @@ -29,6 +30,15 @@ internal sealed class Program public const string Creator_Haxy = "Haxy"; public const string Creator_Hauskaz = "Hauskaz"; public const string Creator_DubyaDude = "DubyaDude"; + + // Single source of truth for this fork's identity. The updater downloads and swaps in a + // release asset from here, so pointing it at the wrong repo silently replaces the user's + // install with a different build — keep every repo reference derived from these two. + public const string RepoOwner = "Bluscream"; + public const string RepoName = "VRCVideoCacherPlusPlus"; + public const string RepoUrl = $"https://github.com/{RepoOwner}/{RepoName}"; + public const string LatestReleaseUrl = $"{RepoUrl}/releases/latest"; + public const string LatestReleaseApiUrl = $"https://api.github.com/repos/{RepoOwner}/{RepoName}/releases/latest"; public static ILogger Logger = Log.ForContext("SourceContext", "Core"); public static readonly string CurrentProcessPath = Path.GetDirectoryName(Environment.ProcessPath) ?? string.Empty; public static readonly string DataPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VRCVideoCacher"); @@ -38,6 +48,28 @@ internal sealed class Program private const string SingleInstanceMutexName = @"Local\VRCVideoCacher_SingleInstance"; private static Mutex? _singleInstanceMutex; + private static readonly CancellationTokenSource ShutdownCts = new(); + + /// + /// Cancelled when the application is shutting down. Long-running background loops + /// should await on this so they unwind promptly instead of being terminated mid-step by + /// the Environment.Exit at the end of Main. + /// + public static CancellationToken ShutdownToken => ShutdownCts.Token; + + public static void SignalShutdown() + { + try + { + if (!ShutdownCts.IsCancellationRequested) + ShutdownCts.Cancel(); + } + catch (Exception ex) + { + Logger.Debug("Error signalling shutdown: {Error}", ex.Message); + } + } + private static bool TryAcquireSingleInstanceMutex() { _singleInstanceMutex = new Mutex(false, SingleInstanceMutexName); @@ -55,10 +87,19 @@ private static bool TryAcquireSingleInstanceMutex() [STAThread] public static void Main(string[] args) { - // Must run before Steam API init — this process may be a privileged subprocess invoked by ElevatorManager - HostsManager.TryRun(); LaunchArgs.SetupArguments(args); + // Logging comes first so that everything below is actually recorded. It used to be + // initialised further down, which meant HostsManager.TryRun, WaitForPreviousInstance + // and the kill-existing-instance branch all logged into Serilog's silent default + // sink — a failed elevated hosts edit produced no output anywhere at all. + InitializeLogger(); + + // Must run before Steam API init — this process may be a privileged subprocess + // invoked by ElevatorManager, in which case it does its one job and exits. + HostsManager.TryRun(); + Utils.ConnectionSevering.TryRunElevatedCommand(); + #if STEAMRELEASE if (LaunchArgs.SteamSdk) { @@ -124,37 +165,7 @@ public static void Main(string[] args) } Updater.Cleanup(); - InitializeLogger(); - - TaskScheduler.UnobservedTaskException += (_, e) => - { - if (e.Exception != null) - Logger.Warning(e.Exception, "Unobserved task exception"); - }; - -#if !DEBUG - AppDomain.CurrentDomain.UnhandledException += (_, e) => - { - try - { - var ex = e.ExceptionObject as Exception; - Logger.Error(ex, "Unhandled Exception"); - } - catch - { - } - - try - { - Console.WriteLine("Unhandled Exception: " + e.ExceptionObject); - } - catch - { - } - - Log.CloseAndFlush(); - }; -#endif + SetupGlobalExceptionHandlers(); if (!LaunchArgs.HasGui) { @@ -168,7 +179,9 @@ public static void Main(string[] args) // Start the UI — blocks until Avalonia shuts down BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); - // Force-exit so background threads (web server, download loop, OpenVR) don't keep the process alive + // Ask the background loops to unwind first, then force-exit as a backstop for + // anything still holding the process open (web server, OpenVR). + SignalShutdown(); Environment.Exit(0); } @@ -199,7 +212,9 @@ private static void InitializeLogger() rollingInterval: RollingInterval.Day, retainedFileCountLimit: 5); - if (LaunchArgs.HasGui) + // The hosts-edit subprocess has no UI, and UiLogSink reads ConfigManager.Config — + // which under elevation would create a second config under the admin's profile. + if (LaunchArgs.HasGui && !LaunchArgs.IsPrivilegedHelper) { loggerConfiguration = loggerConfiguration.WriteTo.Sink(new UiLogSink()); } @@ -232,30 +247,51 @@ private static async Task InitVrcVideoCacher() AppDomain.CurrentDomain.ProcessExit += (_, _) => OnAppQuit(); YtdlpHash = GetOurYtdlpHash(); + + // Nothing below needs the message of the day, so don't hold the application behind + // a network round trip to fetch it. + RunDetached(VvcConfigService.GetConfig(), "Config API fetch"); + if (ConfigManager.Config.YtdlpAutoUpdate && !LaunchArgs.UseGlobalPath) { + // Awaited deliberately: yt-dlp and Deno have to be on disk before the web + // server starts answering resolve requests with them. await Task.WhenAll( YtdlManager.TryDownloadYtdlp(), YtdlManager.TryDownloadDeno() ); YtdlManager.StartYtdlUpdaterThread(); - _ = YtdlManager.TryDownloadFfmpeg(); + RunDetached(YtdlManager.TryDownloadFfmpeg(), "FFmpeg download"); } if (OperatingSystem.IsWindows()) AutoStartShortcut.TryUpdateShortcutPath(); WebServer.Init(); - FileTools.BackupAllYtdl(); - await BulkPreCache.DownloadFileList(); + FileTools.ApplyPatchSettings(); + + // Mirrors listed in PreCacheUrls can run to gigabytes. Awaiting them meant the + // cache index and the download queue did not come up until every one had finished. + RunDetached(BulkPreCache.DownloadFileList(), "Bulk pre-cache"); + + // Console mode has no window to put a dialog on, so the same one-time notice the UI + // shows goes to the log instead. + if (!LaunchArgs.HasGui && !ConfigManager.Config.HasShownSharedConfigNotice) + { + Logger.Warning("{Notice}", Jeek.Avalonia.Localization.Localizer.Get("SharedConfigNotice")); + ConfigManager.Config.HasShownSharedConfigNotice = true; + ConfigManager.TrySaveConfig(); + } if (ConfigManager.Config.YtdlpUseCookies && !IsCookiesEnabledAndValid()) Logger.Warning("No cookies found, please use the browser extension to send cookies or disable \"ytdlUseCookies\" in config."); CacheManager.Init(); + VideoDownloader.Start(); // Runs after CacheManager.Init so already-cached videos are skipped; not awaited // because resolving each URL hits the network and must not delay startup. - _ = VideoPreCache.QueueConfiguredVideos(); + RunDetached(VideoPreCache.QueueConfiguredVideos(), "Video pre-cache"); VRDancingSheetService.StartBackgroundSync(); + VrcLogMonitor.Start(); // run after init to avoid text spam blocking user input if (OperatingSystem.IsWindows()) @@ -264,6 +300,17 @@ await Task.WhenAll( await Task.Delay(-1); } + /// + /// Starts a task without waiting for it, logging a failure rather than letting it + /// surface later as an unobserved task exception at an arbitrary GC. + /// + private static void RunDetached(Task task, string description) + { + _ = task.ContinueWith( + completed => Logger.Warning(completed.Exception?.GetBaseException(), "{Description} failed.", description), + TaskContinuationOptions.OnlyOnFaulted); + } + private static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() @@ -367,8 +414,8 @@ public static bool IsCookiesValid(string cookies) client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - using var response = await client.GetAsync("https://www.youtube.com/new", cts.Token); - return response.StatusCode == HttpStatusCode.OK; + using var response = await client.GetAsync("https://www.youtube.com/", cts.Token); + return (int)response.StatusCode >= 200 && (int)response.StatusCode < 400; } catch (Exception ex) { @@ -401,13 +448,15 @@ private static string GetOurYtdlpHash() return ComputeBinaryContentHash(ms.ToArray()); } - public static string ComputeBinaryContentHash(byte[] base64) + public static string ComputeBinaryContentHash(byte[] content) { - return Convert.ToBase64String(SHA256.HashData(base64)); + return Convert.ToBase64String(SHA256.HashData(content)); } private static void OnAppQuit() { + SignalShutdown(); + VrcLogMonitor.Stop(); API.WebServer.Stop(); FileTools.RestoreAllYtdl(); Logger.Information("Exiting..."); @@ -418,4 +467,68 @@ public static void NotifyCookiesUpdated() { OnCookiesUpdated?.Invoke(); } + + private static void SetupGlobalExceptionHandlers() + { + AppDomain.CurrentDomain.UnhandledException += (_, e) => + { + if (e.ExceptionObject is Exception ex) + { + Logger.Error(ex, "Unhandled AppDomain Exception"); + SaveCrashReport(ex, "AppDomain.CurrentDomain.UnhandledException"); + } + Log.CloseAndFlush(); + }; + + TaskScheduler.UnobservedTaskException += (_, e) => + { + if (e.Exception != null) + { + Logger.Warning(e.Exception, "Unobserved Task Exception"); + SaveCrashReport(e.Exception, "TaskScheduler.UnobservedTaskException"); + } + }; + + AppDomain.CurrentDomain.ProcessExit += (_, _) => + { + Logger.Information("ProcessExit signal received, performing shutdown tasks..."); + Log.CloseAndFlush(); + }; + } + + public static void SaveCrashReport(Exception ex, string source) + { + try + { + var reportPath = Path.Combine(DataPath, "CRASH_REPORT.txt"); + Directory.CreateDirectory(DataPath); + var reportContent = $@"================================================== +VRCVideoCacher Crash Report +Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} +Source: {source} +Version: {Version} +OS: {Environment.OSVersion} (64-bit: {Environment.Is64BitOperatingSystem}) +Process ID: {Environment.ProcessId} +Command Line: {Environment.CommandLine} +================================================== +Exception Type: {ex.GetType().FullName} +Message: {ex.Message} +-------------------------------------------------- +Stack Trace: +{ex.StackTrace} +================================================== +"; + if (ex.InnerException != null) + { + reportContent += $@" +Inner Exception: {ex.InnerException.GetType().FullName}: {ex.InnerException.Message} +{ex.InnerException.StackTrace} +================================================== +"; + } + + File.WriteAllText(reportPath, reportContent); + } + catch { /* Ignore errors writing crash report */ } + } } diff --git a/VRCVideoCacher/Services/LogService.cs b/VRCVideoCacher/Services/LogService.cs index 4c130a9e..7a7d8f1e 100644 --- a/VRCVideoCacher/Services/LogService.cs +++ b/VRCVideoCacher/Services/LogService.cs @@ -61,30 +61,60 @@ public class UiLogSink : ILogEventSink { private static PopupWindow? _currentPopup; + // The same error usually repeats — a failing CDN retried once per request, a tool that + // stays missing. A modal for each occurrence buries the user in dialogs, mid-session, + // in VR. Identical text is shown at most once per window. + private static readonly TimeSpan RepeatSuppression = TimeSpan.FromMinutes(1); + private static readonly object PopupLock = new(); + private static string? _lastMessage; + private static DateTime _lastShownAt = DateTime.MinValue; + public void Emit(LogEvent logEvent) { - if (ConfigManager.Config is { ErrorPopups: true } && logEvent.Level >= LogEventLevel.Error) + // Feed the log viewer first, so an entry still reaches it when the popup below is + // suppressed or the config isn't loaded yet. + LogService.EmitLogEntry(logEvent); + + if (ConfigManager.Config is not { ErrorPopups: true } || logEvent.Level < LogEventLevel.Error) + return; + + var message = logEvent.RenderMessage(); + lock (PopupLock) { - Dispatcher.UIThread.Post(() => - { - App.MainWindow?.Show(); - _currentPopup?.Close(); - _currentPopup = null; - var source = logEvent.Properties.TryGetValue("SourceContext", out var sourceContext) - ? sourceContext.ToString() - : "Unknown"; - var message = logEvent.RenderMessage(); - _currentPopup = new PopupWindow(message) - { - Title = $"Error from {source}" - }; - if (source.Contains("YtdlManager")) - _currentPopup.SetFolderHint( - "You can manually place deno.exe / yt-dlp.exe / ffmpeg.exe here:", - Program.UtilsPath); - _ = _currentPopup.ShowDialog(App.MainWindow!); - }); + var now = DateTime.UtcNow; + if (message == _lastMessage && now - _lastShownAt < RepeatSuppression) + return; + + _lastMessage = message; + _lastShownAt = now; } - LogService.EmitLogEntry(logEvent); + + var source = logEvent.Properties.TryGetValue("SourceContext", out var sourceContext) + ? sourceContext.ToString() + : "Unknown"; + + Dispatcher.UIThread.Post(() => + { + // No window yet — an error logged during startup, before the UI exists. The old + // code force-unwrapped App.MainWindow here, so that threw on the UI thread and + // brought the application down over a log line. + var owner = App.MainWindow; + if (owner == null) + return; + + if (!owner.IsVisible) + owner.Show(); + + _currentPopup?.Close(); + _currentPopup = new PopupWindow(message) + { + Title = $"Error from {source}" + }; + if (source.Contains("YtdlManager")) + _currentPopup.SetFolderHint( + "You can manually place deno.exe / yt-dlp.exe / ffmpeg.exe here:", + Program.UtilsPath); + _ = _currentPopup.ShowDialog(owner); + }); } } diff --git a/VRCVideoCacher/Services/OpenVRService.cs b/VRCVideoCacher/Services/OpenVRService.cs index 57829d8a..a6df09e1 100644 --- a/VRCVideoCacher/Services/OpenVRService.cs +++ b/VRCVideoCacher/Services/OpenVRService.cs @@ -39,25 +39,32 @@ public static void Start(string dataPath) switch (initError) { case EVRInitError.None: - // Upstream EllyVR build (including its Steam release) registers itself under - // "com.github.ellyvr.vrcvideocacher". If a user previously ran the Steam build - // and SteamVR still has that key set to auto-launch, SteamVR tries to launch - // it via Steam and Steam pops the store page when the app isn't owned. - // Proactively clear that auto-launch on startup. - const string LegacyAppKey = "com.github.ellyvr.vrcvideocacher"; - const string ForkAppKey = "com.github.codeyumx.vrcvideocacherplus"; - try + // Builds we may have previously registered as. The upstream EllyVR build + // (including its Steam release) uses "com.github.ellyvr.vrcvideocacher"; the + // codeyumx Plus fork — which this fork used to identify as — uses its own key. + // If SteamVR still has either set to auto-launch it tries to start them via + // Steam, which pops the store page when the app isn't owned. Clear both. + string[] legacyAppKeys = + [ + "com.github.ellyvr.vrcvideocacher", + "com.github.codeyumx.vrcvideocacherplus" + ]; + const string ForkAppKey = "com.github.bluscream.vrcvideocacherplusplus"; + foreach (var legacyAppKey in legacyAppKeys) { - if (OpenVR.Applications.IsApplicationInstalled(LegacyAppKey) && - OpenVR.Applications.GetApplicationAutoLaunch(LegacyAppKey)) + try { - Logger.Information("Disabling stale SteamVR auto-launch for legacy app key {Key}", LegacyAppKey); - OpenVR.Applications.SetApplicationAutoLaunch(LegacyAppKey, false); + if (OpenVR.Applications.IsApplicationInstalled(legacyAppKey) && + OpenVR.Applications.GetApplicationAutoLaunch(legacyAppKey)) + { + Logger.Information("Disabling stale SteamVR auto-launch for legacy app key {Key}", legacyAppKey); + OpenVR.Applications.SetApplicationAutoLaunch(legacyAppKey, false); + } + } + catch (Exception ex) + { + Logger.Warning(ex, "Failed to clear legacy auto-launch entry {Key}", legacyAppKey); } - } - catch (Exception ex) - { - Logger.Warning(ex, "Failed to clear legacy auto-launch entry"); } // Write the manifest with the real on-disk exe name so SteamVR auto-launch @@ -82,15 +89,19 @@ public static void Start(string dataPath) }] } """; - await File.WriteAllTextAsync(manifestPath, manifestJson); - var manifestError = OpenVR.Applications.AddApplicationManifest(manifestPath, false); - if (manifestError != EVRApplicationError.None) - { - Logger.Warning("Failed to register startup manifest: {Error}", manifestError); - } - else + // The manifest lands next to the executable, which may well be a + // read-only install directory. This runs inside a fire-and-forget + // Task, so an escaping exception surfaces only as an unobserved + // task fault — SteamVR registration failing is not worth that. + try { - if (OpenVR.Applications.IsApplicationInstalled(ForkAppKey)) + await File.WriteAllTextAsync(manifestPath, manifestJson); + var manifestError = OpenVR.Applications.AddApplicationManifest(manifestPath, false); + if (manifestError != EVRApplicationError.None) + { + Logger.Warning("Failed to register startup manifest: {Error}", manifestError); + } + else if (OpenVR.Applications.IsApplicationInstalled(ForkAppKey)) { Logger.Information("Startup manifest registered successfully"); @@ -102,6 +113,10 @@ public static void Start(string dataPath) Logger.Warning("Failed to register startup manifest"); } } + catch (Exception ex) + { + Logger.Warning(ex, "Could not write or register the SteamVR manifest at {Path}", manifestPath); + } if (LaunchArgs.CloseWithSteamVr) { diff --git a/VRCVideoCacher/Services/RuleEngine.cs b/VRCVideoCacher/Services/RuleEngine.cs new file mode 100644 index 00000000..af4e9cab --- /dev/null +++ b/VRCVideoCacher/Services/RuleEngine.cs @@ -0,0 +1,180 @@ +using System.Text.RegularExpressions; +using System.Web; +using Serilog; +using VRCVideoCacher.Models; + +namespace VRCVideoCacher.Services; + +public class RuleEvaluationResult +{ + public UriRule MatchedRule { get; set; } = null!; + public string FinalUrl { get; set; } = string.Empty; + public RuleAction Action { get; set; } = RuleAction.Direct; + public int? MaxResolution { get; set; } + public int? MaxDurationMinutes { get; set; } + public string RedirectUrl { get; set; } = string.Empty; +} + +public static class RuleEngine +{ + private static readonly Serilog.ILogger Log = Program.Logger.ForContext(typeof(RuleEngine)); + + public static event Action? OnRuleMatched; + + private static readonly System.Collections.Concurrent.ConcurrentDictionary RegexCache = new(); + + // Rules are few; this only exists so that a config edited into thousands of distinct + // patterns cannot grow the cache without bound. + private const int MaxCachedRegexes = 256; + + /// + /// Returns a cached for a rule pattern. + /// + /// Every rule was previously constructed fresh for every URL — a dozen pattern parses + /// per video request, and another dozen per keystroke in the Rules tab's live matcher. + /// Compiling once per distinct pattern instead makes evaluation essentially free. + /// + /// CultureInvariant matters as much as the caching: with IgnoreCase alone, case folding + /// follows the current culture, so under a Turkish locale "I" does not match "i" and + /// patterns like YOUTUBE\.COM quietly stop matching. + /// + public static Regex GetRegex(string pattern) + { + if (RegexCache.TryGetValue(pattern, out var cached)) + return cached; + + var regex = new Regex( + pattern, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(500)); + + if (RegexCache.Count >= MaxCachedRegexes) + RegexCache.Clear(); + + RegexCache[pattern] = regex; + return regex; + } + + public static RuleEvaluationResult EvaluateUrl(string requestUrl) + { + var currentUrl = requestUrl.Trim(); + var rules = PlusConfigManager.Config.UriRules; + + if (rules == null || rules.Count == 0) + { + rules = ConfigModel.GetDefaultRules(); + } + + foreach (var rule in rules) + { + if (!rule.Enabled || string.IsNullOrWhiteSpace(rule.Pattern)) + continue; + + try + { + var match = GetRegex(rule.Pattern).Match(currentUrl); + + if (!match.Success) + continue; + + Log.Information("URL '{URL}' matched rule '{RuleName}' ({Action})", currentUrl, rule.Name, rule.Action); + OnRuleMatched?.Invoke(rule.Id); + + var result = new RuleEvaluationResult + { + MatchedRule = rule, + Action = rule.Action, + FinalUrl = currentUrl, + MaxResolution = rule.MaxResolution, + MaxDurationMinutes = rule.MaxDurationMinutes + }; + + switch (rule.Action) + { + case RuleAction.Rewrite: + var expandedRewrite = ExpandTemplate(rule.RedirectTarget, currentUrl, match); + Log.Information("Rule '{RuleName}' rewritten URL: '{Original}' -> '{Rewritten}'", rule.Name, currentUrl, expandedRewrite); + currentUrl = expandedRewrite; + // Continue loop so lower rules evaluate against the rewritten URL + break; + + case RuleAction.Redirect: + var expandedRedirect = ExpandTemplate(rule.RedirectTarget, currentUrl, match); + Log.Information("Rule redirect expanded: '{Target}'", expandedRedirect); + result.RedirectUrl = expandedRedirect; + result.FinalUrl = expandedRedirect; + return result; + + case RuleAction.Block: + case RuleAction.Resolve: + case RuleAction.Direct: + default: + result.FinalUrl = currentUrl; + return result; + } + } + catch (Exception ex) + { + Log.Error(ex, "Error evaluating rule pattern '{Pattern}' for URL '{URL}'", rule.Pattern, currentUrl); + } + } + + // Fallback default if no rule matched + return new RuleEvaluationResult + { + MatchedRule = new UriRule { Name = "Everything else", Action = RuleAction.Resolve, Cache = false }, + Action = RuleAction.Resolve, + FinalUrl = currentUrl + }; + } + + public static string ExpandTemplate(string template, string originalUrl, Match regexMatch) + { + if (string.IsNullOrEmpty(template)) + return originalUrl; + + var result = template; + + // 1. First substitute regex capture groups ($0, $1, $2, etc.) + if (regexMatch.Success) + { + result = regexMatch.Result(result); + } + + // 2. Parse URL for token substitution {url...} + Uri.TryCreate(originalUrl, UriKind.Absolute, out var uri); + + // Token replacements + result = result.Replace("{url}", originalUrl); + result = result.Replace("{url.raw}", originalUrl); + result = result.Replace("{url.full}", originalUrl); + + if (uri != null) + { + result = result.Replace("{url.scheme}", uri.Scheme); + result = result.Replace("{url.host}", uri.Host); + result = result.Replace("{url.domain}", uri.Host); + result = result.Replace("{url.port}", uri.Port.ToString()); + result = result.Replace("{url.path}", uri.AbsolutePath); + result = result.Replace("{url.query}", uri.Query); + result = result.Replace("{url.authority}", uri.Authority); + result = result.Replace("{url.fragment}", uri.Fragment.TrimStart('#')); + result = result.Replace("{url.hash}", uri.Fragment.TrimStart('#')); + + // Handle {url.query.PARAM} replacements + if (result.Contains("{url.query.")) + { + var queryParams = HttpUtility.ParseQueryString(uri.Query); + var tokenRegex = new Regex(@"\{url\.query\.([a-zA-Z0-9_\-]+)\}"); + result = tokenRegex.Replace(result, m => + { + var paramName = m.Groups[1].Value; + var paramVal = queryParams[paramName]; + return paramVal ?? string.Empty; + }); + } + } + + return result; + } +} diff --git a/VRCVideoCacher/Services/VVCConfigService.cs b/VRCVideoCacher/Services/VVCConfigService.cs new file mode 100644 index 00000000..d569f1b4 --- /dev/null +++ b/VRCVideoCacher/Services/VVCConfigService.cs @@ -0,0 +1,55 @@ +using System.Text.Json.Serialization; +using Serilog; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.Services; + +public class VvcConfigService +{ + public static VvcConfig CurrentConfig = new(); + public static event Action? OnApiConfigChanged; + public static ILogger Logger = Log.ForContext(); + + // Short timeout: this runs on the startup path and there is nothing here worth + // delaying the application for. The 100s default would have stalled launch that long + // if the endpoint hung. + private static readonly HttpClient HttpClient = new() + { + DefaultRequestHeaders = { { "User-Agent", $"VRCVideoCacher v{Program.Version}" } }, + Timeout = TimeSpan.FromSeconds(10) + }; + + public static async Task GetConfig() + { + try + { + var req = await HttpClient.GetAsync("https://vvc.ellyvr.dev/api/v1/config"); + if (req.IsSuccessStatusCode) + { + var deserialized = Json.Deserialize(await req.Content.ReadAsStringAsync()); + if (deserialized != null) + { + CurrentConfig = deserialized; + OnApiConfigChanged?.Invoke(); + } + } + } + catch (Exception ex) + { + Logger.Warning(ex, "Failed to get config from Video Cacher API."); + } + + } +} + +public class VvcConfig +{ + [JsonPropertyName("motd")] + public string Motd { get; set; } = string.Empty; + + // Intentionally not consumed: ApiController pins the prefetch retry count locally + // rather than taking it from an upstream server. Kept so the payload shape is + // documented and an unknown-property change is visible here. + [JsonPropertyName("retryCount")] + public int RetryCount { get; set; } = 7; +} \ No newline at end of file diff --git a/VRCVideoCacher/Updater.cs b/VRCVideoCacher/Updater.cs index 0c3a31f8..53d3da5c 100644 --- a/VRCVideoCacher/Updater.cs +++ b/VRCVideoCacher/Updater.cs @@ -1,6 +1,4 @@ using System.Diagnostics; -using System.Security.Cryptography; -using Newtonsoft.Json; using Semver; using Serilog; using VRCVideoCacher.Models; @@ -10,7 +8,7 @@ namespace VRCVideoCacher; public class Updater { - private const string UpdateUrl = "https://api.github.com/repos/codeyumx/VRCVideoCacherPlus/releases/latest"; + private const string UpdateUrl = Program.LatestReleaseApiUrl; private static readonly string ReleaseAssetName = OperatingSystem.IsWindows() ? "VRCVideoCacher.exe" : "VRCVideoCacher"; private static readonly HttpClient HttpClient = new() { @@ -25,6 +23,15 @@ public class Updater public static async Task CheckForUpdates() { + // The Settings toggle is the user's "don't bother me about updates" switch. Honouring + // it here covers both callers — the startup check and the UI banner — so turning it + // off actually suppresses the network call as well as the prompt. + if (!ConfigManager.Config.AutoUpdateVrcVideoCacher) + { + Log.Information("Update check disabled in config. Skipping."); + return null; + } + Log.Information("Checking for updates..."); var isDebug = false; #if DEBUG @@ -58,7 +65,7 @@ public class Updater return null; } - var latestRelease = JsonConvert.DeserializeObject(data); + var latestRelease = Json.Deserialize(data); if (latestRelease == null) { Log.Warning("Failed to parse update response."); @@ -140,7 +147,7 @@ public static async Task ApplyUpdate(GitHubRelease release) await stream.CopyToAsync(fileStream); } - if (!await HashCheck(NewFilePath, asset.digest)) + if (!await FileHash.VerifyGitHubDigestAsync(NewFilePath, asset.digest, ReleaseAssetName)) { Log.Warning("Hash check failed, aborting update."); TryDelete(NewFilePath); @@ -203,18 +210,6 @@ public static async Task ApplyUpdate(GitHubRelease release) return true; // unreachable } - private static async Task HashCheck(string path, string githubHash) - { - using var sha256 = SHA256.Create(); - await using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - var hashBytes = await sha256.ComputeHashAsync(stream); - var hashString = Convert.ToHexString(hashBytes); - var expected = githubHash.Contains(':') ? githubHash.Split(':')[1] : githubHash; - var match = string.Equals(expected, hashString, StringComparison.OrdinalIgnoreCase); - Log.Information("FileHash: {FileHash} GitHubHash: {GitHubHash} HashMatch: {HashMatches}", hashString, expected, match); - return match; - } - private static void TryDelete(string path) { try diff --git a/VRCVideoCacher/Utils/AppJsonContext.cs b/VRCVideoCacher/Utils/AppJsonContext.cs new file mode 100644 index 00000000..1251b526 --- /dev/null +++ b/VRCVideoCacher/Utils/AppJsonContext.cs @@ -0,0 +1,30 @@ +using System.Text.Json.Serialization; +using VRCVideoCacher.Models; +using VRCVideoCacher.Integrations.VRDancing; +using VRCVideoCacher.Services; + +namespace VRCVideoCacher.Utils; + +/// +/// Source-generated serialisation metadata for every type this application reads or writes +/// as JSON. +/// +/// Generating the metadata rather than reflecting for it is what makes serialisation +/// trim-safe: the trimmer can see exactly which members are used, instead of the members +/// being reachable only through reflection it cannot follow. That was the whole reason +/// Newtonsoft needed the assembly rooted. +/// +/// IncludeFields is set here as well as on the options — ConfigModel is all public fields. +/// +[JsonSourceGenerationOptions( + IncludeFields = true, + WriteIndented = true, + PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(ConfigModel))] +[JsonSerializable(typeof(VersionJson))] +[JsonSerializable(typeof(GitHubRelease))] +[JsonSerializable(typeof(VvcConfig))] +[JsonSerializable(typeof(VRDSongInfo))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(List))] +internal partial class AppJsonContext : JsonSerializerContext; diff --git a/VRCVideoCacher/Utils/AtomicFile.cs b/VRCVideoCacher/Utils/AtomicFile.cs new file mode 100644 index 00000000..f5e3d619 --- /dev/null +++ b/VRCVideoCacher/Utils/AtomicFile.cs @@ -0,0 +1,62 @@ +using Serilog; + +namespace VRCVideoCacher.Utils; + +/// +/// Writes a small text file without the possibility of leaving a truncated one behind. +/// +/// File.WriteAllText truncates the target and then writes into it, so a crash — or a power +/// cut, or a full disk — in between leaves a zero-length or half-written file. That matters +/// here because every reader of these files responds to a parse failure by silently falling +/// back to defaults: the user loses their settings, their rules, and the record of which +/// tool versions are installed, with only a line in the log to say why. +/// +/// Writing to a sibling temp file and renaming it over the target makes the swap atomic, so +/// a reader sees either the old contents or the new ones and never something in between. +/// +public static class AtomicFile +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(AtomicFile)); + + // Config saves are infrequent and small; one lock across all of them is plenty and + // removes any chance of two writers interleaving on the same temp path. + private static readonly object WriteLock = new(); + + public static void WriteAllText(string path, string contents) + { + var tempPath = path + ".tmp"; + + lock (WriteLock) + { + try + { + using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var writer = new StreamWriter(stream)) + { + writer.Write(contents); + writer.Flush(); + // Push it to the platter before the rename: otherwise the rename can + // land while the contents are still only in the page cache, which is + // exactly the truncated-file case this is meant to prevent. + stream.Flush(flushToDisk: true); + } + + File.Move(tempPath, path, overwrite: true); + } + catch + { + try + { + if (File.Exists(tempPath)) + File.Delete(tempPath); + } + catch (Exception cleanupError) + { + Log.Debug("Could not remove temporary file {Path}: {Error}", tempPath, cleanupError.Message); + } + + throw; + } + } + } +} diff --git a/VRCVideoCacher/Utils/AutoStartShortcut.cs b/VRCVideoCacher/Utils/AutoStartShortcut.cs index fb575ef7..433cfda1 100644 --- a/VRCVideoCacher/Utils/AutoStartShortcut.cs +++ b/VRCVideoCacher/Utils/AutoStartShortcut.cs @@ -17,6 +17,22 @@ public class AutoStartShortcut [SupportedOSPlatform("windows")] public static void TryUpdateShortcutPath() + { + // Runs unguarded from startup. Everything below touches files in VRCX's startup + // folder that we do not own — a locked file, a corrupt .lnk or a permissions + // problem must not take the whole application down over a shortcut refresh. + try + { + UpdateShortcutPath(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to update the VRCX autostart shortcut; continuing without it."); + } + } + + [SupportedOSPlatform("windows")] + private static void UpdateShortcutPath() { RemoveLegacyShortcut(true); @@ -140,9 +156,17 @@ private static void RemoveLegacyShortcut(bool createIfAnyFound) private static List FindShortcutFiles(string folderPath) { - var directoryInfo = new DirectoryInfo(folderPath); - var files = directoryInfo.GetFiles(); var ret = new List(); + FileInfo[] files; + try + { + files = new DirectoryInfo(folderPath).GetFiles(); + } + catch (Exception ex) + { + Log.Warning(ex, "Could not enumerate {FolderPath}", folderPath); + return ret; + } foreach (var file in files) { @@ -155,16 +179,27 @@ private static List FindShortcutFiles(string folderPath) return ret; } + // Opens every file in a folder we don't own to sniff its header, so a single locked or + // unreadable file used to be enough to abort startup. Treat anything unreadable as + // "not one of ours" and move on. private static bool IsShortcutFile(string filePath) { - var headerBytes = new byte[4]; - using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - if (fileStream.Length >= 4) + try { - fileStream.ReadExactly(headerBytes, 0, 4); - } + var headerBytes = new byte[4]; + using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + if (fileStream.Length >= 4) + { + fileStream.ReadExactly(headerBytes, 0, 4); + } - return headerBytes.SequenceEqual(ShortcutSignatureBytes); + return headerBytes.SequenceEqual(ShortcutSignatureBytes); + } + catch (Exception ex) + { + Log.Debug("Could not read {FilePath} while looking for shortcuts: {Error}", filePath, ex.Message); + return false; + } } [SupportedOSPlatform("windows")] diff --git a/VRCVideoCacher/Utils/BulkPreCache.cs b/VRCVideoCacher/Utils/BulkPreCache.cs index d3ec9c4f..f614c850 100755 --- a/VRCVideoCacher/Utils/BulkPreCache.cs +++ b/VRCVideoCacher/Utils/BulkPreCache.cs @@ -1,16 +1,42 @@ -using Newtonsoft.Json; using Serilog; +using VRCVideoCacher.YTDL; namespace VRCVideoCacher.Utils; public class BulkPreCache { private static readonly ILogger Log = Program.Logger.ForContext(); + + // Generous but bounded: these are whole video files from a user-configured mirror, and + // the 100s default cancelled anything large. Unlike the main download path there is no + // per-read stall guard here, so an overall ceiling is what stops a dead mirror from + // hanging the startup pre-cache indefinitely. private static readonly HttpClient HttpClient = new() { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } } + DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, + Timeout = TimeSpan.FromMinutes(30) }; + /// + /// Manifest-supplied names are untrusted. Joining one straight onto the cache directory + /// let an entry like "../../Startup/evil.exe" write anywhere the process can reach. + /// Every legitimate entry is a bare "<videoId>.mp4", so require exactly that. + /// + internal static bool IsSafeCacheFileName(string? fileName) + { + if (string.IsNullOrWhiteSpace(fileName)) + return false; + + // Rejects any directory component, absolute paths, and drive-relative forms. + if (fileName != Path.GetFileName(fileName)) + return false; + + if (fileName is "." or "..") + return false; + + return fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0; + } + // FileName and Url are required // LastModified and Size are optional // e.g. JSON response @@ -59,7 +85,7 @@ internal static async Task ProcessManifests( if (content == null) continue; - files = JsonConvert.DeserializeObject>(content); + files = Json.Deserialize>(content); } catch (Exception ex) { @@ -73,8 +99,17 @@ internal static async Task ProcessManifests( continue; } - await downloadFiles(files); - Log.Information("All {Count} files for {URL} are up to date.", files.Count, url); + try + { + await downloadFiles(files); + Log.Information("All {Count} files for {URL} are up to date.", files.Count, url); + } + catch (Exception ex) + { + // DownloadFileList is awaited during startup, and in console mode there is + // nothing above it to catch — one unreachable mirror must not be fatal. + Log.Warning("Failed while downloading files for {Url}: {Error}", url, ex.Message); + } } } @@ -84,8 +119,11 @@ private static async Task DownloadVideos(List files) for (var index = 0; index < files.Count; index++) { var file = files[index]; - if (string.IsNullOrEmpty(file.FileName)) + if (!IsSafeCacheFileName(file.FileName)) + { + Log.Warning("Skipping manifest entry with an unsafe file name: {FileName}", file.FileName); continue; + } try { @@ -110,30 +148,71 @@ private static async Task DownloadVideos(List files) await DownloadFile(file); } } - catch (HttpRequestException ex) + catch (Exception ex) { - Log.Error("Error downloading {FileName}: {ExMessage}", file.FileName, ex.ToString()); + // Was HttpRequestException only, so a timeout (TaskCanceledException) or a + // disk error aborted the whole manifest instead of skipping one file. + Log.Warning("Error downloading {FileName}: {ExMessage}", file.FileName, ex.Message); } } } private static async Task DownloadFile(DownloadInfo fileInfo) { - using var response = await HttpClient.GetAsync(fileInfo.Url); + // ResponseHeadersRead so the body streams to disk instead of being buffered whole + // in memory — these entries are full video files. + using var response = await HttpClient.GetAsync(fileInfo.Url, HttpCompletionOption.ResponseHeadersRead); if (!response.IsSuccessStatusCode) { Log.Information("Failed to download {Url}: {ResponseStatusCode}", fileInfo.Url, response.StatusCode); return; } - var fileStream = new FileStream(fileInfo.FilePath, FileMode.Create, FileAccess.Write); - await response.Content.CopyToAsync(fileStream); - fileStream.Close(); - if (fileInfo.LastModified > 0) + + // Stage under the _tempVideo. prefix that BuildCache skips and SweepStaleTempFiles + // cleans up, then validate before publishing. Writing straight to the final name + // meant a mirror answering 200 with an HTML error page put that page into the cache + // under a .mp4 name, to be served to VRChat until someone noticed. + var tempPath = Path.Join(CacheManager.CachePath, $"_tempVideo.{fileInfo.FileName}"); + try { - await Task.Delay(10); - File.SetLastWriteTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); - File.SetCreationTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); - File.SetLastAccessTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); + await using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + await response.Content.CopyToAsync(fileStream); + } + + var contentType = response.Content.Headers.ContentType?.MediaType; + if (!VideoFileValidator.IsLikelyValidVideo(tempPath, contentType)) + { + Log.Warning("Discarding {FileName}: the downloaded body does not look like a video.", fileInfo.FileName); + VideoFileValidator.TryDelete(tempPath); + return; + } + + File.Move(tempPath, fileInfo.FilePath, overwrite: true); + } + catch + { + VideoFileValidator.TryDelete(tempPath); + throw; + } + + // Pinned across the timestamp rewrite and the publish. These files deliberately + // carry the manifest's own mtime, which can be years old, so the moment they are + // indexed they are the least-recently-used entry in the cache — without the pin, + // AddToCache's size-budget flush would delete what was just downloaded. + using (CacheManager.PinFile(fileInfo.FileName)) + { + if (fileInfo.LastModified > 0) + { + File.SetLastWriteTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); + File.SetCreationTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); + File.SetLastAccessTimeUtc(fileInfo.FilePath, fileInfo.LastModifiedDate); + } + + // Register with the cache, so these files count against the size budget and take + // part in LRU eviction like every other cached video. They used to be invisible to + // CacheManager entirely until the next restart rebuilt the index. + CacheManager.AddToCache(fileInfo.FileName); } } } \ No newline at end of file diff --git a/VRCVideoCacher/Utils/ConnectionSevering.cs b/VRCVideoCacher/Utils/ConnectionSevering.cs new file mode 100644 index 00000000..2952c34f --- /dev/null +++ b/VRCVideoCacher/Utils/ConnectionSevering.cs @@ -0,0 +1,484 @@ +using System.Diagnostics; +using System.Net; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Serilog; +using Vanara.PInvoke; +using static Vanara.PInvoke.IpHlpApi; + +namespace VRCVideoCacher.Utils; + +/// How a sever attempt against the operating system actually went. +public enum SeverOutcome +{ + /// Nothing matched — there was nothing to close. + NothingToDo, + + /// At least one socket was genuinely closed. + Severed, + + /// The kernel refused: this needs administrator/root and we do not have it. + NotPermitted, + + /// No mechanism exists on this platform, or the tooling is missing. + Unsupported, + + /// Attempted and failed for some other reason. + Failed +} + +/// +/// The result of severing. Local and remote are reported separately because they have very +/// different reliability, and conflating them is what let the previous implementation claim +/// success while doing nothing. +/// +public readonly record struct SeverResult(int LocalStreamsClosed, int RemoteSocketsSevered, SeverOutcome RemoteOutcome) +{ + public bool AnythingClosed => LocalStreamsClosed > 0 || RemoteSocketsSevered > 0; +} + +/// +/// Stops in-flight video playback. +/// +/// There are two very different cases, and the distinction matters: +/// +/// Local — the video is cached and VRChat is streaming it from our own web server. We +/// own that socket, so closing it always works, on every platform, with no +/// special privileges. +/// +/// Remote — the video is not cached and VRChat is talking to a CDN directly. Closing +/// somebody else's socket is a privileged operation: SetTcpEntry needs +/// administrator on Windows, and `ss -K` needs CAP_NET_ADMIN on Linux. +/// +/// The remote path therefore fails for most users, and it fails *quietly*: `ss` writes +/// "SOCK_DESTROY answers: Operation not permitted" to stderr, prints its column header to +/// stdout, and still exits 0. The previous implementation treated exit-code-0-plus-nonempty- +/// stdout as success, so it reported "Successfully severed N connections" every time while +/// changing nothing. Everything here is built around not doing that again: outcomes are +/// classified from what actually happened, and "not permitted" is reported as such. +/// +public static class ConnectionSevering +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(ConnectionSevering)); + + // ss reports a refused SOCK_DESTROY on stderr but still exits 0. + private const string PermissionDeniedMarker = "Operation not permitted"; + + // Exit codes of the elevated helper, read back by the unprivileged parent. Deliberately + // outside the 0-1 range so an unrelated crash is never mistaken for a real outcome. + private const int HelperSevered = 0; + private const int HelperNothingToDo = 10; + private const int HelperNotPermitted = 11; + private const int HelperUnsupported = 12; + private const int HelperFailed = 13; + + /// + /// Entry point for the short-lived privileged instance spawned by + /// . Closes the requested sockets and + /// exits — it never starts the UI, the web server, or touches the user's config. + /// + /// Called from Program.Main before anything else is initialised. + /// + public static void TryRunElevatedCommand() + { + if (!LaunchArgs.IsSeverCommand) + return; + + // This runs as root. Everything on the command line is re-parsed as an IP address and + // anything that is not one is dropped, so nothing reaches `ss` that could be read as a + // filter expression or a shell fragment. + var addresses = LaunchArgs.SeverAddresses + .Where(a => IPAddress.TryParse(a, out _)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + var rejected = LaunchArgs.SeverAddresses.Count - addresses.Count; + if (rejected > 0) + Log.Warning("Ignored {Count} --sever-connections value(s) that are not IP addresses.", rejected); + + if (addresses.Count == 0) + { + Environment.Exit(HelperNothingToDo); + return; + } + + var (severed, outcome) = SeverRemoteAsync(addresses).GetAwaiter().GetResult(); + Log.Information("Elevated sever helper closed {Count} socket(s): {Outcome}", severed, outcome); + + Environment.Exit(outcome switch + { + SeverOutcome.Severed => HelperSevered, + SeverOutcome.NothingToDo => HelperNothingToDo, + SeverOutcome.NotPermitted => HelperNotPermitted, + SeverOutcome.Unsupported => HelperUnsupported, + _ => HelperFailed + }); + } + + /// + /// Closes everything: our own streams, then best-effort on VRChat's direct connections. + /// + /// + /// Whether to fall back to an elevation prompt when the kernel refuses. Off by default: + /// this method is also called from the automatic "block all videos" toggle, and throwing a + /// polkit or UAC dialog at somebody mid-session because a setting flipped is hostile. Pass + /// true only when the user explicitly asked for this connection to be cut. + /// + public static async Task SeverAllAsync(bool allowElevation = false) + { + var localClosed = API.LocalStreamRegistry.CloseAll(); + if (localClosed > 0) + Log.Information("Closed {Count} cached-video stream(s) served by this application.", localClosed); + + var targets = YTDL.ActiveStreamTracker.GetActiveVideoIps(); + var (severed, outcome) = await SeverRemoteAsync(targets); + + if (outcome == SeverOutcome.NotPermitted && allowElevation) + (severed, outcome) = await SeverElevatedAsync(targets); + + YTDL.ActiveStreamTracker.ClearActiveVideoIps(); + LogOutcome(outcome, severed, targets.Count); + + return new SeverResult(localClosed, severed, outcome); + } + + /// + /// Closes the connections to one remote address. + /// + /// Does not touch other cached streams — severing one CDN connection used to call + /// CloseAllLocalStreams and take every other playing video down with it. + /// + public static async Task SeverAddressAsync(string address, bool allowElevation = false) + { + if (string.IsNullOrWhiteSpace(address)) + return new SeverResult(0, 0, SeverOutcome.NothingToDo); + + // Streaming from us: we own the socket, so this always works. + if (IsLoopback(address)) + { + var closed = API.LocalStreamRegistry.CloseAll(); + Log.Information("Closed {Count} local stream(s) for {Address}.", closed, address); + return new SeverResult(closed, 0, SeverOutcome.NothingToDo); + } + + var (severed, outcome) = await SeverRemoteAsync([address]); + + if (outcome == SeverOutcome.NotPermitted && allowElevation) + (severed, outcome) = await SeverElevatedAsync([address]); + + LogOutcome(outcome, severed, 1); + return new SeverResult(0, severed, outcome); + } + + /// + /// Re-runs the sever as root by asking the desktop's authorisation agent — polkit on + /// Linux (KDE, GNOME and the rest all ship an agent for it), UAC on Windows. The prompt + /// is the system's, so the password never passes through this process. + /// + /// Users who would rather never see the prompt can grant the capability once instead; + /// spells out how. + /// + private static async Task<(int, SeverOutcome)> SeverElevatedAsync(IReadOnlyCollection addresses) + { + var targets = addresses + .Where(a => IPAddress.TryParse(a, out _)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (targets.Count == 0) + return (0, SeverOutcome.NothingToDo); + + Log.Information("Requesting elevated privileges to close {Count} connection(s).", targets.Count); + + var exitCode = await ElevatorManager.RunElevatedSelfAsync( + $"--sever-connections={string.Join(',', targets)}"); + + if (exitCode is null) + { + // No elevation mechanism, or the user dismissed the prompt. Either way the + // original refusal still stands — say so rather than inventing a new failure. + Log.Information("Elevation was declined or unavailable. {Hint}", CapabilityHint); + return (0, SeverOutcome.NotPermitted); + } + + switch (exitCode) + { + case HelperSevered: + // The helper does not report a count across the process boundary; one + // confirmed close is enough for the UI to say the connection was cut. + return (targets.Count, SeverOutcome.Severed); + case HelperNothingToDo: + return (0, SeverOutcome.NothingToDo); + case HelperUnsupported: + return (0, SeverOutcome.Unsupported); + case HelperNotPermitted: + Log.Warning("Even with elevation the kernel refused to close the connection."); + return (0, SeverOutcome.NotPermitted); + default: + Log.Warning("Elevated sever helper exited with {Code}.", exitCode); + return (0, SeverOutcome.Failed); + } + } + + /// + /// The one-off alternative to being prompted every time. CAP_NET_ADMIN is exactly the + /// privilege SOCK_DESTROY requires, so granting it to the binary removes the need for + /// root entirely — this is the "do we still need sudo" answer, and the answer is no. + /// + /// It has to be re-applied after an update, because the updater replaces the binary and + /// file capabilities live on the inode. + /// + public static string CapabilityHint => + OperatingSystem.IsLinux() + ? $"To close connections without a password prompt, grant the capability once: " + + $"sudo setcap cap_net_admin+ep \"{Environment.ProcessPath}\" (re-apply after each update)." + : "Run VRCVideoCacher as administrator to close connections without a prompt."; + + private static bool IsLoopback(string address) => + IPAddress.TryParse(address, out var parsed) && IPAddress.IsLoopback(parsed); + + private static void LogOutcome(SeverOutcome outcome, int severed, int targetCount) + { + switch (outcome) + { + case SeverOutcome.Severed: + Log.Information("Severed {Count} direct connection(s) to video hosts.", severed); + break; + + case SeverOutcome.NotPermitted: + Log.Warning( + "Could not close VRChat's direct connections: this needs {Requirement}. " + + "Cached videos were still stopped, and further requests are blocked, but a video " + + "already streaming from a CDN will keep playing until it ends. {Hint}", + OperatingSystem.IsWindows() ? "administrator rights" : "root (CAP_NET_ADMIN)", + CapabilityHint); + break; + + case SeverOutcome.Unsupported: + Log.Information("No mechanism available on this platform to close VRChat's direct connections."); + break; + + case SeverOutcome.Failed: + Log.Warning("Failed to close VRChat's direct connections."); + break; + + case SeverOutcome.NothingToDo when targetCount == 0: + Log.Debug("No direct video connections were being tracked."); + break; + } + } + + private static async Task<(int Severed, SeverOutcome Outcome)> SeverRemoteAsync(IReadOnlyCollection addresses) + { + if (addresses.Count == 0) + return (0, SeverOutcome.NothingToDo); + + if (OperatingSystem.IsWindows()) + { + // Windows exposes MIB_TCP6ROW for *listing* IPv6 connections but has never shipped + // a SetTcp6Entry to close one — there is no public API for it at any privilege + // level, elevation included. Severing IPv6 here is not a permissions problem and + // must not be reported as one, or the UI will offer an elevation prompt that + // cannot possibly help. + var v6 = addresses.Where(IsIpV6).ToList(); + var v4 = addresses.Where(a => !IsIpV6(a)).ToList(); + + var result = v4.Count > 0 ? SeverRemoteWindows(v4) : (0, SeverOutcome.NothingToDo); + + if (v6.Count > 0) + { + Log.Warning( + "{Count} connection(s) are over IPv6, which Windows provides no way to close. " + + "Blocking still applies to new requests.", v6.Count); + + // Only downgrade when nothing else happened — an IPv4 sever that worked is + // still a success, it just did not cover everything. + if (result.Item2 == SeverOutcome.NothingToDo) + result = (result.Item1, SeverOutcome.Unsupported); + } + + return result; + } + + if (OperatingSystem.IsLinux()) + return await SeverRemoteLinuxAsync(addresses); + + return (0, SeverOutcome.Unsupported); + } + + private static bool IsIpV6(string address) => + IPAddress.TryParse(address, out var parsed) && + parsed.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6; + + [SupportedOSPlatform("windows")] + private static (int, SeverOutcome) SeverRemoteWindows(IReadOnlyCollection addresses) + { + var processes = NetworkConnections.GetVrChatProcesses(); + if (processes.Count == 0) + return (0, SeverOutcome.NothingToDo); + + var wanted = new HashSet(addresses, StringComparer.OrdinalIgnoreCase); + var severed = 0; + var denied = false; + var attempted = 0; + + const int afInet = 2; + uint bufferSize = 0; + GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, false, afInet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL); + if (bufferSize == 0) + return (0, SeverOutcome.NothingToDo); + + var buffer = Marshal.AllocHGlobal((int)bufferSize); + try + { + if (GetExtendedTcpTable(buffer, ref bufferSize, false, afInet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL) != 0) + return (0, SeverOutcome.Failed); + + var count = Marshal.ReadInt32(buffer); + var rowPtr = buffer + sizeof(int); + var rowSize = Marshal.SizeOf(); + + for (var i = 0; i < count; i++) + { + var row = Marshal.PtrToStructure(rowPtr); + rowPtr += rowSize; + + if (!processes.ContainsKey((int)row.dwOwningPid)) + continue; + + var remote = new IPAddress((long)row.dwRemoteAddr).ToString(); + if (!wanted.Contains(remote)) + continue; + + attempted++; + var closing = new MIB_TCPROW + { + dwState = MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB, + dwLocalAddr = row.dwLocalAddr, + dwLocalPort = row.dwLocalPort, + dwRemoteAddr = row.dwRemoteAddr, + dwRemotePort = row.dwRemotePort + }; + + var result = SetTcpEntry(closing); + if (result.Succeeded) + { + severed++; + continue; + } + + // ERROR_ACCESS_DENIED is the ordinary outcome without elevation, and it is + // the whole reason this feature appears to do nothing for most users. + if (result == Win32Error.ERROR_ACCESS_DENIED) + denied = true; + else + Log.Debug("SetTcpEntry failed for PID {Pid}: {Error}", row.dwOwningPid, result); + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + + if (severed > 0) + return (severed, SeverOutcome.Severed); + if (denied) + return (0, SeverOutcome.NotPermitted); + + return (0, attempted == 0 ? SeverOutcome.NothingToDo : SeverOutcome.Failed); + } + + private static async Task<(int, SeverOutcome)> SeverRemoteLinuxAsync(IReadOnlyCollection addresses) + { + var severed = 0; + var denied = false; + + foreach (var address in addresses) + { + if (string.IsNullOrWhiteSpace(address)) + continue; + + var outcome = await RunSsKillAsync(address); + + switch (outcome) + { + case SeverOutcome.Severed: + severed++; + break; + case SeverOutcome.NotPermitted: + denied = true; + break; + case SeverOutcome.Unsupported: + // ss is not installed; no point trying the remaining addresses. + return (severed, severed > 0 ? SeverOutcome.Severed : SeverOutcome.Unsupported); + } + } + + if (severed > 0) + return (severed, SeverOutcome.Severed); + if (denied) + return (0, SeverOutcome.NotPermitted); + + return (0, SeverOutcome.NothingToDo); + } + + /// + /// ss parses its address filter itself, and a bare IPv6 literal loses: the colons read as + /// a host:port separator, so `dst 2001:db8::1` is rejected with + /// "an inet prefix is expected rather than 2001:db8:" and nothing is closed. Brackets + /// disambiguate it, and IPv4 is unaffected either way — so this is the whole of IPv6 + /// support on Linux. + /// + internal static string FormatSsDestination(string address) => + IsIpV6(address) ? $"[{address}]" : address; + + /// + /// Runs `ss -t -K dst ADDRESS` and works out what really happened. + /// + /// Unlike Windows, Linux closes IPv6 sockets through the very same SOCK_DESTROY call, so + /// there is nothing extra to implement — only the filter has to be spelled correctly. + /// + /// ss exits 0 whether or not it managed to destroy anything, and always prints a column + /// header to stdout, so neither the exit code nor "stdout is non-empty" tells us + /// anything. What does: the permission error on stderr, and whether any socket rows were + /// printed beneath the header. + /// + private static async Task RunSsKillAsync(string address) + { + try + { + var result = await ProcessRunner.RunAsync("ss", ["-t", "-K", "dst", FormatSsDestination(address)]); + + if (result.Error.Contains(PermissionDeniedMarker, StringComparison.OrdinalIgnoreCase)) + { + Log.Debug("ss -K refused for {Address}: {Error}", address, result.Error); + return SeverOutcome.NotPermitted; + } + + if (result.ExitCode != 0) + { + Log.Debug("ss -K exited {Code} for {Address}: {Error}", result.ExitCode, address, result.Error); + return SeverOutcome.Failed; + } + + // First line is the header; anything after it is a socket that was destroyed. + var closedRows = result.Output + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Skip(1) + .Count(line => !string.IsNullOrWhiteSpace(line)); + + return closedRows > 0 ? SeverOutcome.Severed : SeverOutcome.NothingToDo; + } + catch (System.ComponentModel.Win32Exception) + { + // ss is not installed (iproute2 missing). + Log.Debug("ss is not available; cannot close VRChat's direct connections."); + return SeverOutcome.Unsupported; + } + catch (Exception ex) + { + Log.Debug("ss -K failed for {Address}: {Error}", address, ex.Message); + return SeverOutcome.Failed; + } + } +} diff --git a/VRCVideoCacher/Utils/ElevatorManager.cs b/VRCVideoCacher/Utils/ElevatorManager.cs index 28b63a58..bdd32afd 100644 --- a/VRCVideoCacher/Utils/ElevatorManager.cs +++ b/VRCVideoCacher/Utils/ElevatorManager.cs @@ -7,7 +7,23 @@ namespace VRCVideoCacher.Utils; public class ElevatorManager { private static readonly ILogger Log = Program.Logger.ForContext(); - public static bool HasHostsLine = HostsManager.IsHostAdded(); + // Reading /etc/hosts can throw (permissions, or the file simply being absent on a + // stripped-down system). A static field initialiser that throws surfaces as a + // TypeInitializationException from whatever first touched this class. + public static bool HasHostsLine = SafeIsHostAdded(); + + private static bool SafeIsHostAdded() + { + try + { + return HostsManager.IsHostAdded(); + } + catch (Exception ex) + { + Log.Warning(ex, "Could not read the hosts file; assuming the entry is absent."); + return false; + } + } private static readonly bool InPressureVessel = Directory.Exists("/run/pressure-vessel"); @@ -35,23 +51,44 @@ public class ElevatorManager return null; } - private static Process? MakeLinuxElevatedProcess(string flag) + private static Process? MakeLinuxElevatedProcess(params string[] flags) { var launchClient = InPressureVessel ? FindLaunchClient() : null; Log.Debug("InPressureVessel={InPressureVessel} launch-client={LC}", InPressureVessel, launchClient ?? "n/a"); string appPath = Environment.ProcessPath!; - ProcessStartInfo MakeStartInfo(string exe, string args) => launchClient != null - ? new ProcessStartInfo { FileName = launchClient, Arguments = $"--alongside-steam -- {exe} {args}", UseShellExecute = false } - : new ProcessStartInfo { FileName = exe, Arguments = args, UseShellExecute = false }; + // ArgumentList rather than a formatted command line: appPath is an install location + // that routinely contains spaces (a Steam library on an external drive, say), and + // interpolating it unquoted split it into two arguments — so the elevated command + // either failed or, worse, ran against a truncated path. + ProcessStartInfo MakeStartInfo(string exe, string[] args) + { + var psi = new ProcessStartInfo { UseShellExecute = false }; + if (launchClient != null) + { + psi.FileName = launchClient; + psi.ArgumentList.Add("--alongside-steam"); + psi.ArgumentList.Add("--"); + psi.ArgumentList.Add(exe); + } + else + { + psi.FileName = exe; + } + + foreach (var arg in args) + psi.ArgumentList.Add(arg); + + return psi; + } // 1. Try pkexec var pkexec = FindHostBin("pkexec"); if (pkexec != null) { Log.Debug("Using pkexec"); - return new Process { StartInfo = MakeStartInfo(pkexec, $"{appPath} {flag}") }; + return new Process { StartInfo = MakeStartInfo(pkexec, [appPath, .. flags]) }; } // 2. Try sudo -A with a graphical askpass helper @@ -67,7 +104,7 @@ ProcessStartInfo MakeStartInfo(string exe, string args) => launchClient != null var check = InPressureVessel ? $"/run/host{askpass}" : askpass; if (!File.Exists(check)) continue; Log.Debug("Using sudo -A with askpass: {Askpass}", askpass); - var psi = MakeStartInfo("/usr/bin/sudo", $"-A {appPath} {flag}"); + var psi = MakeStartInfo("/usr/bin/sudo", ["-A", appPath, .. flags]); psi.Environment["SUDO_ASKPASS"] = askpass; return new Process { StartInfo = psi }; } @@ -79,25 +116,81 @@ ProcessStartInfo MakeStartInfo(string exe, string args) => launchClient != null var termPath = FindHostBin(term); if (termPath == null) continue; Log.Debug("Using terminal {Term} with sudo", termPath); - var termArgs = termPath.Contains("gnome-terminal") - ? $"-- /usr/bin/sudo {appPath} {flag}" - : $"-e /usr/bin/sudo {appPath} {flag}"; - return new Process { StartInfo = MakeStartInfo(termPath, termArgs) }; + // gnome-terminal wants "-- cmd args", the others "-e cmd args". + var termFlag = termPath.Contains("gnome-terminal") ? "--" : "-e"; + return new Process { StartInfo = MakeStartInfo(termPath, [termFlag, "/usr/bin/sudo", appPath, .. flags]) }; } - Log.Error("No elevation method found. Please manually edit /etc/hosts."); + Log.Error("No elevation method found (tried pkexec, sudo with a graphical askpass, and a terminal)."); return null; } - public static void ToggleHostLine() + /// + /// Result of asking the system for elevation and running ourselves with . + /// + /// + /// The helper's exit code, or null when elevation was unavailable or the user dismissed + /// the prompt — those are not failures of the operation, they are the user declining it. + /// + public static async Task RunElevatedSelfAsync(string argument) { - if (HasHostsLine) - RemoveHostFile(); + Process? proc; + if (OperatingSystem.IsWindows()) + { + proc = new Process + { + StartInfo = { FileName = Environment.ProcessPath, Arguments = argument, UseShellExecute = true, Verb = "runas" } + }; + try + { + proc.Start(); + } + catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223) + { + Log.Information("User cancelled the UAC prompt."); + return null; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to launch elevated helper."); + return null; + } + } else - AddHostFile(); + { + proc = MakeLinuxElevatedProcess(argument); + if (proc == null) + return null; + + try + { + proc.Start(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to launch privilege elevator."); + return null; + } + } + + using (proc) + { + await proc.WaitForExitAsync(); + return proc.ExitCode; + } } - private static void AddHostFile() + /// + /// Adds or removes the hosts entry, elevating as required. + /// + /// Async because the elevation prompt is modal to the *system*, not to us: the previous + /// synchronous WaitForExit ran on the UI thread, so the whole window froze — no repaint, + /// no tray, no response — for as long as the UAC or polkit dialog stayed open. + /// + public static Task ToggleHostLineAsync() => + HasHostsLine ? RemoveHostFileAsync() : AddHostFileAsync(); + + private static async Task AddHostFileAsync() { Process? proc; if (OperatingSystem.IsWindows()) @@ -122,7 +215,7 @@ private static void AddHostFile() } } - proc.WaitForExit(); + await proc.WaitForExitAsync(); if (HostsManager.IsHostAdded()) { @@ -138,7 +231,7 @@ private static void AddHostFile() } } - private static void RemoveHostFile() + private static async Task RemoveHostFileAsync() { Process? proc; if (OperatingSystem.IsWindows()) @@ -163,7 +256,7 @@ private static void RemoveHostFile() } } - proc.WaitForExit(); + await proc.WaitForExitAsync(); if (!HostsManager.IsHostAdded()) { diff --git a/VRCVideoCacher/Utils/FileHash.cs b/VRCVideoCacher/Utils/FileHash.cs new file mode 100644 index 00000000..d9c986aa --- /dev/null +++ b/VRCVideoCacher/Utils/FileHash.cs @@ -0,0 +1,55 @@ +using System.Security.Cryptography; +using Serilog; + +namespace VRCVideoCacher.Utils; + +/// +/// SHA-256 helpers for checking downloaded binaries against the digest GitHub publishes +/// alongside each release asset. +/// +/// Everything this application downloads into the utils directory is subsequently marked +/// executable and run — yt-dlp, Deno and FFmpeg all are — so TLS alone is a thin guarantee. +/// +public static class FileHash +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(FileHash)); + + public static async Task ComputeSha256HexAsync(string path) + { + await using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); + var hash = await SHA256.HashDataAsync(stream); + return Convert.ToHexString(hash); + } + + /// + /// Verifies against a GitHub asset digest, which has the form + /// "sha256:<hex>". + /// + /// Returns true on a match, and also when GitHub published no digest at all: older + /// assets and third-party mirrors have none, and refusing those outright would break + /// tool updates entirely. That case is logged as a warning so it stays visible rather + /// than silently degrading to no verification. + /// + public static async Task VerifyGitHubDigestAsync(string path, string? digest, string label) + { + if (string.IsNullOrWhiteSpace(digest)) + { + Log.Warning("{Label}: no digest published for this asset, download cannot be verified.", label); + return true; + } + + var separator = digest.IndexOf(':'); + var expected = separator >= 0 ? digest[(separator + 1)..] : digest; + var actual = await ComputeSha256HexAsync(path); + + if (string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase)) + { + Log.Information("{Label}: digest verified.", label); + return true; + } + + Log.Error("{Label}: digest mismatch — expected {Expected}, got {Actual}. Discarding the download.", + label, expected, actual); + return false; + } +} diff --git a/VRCVideoCacher/Utils/HostsManager.cs b/VRCVideoCacher/Utils/HostsManager.cs index c3a13960..1ae9d64f 100644 --- a/VRCVideoCacher/Utils/HostsManager.cs +++ b/VRCVideoCacher/Utils/HostsManager.cs @@ -4,15 +4,23 @@ public class HostsManager { private static readonly Serilog.ILogger Log = Program.Logger.ForContext(); - private static readonly string Header = $"{Environment.NewLine}# ----- BEGIN VRCVIDEOCACHER -----{Environment.NewLine}"; - private static readonly string Footer = $"{Environment.NewLine}# ----- END VRCVIDEOCACHER -----{Environment.NewLine}"; + // Detection keys off the bare markers, not the newline-wrapped forms below: the hosts + // file may use LF while Environment.NewLine is CRLF, and a mismatch there made + // IsHostAdded report "absent" for a block that was plainly present — which in turn made + // Add() append a second copy every time. + private const string HeaderMarker = "# ----- BEGIN VRCVIDEOCACHER -----"; + private const string FooterMarker = "# ----- END VRCVIDEOCACHER -----"; + private const string ManagedHostLine = "127.0.0.1 localhost.youtube.com"; + + private static readonly string Header = $"{Environment.NewLine}{HeaderMarker}{Environment.NewLine}"; + private static readonly string Footer = $"{Environment.NewLine}{FooterMarker}{Environment.NewLine}"; private static readonly string HostsPath = OperatingSystem.IsWindows() ? $"{Environment.GetFolderPath(Environment.SpecialFolder.System)}/drivers/etc/hosts" : "/etc/hosts"; public static void TryRun() { - if (Environment.CommandLine.Contains("--addhost")) + if (LaunchArgs.AddHost) { try { @@ -26,7 +34,7 @@ public static void TryRun() Environment.Exit(1); } } - if (Environment.CommandLine.Contains("--removehost")) + if (LaunchArgs.RemoveHost) { try { @@ -46,24 +54,46 @@ private static void Add() { CreateHostsIfNotExists(); var hostsFile = File.ReadAllText(HostsPath); - if (hostsFile.Contains(Header)) + if (hostsFile.Contains(HeaderMarker, StringComparison.Ordinal)) return; - File.AppendAllText(HostsPath, - $"{Header}127.0.0.1 localhost.youtube.com{Footer}"); + File.AppendAllText(HostsPath, $"{Header}{ManagedHostLine}{Footer}"); } private static void Remove() { CreateHostsIfNotExists(); var hostsFile = File.ReadAllText(HostsPath); - if (!hostsFile.Contains(Header)) + + var headerStart = hostsFile.IndexOf(HeaderMarker, StringComparison.Ordinal); + if (headerStart < 0) return; - var headerStart = hostsFile.IndexOf(Header, StringComparison.Ordinal); - var headerEnd = hostsFile.IndexOf(Footer, StringComparison.Ordinal) + Footer.Length; - var newHostsFile = hostsFile.Remove(headerStart, headerEnd - headerStart); - File.WriteAllText(HostsPath, newHostsFile); + // Search for the footer *after* the header. Searching from index 0 meant that a + // hand-edited file with the footer deleted (IndexOf returns -1) or sitting before + // the header yielded a negative length, and String.Remove threw + // ArgumentOutOfRangeException — inside an elevated subprocess, where it is close to + // invisible and leaves the entry in place. + var footerStart = hostsFile.IndexOf(FooterMarker, headerStart, StringComparison.Ordinal); + if (footerStart >= 0) + { + var blockEnd = footerStart + FooterMarker.Length; + File.WriteAllText(HostsPath, hostsFile.Remove(headerStart, blockEnd - headerStart)); + return; + } + + // No footer, so there is no way to know how far the block was meant to extend, and + // everything after it may be the user's own entries. Drop only the marker and the + // single line we manage rather than guessing. + Log.Warning("Hosts block end marker missing; removing only the start marker and the managed entry."); + var kept = hostsFile + .Split('\n') + .Where(line => + { + var trimmed = line.Trim(); + return trimmed != HeaderMarker && trimmed != FooterMarker && trimmed != ManagedHostLine; + }); + File.WriteAllText(HostsPath, string.Join('\n', kept)); } public static bool IsHostAdded() @@ -72,7 +102,7 @@ public static bool IsHostAdded() return false; var hostsFile = File.ReadAllText(HostsPath); - return hostsFile.Contains(Header); + return hostsFile.Contains(HeaderMarker, StringComparison.Ordinal); } private static void CreateHostsIfNotExists() diff --git a/VRCVideoCacher/Utils/HttpUtil.cs b/VRCVideoCacher/Utils/HttpUtil.cs deleted file mode 100644 index 18b23722..00000000 --- a/VRCVideoCacher/Utils/HttpUtil.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace VRCVideoCacher.Utils; - -public class HttpUtil -{ - internal static readonly HttpClient HttpClient = new() - { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } } - }; -} \ No newline at end of file diff --git a/VRCVideoCacher/Utils/Json.cs b/VRCVideoCacher/Utils/Json.cs new file mode 100644 index 00000000..0f7f6503 --- /dev/null +++ b/VRCVideoCacher/Utils/Json.cs @@ -0,0 +1,61 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace VRCVideoCacher.Utils; + +/// +/// The single System.Text.Json configuration used for every file and API payload. +/// +/// Three of these settings exist specifically to reproduce what Newtonsoft did, because +/// these options read and write files that already exist on every user's disk: +/// +/// IncludeFields — ConfigModel's twenty-five settings are public fields, not properties, +/// and STJ ignores fields unless told otherwise. Without this, every +/// setting would read back as its default: a silent config reset for +/// everyone on upgrade. +/// Encoder — the default encoder escapes &, + and < as \u00XX, which would turn +/// every URL and every regex pattern in the rule list into something +/// unreadable. These files go to disk and are never embedded in HTML, +/// so relaxed escaping is the correct trade. +/// WriteIndented — matches Newtonsoft's Formatting.Indented, so a saved file stays +/// diffable and hand-editable. +/// +/// Enums serialise as numbers in both libraries, so RuleAction values already on disk are +/// read back unchanged. +/// +public static class Json +{ + public static readonly JsonSerializerOptions Options = Create(); + + private static JsonSerializerOptions Create() + { + var options = new JsonSerializerOptions + { + IncludeFields = true, + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + + // Tolerate a hand-edited file rather than discarding the whole config over a + // stray comma or comment. + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip, + + // Newtonsoft matched property names case-insensitively; config files and the + // GitHub API both rely on that. + PropertyNameCaseInsensitive = true, + }; + + // Source-generated metadata first, reflection second. The generated context covers + // everything this application serialises, so the reflection resolver is only a + // fallback — but keeping it means a type added later still works before somebody + // remembers to register it. + options.TypeInfoResolverChain.Add(AppJsonContext.Default); + options.TypeInfoResolverChain.Add(new DefaultJsonTypeInfoResolver()); + return options; + } + + public static T? Deserialize(string json) => JsonSerializer.Deserialize(json, Options); + + public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); +} diff --git a/VRCVideoCacher/Utils/LaunchArgs.cs b/VRCVideoCacher/Utils/LaunchArgs.cs index 0bf7a89c..65f1ac31 100644 --- a/VRCVideoCacher/Utils/LaunchArgs.cs +++ b/VRCVideoCacher/Utils/LaunchArgs.cs @@ -9,6 +9,9 @@ public class LaunchArgs private const string NoSteamArg = "--no-steam"; private const string NoOvrArg = "--no-ovr"; private const string CloseWithSteamVrArg = "--close-with-steamvr"; + private const string AddHostArg = "--addhost"; + private const string RemoveHostArg = "--removehost"; + private const string SeverArg = "--sever-connections"; public static bool HasGui = true; public static bool UseGlobalPath; @@ -17,6 +20,28 @@ public class LaunchArgs public static bool SteamSdk = true; public static bool OVR = true; public static bool CloseWithSteamVr = false; + public static bool AddHost = false; + public static bool RemoveHost = false; + + /// + /// Addresses passed to an elevated instance spawned purely to close sockets and exit. + /// Populated from --sever-connections=1.2.3.4,2001:db8::1 + /// + public static IReadOnlyList SeverAddresses = []; + + /// + /// True when this process was spawned by the elevation helper purely to edit the hosts + /// file and exit. Such a process has no UI and should not touch user config. + /// + public static bool IsHostsEdit => AddHost || RemoveHost; + + /// True when this process exists only to sever connections and exit. + public static bool IsSeverCommand => SeverAddresses.Count > 0; + + /// + /// A short-lived privileged helper: no window, no config writes, no background work. + /// + public static bool IsPrivilegedHelper => IsHostsEdit || IsSeverCommand; public static void SetupArguments(params string[] args) { @@ -46,9 +71,31 @@ public static void SetupArguments(params string[] args) if (arg.Equals(CloseWithSteamVrArg, StringComparison.OrdinalIgnoreCase)) CloseWithSteamVr = true; + + if (arg.Equals(AddHostArg, StringComparison.OrdinalIgnoreCase)) + AddHost = true; + + if (arg.Equals(RemoveHostArg, StringComparison.OrdinalIgnoreCase)) + RemoveHost = true; + + if (arg.StartsWith(SeverArg + "=", StringComparison.OrdinalIgnoreCase)) + { + SeverAddresses = arg[(SeverArg.Length + 1)..] + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .ToList(); + } } } + /// + /// Reconstructs the flags this process was started with, so that the updater's relaunch + /// preserves how the user (or SteamVR, or VRCX) launched it. Only --no-gui and + /// --global-path used to be re-emitted, so an update silently dropped --no-steam, + /// --no-ovr, --close-with-steamvr and --kill-existing-instance. + /// + /// Deliberately excludes --wait-for-pid, which the updater supplies itself, and the + /// one-shot hosts commands, which belong to a subprocess that exits immediately. + /// public static List BuildArgs() { var args = new List(); @@ -58,6 +105,18 @@ public static List BuildArgs() if (UseGlobalPath) args.Add(GlobalPathArg); + if (!SteamSdk) + args.Add(NoSteamArg); + + if (!OVR) + args.Add(NoOvrArg); + + if (CloseWithSteamVr) + args.Add(CloseWithSteamVrArg); + + if (KillExistingInstance) + args.Add(KillExistingInstanceArg); + return args; } } diff --git a/VRCVideoCacher/Utils/LoggerUtils.cs b/VRCVideoCacher/Utils/LoggerUtils.cs index b506af45..d543ec01 100644 --- a/VRCVideoCacher/Utils/LoggerUtils.cs +++ b/VRCVideoCacher/Utils/LoggerUtils.cs @@ -23,16 +23,17 @@ public static void LogUnhandledException(Exception ex, string message) Program.Logger.Error(ex, "{Message}", message); var logFile = Path.Combine(LogsPath, $"VRCVideoCacher{(LoggerStartDateTime ?? DateTime.Now):yyyyMMdd}.log"); - if (OperatingSystem.IsWindows()) + if (OperatingSystem.IsWindows() && File.Exists(logFile)) { - if (File.Exists(logFile)) - Process.Start("explorer.exe", $"/select,\"{logFile}\""); - else - Process.Start("explorer.exe", LogsPath); + // /select, needs the argument as a single token including the comma, which + // ArgumentList would quote wrongly — so this one case stays hand-built. + var psi = new ProcessStartInfo { FileName = "explorer.exe", UseShellExecute = false }; + psi.ArgumentList.Add($"/select,{logFile}"); + Process.Start(psi); } - else if (OperatingSystem.IsLinux()) + else { - Process.Start("xdg-open", LogsPath); + OpenUrl.OpenFolder(LogsPath); } } catch diff --git a/VRCVideoCacher/Utils/MarkdownInlineParser.cs b/VRCVideoCacher/Utils/MarkdownInlineParser.cs new file mode 100644 index 00000000..73d3baa4 --- /dev/null +++ b/VRCVideoCacher/Utils/MarkdownInlineParser.cs @@ -0,0 +1,204 @@ +using System.Text; + +namespace VRCVideoCacher.Utils; + +/// One piece of a parsed MOTD: a run of text, or a line break. +/// The literal text to show. Empty for a line break. +/// Non-null when this run is a link. Always an absolute http/https URL. +public readonly record struct MarkdownSpan( + string Text, + bool Bold = false, + bool Italic = false, + string? Url = null, + bool LineBreak = false); + +/// +/// Parses the small markdown subset the MOTD banner supports: [text](url), bare URLs, +/// **bold**, *italic* and newlines. Anything else — including unterminated markers — is +/// literal text, because the MOTD is written by hand and half-rendered markup is worse than none. +/// +/// This deliberately holds no Avalonia types. It is the part with all the edge cases, so keeping it +/// pure means it can be unit-tested without a headless UI harness; Controls.MarkdownText turns +/// the spans into inlines. +/// +/// URLs are validated here, not at render time. The MOTD is remote content, so a candidate only +/// becomes a link if it parses as an absolute http/https URI — a javascript: or file: URL +/// never reaches a clickable control at all. re-checks on click; both gates +/// are intentional. +/// +public static class MarkdownInlineParser +{ + // Trailing punctuation almost always belongs to the sentence, not the URL: + // "see https://x.dev/page." should link the page, not the full stop. + private const string TrailingPunctuation = ".,;:!?)]}'\""; + + public static IReadOnlyList Parse(string? text) + { + var spans = new List(); + if (string.IsNullOrEmpty(text)) + return spans; + + var buffer = new StringBuilder(); + var bold = false; + var italic = false; + var i = 0; + + void Flush() + { + if (buffer.Length == 0) + return; + spans.Add(new MarkdownSpan(buffer.ToString(), bold, italic)); + buffer.Clear(); + } + + while (i < text.Length) + { + var c = text[i]; + + // Escapes: \* \[ \\ emit the next character literally. + if (c == '\\' && i + 1 < text.Length && text[i + 1] is '*' or '[' or '\\') + { + buffer.Append(text[i + 1]); + i += 2; + continue; + } + + if (c is '\n') + { + Flush(); + spans.Add(new MarkdownSpan(string.Empty, LineBreak: true)); + i++; + continue; + } + + if (c is '\r') + { + i++; // \r\n — the \n does the work + continue; + } + + if (c == '[' && TryParseLink(text, i, out var linkText, out var linkUrl, out var linkEnd)) + { + Flush(); + spans.Add(new MarkdownSpan(linkText, bold, italic, linkUrl)); + i = linkEnd; + continue; + } + + if (c is 'h' && TryParseBareUrl(text, i, out var bareUrl, out var bareEnd)) + { + Flush(); + spans.Add(new MarkdownSpan(bareUrl, bold, italic, bareUrl)); + i = bareEnd; + continue; + } + + // Emphasis only toggles when there is a closing marker; otherwise a lone "*" is just an + // asterisk and the rest of the message must not silently turn italic. + if (c == '*') + { + var isBold = i + 1 < text.Length && text[i + 1] == '*'; + var marker = isBold ? "**" : "*"; + var open = isBold ? !bold : !italic; + + if (!open || HasCloser(text, i + marker.Length, marker)) + { + Flush(); + if (isBold) bold = !bold; else italic = !italic; + i += marker.Length; + continue; + } + } + + buffer.Append(c); + i++; + } + + Flush(); + return spans; + } + + /// [text](url). Fails (so the '[' stays literal) on a malformed or non-web URL. + private static bool TryParseLink(string text, int start, out string linkText, out string url, out int end) + { + linkText = string.Empty; + url = string.Empty; + end = start; + + var close = text.IndexOf(']', start + 1); + if (close < 0 || close + 1 >= text.Length || text[close + 1] != '(') + return false; + + var urlEnd = text.IndexOf(')', close + 2); + if (urlEnd < 0) + return false; + + var candidate = text[(close + 2)..urlEnd].Trim(); + if (!IsWebUrl(candidate)) + return false; + + linkText = text[(start + 1)..close]; + if (linkText.Length == 0) + return false; + + url = candidate; + end = urlEnd + 1; + return true; + } + + /// A bare http(s):// URL running to the next whitespace, minus trailing punctuation. + private static bool TryParseBareUrl(string text, int start, out string url, out int end) + { + url = string.Empty; + end = start; + + if (!text.AsSpan(start).StartsWith("http://", StringComparison.OrdinalIgnoreCase) && + !text.AsSpan(start).StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + return false; + + var stop = start; + while (stop < text.Length && !char.IsWhiteSpace(text[stop])) + stop++; + + var candidate = text[start..stop]; + while (candidate.Length > 0 && TrailingPunctuation.Contains(candidate[^1])) + candidate = candidate[..^1]; + + if (!IsWebUrl(candidate)) + return false; + + url = candidate; + end = start + candidate.Length; + return true; + } + + private static bool IsWebUrl(string candidate) => + Uri.TryCreate(candidate, UriKind.Absolute, out var uri) && + (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); + + /// Is there a matching closing marker later on? A lone "*" must stay literal. + private static bool HasCloser(string text, int from, string marker) + { + if (marker == "**") + return text.IndexOf("**", from, StringComparison.Ordinal) >= 0; + + // A single "*" is only closed by a lone "*". Asterisks belonging to a "**" pair do not count, + // or "2 * 3 is not **bold" would treat the bold marker as the italic closer. + for (var i = from; i < text.Length; i++) + { + if (text[i] != '*') + continue; + + var runEnd = i; + while (runEnd + 1 < text.Length && text[runEnd + 1] == '*') + runEnd++; + + if (runEnd == i) + return true; + + i = runEnd; // skip the whole run of asterisks + } + + return false; + } +} diff --git a/VRCVideoCacher/Utils/NetworkConnections.cs b/VRCVideoCacher/Utils/NetworkConnections.cs new file mode 100644 index 00000000..4f5729af --- /dev/null +++ b/VRCVideoCacher/Utils/NetworkConnections.cs @@ -0,0 +1,381 @@ +using System.Diagnostics; +using System.Net; +using System.Runtime.InteropServices; +using Serilog; +using Vanara.PInvoke; +using static Vanara.PInvoke.IpHlpApi; + +namespace VRCVideoCacher.Utils; + +/// +/// Read-only enumeration of the TCP connections owned by VRChat. +/// +/// Deliberately separate from : listing is safe, needs no +/// privileges and drives a UI that refreshes on a timer, whereas severing is privileged and +/// destructive. Keeping them together made it easy to assume that seeing a connection meant +/// being able to close it, which is not true on either platform. +/// +public static class NetworkConnections +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(NetworkConnections)); + + // Ports worth showing: our own server, and plain HTTP/HTTPS to a CDN. + private static readonly int[] InterestingPorts = [9696, 80, 443]; + + // Enumerating every process is expensive and the answer barely changes, so it is cached + // briefly. This runs on a repeating refresh, and Process.GetProcesses() is by far the + // most costly part of a tick. + private static readonly TimeSpan PidCacheLifetime = TimeSpan.FromSeconds(15); + private static readonly object PidCacheLock = new(); + private static Dictionary _cachedPids = []; + private static DateTime _pidsCachedAt = DateTime.MinValue; + + /// + /// VRChat's PIDs mapped to process names. Cached for a few seconds. + /// + public static Dictionary GetVrChatProcesses() + { + lock (PidCacheLock) + { + if (DateTime.UtcNow - _pidsCachedAt < PidCacheLifetime) + return _cachedPids; + } + + var found = new Dictionary(); + foreach (var process in Process.GetProcesses()) + { + try + { + var name = process.ProcessName; + // Match VRChat itself, not this application — "VRCVideoCacher" must never + // appear here or we would list and sever our own connections. + if (name.Equals("VRChat", StringComparison.OrdinalIgnoreCase) || + name.StartsWith("VRChat.", StringComparison.OrdinalIgnoreCase)) + { + found[process.Id] = name; + } + } + catch + { + // Process exited between enumeration and inspection, or is inaccessible. + } + finally + { + process.Dispose(); + } + } + + lock (PidCacheLock) + { + _cachedPids = found; + _pidsCachedAt = DateTime.UtcNow; + } + + return found; + } + + /// + /// Lists VRChat's current TCP connections on ports we care about. Safe to call from a + /// background thread; never touches the UI. + /// + public static List List() + { + try + { + if (OperatingSystem.IsWindows()) + return ListWindows(); + + if (OperatingSystem.IsLinux()) + return ListLinux(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to list active connections."); + } + + return []; + } + + private static void Annotate(ActiveConnectionInfo info) + { + if (YTDL.ActiveStreamTracker.TryGetUrlInfo(info.RemoteAddress, out var urlInfo)) + { + info.AssociatedUrl = urlInfo.OriginalUrl; + info.AssociatedTitle = urlInfo.Title; + return; + } + + var match = YTDL.ActiveStreamTracker.GetActiveSessions() + .FirstOrDefault(s => s.RemoteIp == info.RemoteAddress); + if (match == null) + return; + + info.AssociatedUrl = match.OriginalUrl; + info.AssociatedTitle = match.Title; + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static List ListWindows() + { + var list = new List(); + var processes = GetVrChatProcesses(); + if (processes.Count == 0) + return list; + + foreach (var row in ReadWindowsTcpTable()) + { + if (!processes.TryGetValue((int)row.dwOwningPid, out var processName)) + continue; + + var localPort = NetworkPort(row.dwLocalPort); + var remotePort = NetworkPort(row.dwRemotePort); + if (!InterestingPorts.Contains(localPort) && !InterestingPorts.Contains(remotePort)) + continue; + + var info = new ActiveConnectionInfo + { + LocalAddress = new IPAddress((long)row.dwLocalAddr).ToString(), + LocalPort = localPort, + RemoteAddress = new IPAddress((long)row.dwRemoteAddr).ToString(), + RemotePort = remotePort, + OwningPid = (int)row.dwOwningPid, + ProcessName = processName + }; + + Annotate(info); + list.Add(info); + } + + return list; + } + + /// + /// Reads the IPv4 TCP table with owning PIDs. + /// + /// Note this is IPv4 only: there is no IPv6 equivalent wired up, so an IPv6 stream is + /// invisible here and cannot be severed. CDNs increasingly serve over IPv6, which is a + /// real gap rather than a theoretical one. + /// + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static IEnumerable ReadWindowsTcpTable() + { + const int afInet = 2; + + uint bufferSize = 0; + GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, false, afInet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL); + if (bufferSize == 0) + yield break; + + var buffer = Marshal.AllocHGlobal((int)bufferSize); + try + { + var result = GetExtendedTcpTable(buffer, ref bufferSize, false, afInet, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL); + if (result != 0) + { + Log.Debug("GetExtendedTcpTable returned {Result}", result); + yield break; + } + + var count = Marshal.ReadInt32(buffer); + var rowPtr = buffer + sizeof(int); + var rowSize = Marshal.SizeOf(); + + for (var i = 0; i < count; i++) + { + yield return Marshal.PtrToStructure(rowPtr); + rowPtr += rowSize; + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + + /// Windows reports ports in network byte order packed into a DWORD. + private static int NetworkPort(uint value) => (ushort)IPAddress.NetworkToHostOrder((short)(ushort)value); + + private static List ListLinux() + { + var list = new List(); + var processes = GetVrChatProcesses(); + if (processes.Count == 0) + return list; + + var socketInodes = ReadSocketInodes(processes.Keys); + if (socketInodes.Count == 0) + return list; + + // Both families, so an IPv6 stream is at least visible even though severing it is + // still not supported. + foreach (var path in new[] { "/proc/net/tcp", "/proc/net/tcp6" }) + { + foreach (var entry in ReadProcNetTcp(path)) + { + if (!socketInodes.TryGetValue(entry.Inode, out var pid)) + continue; + + if (!InterestingPorts.Contains(entry.LocalPort) && !InterestingPorts.Contains(entry.RemotePort)) + continue; + + var info = new ActiveConnectionInfo + { + LocalAddress = entry.LocalAddress, + LocalPort = entry.LocalPort, + RemoteAddress = entry.RemoteAddress, + RemotePort = entry.RemotePort, + OwningPid = pid, + ProcessName = processes.TryGetValue(pid, out var name) ? name : "VRChat" + }; + + Annotate(info); + list.Add(info); + } + } + + return list; + } + + private static Dictionary ReadSocketInodes(IEnumerable pids) + { + var inodes = new Dictionary(); + + foreach (var pid in pids) + { + var fdDir = $"/proc/{pid}/fd"; + if (!Directory.Exists(fdDir)) + continue; + + try + { + foreach (var fd in Directory.EnumerateFiles(fdDir)) + { + try + { + var target = File.ResolveLinkTarget(fd, true)?.FullName; + if (target == null || !target.StartsWith("socket:[", StringComparison.Ordinal) || !target.EndsWith(']')) + continue; + + inodes[target[8..^1]] = pid; + } + catch + { + // Descriptor closed mid-enumeration; skip it. + } + } + } + catch (Exception ex) + { + Log.Debug("Could not enumerate {FdDir}: {Error}", fdDir, ex.Message); + } + } + + return inodes; + } + + private readonly record struct ProcNetEntry( + string LocalAddress, int LocalPort, string RemoteAddress, int RemotePort, string Inode); + + private static IEnumerable ReadProcNetTcp(string path) + { + if (!File.Exists(path)) + yield break; + + IEnumerable lines; + try + { + lines = File.ReadLines(path); + } + catch (Exception ex) + { + Log.Debug("Could not read {Path}: {Error}", path, ex.Message); + yield break; + } + + foreach (var line in lines) + { + var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 10) + continue; + + if (!TryParseEndpoint(parts[1], out var localAddress, out var localPort) || + !TryParseEndpoint(parts[2], out var remoteAddress, out var remotePort)) + continue; + + yield return new ProcNetEntry(localAddress, localPort, remoteAddress, remotePort, parts[9]); + } + } + + /// + /// Parses a procfs "ADDRESS:PORT" field, where the address is little-endian hex — 8 hex + /// digits for IPv4, 32 for IPv6. + /// + /// Returns false rather than guessing. The previous implementation returned "127.0.0.1" + /// for anything it could not parse, which is not an error value: it is a real address + /// that would then be matched against and severed. + /// + private static bool TryParseEndpoint(string field, out string address, out int port) + { + address = string.Empty; + port = 0; + + var separator = field.LastIndexOf(':'); + if (separator <= 0) + return false; + + var hexAddress = field[..separator]; + if (!int.TryParse(field[(separator + 1)..], System.Globalization.NumberStyles.HexNumber, null, out port)) + return false; + + return hexAddress.Length switch + { + 8 => TryParseIpV4(hexAddress, out address), + 32 => TryParseIpV6(hexAddress, out address), + _ => false + }; + } + + private static bool TryParseIpV4(string hex, out string address) + { + address = string.Empty; + if (!uint.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out var value)) + return false; + + // Stored host-endian on a little-endian machine, i.e. already network order bytes. + address = new IPAddress(BitConverter.GetBytes(value)).ToString(); + return true; + } + + private static bool TryParseIpV6(string hex, out string address) + { + address = string.Empty; + var bytes = new byte[16]; + + // Four little-endian 32-bit words. + for (var word = 0; word < 4; word++) + { + if (!uint.TryParse(hex.Substring(word * 8, 8), System.Globalization.NumberStyles.HexNumber, null, out var value)) + return false; + + BitConverter.GetBytes(value).CopyTo(bytes, word * 4); + } + + address = new IPAddress(bytes).ToString(); + return true; + } +} + +public class ActiveConnectionInfo +{ + public string LocalAddress { get; set; } = string.Empty; + public int LocalPort { get; set; } + public string RemoteAddress { get; set; } = string.Empty; + public int RemotePort { get; set; } + public int OwningPid { get; set; } + public string ProcessName { get; set; } = string.Empty; + public string AssociatedUrl { get; set; } = string.Empty; + public string AssociatedTitle { get; set; } = string.Empty; + + /// Identity for reconciling a refreshed list against what the UI already shows. + public string Key => $"{LocalAddress}:{LocalPort}->{RemoteAddress}:{RemotePort}#{OwningPid}"; +} diff --git a/VRCVideoCacher/Utils/OpenUrl.cs b/VRCVideoCacher/Utils/OpenUrl.cs index e96ebb08..9d664239 100644 --- a/VRCVideoCacher/Utils/OpenUrl.cs +++ b/VRCVideoCacher/Utils/OpenUrl.cs @@ -43,4 +43,59 @@ public static bool Open(string url) return false; } } + + /// + /// Reveals a file in the system file manager, falling back to opening its containing + /// folder where selecting is not supported. + /// + public static bool RevealFile(string path) + { + var folder = Path.GetDirectoryName(path); + + if (!OperatingSystem.IsWindows() || !File.Exists(path)) + return OpenFolder(folder ?? path); + + try + { + // "/select," has to arrive as one token including the comma, which is why + // this cannot use a plain ArgumentList entry per word. + var psi = new ProcessStartInfo { FileName = "explorer.exe", UseShellExecute = false }; + psi.ArgumentList.Add($"/select,{path}"); + return Process.Start(psi) != null; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to reveal {Path}; opening the folder instead.", path); + return OpenFolder(folder ?? path); + } + } + + /// + /// Opens a local folder in the system file manager. Separate from , + /// which deliberately refuses anything that is not http(s) — the callers that wanted a + /// folder were each hand-rolling their own Process.Start instead. + /// + public static bool OpenFolder(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + Log.Warning("Refused to open an empty folder path"); + return false; + } + + try + { + Directory.CreateDirectory(path); + + var fileManager = OperatingSystem.IsWindows() ? "explorer.exe" : "xdg-open"; + var psi = new ProcessStartInfo { FileName = fileManager, UseShellExecute = false }; + psi.ArgumentList.Add(path); + return Process.Start(psi) != null; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to open folder: {Path}", path); + return false; + } + } } \ No newline at end of file diff --git a/VRCVideoCacher/Utils/ProcessRunner.cs b/VRCVideoCacher/Utils/ProcessRunner.cs new file mode 100644 index 00000000..a69168fa --- /dev/null +++ b/VRCVideoCacher/Utils/ProcessRunner.cs @@ -0,0 +1,87 @@ +using System.Diagnostics; +using System.Text; + +namespace VRCVideoCacher.Utils; + +/// +/// Runs a child process to completion and captures both of its output streams. +/// +/// Both pipes have to be drained concurrently. Reading stdout to the end and only then +/// reading stderr deadlocks as soon as the child fills the pipe buffer (~64 KB on both +/// Windows and Linux) on the stream nobody is reading yet: the child blocks writing, so it +/// never closes stdout, so the parent never stops waiting. yt-dlp is more than capable of +/// producing that much stderr on a bad extraction, and when it happens the calling HTTP +/// request never returns at all. +/// +public static class ProcessRunner +{ + public readonly record struct ProcessResult(string Output, string Error, int ExitCode); + + /// + /// Runs with each element of + /// passed as one argv entry. Prefer this over building a command-line string: quoting + /// is then the runtime's problem, and untrusted values cannot inject extra arguments. + /// + public static Task RunAsync(string fileName, IEnumerable arguments, CancellationToken ct = default) + { + var startInfo = new ProcessStartInfo { FileName = fileName }; + foreach (var argument in arguments) + startInfo.ArgumentList.Add(argument); + + return RunAsync(startInfo, ct); + } + + /// + /// Starts with both streams redirected, drains them in + /// parallel with the wait, and returns the trimmed output once the process exits. + /// + public static async Task RunAsync(ProcessStartInfo startInfo, CancellationToken ct = default) + { + startInfo.UseShellExecute = false; + startInfo.RedirectStandardOutput = true; + startInfo.RedirectStandardError = true; + startInfo.CreateNoWindow = true; + startInfo.StandardOutputEncoding ??= Encoding.UTF8; + startInfo.StandardErrorEncoding ??= Encoding.UTF8; + + if (OperatingSystem.IsLinux() && startInfo.EnvironmentVariables.ContainsKey("LD_PRELOAD")) + { + var ldPreload = startInfo.EnvironmentVariables["LD_PRELOAD"]; + if (!string.IsNullOrEmpty(ldPreload) && ldPreload.Contains("libextest.so")) + { + startInfo.EnvironmentVariables.Remove("LD_PRELOAD"); + } + } + + using var process = new Process { StartInfo = startInfo }; + process.Start(); + + // Start both reads before awaiting the exit — that ordering is the whole point. + var outputTask = process.StandardOutput.ReadToEndAsync(ct); + var errorTask = process.StandardError.ReadToEndAsync(ct); + + try + { + await process.WaitForExitAsync(ct); + } + catch (OperationCanceledException) + { + try { if (!process.HasExited) process.Kill(entireProcessTree: true); } + catch { /* already gone */ } + throw; + } + + var output = await outputTask; + var error = await errorTask; + + if (!string.IsNullOrEmpty(error)) + { + var lines = error.Split('\n') + .Where(l => !l.Contains("wrong ELF class") && !l.Contains("libextest.so")) + .Select(l => l.TrimEnd('\r')); + error = string.Join("\n", lines); + } + + return new ProcessResult(output.Trim(), error.Trim(), process.ExitCode); + } +} diff --git a/VRCVideoCacher/Utils/UrlPolicy.cs b/VRCVideoCacher/Utils/UrlPolicy.cs new file mode 100644 index 00000000..eae0b208 --- /dev/null +++ b/VRCVideoCacher/Utils/UrlPolicy.cs @@ -0,0 +1,80 @@ +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using Serilog; + +namespace VRCVideoCacher.Utils; + +/// +/// Guards on the outbound requests this application makes on behalf of whoever asked for a +/// video. URLs arrive from a VRChat world — i.e. from anyone in the instance — and are then +/// probed, redirect-followed and downloaded, so they need some floor of validation. +/// +/// Deliberately does NOT block private LAN ranges: hosting videos on a NAS or a local media +/// server is an ordinary thing to do and blocking it would break real setups. What is +/// blocked is link-local, which is where cloud instance-metadata services live +/// (169.254.169.254 and friends) and which no video is ever served from. +/// +public static class UrlPolicy +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(UrlPolicy)); + + /// + /// Only http(s) is meaningful for a video URL. Anything else — file://, ftp://, and the + /// rest — is a way to make the application read something it was never meant to. + /// + public static bool IsFetchableWebUrl(Uri uri) => + uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps; + + public static bool IsFetchableWebUrl(string url) => + Uri.TryCreate(url, UriKind.Absolute, out var uri) && IsFetchableWebUrl(uri); + + /// + /// Link-local addresses, which is where cloud metadata endpoints live. Reaching one of + /// those from a request an untrusted party chose is the classic SSRF payoff, and + /// nothing legitimate serves video from 169.254/16 or fe80::/10. + /// + public static bool IsBlockedAddress(IPAddress address) => + address.IsIPv4LinkLocal() || address.IsIPv6LinkLocal; + + private static bool IsIPv4LinkLocal(this IPAddress address) + { + if (address.AddressFamily != AddressFamily.InterNetwork) + return false; + + var octets = address.GetAddressBytes(); + return octets[0] == 169 && octets[1] == 254; + } + + /// + /// A SocketsHttpHandler ConnectCallback that refuses to open a connection to a blocked + /// address. Enforcing at connect time rather than by inspecting the request URL means + /// redirects and DNS results are covered too — a check on the original URL alone sees + /// neither. + /// + public static async ValueTask GuardedConnectAsync( + SocketsHttpConnectionContext context, CancellationToken cancellationToken) + { + var endPoint = context.DnsEndPoint; + var addresses = await Dns.GetHostAddressesAsync(endPoint.Host, cancellationToken); + var allowed = addresses.Where(address => !IsBlockedAddress(address)).ToArray(); + + if (allowed.Length == 0) + { + Log.Warning("Refusing to connect to {Host}: resolves only to blocked addresses.", endPoint.Host); + throw new HttpRequestException($"Refusing to connect to {endPoint.Host}: blocked address."); + } + + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(allowed, endPoint.Port, cancellationToken); + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + socket.Dispose(); + throw; + } + } +} diff --git a/VRCVideoCacher/Utils/VrcLogMonitor.cs b/VRCVideoCacher/Utils/VrcLogMonitor.cs new file mode 100644 index 00000000..bf11e079 --- /dev/null +++ b/VRCVideoCacher/Utils/VrcLogMonitor.cs @@ -0,0 +1,307 @@ +using System; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Serilog; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.Utils; + +public static class VrcLogMonitor +{ + private static readonly ILogger Log = Program.Logger.ForContext(typeof(VrcLogMonitor)); + + private static CancellationTokenSource? _cts; + private static Task? _monitorTask; + + // Compiled Regular Expressions for parsing VRChat log lines + private static readonly Regex ResolveUrlRegex = new( + @"^[\d\.:\s\w\-]+\[Video Playback\]\s+(?:Attempting to resolve|Resolving) URL\s+'(?[^']+)'", + RegexOptions.Compiled); + + private static readonly Regex ResolvedUrlRegex = new( + @"^[\d\.:\s\w\-]+\[Video Playback\]\s+URL\s+'(?[^']+)'\s+resolved to\s+'(?[^']+)'", + RegexOptions.Compiled); + + private static readonly Regex AvProOpeningRegex = new( + @"^[\d\.:\s\w\-]+\[AVProVideo\]\s+Opening\s+(?https?://[^\s\)]+)", + RegexOptions.Compiled); + + private static readonly Regex AvProPlayingRegex = new( + @"^[\d\.:\s\w\-]+\[AVProVideo\]\s+Using playback path", + RegexOptions.Compiled); + + private static readonly Regex AvProErrorRegex = new( + @"^[\d\.:\s\w\-]+\[AVProVideo\]\s+Error:\s+(?.+)", + RegexOptions.Compiled); + + private static readonly Regex AvProShutdownRegex = new( + @"^[\d\.:\s\w\-]+\[AVProVideo\]\s+Shutdown", + RegexOptions.Compiled); + + public static void Start() + { + if (_monitorTask != null) return; + + // Linked to the application shutdown token as well as our own, so the loop unwinds on + // its own during shutdown instead of relying on Stop() being reached. Program.Main + // signals shutdown and then force-exits, and a monitor that has not observed it is + // killed mid-read — which meant a half-consumed log tail and, on Windows, an open + // FileStream handle on the log VRChat was still writing to. + _cts = CancellationTokenSource.CreateLinkedTokenSource(Program.ShutdownToken); + _monitorTask = Task.Run(() => MonitorLoop(_cts.Token), _cts.Token); + Log.Information("VRChat Log Monitor service started."); + } + + public static void Stop() + { + if (_cts != null) + { + _cts.Cancel(); + try + { + _monitorTask?.Wait(2000); + } + catch (Exception ex) + { + Log.Debug(ex, "Error stopping log monitor task."); + } + _cts.Dispose(); + _cts = null; + _monitorTask = null; + Log.Information("VRChat Log Monitor service stopped."); + } + } + + private static async Task MonitorLoop(CancellationToken ct) + { + string? currentFile = null; + CancellationTokenSource? tailCts = null; + Task? tailTask = null; + + while (!ct.IsCancellationRequested) + { + try + { + var latestFile = FindLatestLogFile(); + if (latestFile != currentFile) + { + // If we were tailing a file, stop it + if (tailCts != null) + { + tailCts.Cancel(); + if (tailTask != null) + { + try { await tailTask; } catch { /* ignore task cancellation exception */ } + } + tailCts.Dispose(); + tailCts = null; + tailTask = null; + } + + currentFile = latestFile; + + if (currentFile != null) + { + Log.Information("Now monitoring VRChat log file: {File}", Path.GetFileName(currentFile)); + tailCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + tailTask = Task.Run(() => TailFileAsync(currentFile, tailCts.Token)); + } + } + } + catch (Exception ex) + { + Log.Error(ex, "Error in log monitor directory polling loop."); + } + + // Check for log file rollover every 5 seconds + try + { + await Task.Delay(5000, ct); + } + catch (TaskCanceledException) + { + break; + } + } + + // Clean up tail task on shutdown + if (tailCts != null) + { + tailCts.Cancel(); + if (tailTask != null) + { + try { await tailTask; } catch { } + } + tailCts.Dispose(); + } + } + + private static string? FindLatestLogFile() + { + if (string.IsNullOrEmpty(FileTools.YtdlPathVrc)) + return null; + + try + { + // Logs are in the parent directory of Tools (which is LocalLow/VRChat/VRChat) + var parent = Path.GetDirectoryName(FileTools.YtdlPathVrc); + if (string.IsNullOrEmpty(parent)) return null; + + var logDir = Path.GetDirectoryName(parent); + if (string.IsNullOrEmpty(logDir) || !Directory.Exists(logDir)) + return null; + + var files = Directory.GetFiles(logDir, "output_log_*.txt"); + if (files.Length == 0) return null; + + // Sort by write time descending to find the latest + Array.Sort(files, (a, b) => File.GetLastWriteTimeUtc(b).CompareTo(File.GetLastWriteTimeUtc(a))); + return files[0]; + } + catch (Exception ex) + { + Log.Debug(ex, "Failed to resolve latest log file path."); + return null; + } + } + + private static async Task TailFileAsync(string filePath, CancellationToken ct) + { + try + { + using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var sr = new StreamReader(fs, Encoding.UTF8); + + // Seek to the end of the file so we only tail new output log entries in the current session + fs.Seek(0, SeekOrigin.End); + + while (!ct.IsCancellationRequested) + { + var line = await sr.ReadLineAsync(ct); + if (line != null) + { + ParseLogLine(line); + } + else + { + await Task.Delay(250, ct); + } + } + } + catch (OperationCanceledException) + { + // Normal shutdown + } + catch (Exception ex) + { + Log.Error(ex, "Error tailing VRChat log file: {File}", Path.GetFileName(filePath)); + } + } + + private static void ParseLogLine(string line) + { + try + { + // 1. Check for attempt to resolve URL + var match = ResolveUrlRegex.Match(line); + if (match.Success) + { + var url = match.Groups["url"].Value; + Log.Debug("VRChat log: resolve attempt for {Url}", url); + return; + } + + // 2. Check for URL resolved + match = ResolvedUrlRegex.Match(line); + if (match.Success) + { + var url = match.Groups["url"].Value; + var resolvedUrl = match.Groups["resolvedUrl"].Value; + ActiveStreamTracker.AssociateUrlInfo(resolvedUrl, url, url, null, null); + return; + } + + // 3. Check for AVPro Opening URL + match = AvProOpeningRegex.Match(line); + if (match.Success) + { + var url = match.Groups["url"].Value; + Log.Information("VRChat log: AVPro opening {Url}", url); + + var session = new ActiveVideoSession + { + ResolvedUrl = url, + StartTime = DateTime.UtcNow, + Status = "Loading" + }; + + if (ActiveStreamTracker.TryGetUrlInfo(url, out var info)) + { + session.Title = info.Title; + session.OriginalUrl = info.OriginalUrl; + session.VideoId = info.VideoId; + session.Duration = info.Duration; + } + else + { + session.Title = url; + session.OriginalUrl = url; + } + + // Resolve IP address in background + if (Uri.TryCreate(url, UriKind.Absolute, out var uri) && !url.Contains("localhost") && !url.Contains("127.0.0.1")) + { + Task.Run(async () => + { + try + { + var addresses = await System.Net.Dns.GetHostAddressesAsync(uri.Host); + if (addresses.Length > 0) + { + session.RemoteIp = addresses[0].ToString(); + ActiveStreamTracker.AddOrUpdateSession(session); + } + } + catch { } + }); + } + + ActiveStreamTracker.AddOrUpdateSession(session); + return; + } + + // 4. Check for AVPro Playback Started + if (AvProPlayingRegex.IsMatch(line)) + { + Log.Information("VRChat log: AVPro playback started."); + ActiveStreamTracker.UpdateSessionStatus(string.Empty, "Playing", DateTime.UtcNow); + return; + } + + // 5. Check for AVPro Loading Error + match = AvProErrorRegex.Match(line); + if (match.Success) + { + var error = match.Groups["error"].Value; + Log.Warning("VRChat log: AVPro load error: {Error}", error); + ActiveStreamTracker.UpdateSessionStatus(string.Empty, "Failed"); + return; + } + + // 6. Check for AVPro Shutdown (e.g. world change or app close) + if (AvProShutdownRegex.IsMatch(line)) + { + Log.Information("VRChat log: AVPro shutdown. Clearing active sessions."); + ActiveStreamTracker.ClearAllSessions(); + return; + } + } + catch (Exception ex) + { + Log.Debug(ex, "Error parsing log line: {Line}", line); + } + } +} diff --git a/VRCVideoCacher/Utils/WinGet.cs b/VRCVideoCacher/Utils/WinGet.cs index 928f9482..b19ade91 100644 --- a/VRCVideoCacher/Utils/WinGet.cs +++ b/VRCVideoCacher/Utils/WinGet.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using System.Runtime.Versioning; -using System.Text; using Serilog; namespace VRCVideoCacher.Utils; @@ -20,18 +19,18 @@ public class WinGet public static async Task TryInstallPackages() { Log.Information("Checking for missing codec packages..."); - if (!IsOurPackagesInstalled()) + if (!await IsOurPackagesInstalled()) { Log.Information("Installing missing codec packages..."); await InstallAllPackages(); } } - private static bool IsOurPackagesInstalled() + private static async Task IsOurPackagesInstalled() { foreach (var package in WingetPackages.Values) { - if (!IsPackageInstalled(package)) + if (!await IsPackageInstalled(package)) { return false; } @@ -41,27 +40,16 @@ private static bool IsOurPackagesInstalled() return true; } - private static bool IsPackageInstalled(string packageId) + private static async Task IsPackageInstalled(string packageId) { try { - var process = new Process + var result = await ProcessRunner.RunAsync(new ProcessStartInfo { - StartInfo = - { - FileName = WingetPath, - Arguments = $"list \"{packageId}\" -s msstore --accept-source-agreements", - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - } - }; - process.Start(); - process.WaitForExit(); - return process.ExitCode == 0; + FileName = WingetPath, + Arguments = $"list \"{packageId}\" -s msstore --accept-source-agreements" + }); + return result.ExitCode == 0; } catch (Exception ex) { @@ -82,34 +70,23 @@ private static async Task InstallPackage(string packageId) { try { - var process = new Process + var (output, error, exitCode) = await ProcessRunner.RunAsync(new ProcessStartInfo { - StartInfo = - { - FileName = WingetPath, - Arguments = $"install --id {packageId} -s msstore --accept-package-agreements --accept-source-agreements", - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - } - }; - process.Start(); - string? line; - while ((line = await process.StandardOutput.ReadLineAsync()) != null) + FileName = WingetPath, + Arguments = $"install --id {packageId} -s msstore --accept-package-agreements --accept-source-agreements" + }); + + foreach (var line in output.Split('\n')) { - if (!string.IsNullOrEmpty(line.Trim())) - Log.Debug("{Winget}: {Line}", "winget", line); + if (!string.IsNullOrWhiteSpace(line)) + Log.Debug("{Winget}: {Line}", "winget", line.TrimEnd()); } - var error = await process.StandardError.ReadToEndAsync(); - await process.WaitForExitAsync(); - if (process.ExitCode != 0 && !string.IsNullOrEmpty(error)) - throw new Exception($"Installation failed with exit code {process.ExitCode}. Error: {error}"); + + if (exitCode != 0 && !string.IsNullOrEmpty(error)) + throw new Exception($"Installation failed with exit code {exitCode}. Error: {error}"); var packageName = WingetPackages.FirstOrDefault(x => x.Value == packageId).Key; - if (process.ExitCode == 0) + if (exitCode == 0) Log.Information("Successfully installed package: {PackageName}", packageName); } catch (Exception ex) diff --git a/VRCVideoCacher/VRCVideoCacher.csproj b/VRCVideoCacher/VRCVideoCacher.csproj index 7615483d..587c7f44 100755 --- a/VRCVideoCacher/VRCVideoCacher.csproj +++ b/VRCVideoCacher/VRCVideoCacher.csproj @@ -1,9 +1,9 @@ - + WinExe net10.0 - 2026.8.14 + 2026.8.22 false enable enable @@ -21,7 +21,8 @@ true true partial - + true $(NoWarn);IL2037 @@ -35,7 +36,8 @@ true true partial - + true $(NoWarn);IL2037 @@ -45,6 +47,25 @@ + + + + + @@ -59,7 +80,6 @@ - @@ -69,11 +89,13 @@ - + + diff --git a/VRCVideoCacher/ViewModels/AboutViewModel.cs b/VRCVideoCacher/ViewModels/AboutViewModel.cs index 9cb4c35b..8e9ae293 100755 --- a/VRCVideoCacher/ViewModels/AboutViewModel.cs +++ b/VRCVideoCacher/ViewModels/AboutViewModel.cs @@ -1,17 +1,20 @@ -using Jeek.Avalonia.Localization; - -namespace VRCVideoCacher.ViewModels; - -public class AboutViewModel : ViewModelBase -{ - public string Version { get; } - public string PlusAuthor { get; } = "VRCVideoCacherPlus by codeyumx"; - public string CreatedBy { get; } - public StatsViewModel Stats { get; } = new(); - - public AboutViewModel() - { - Version = VRCVideoCacher.Program.Version; - CreatedBy = Localizer.Get("CreatedBy") + $" {VRCVideoCacher.Program.Creator_Elly}, {VRCVideoCacher.Program.Creator_Natsumi}, {VRCVideoCacher.Program.Creator_Haxy}, {VRCVideoCacher.Program.Creator_Hauskaz}, {VRCVideoCacher.Program.Creator_DubyaDude}"; - } -} +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Services; + +namespace VRCVideoCacher.ViewModels; + +public partial class AboutViewModel : ViewModelBase +{ + public string Version { get; } + public string PlusAuthor { get; } = "VRCVideoCacherPlus by codeyumx"; + public string CreatedBy { get; } + public StatsViewModel Stats { get; } = new(); + + public AboutViewModel() + { + Version = VRCVideoCacher.Program.Version; + CreatedBy = Localizer.Get("CreatedBy") + $" {VRCVideoCacher.Program.Creator_Elly}, {VRCVideoCacher.Program.Creator_Natsumi}, {VRCVideoCacher.Program.Creator_Haxy}, {VRCVideoCacher.Program.Creator_Hauskaz}, {VRCVideoCacher.Program.Creator_DubyaDude}"; + } +} diff --git a/VRCVideoCacher/ViewModels/ActiveConnectionsViewModel.cs b/VRCVideoCacher/ViewModels/ActiveConnectionsViewModel.cs new file mode 100644 index 00000000..221952f2 --- /dev/null +++ b/VRCVideoCacher/ViewModels/ActiveConnectionsViewModel.cs @@ -0,0 +1,225 @@ +using System.Collections.ObjectModel; +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input.Platform; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.ViewModels; + +public partial class ActiveConnectionsViewModel : ViewModelBase, IDisposable +{ + public ObservableCollection Connections { get; } = []; + + [ObservableProperty] + private string _searchText = string.Empty; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private string _statusMessageColor = "#81C784"; + + [ObservableProperty] + private bool _hasConnections; + + private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(3); + + private readonly CancellationTokenSource _cts = new(); + + // The unfiltered result of the last poll. Typing in the search box filters this rather + // than re-querying the operating system on every keystroke, which is what it used to do. + private List _lastSnapshot = []; + + public ActiveConnectionsViewModel() + { + _ = RefreshLoopAsync(_cts.Token); + } + + /// + /// Polls on a background task. + /// + /// This was a DispatcherTimer, so every tick ran the whole enumeration — every process + /// on the machine, a walk of /proc/[pid]/fd, and a parse of /proc/net/tcp — on the UI + /// thread, every three seconds, for as long as the application was running. Only the + /// finished list is marshalled back to the UI now. + /// + private async Task RefreshLoopAsync(CancellationToken token) + { + using var timer = new PeriodicTimer(RefreshInterval); + + while (!token.IsCancellationRequested) + { + try + { + var snapshot = await Task.Run(NetworkConnections.List, token); + await Dispatcher.UIThread.InvokeAsync(() => Apply(snapshot)); + await timer.WaitForNextTickAsync(token); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + Serilog.Log.Debug(ex, "Active connection refresh failed."); + + try { await timer.WaitForNextTickAsync(token); } + catch (OperationCanceledException) { return; } + } + } + } + + private void Apply(List snapshot) + { + _lastSnapshot = snapshot; + ApplyFilter(); + } + + partial void OnSearchTextChanged(string value) => ApplyFilter(); + + /// + /// Reconciles the visible list in place rather than clearing and rebuilding it. A full + /// rebuild every three seconds dropped the grid selection, which made the per-row Sever + /// and Create Rule buttons a race against the next tick. + /// + private void ApplyFilter() + { + var query = SearchText.Trim(); + var desired = string.IsNullOrEmpty(query) + ? _lastSnapshot + : _lastSnapshot.Where(c => Matches(c, query)).ToList(); + + var desiredKeys = desired.Select(c => c.Key).ToHashSet(StringComparer.Ordinal); + + for (var i = Connections.Count - 1; i >= 0; i--) + { + if (!desiredKeys.Contains(Connections[i].Key)) + Connections.RemoveAt(i); + } + + var presentKeys = Connections.Select(c => c.Key).ToHashSet(StringComparer.Ordinal); + foreach (var connection in desired) + { + if (presentKeys.Contains(connection.Key)) + continue; + + Connections.Add(connection); + } + + HasConnections = Connections.Count > 0; + } + + private static bool Matches(ActiveConnectionInfo connection, string query) => + connection.ProcessName.Contains(query, StringComparison.OrdinalIgnoreCase) || + connection.RemoteAddress.Contains(query, StringComparison.OrdinalIgnoreCase) || + connection.LocalAddress.Contains(query, StringComparison.OrdinalIgnoreCase) || + connection.AssociatedTitle.Contains(query, StringComparison.OrdinalIgnoreCase) || + connection.AssociatedUrl.Contains(query, StringComparison.OrdinalIgnoreCase); + + [RelayCommand] + private async Task RefreshConnections() + { + var snapshot = await Task.Run(NetworkConnections.List); + Apply(snapshot); + } + + [RelayCommand] + private async Task SeverAllConnections() + { + var result = await ConnectionSevering.SeverAllAsync(allowElevation: true); + ReportSeverResult(result); + await RefreshConnections(); + } + + [RelayCommand] + private async Task SeverConnection(ActiveConnectionInfo? connection) + { + if (connection == null) + return; + + var result = await ConnectionSevering.SeverAddressAsync(connection.RemoteAddress, allowElevation: true); + ReportSeverResult(result); + await RefreshConnections(); + } + + /// + /// Says what actually happened. "Not permitted" is reported as its own outcome rather + /// than being dressed up as success, which is what the old code did on every Linux + /// machine without root and every Windows machine without elevation. + /// + private void ReportSeverResult(SeverResult result) + { + switch (result.RemoteOutcome) + { + case SeverOutcome.NotPermitted: + SetStatus(Localizer.Get("SeverNeedsPrivileges"), "#FFB74D"); + return; + + case SeverOutcome.Unsupported when result.LocalStreamsClosed == 0: + SetStatus(Localizer.Get("SeverUnsupported"), "#FFB74D"); + return; + + case SeverOutcome.Failed: + SetStatus(Localizer.Get("SeverFailed"), "#E57373"); + return; + } + + if (result.AnythingClosed) + { + var total = result.LocalStreamsClosed + result.RemoteSocketsSevered; + SetStatus(string.Format(Localizer.Get("SeverSucceeded"), total), "#81C784"); + return; + } + + SetStatus(Localizer.Get("SeverNothingToDo"), "#888888"); + } + + [RelayCommand] + private async Task CreateRule(ActiveConnectionInfo? connection) + { + if (connection == null) + return; + + var pattern = !string.IsNullOrEmpty(connection.AssociatedUrl) ? connection.AssociatedUrl : connection.RemoteAddress; + if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime lifetime) + return; + + if (lifetime.MainWindow?.DataContext is not MainWindowViewModel mainVm) + return; + + await mainVm.NavigateToRulesCommand.ExecuteAsync(null); + await mainVm.Rules.AddRuleWithPattern(pattern); + } + + [RelayCommand] + private async Task CopyAddress(ActiveConnectionInfo? connection) + { + if (connection == null) + return; + + var text = !string.IsNullOrEmpty(connection.AssociatedUrl) ? connection.AssociatedUrl : connection.RemoteAddress; + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var clipboard = lifetime?.MainWindow?.Clipboard; + if (clipboard == null) + return; + + await clipboard.SetTextAsync(text); + SetStatus(Localizer.Get("AddressCopied"), "#81C784"); + } + + private void SetStatus(string message, string colorHex) + { + StatusMessage = message; + StatusMessageColor = colorHex; + } + + public void Dispose() + { + _cts.Cancel(); + _cts.Dispose(); + } +} diff --git a/VRCVideoCacher/ViewModels/CacheBrowserViewModel.cs b/VRCVideoCacher/ViewModels/CacheBrowserViewModel.cs index c256f7ea..ca0d47bc 100644 --- a/VRCVideoCacher/ViewModels/CacheBrowserViewModel.cs +++ b/VRCVideoCacher/ViewModels/CacheBrowserViewModel.cs @@ -1,339 +1,333 @@ -using System.Collections.ObjectModel; -using Avalonia.Input.Platform; -using Avalonia.Threading; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using Jeek.Avalonia.Localization; -using VRCVideoCacher.Database; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; - -namespace VRCVideoCacher.ViewModels; - -public partial class CacheItemViewModel : ViewModelBase -{ - public string FileName { get; init; } = string.Empty; - public string VideoId { get; init; } = string.Empty; - public long Size { get; init; } - public DateTime LastModified { get; init; } - public string Extension { get; init; } = string.Empty; - - [ObservableProperty] - private string _title = string.Empty; - - [ObservableProperty] - private string _thumbnailSource = string.Empty; - - [ObservableProperty] - private UrlType _urlType = UrlType.Other; - - [ObservableProperty] - private string? _originalUrl; - - public bool IsYouTube => UrlType == UrlType.YouTube; - - public bool HasOpenSourceLink => !IsYouTube && !string.IsNullOrEmpty(OriginalUrl); - - // For VRDancing the VideoId is a URL hash and unhelpful in the UI; show the - // human-readable code from the source URL (e.g. 13451) instead. Other types - // (YouTube id, etc.) keep their VideoId as-is. - public string DisplayId => UrlType == UrlType.VRDancing && !string.IsNullOrEmpty(OriginalUrl) - ? ExtractVRDancingCode(OriginalUrl!) - : VideoId; - - private static string ExtractVRDancingCode(string url) - { - var trimmed = url.TrimEnd('/'); - var idx = trimmed.LastIndexOf('/'); - return idx >= 0 && idx < trimmed.Length - 1 ? trimmed[(idx + 1)..] : trimmed; - } - - partial void OnUrlTypeChanged(UrlType value) - { - OnPropertyChanged(nameof(IsYouTube)); - OnPropertyChanged(nameof(HasOpenSourceLink)); - OnPropertyChanged(nameof(HasCopyableUrl)); - OnPropertyChanged(nameof(DisplayId)); - } - - partial void OnOriginalUrlChanged(string? value) - { - OnPropertyChanged(nameof(HasOpenSourceLink)); - OnPropertyChanged(nameof(HasCopyableUrl)); - OnPropertyChanged(nameof(DisplayId)); - } - - public string DisplayTitle => string.IsNullOrEmpty(Title) ? DisplayId : Title; - - public string SizeFormatted => FormatSize(Size); - - // Event to notify parent when item is deleted - public event Action? OnDeleted; - - public async Task LoadMetadataAsync(string? originalUrl = null, UrlType? historyType = null) - { - // Load from DB - var videoInfo = await YouTubeMetadataService.GetVideoMetadataAsync(VideoId); - - if (videoInfo != null) - { - UrlType = videoInfo.Type; - if (!string.IsNullOrEmpty(videoInfo.Title)) - { - Title = videoInfo.Title; - OnPropertyChanged(nameof(DisplayTitle)); - } - } - else if (historyType.HasValue) - { - // No VideoInfoCache row (legacy item) — classify from the latest History entry instead. - UrlType = historyType.Value; - } - - // Original URL for non-YouTube items so we can open the source stream/page. - // Prefer the caller-provided value (batch-fetched) to avoid an extra DB round-trip per item. - OriginalUrl = originalUrl ?? DatabaseManager.GetLatestHistoryUrl(VideoId); - - // Load thumbnail - var thumbnailPath = ThumbnailManager.GetThumbnail(VideoId); - if (VideoId.Length == 11 && string.IsNullOrEmpty(thumbnailPath)) - thumbnailPath = await YouTubeMetadataService.GetThumbnail(VideoId); - - if (!string.IsNullOrEmpty(thumbnailPath)) - ThumbnailSource = thumbnailPath; - } - - [RelayCommand] - private void WatchVideo() - { - var filePath = Path.Join(CacheManager.CachePath, FileName); - if (!File.Exists(filePath)) return; - try - { - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo - { - FileName = filePath, - UseShellExecute = true - }); - } - catch { /* Ignore errors */ } - } - - [RelayCommand] - private void OpenOnYouTube() - { - var url = $"https://www.youtube.com/watch?v={VideoId}"; - OpenUrlExternal(url); - } - - [RelayCommand] - private void OpenSource() - { - if (string.IsNullOrEmpty(OriginalUrl)) return; - OpenUrlExternal(OriginalUrl); - } - - private static void OpenUrlExternal(string url) - { - try - { - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo - { - FileName = url, - UseShellExecute = true - }); - } - catch { /* Ignore errors */ } - } - - public bool HasCopyableUrl => IsYouTube || !string.IsNullOrEmpty(OriginalUrl); - - [RelayCommand] - private async Task CopyUrl() - { - var url = IsYouTube - ? $"https://www.youtube.com/watch?v={VideoId}" - : OriginalUrl; - if (string.IsNullOrEmpty(url)) return; - if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) - { - var clipboard = desktop.MainWindow?.Clipboard; - if (clipboard != null) - { - await clipboard.SetTextAsync(url); - } - } - } - - [RelayCommand] - private void Delete() - { - CacheManager.DeleteCacheItem(FileName); - OnDeleted?.Invoke(this); - } - - private static string FormatSize(long bytes) - { - string[] suffixes = ["B", "KB", "MB", "GB"]; - if (bytes == 0) return "0 B"; - var mag = (int)Math.Log(bytes, 1024); - mag = Math.Min(mag, suffixes.Length - 1); - var adjustedSize = bytes / Math.Pow(1024, mag); - return $"{adjustedSize:N2} {suffixes[mag]}"; - } -} - -public partial class CacheBrowserViewModel : ViewModelBase -{ - [ObservableProperty] - private string _searchFilter = string.Empty; - - [ObservableProperty] - private CacheItemViewModel? _selectedItem; - - [ObservableProperty] - private string _statusText = string.Empty; - - public ObservableCollection CachedVideos { get; } = []; - public ObservableCollection FilteredVideos { get; } = []; - - public CacheBrowserViewModel() - { - CacheManager.OnCacheChanged += OnCacheChanged; - } - - private void OnCacheChanged(string fileName, CacheChangeType changeType) - { - Dispatcher.UIThread.InvokeAsync(RefreshCache); - } - - partial void OnSearchFilterChanged(string value) - { - ApplyFilter(); - } - - private void ApplyFilter() - { - FilteredVideos.Clear(); - - var filter = SearchFilter?.ToLowerInvariant() ?? string.Empty; - foreach (var video in CachedVideos) - { - if (string.IsNullOrEmpty(filter) || - video.FileName.Contains(filter, StringComparison.OrdinalIgnoreCase) || - video.VideoId.Contains(filter, StringComparison.OrdinalIgnoreCase) || - video.DisplayId.Contains(filter, StringComparison.OrdinalIgnoreCase) || - video.DisplayTitle.Contains(filter, StringComparison.OrdinalIgnoreCase)) - { - FilteredVideos.Add(video); - } - } - - StatusText = string.Format(Localizer.Get("VideosCountFormat"), FilteredVideos.Count, CachedVideos.Count); - } - - [RelayCommand] - private void RefreshCache() - { - CachedVideos.Clear(); - FilteredVideos.Clear(); - - var cachedAssets = CacheManager.GetCachedAssets(); - var itemsToLoad = new List(); - - foreach (var (fileName, cache) in cachedAssets.OrderByDescending(x => x.Value.LastModified)) - { - // Filter out non-video files like index.html - if (fileName.Equals("index.html", StringComparison.OrdinalIgnoreCase)) - continue; - - var videoId = Path.GetFileNameWithoutExtension(fileName); - var extension = Path.GetExtension(fileName); - - var item = new CacheItemViewModel - { - FileName = fileName, - VideoId = videoId, - Size = cache.Size, - LastModified = cache.LastModified, - Extension = extension - }; - - // Subscribe to delete event - item.OnDeleted += OnItemDeleted; - - CachedVideos.Add(item); - itemsToLoad.Add(item); - } - - ApplyFilter(); - - // Load metadata (titles + thumbnails) asynchronously in the background - _ = Task.Run(async () => - { - // Batch-fetch original URLs (and history-derived type) in one query instead of N. - var history = DatabaseManager.GetLatestHistoryUrls(itemsToLoad.Select(i => i.VideoId)); - foreach (var item in itemsToLoad) - { - history.TryGetValue(item.VideoId, out var entry); - await item.LoadMetadataAsync(entry.Url, entry.Url == null ? null : entry.Type); - } - }); - } - - private void OnItemDeleted(CacheItemViewModel item) - { - Dispatcher.UIThread.InvokeAsync(() => - { - CachedVideos.Remove(item); - FilteredVideos.Remove(item); - StatusText = string.Format(Localizer.Get("VideosCountFormat"), FilteredVideos.Count, CachedVideos.Count); - }); - } - - [RelayCommand] - private async Task DeleteAll() - { - var lifetime = Avalonia.Application.Current?.ApplicationLifetime - as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime; - var owner = lifetime?.MainWindow; - if (owner == null) - { - // No UI available — fall back to direct clear so headless/console mode still works. - CacheManager.ClearCache(); - return; - } - - var message = string.Format( - Localizer.Get("ConfirmClearCacheFormat"), - CachedVideos.Count); - var dialog = Views.PopupWindow.CreateConfirm(message, Localizer.Get("Yes"), Localizer.Get("No")); - dialog.Title = Localizer.Get("ConfirmClearCacheTitle"); - await dialog.ShowDialog(owner); - if (dialog.Confirmed) - CacheManager.ClearCache(); - } - - [RelayCommand] - private void OpenInExplorer() - { - var cachePath = CacheManager.CachePath; - if (OperatingSystem.IsWindows()) - { - if (SelectedItem != null) - { - var filePath = Path.Join(cachePath, SelectedItem.FileName); - System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\""); - } - else - { - System.Diagnostics.Process.Start("explorer.exe", cachePath); - } - } - else if (OperatingSystem.IsLinux()) - { - System.Diagnostics.Process.Start("xdg-open", cachePath); - } - } - -} +using System.Collections.ObjectModel; +using Avalonia.Input.Platform; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Database; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using VRCVideoCacher.Integrations.YouTube; + +namespace VRCVideoCacher.ViewModels; + +public partial class CacheItemViewModel : ViewModelBase +{ + public string FileName { get; init; } = string.Empty; + public string VideoId { get; init; } = string.Empty; + public long Size { get; init; } + public DateTime LastModified { get; init; } + public string Extension { get; init; } = string.Empty; + + [ObservableProperty] + private string _title = string.Empty; + + [ObservableProperty] + private string _thumbnailSource = string.Empty; + + [ObservableProperty] + private UrlType _urlType = UrlType.Other; + + [ObservableProperty] + private string? _originalUrl; + + public bool IsYouTube => UrlType == UrlType.YouTube; + + public bool HasOpenSourceLink => !IsYouTube && !string.IsNullOrEmpty(OriginalUrl); + + // For VRDancing the VideoId is a URL hash and unhelpful in the UI; show the + // human-readable code from the source URL (e.g. 13451) instead. Other types + // (YouTube id, etc.) keep their VideoId as-is. + public string DisplayId => UrlType == UrlType.VRDancing && !string.IsNullOrEmpty(OriginalUrl) + ? ExtractVRDancingCode(OriginalUrl!) + : VideoId; + + private static string ExtractVRDancingCode(string url) + { + var trimmed = url.TrimEnd('/'); + var idx = trimmed.LastIndexOf('/'); + return idx >= 0 && idx < trimmed.Length - 1 ? trimmed[(idx + 1)..] : trimmed; + } + + partial void OnUrlTypeChanged(UrlType value) + { + OnPropertyChanged(nameof(IsYouTube)); + OnPropertyChanged(nameof(HasOpenSourceLink)); + OnPropertyChanged(nameof(HasCopyableUrl)); + OnPropertyChanged(nameof(DisplayId)); + } + + partial void OnOriginalUrlChanged(string? value) + { + OnPropertyChanged(nameof(HasOpenSourceLink)); + OnPropertyChanged(nameof(HasCopyableUrl)); + OnPropertyChanged(nameof(DisplayId)); + } + + public string DisplayTitle => string.IsNullOrEmpty(Title) ? DisplayId : Title; + + public string SizeFormatted => FormatSize(Size); + + // Event to notify parent when item is deleted + public event Action? OnDeleted; + + public async Task LoadMetadataAsync(string? originalUrl = null, UrlType? historyType = null) + { + // Load from DB + var videoInfo = await YouTubeMetadataService.GetVideoMetadataAsync(VideoId); + + if (videoInfo != null) + { + UrlType = videoInfo.Type; + if (!string.IsNullOrEmpty(videoInfo.Title)) + { + Title = videoInfo.Title; + OnPropertyChanged(nameof(DisplayTitle)); + } + } + else if (historyType.HasValue) + { + // No VideoInfoCache row (legacy item) — classify from the latest History entry instead. + UrlType = historyType.Value; + } + + // Original URL for non-YouTube items so we can open the source stream/page. + // Prefer the caller-provided value (batch-fetched) to avoid an extra DB round-trip per item. + OriginalUrl = originalUrl ?? DatabaseManager.GetLatestHistoryUrl(VideoId); + + // Load thumbnail + var thumbnailPath = ThumbnailManager.GetThumbnail(VideoId); + if (VideoId.Length == 11 && string.IsNullOrEmpty(thumbnailPath)) + thumbnailPath = await YouTubeMetadataService.GetThumbnail(VideoId); + + if (!string.IsNullOrEmpty(thumbnailPath)) + ThumbnailSource = thumbnailPath; + } + + [RelayCommand] + private async Task CopyPath() + { + var filePath = Path.Join(CacheManager.CachePath, FileName); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + { + var clipboard = desktop.MainWindow?.Clipboard; + if (clipboard != null) + { + await clipboard.SetTextAsync(filePath); + } + } + } + + [RelayCommand] + private void WatchVideo() + { + var filePath = Path.Join(CacheManager.CachePath, FileName); + if (!File.Exists(filePath)) return; + try + { + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo + { + FileName = filePath, + UseShellExecute = true + }); + } + catch { /* Ignore errors */ } + } + + [RelayCommand] + private void OpenOnYouTube() + { + var url = $"https://www.youtube.com/watch?v={VideoId}"; + OpenUrlExternal(url); + } + + [RelayCommand] + private void OpenSource() + { + if (string.IsNullOrEmpty(OriginalUrl)) return; + OpenUrlExternal(OriginalUrl); + } + + // OriginalUrl comes from play history — i.e. from whatever a world handed us — so it + // goes through OpenUrl.Open, which refuses anything that is not http(s). + private static void OpenUrlExternal(string url) => Utils.OpenUrl.Open(url); + + public bool HasCopyableUrl => IsYouTube || !string.IsNullOrEmpty(OriginalUrl); + + [RelayCommand] + private async Task CopyUrl() + { + var url = IsYouTube + ? $"https://www.youtube.com/watch?v={VideoId}" + : OriginalUrl; + if (string.IsNullOrEmpty(url)) return; + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + { + var clipboard = desktop.MainWindow?.Clipboard; + if (clipboard != null) + { + await clipboard.SetTextAsync(url); + } + } + } + + [RelayCommand] + private void Delete() + { + CacheManager.DeleteCacheItem(FileName); + OnDeleted?.Invoke(this); + } + + private static string FormatSize(long bytes) + { + string[] suffixes = ["B", "KB", "MB", "GB"]; + if (bytes == 0) return "0 B"; + var mag = (int)Math.Log(bytes, 1024); + mag = Math.Min(mag, suffixes.Length - 1); + var adjustedSize = bytes / Math.Pow(1024, mag); + return $"{adjustedSize:N2} {suffixes[mag]}"; + } +} + +public partial class CacheBrowserViewModel : ViewModelBase +{ + [ObservableProperty] + private string _searchFilter = string.Empty; + + [ObservableProperty] + private CacheItemViewModel? _selectedItem; + + [ObservableProperty] + private string _statusText = string.Empty; + + public ObservableCollection CachedVideos { get; } = []; + public ObservableCollection FilteredVideos { get; } = []; + + public CacheBrowserViewModel() + { + CacheManager.OnCacheChanged += OnCacheChanged; + } + + private void OnCacheChanged(string fileName, CacheChangeType changeType) + { + Dispatcher.UIThread.InvokeAsync(RefreshCache); + } + + partial void OnSearchFilterChanged(string value) + { + ApplyFilter(); + } + + private void ApplyFilter() + { + FilteredVideos.Clear(); + + var filter = SearchFilter?.ToLowerInvariant() ?? string.Empty; + foreach (var video in CachedVideos) + { + if (string.IsNullOrEmpty(filter) || + video.FileName.Contains(filter, StringComparison.OrdinalIgnoreCase) || + video.VideoId.Contains(filter, StringComparison.OrdinalIgnoreCase) || + video.DisplayId.Contains(filter, StringComparison.OrdinalIgnoreCase) || + video.DisplayTitle.Contains(filter, StringComparison.OrdinalIgnoreCase)) + { + FilteredVideos.Add(video); + } + } + + StatusText = string.Format(Localizer.Get("VideosCountFormat"), FilteredVideos.Count, CachedVideos.Count); + } + + [RelayCommand] + private void RefreshCache() + { + CachedVideos.Clear(); + FilteredVideos.Clear(); + + var cachedAssets = CacheManager.GetCachedAssets(); + var itemsToLoad = new List(); + + foreach (var (fileName, cache) in cachedAssets.OrderByDescending(x => x.Value.LastModified)) + { + // Filter out non-video files like index.html + if (fileName.Equals("index.html", StringComparison.OrdinalIgnoreCase)) + continue; + + var videoId = Path.GetFileNameWithoutExtension(fileName); + var extension = Path.GetExtension(fileName); + + var item = new CacheItemViewModel + { + FileName = fileName, + VideoId = videoId, + Size = cache.Size, + LastModified = cache.LastModified, + Extension = extension + }; + + // Subscribe to delete event + item.OnDeleted += OnItemDeleted; + + CachedVideos.Add(item); + itemsToLoad.Add(item); + } + + ApplyFilter(); + + // Load metadata (titles + thumbnails) asynchronously in the background + _ = Task.Run(async () => + { + // Batch-fetch original URLs (and history-derived type) in one query instead of N. + var history = DatabaseManager.GetLatestHistoryUrls(itemsToLoad.Select(i => i.VideoId)); + foreach (var item in itemsToLoad) + { + history.TryGetValue(item.VideoId, out var entry); + await item.LoadMetadataAsync(entry.Url, entry.Url == null ? null : entry.Type); + } + }); + } + + private void OnItemDeleted(CacheItemViewModel item) + { + Dispatcher.UIThread.InvokeAsync(() => + { + CachedVideos.Remove(item); + FilteredVideos.Remove(item); + StatusText = string.Format(Localizer.Get("VideosCountFormat"), FilteredVideos.Count, CachedVideos.Count); + }); + } + + [RelayCommand] + private async Task DeleteAll() + { + var lifetime = Avalonia.Application.Current?.ApplicationLifetime + as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime; + var owner = lifetime?.MainWindow; + if (owner == null) + { + // No UI available — fall back to direct clear so headless/console mode still works. + CacheManager.ClearCache(); + return; + } + + var message = string.Format( + Localizer.Get("ConfirmClearCacheFormat"), + CachedVideos.Count); + var dialog = Views.PopupWindow.CreateConfirm(message, Localizer.Get("Yes"), Localizer.Get("No")); + dialog.Title = Localizer.Get("ConfirmClearCacheTitle"); + await dialog.ShowDialog(owner); + if (dialog.Confirmed) + CacheManager.ClearCache(); + } + + [RelayCommand] + private void OpenInExplorer() + { + var cachePath = CacheManager.CachePath; + if (SelectedItem != null) + Utils.OpenUrl.RevealFile(Path.Join(cachePath, SelectedItem.FileName)); + else + Utils.OpenUrl.OpenFolder(cachePath); + } + +} diff --git a/VRCVideoCacher/ViewModels/CookieSetupViewModel.cs b/VRCVideoCacher/ViewModels/CookieSetupViewModel.cs index 4507fac3..b5de4997 100644 --- a/VRCVideoCacher/ViewModels/CookieSetupViewModel.cs +++ b/VRCVideoCacher/ViewModels/CookieSetupViewModel.cs @@ -236,17 +236,17 @@ private async Task SaveManualCookies() } [RelayCommand] - private void ToggleHost() + private async Task ToggleHost() { - ElevatorManager.ToggleHostLine(); - Dispatcher.UIThread.Post(() => - { - HostState = ElevatorManager.HasHostsLine; - OnPropertyChanged(nameof(HostButtonText)); - OnPropertyChanged(nameof(HostStatusText)); - OnPropertyChanged(nameof(HostStatusIcon)); - OnPropertyChanged(nameof(HostStatusColor)); - }); + // Awaiting resumes on the UI thread, so the Dispatcher.Post that used to wrap these + // updates is no longer needed. + await ElevatorManager.ToggleHostLineAsync(); + + HostState = ElevatorManager.HasHostsLine; + OnPropertyChanged(nameof(HostButtonText)); + OnPropertyChanged(nameof(HostStatusText)); + OnPropertyChanged(nameof(HostStatusIcon)); + OnPropertyChanged(nameof(HostStatusColor)); } [RelayCommand] @@ -284,12 +284,5 @@ private void Cancel() RequestClose?.Invoke(); } - private static void OpenUrl(string url) - { - try - { - Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true }); - } - catch { /* Ignore errors */ } - } + private static void OpenUrl(string url) => Utils.OpenUrl.Open(url); } diff --git a/VRCVideoCacher/ViewModels/DashboardViewModel.cs b/VRCVideoCacher/ViewModels/DashboardViewModel.cs index 3c213439..04156658 100644 --- a/VRCVideoCacher/ViewModels/DashboardViewModel.cs +++ b/VRCVideoCacher/ViewModels/DashboardViewModel.cs @@ -1,224 +1,346 @@ -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Threading; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using Jeek.Avalonia.Localization; -using VRCVideoCacher.Services; -using VRCVideoCacher.Utils; -using VRCVideoCacher.Views; -using VRCVideoCacher.YTDL; - -namespace VRCVideoCacher.ViewModels; - -public partial class MainWindowViewModel; - -public partial class DashboardViewModel : ViewModelBase -{ - [ObservableProperty] - private bool _serverRunning = true; - - [ObservableProperty] - private string _serverUrl = "http://localhost:9696"; - - [ObservableProperty] - private long _totalCacheSize; - - [ObservableProperty] - private float _maxCacheSize; - - [ObservableProperty] - private int _cachedVideoCount; - - [ObservableProperty] - private int _downloadQueueCount; - - [ObservableProperty] - private string _cookieStatus = Localizer.Get("NotSet"); - - [ObservableProperty] - private string _currentDownloadText = Localizer.Get("None"); - - [ObservableProperty] - private bool _hostState; - - [ObservableProperty] - private bool _cookiesFileExists = false; - - public DashboardViewModel() - { - ServerUrl = ConfigManager.Config.YtdlpWebServerUrl; - MaxCacheSize = ConfigManager.Config.CacheMaxSizeInGb; - HostState = ElevatorManager.HasHostsLine; - - // Initial data load - RefreshData(); - - // Subscribe to language changes to refresh localized strings - Localizer.LanguageChanged += (_, _) => Dispatcher.UIThread.InvokeAsync(RefreshLocalizedStrings); - - // Subscribe to events - CacheManager.OnCacheChanged += OnCacheChanged; - VideoDownloader.OnDownloadStarted += OnDownloadStarted; - VideoDownloader.OnDownloadCompleted += OnDownloadCompleted; - VideoDownloader.OnQueueChanged += OnQueueChanged; - ConfigManager.OnConfigChanged += OnConfigChanged; - Program.OnCookiesUpdated += OnCookiesUpdated; - } - - private void RefreshLocalizedStrings() - { - // Force BoolToStatusConverter to re-evaluate with new language - OnPropertyChanged(nameof(ServerRunning)); - - // Refresh directly-assigned localized strings - if (VideoDownloader.GetCurrentDownload() == null) - CurrentDownloadText = Localizer.Get("None"); - } - - private void OnCookiesUpdated() - { - _ = ValidateCookiesAsync(); - } - - private void OnCacheChanged(string fileName, CacheChangeType changeType) - { - Dispatcher.UIThread.InvokeAsync(RefreshCacheStats); - } - - private void OnDownloadStarted(Models.VideoInfo video) - { - Dispatcher.UIThread.InvokeAsync(() => - { - CurrentDownloadText = $"{video.UrlType}: {video.VideoId}"; - }); - } - - private void OnDownloadCompleted(Models.VideoInfo video, bool success, string? failReason) - { - Dispatcher.UIThread.InvokeAsync(() => - { - CurrentDownloadText = Localizer.Get("None"); - }); - } - - private void OnQueueChanged() - { - Dispatcher.UIThread.InvokeAsync(() => - { - DownloadQueueCount = VideoDownloader.GetQueueCount(); - }); - } - - private void OnConfigChanged() - { - Dispatcher.UIThread.InvokeAsync(() => - { - ServerUrl = ConfigManager.Config.YtdlpWebServerUrl; - MaxCacheSize = ConfigManager.Config.CacheMaxSizeInGb; - }); - _ = ValidateCookiesAsync(); - } - - [RelayCommand] - private void RefreshData() - { - RefreshCacheStats(); - DownloadQueueCount = VideoDownloader.GetQueueCount(); - - var currentDownload = VideoDownloader.GetCurrentDownload(); - CurrentDownloadText = currentDownload != null - ? $"{currentDownload.UrlType}: {currentDownload.VideoId}" - : Localizer.Get("None"); - - _ = ValidateCookiesAsync(); - } - - [RelayCommand] - private void ToggleHost() - { - ElevatorManager.ToggleHostLine(); - Dispatcher.UIThread.Post(() => { HostState = ElevatorManager.HasHostsLine; }); - } - - private void RefreshCacheStats() - { - TotalCacheSize = CacheManager.GetTotalCacheSize(); - // Subtract 1 for index.html if it exists in the cache - var count = CacheManager.GetCachedVideoCount(); - var assets = CacheManager.GetCachedAssets(); - if (assets.ContainsKey("index.html")) - count--; - CachedVideoCount = count; - } - - [RelayCommand] - private void OpenCacheFolder() - { - var cachePath = CacheManager.CachePath; - if (OperatingSystem.IsWindows()) - { - System.Diagnostics.Process.Start("explorer.exe", cachePath); - } - else if (OperatingSystem.IsLinux()) - { - System.Diagnostics.Process.Start("xdg-open", cachePath); - } - } - - private async Task ValidateCookiesAsync() - { - CookiesFileExists = Program.DoesCookieFileExist(); - - if (!Program.IsCookiesEnabledAndValid()) - { - Dispatcher.UIThread.Post(() => CookieStatus = Localizer.Get("NotSet")); - return; - } - - Dispatcher.UIThread.Post(() => CookieStatus = Localizer.Get("Checking")); - - var result = await Program.ValidateCookiesAsync(); - Dispatcher.UIThread.Post(() => - { - CookieStatus = result switch - { - true => Localizer.Get("Valid"), - false => Localizer.Get("Expired"), - null => Localizer.Get("Unknown") - }; - }); - } - - [RelayCommand] - private async Task SetupCookieExtension() - { - if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - if (!ConfigManager.Config.YtdlpUseCookies) - { - await new PopupWindow(Localizer.Get("CookiesDisabledWarning")).ShowDialog(desktop.MainWindow!); - return; - } - - var viewModel = new CookieSetupViewModel(); - var window = new CookieSetupWindow - { - DataContext = viewModel - }; - - viewModel.RequestClose += () => window.Close(); - - await window.ShowDialog(desktop.MainWindow!); - - // Refresh cookies status after dialog closes - _ = ValidateCookiesAsync(); - } - } - - [RelayCommand] - private async Task ClearCookies() - { - Program.DeleteCookieFile(); - await ValidateCookiesAsync(); - } -} +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using VRCVideoCacher.Utils; +using VRCVideoCacher.Views; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.ViewModels; + +public partial class DashboardViewModel : ViewModelBase +{ + [ObservableProperty] + private bool _serverRunning = true; + + [ObservableProperty] + private string _serverUrl = "http://localhost:9696"; + + [ObservableProperty] + private long _totalCacheSize; + + [ObservableProperty] + private float _maxCacheSize; + + [ObservableProperty] + private int _cachedVideoCount; + + [ObservableProperty] + private int _downloadQueueCount; + + [ObservableProperty] + private string _cookieStatus = Localizer.Get("NotSet"); + + [ObservableProperty] + private string _currentDownloadText = Localizer.Get("None"); + + [ObservableProperty] + private bool _hostState; + + [ObservableProperty] + private bool _cookiesFileExists = false; + + [ObservableProperty] + private string _ytdlpStatus = "Up-To-Date"; + + [ObservableProperty] + private string _denoStatus = "Up-To-Date"; + + [ObservableProperty] + private string _ffmpegStatus = "Up-To-Date"; + + [ObservableProperty] + private bool _videoPlayersEnabled = true; + + [ObservableProperty] + private string? _motd; + + public bool HasMotd => + !string.IsNullOrWhiteSpace(Motd) && + ConfigManager.Config.DismissedMotdHash != ComputeMotdHash(Motd); + + partial void OnMotdChanged(string? value) => OnPropertyChanged(nameof(HasMotd)); + + private static string ComputeMotdHash(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var bytes = System.Text.Encoding.UTF8.GetBytes(text); + var hash = System.Security.Cryptography.SHA256.HashData(bytes); + return Convert.ToHexString(hash); + } + + [RelayCommand] + private void DismissMotd() + { + if (!string.IsNullOrWhiteSpace(Motd)) + { + ConfigManager.Config.DismissedMotdHash = ComputeMotdHash(Motd); + ConfigManager.TrySaveConfig(); + OnPropertyChanged(nameof(HasMotd)); + } + } + + public DashboardViewModel() + { + VideoPlayersEnabled = ConfigManager.Config.VideoPlayersEnabled; + ServerUrl = ConfigManager.Config.YtdlpWebServerUrl; + MaxCacheSize = ConfigManager.Config.CacheMaxSizeInGb; + HostState = ElevatorManager.HasHostsLine; + Motd = VvcConfigService.CurrentConfig.Motd; + VvcConfigService.OnApiConfigChanged += () => + { + Dispatcher.UIThread.Post(() => Motd = VvcConfigService.CurrentConfig.Motd); + }; + + // Initial data load + RefreshData(); + + // Subscribe to language changes to refresh localized strings + Localizer.LanguageChanged += (_, _) => Dispatcher.UIThread.InvokeAsync(RefreshLocalizedStrings); + + // Subscribe to events + CacheManager.OnCacheChanged += OnCacheChanged; + VideoDownloader.OnDownloadStarted += OnDownloadStarted; + VideoDownloader.OnDownloadCompleted += OnDownloadCompleted; + VideoDownloader.OnDownloadProgress += OnDownloadProgress; + VideoDownloader.OnQueueChanged += OnQueueChanged; + ConfigManager.OnConfigChanged += OnConfigChanged; + Program.OnCookiesUpdated += OnCookiesUpdated; + } + + private void RefreshLocalizedStrings() + { + // Force BoolToStatusConverter to re-evaluate with new language + OnPropertyChanged(nameof(ServerRunning)); + + // Refresh directly-assigned localized strings + if (VideoDownloader.GetCurrentDownload() == null) + CurrentDownloadText = Localizer.Get("None"); + } + + private void OnCookiesUpdated() + { + _ = ValidateCookiesAsync(); + } + + private void OnCacheChanged(string fileName, CacheChangeType changeType) + { + Dispatcher.UIThread.InvokeAsync(RefreshCacheStats); + } + + private void OnDownloadStarted(Models.VideoInfo video) + { + _currentDownloadLabel = $"{video.UrlType}: {video.VideoId}"; + Dispatcher.UIThread.InvokeAsync(() => + { + CurrentDownloadText = _currentDownloadLabel; + }); + } + + // Kept so a progress update can re-append to the same label without re-deriving it. + private string _currentDownloadLabel = string.Empty; + + private void OnDownloadProgress(Models.DownloadProgress progress) + { + if (string.IsNullOrEmpty(_currentDownloadLabel)) + return; + + var eta = progress.FormatEta(); + var suffix = eta != null + ? $" — {progress.Percent:F0}%, {string.Format(Localizer.Get("DownloadTimeRemaining"), eta)}" + : $" — {progress.Percent:F0}%"; + + Dispatcher.UIThread.InvokeAsync(() => CurrentDownloadText = _currentDownloadLabel + suffix); + } + + private void OnDownloadCompleted(Models.VideoInfo video, bool success, string? failReason) + { + _currentDownloadLabel = string.Empty; + Dispatcher.UIThread.InvokeAsync(() => + { + CurrentDownloadText = Localizer.Get("None"); + }); + } + + private void OnQueueChanged() + { + Dispatcher.UIThread.InvokeAsync(() => + { + DownloadQueueCount = VideoDownloader.GetQueueCount(); + }); + } + + private void OnConfigChanged() + { + Dispatcher.UIThread.InvokeAsync(() => + { + ServerUrl = ConfigManager.Config.YtdlpWebServerUrl; + MaxCacheSize = ConfigManager.Config.CacheMaxSizeInGb; + }); + _ = ValidateCookiesAsync(); + } + + [RelayCommand] + private void RefreshData() + { + RefreshCacheStats(); + RefreshUtilStatuses(); + DownloadQueueCount = VideoDownloader.GetQueueCount(); + + var currentDownload = VideoDownloader.GetCurrentDownload(); + CurrentDownloadText = currentDownload != null + ? $"{currentDownload.UrlType}: {currentDownload.VideoId}" + : Localizer.Get("None"); + + _ = ValidateCookiesAsync(); + } + + public void RefreshUtilStatuses() + { + // 1. yt-dlp Status + if (!File.Exists(YtdlManager.YtdlPath)) + { + var sysYtdlp = FileTools.LocateFile(OperatingSystem.IsWindows() ? "yt-dlp.exe" : "yt-dlp"); + YtdlpStatus = sysYtdlp != null ? "Shim" : "Missing"; + } + else + { + try + { + var bytes = File.ReadAllBytes(YtdlManager.YtdlPath); + var hash = Program.ComputeBinaryContentHash(bytes); + if (hash == Program.YtdlpHash) + { + YtdlpStatus = "Shim"; + } + else if (Versions.CurrentVersion.Ytdlp == "Outdated") + { + YtdlpStatus = "Outdated"; + } + else + { + YtdlpStatus = "Up-To-Date"; + } + } + catch + { + YtdlpStatus = "Up-To-Date"; + } + } + + // 2. Deno Status + if (!File.Exists(YtdlManager.DenoPath)) + { + var systemDeno = FileTools.LocateFile(OperatingSystem.IsWindows() ? "deno.exe" : "deno"); + DenoStatus = systemDeno != null ? "Shim" : "Missing"; + } + else if (Versions.CurrentVersion.Deno == "Outdated") + { + DenoStatus = "Outdated"; + } + else + { + DenoStatus = "Up-To-Date"; + } + + // 3. FFmpeg Status + if (!File.Exists(YtdlManager.FfmpegPath)) + { + var systemFfmpeg = FileTools.LocateFile(OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"); + FfmpegStatus = systemFfmpeg != null ? "Shim" : "Missing"; + } + else if (Versions.CurrentVersion.Ffmpeg == "Outdated") + { + FfmpegStatus = "Outdated"; + } + else + { + FfmpegStatus = "Up-To-Date"; + } + } + + [RelayCommand] + private void ToggleVideoPlayers() + { + VideoPlayersEnabled = !VideoPlayersEnabled; + ConfigManager.SetVideoPlayersEnabled(VideoPlayersEnabled); + } + + [RelayCommand] + private async Task ToggleHost() + { + await ElevatorManager.ToggleHostLineAsync(); + HostState = ElevatorManager.HasHostsLine; + } + + private void RefreshCacheStats() + { + TotalCacheSize = CacheManager.GetTotalCacheSize(); + // The index only holds .mp4/.webm now, so index.html is never counted and no + // longer has to be subtracted back out. + CachedVideoCount = CacheManager.GetCachedVideoCount(); + } + + [RelayCommand] + private void OpenCacheFolder() => OpenUrl.OpenFolder(CacheManager.CachePath); + + private async Task ValidateCookiesAsync() + { + CookiesFileExists = Program.DoesCookieFileExist(); + + if (!Program.IsCookiesEnabledAndValid()) + { + Dispatcher.UIThread.Post(() => CookieStatus = Localizer.Get("NotSet")); + return; + } + + Dispatcher.UIThread.Post(() => CookieStatus = Localizer.Get("Checking")); + + var result = await Program.ValidateCookiesAsync(); + Dispatcher.UIThread.Post(() => + { + CookieStatus = result switch + { + true => Localizer.Get("Valid"), + false => Localizer.Get("Expired"), + null => Localizer.Get("Unknown") + }; + }); + } + + [RelayCommand] + private async Task SetupCookieExtension() + { + if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + if (!ConfigManager.Config.YtdlpUseCookies) + { + await new PopupWindow(Localizer.Get("CookiesDisabledWarning")).ShowDialog(desktop.MainWindow!); + return; + } + + var viewModel = new CookieSetupViewModel(); + var window = new CookieSetupWindow + { + DataContext = viewModel + }; + + viewModel.RequestClose += () => window.Close(); + + await window.ShowDialog(desktop.MainWindow!); + + // Refresh cookies status after dialog closes + _ = ValidateCookiesAsync(); + } + } + + [RelayCommand] + private async Task ClearCookies() + { + Program.DeleteCookieFile(); + await ValidateCookiesAsync(); + } +} diff --git a/VRCVideoCacher/ViewModels/DownloadQueueViewModel.cs b/VRCVideoCacher/ViewModels/DownloadQueueViewModel.cs index c19ae5b0..23d07ef4 100644 --- a/VRCVideoCacher/ViewModels/DownloadQueueViewModel.cs +++ b/VRCVideoCacher/ViewModels/DownloadQueueViewModel.cs @@ -1,313 +1,343 @@ -using System.Collections.ObjectModel; -using Avalonia.Threading; -using Jeek.Avalonia.Localization; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using VRCVideoCacher.Database; -using VRCVideoCacher.Models; -using VRCVideoCacher.YTDL; - -namespace VRCVideoCacher.ViewModels; - -public partial class DownloadItemViewModel : ViewModelBase -{ - public int DbKey { get; init; } - public string VideoUrl { get; init; } = string.Empty; - public string VideoId { get; init; } = string.Empty; - public string UrlType { get; init; } = string.Empty; - public string Format { get; init; } = string.Empty; - public string QueuedAt { get; init; } = string.Empty; - public string? Title { get; init; } - - public string DisplayTitle - { - get - { - if (!string.IsNullOrEmpty(Title)) - return Title.Length > 50 ? Title[..47] + "..." : Title; - return VideoId; - } - } -} - -public partial class DownloadQueueViewModel : ViewModelBase -{ - [ObservableProperty] - private DownloadItemViewModel? _currentDownload; - - [ObservableProperty] - private string _currentStatus = "Idle"; - - [ObservableProperty] - private string _manualUrl = string.Empty; - - [ObservableProperty] - private string _statusMessage = string.Empty; - - [ObservableProperty] - private double _downloadProgress; - - [ObservableProperty] - private bool _isDownloading; - - public ObservableCollection QueuedDownloads { get; } = []; - - public DownloadQueueViewModel() - { - RefreshQueue(); - - VideoDownloader.OnDownloadStarted += OnDownloadStarted; - VideoDownloader.OnDownloadCompleted += OnDownloadCompleted; - VideoDownloader.OnDownloadPaused += OnDownloadPaused; - VideoDownloader.OnQueueChanged += OnQueueChanged; - VideoDownloader.OnDownloadProgress += OnDownloadProgressUpdate; - DatabaseManager.OnPendingDownloadsChanged += OnQueueChanged; - } - - private static string? LookupTitle(string videoId) - { - return DatabaseManager.GetVideoInfoCache(videoId)?.Title; - } - - private void OnDownloadStarted(VideoInfo video) - { - var title = LookupTitle(video.VideoId); - Dispatcher.UIThread.InvokeAsync(() => - { - CurrentDownload = new DownloadItemViewModel - { - VideoUrl = video.VideoUrl, - VideoId = video.VideoId, - UrlType = video.UrlType.ToString(), - Format = video.DownloadFormat.ToString(), - Title = title - }; - CurrentStatus = $"Downloading {CurrentDownload.DisplayTitle}..."; - DownloadProgress = 0; - IsDownloading = true; - RefreshQueue(); - }); - } - - private static string TranslateFailReason(string failReason) - { - // Format: "SkipReasonTooLong|34|10" for parameterized keys - var parts = failReason.Split('|'); - var key = parts[0]; - var translated = Localizer.Get(key); - if (translated == key) - return failReason; // not a translation key, use as-is (e.g. exception messages) - if (parts.Length > 1) - { - var args = parts.Skip(1).Cast().ToArray(); - return string.Format(translated, args); - } - return translated; - } - - private void OnDownloadCompleted(VideoInfo video, bool success, string? failReason) - { - var title = LookupTitle(video.VideoId); - var displayName = !string.IsNullOrEmpty(title) ? title : video.VideoId; - Dispatcher.UIThread.InvokeAsync(() => - { - CurrentDownload = null; - CurrentStatus = success ? "Completed" : "Failed"; - if (success) - StatusMessage = string.Format(Localizer.Get("DownloadCompleted"), displayName); - else if (!string.IsNullOrEmpty(failReason)) - StatusMessage = string.Format(Localizer.Get("DownloadSkipped"), displayName, TranslateFailReason(failReason)); - else - StatusMessage = string.Format(Localizer.Get("DownloadFailed"), displayName); - DownloadProgress = 0; - IsDownloading = false; - RefreshQueue(); - }); - } - - private DateTime _lastProgressUpdate; - - private void OnDownloadProgressUpdate(double percent) - { - var now = DateTime.UtcNow; - if ((now - _lastProgressUpdate).TotalMilliseconds < 250 && percent < 99.9) - return; - _lastProgressUpdate = now; - - Dispatcher.UIThread.InvokeAsync(() => - { - DownloadProgress = percent; - }); - } - - private void OnDownloadPaused(VideoInfo video) - { - Dispatcher.UIThread.InvokeAsync(() => - { - CurrentStatus = $"Paused — waiting for stream to finish"; - RefreshQueue(); - }); - } - - private void OnQueueChanged() - { - Dispatcher.UIThread.InvokeAsync(RefreshQueue); - } - - [RelayCommand] - private void RefreshQueue() - { - QueuedDownloads.Clear(); - - var pending = VideoDownloader.GetQueueSnapshot(); - foreach (var item in pending) - { - QueuedDownloads.Add(new DownloadItemViewModel - { - DbKey = item.Key, - VideoUrl = item.VideoUrl, - VideoId = item.VideoId, - UrlType = item.UrlType.ToString(), - Format = item.DownloadFormat.ToString(), - QueuedAt = item.QueuedAt.ToLocalTime().ToString("g"), - Title = LookupTitle(item.VideoId) - }); - } - - var state = VideoDownloader.GetDownloadState(); - var current = VideoDownloader.GetCurrentDownload() ?? VideoDownloader.GetPausedDownload(); - if (current != null) - { - CurrentDownload = new DownloadItemViewModel - { - VideoUrl = current.VideoUrl, - VideoId = current.VideoId, - UrlType = current.UrlType.ToString(), - Format = current.DownloadFormat.ToString(), - Title = LookupTitle(current.VideoId) - }; - CurrentStatus = state switch - { - DownloadState.Paused => "Paused — waiting for stream to finish", - DownloadState.WaitingForIdle => "Waiting for streaming to stop...", - _ => $"Downloading {CurrentDownload.DisplayTitle}..." - }; - } - else - { - CurrentDownload = null; - if (QueuedDownloads.Count == 0) - CurrentStatus = "Idle"; - else if (state == DownloadState.WaitingForIdle) - CurrentStatus = "Waiting for streaming to stop..."; - else - CurrentStatus = $"{QueuedDownloads.Count} pending"; - } - } - - [RelayCommand] - private void DownloadNow(DownloadItemViewModel? item) - { - if (item == null) return; - - // Bump to top of queue first (unless it's already first in DB) - if (item.DbKey > 0) - VideoDownloader.BumpToTopOfQueue(item.DbKey); - - VideoDownloader.ForceDownloadNext(); - StatusMessage = $"Force downloading: {item.DisplayTitle}"; - RefreshQueue(); - } - - [RelayCommand] - private void RemoveFromQueue(DownloadItemViewModel? item) - { - if (item == null) return; - - if (item.DbKey > 0) - VideoDownloader.RemoveFromQueueByKey(item.DbKey); - else - VideoDownloader.RemoveFromQueue(item.VideoId, Enum.Parse(item.Format)); - - StatusMessage = $"Removed: {item.DisplayTitle}"; - RefreshQueue(); - } - - [RelayCommand] - private async Task AddManualDownload() - { - if (string.IsNullOrWhiteSpace(ManualUrl)) - { - StatusMessage = "Please enter a URL"; - return; - } - - var urls = ManualUrl.Split(['\n', '\r', ',', ' '], StringSplitOptions.RemoveEmptyEntries) - .Select(u => u.Trim()) - .Where(u => !string.IsNullOrWhiteSpace(u)) - .ToList(); - - var added = 0; - var failed = 0; - var errors = new List(); - - foreach (var url in urls) - { - try - { - if (VideoId.IsYouTubePlaylist(url)) - { - StatusMessage = "Extracting playlist..."; - var playlistVideos = await VideoId.GetPlaylistVideoInfos(url, true); - if (playlistVideos.Count == 0) - { - errors.Add($"No videos found in playlist: {url}"); - failed++; - continue; - } - foreach (var video in playlistVideos) - { - VideoDownloader.QueueDownload(video); - added++; - } - } - else - { - var videoInfo = await VideoId.GetVideoId(url, true); - if (videoInfo != null) - { - VideoDownloader.QueueDownload(videoInfo); - added++; - } - else - { - errors.Add($"Could not parse: {url}"); - failed++; - } - } - } - catch (Exception ex) - { - errors.Add($"Error with {url}: {ex.Message}"); - failed++; - } - } - - if (added > 0) - ManualUrl = string.Empty; - - if (failed == 0) - StatusMessage = $"Added {added} video(s) to queue"; - else if (added == 0) - StatusMessage = string.Join("; ", errors); - else - StatusMessage = $"Added {added} video(s), {failed} failed: {string.Join("; ", errors)}"; - } - - [RelayCommand] - private void ClearQueue() - { - VideoDownloader.ClearQueue(); - StatusMessage = "Download queue cleared"; - } -} +using System.Collections.ObjectModel; +using Avalonia.Threading; +using Jeek.Avalonia.Localization; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using VRCVideoCacher.Database; +using VRCVideoCacher.Models; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.ViewModels; + +public partial class DownloadItemViewModel : ViewModelBase +{ + public int DbKey { get; init; } + public string VideoUrl { get; init; } = string.Empty; + public string VideoId { get; init; } = string.Empty; + public string UrlType { get; init; } = string.Empty; + public string Format { get; init; } = string.Empty; + public string QueuedAt { get; init; } = string.Empty; + public string? Title { get; init; } + + public string DisplayTitle + { + get + { + if (!string.IsNullOrEmpty(Title)) + return Title.Length > 50 ? Title[..47] + "..." : Title; + return VideoId; + } + } +} + +public partial class DownloadQueueViewModel : ViewModelBase +{ + [ObservableProperty] + private DownloadItemViewModel? _currentDownload; + + [ObservableProperty] + private string _currentStatus = "Idle"; + + [ObservableProperty] + private string _manualUrl = string.Empty; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private double _downloadProgress; + + [ObservableProperty] + private bool _isDownloading; + + /// + /// "1.2 MB/s · 3m 20s left", or just the rate when no estimate is available, or empty + /// when neither is known yet. Deliberately blank rather than showing a placeholder: + /// early in a transfer yt-dlp genuinely reports "Unknown". + /// + [ObservableProperty] + private string _downloadRateText = string.Empty; + + public ObservableCollection QueuedDownloads { get; } = []; + + public DownloadQueueViewModel() + { + RefreshQueue(); + + VideoDownloader.OnDownloadStarted += OnDownloadStarted; + VideoDownloader.OnDownloadCompleted += OnDownloadCompleted; + VideoDownloader.OnDownloadPaused += OnDownloadPaused; + VideoDownloader.OnQueueChanged += OnQueueChanged; + VideoDownloader.OnDownloadProgress += OnDownloadProgressUpdate; + DatabaseManager.OnPendingDownloadsChanged += OnQueueChanged; + } + + private static string? LookupTitle(string videoId) + { + return DatabaseManager.GetVideoInfoCache(videoId)?.Title; + } + + private void OnDownloadStarted(VideoInfo video) + { + var title = LookupTitle(video.VideoId); + Dispatcher.UIThread.InvokeAsync(() => + { + CurrentDownload = new DownloadItemViewModel + { + VideoUrl = video.VideoUrl, + VideoId = video.VideoId, + UrlType = video.UrlType.ToString(), + Format = video.DownloadFormat.ToString(), + Title = title + }; + CurrentStatus = $"Downloading {CurrentDownload.DisplayTitle}..."; + DownloadProgress = 0; + DownloadRateText = string.Empty; + IsDownloading = true; + RefreshQueue(); + }); + } + + private static string TranslateFailReason(string failReason) + { + // Format: "SkipReasonTooLong|34|10" for parameterized keys + var parts = failReason.Split('|'); + var key = parts[0]; + var translated = Localizer.Get(key); + if (translated == key) + return failReason; // not a translation key, use as-is (e.g. exception messages) + if (parts.Length > 1) + { + var args = parts.Skip(1).Cast().ToArray(); + return string.Format(translated, args); + } + return translated; + } + + private void OnDownloadCompleted(VideoInfo video, bool success, string? failReason) + { + var title = LookupTitle(video.VideoId); + var displayName = !string.IsNullOrEmpty(title) ? title : video.VideoId; + Dispatcher.UIThread.InvokeAsync(() => + { + CurrentDownload = null; + CurrentStatus = success ? "Completed" : "Failed"; + if (success) + StatusMessage = string.Format(Localizer.Get("DownloadCompleted"), displayName); + else if (!string.IsNullOrEmpty(failReason)) + StatusMessage = string.Format(Localizer.Get("DownloadSkipped"), displayName, TranslateFailReason(failReason)); + else + StatusMessage = string.Format(Localizer.Get("DownloadFailed"), displayName); + DownloadProgress = 0; + DownloadRateText = string.Empty; + IsDownloading = false; + RefreshQueue(); + }); + } + + private DateTime _lastProgressUpdate; + + private void OnDownloadProgressUpdate(DownloadProgress progress) + { + var now = DateTime.UtcNow; + if ((now - _lastProgressUpdate).TotalMilliseconds < 250 && progress.Percent < 99.9) + return; + _lastProgressUpdate = now; + + var detail = FormatProgressDetail(progress); + + Dispatcher.UIThread.InvokeAsync(() => + { + DownloadProgress = progress.Percent; + DownloadRateText = detail; + }); + } + + /// + /// Joins whichever of rate and time-remaining are actually known. + /// + private static string FormatProgressDetail(DownloadProgress progress) + { + var rate = progress.FormatRate(); + var eta = progress.FormatEta(); + + if (eta != null) + { + var remaining = string.Format(Localizer.Get("DownloadTimeRemaining"), eta); + return rate != null ? $"{rate} · {remaining}" : remaining; + } + + return rate ?? string.Empty; + } + + private void OnDownloadPaused(VideoInfo video) + { + Dispatcher.UIThread.InvokeAsync(() => + { + CurrentStatus = $"Paused — waiting for stream to finish"; + RefreshQueue(); + }); + } + + private void OnQueueChanged() + { + Dispatcher.UIThread.InvokeAsync(RefreshQueue); + } + + [RelayCommand] + private void RefreshQueue() + { + QueuedDownloads.Clear(); + + var pending = VideoDownloader.GetQueueSnapshot(); + foreach (var item in pending) + { + QueuedDownloads.Add(new DownloadItemViewModel + { + DbKey = item.Key, + VideoUrl = item.VideoUrl, + VideoId = item.VideoId, + UrlType = item.UrlType.ToString(), + Format = item.DownloadFormat.ToString(), + QueuedAt = item.QueuedAt.ToLocalTime().ToString("g"), + Title = LookupTitle(item.VideoId) + }); + } + + var state = VideoDownloader.GetDownloadState(); + var current = VideoDownloader.GetCurrentDownload() ?? VideoDownloader.GetPausedDownload(); + if (current != null) + { + CurrentDownload = new DownloadItemViewModel + { + VideoUrl = current.VideoUrl, + VideoId = current.VideoId, + UrlType = current.UrlType.ToString(), + Format = current.DownloadFormat.ToString(), + Title = LookupTitle(current.VideoId) + }; + CurrentStatus = state switch + { + DownloadState.Paused => "Paused — waiting for stream to finish", + DownloadState.WaitingForIdle => "Waiting for streaming to stop...", + _ => $"Downloading {CurrentDownload.DisplayTitle}..." + }; + } + else + { + CurrentDownload = null; + if (QueuedDownloads.Count == 0) + CurrentStatus = "Idle"; + else if (state == DownloadState.WaitingForIdle) + CurrentStatus = "Waiting for streaming to stop..."; + else + CurrentStatus = $"{QueuedDownloads.Count} pending"; + } + } + + [RelayCommand] + private void DownloadNow(DownloadItemViewModel? item) + { + if (item == null) return; + + // Bump to top of queue first (unless it's already first in DB) + if (item.DbKey > 0) + VideoDownloader.BumpToTopOfQueue(item.DbKey); + + VideoDownloader.ForceDownloadNext(); + StatusMessage = $"Force downloading: {item.DisplayTitle}"; + RefreshQueue(); + } + + [RelayCommand] + private void RemoveFromQueue(DownloadItemViewModel? item) + { + if (item == null) return; + + if (item.DbKey > 0) + VideoDownloader.RemoveFromQueueByKey(item.DbKey); + else + VideoDownloader.RemoveFromQueue(item.VideoId, Enum.Parse(item.Format)); + + StatusMessage = $"Removed: {item.DisplayTitle}"; + RefreshQueue(); + } + + [RelayCommand] + private async Task AddManualDownload() + { + if (string.IsNullOrWhiteSpace(ManualUrl)) + { + StatusMessage = "Please enter a URL"; + return; + } + + var urls = ManualUrl.Split(['\n', '\r', ',', ' '], StringSplitOptions.RemoveEmptyEntries) + .Select(u => u.Trim()) + .Where(u => !string.IsNullOrWhiteSpace(u)) + .ToList(); + + var added = 0; + var failed = 0; + var errors = new List(); + + foreach (var url in urls) + { + try + { + if (VideoId.IsYouTubePlaylist(url)) + { + StatusMessage = "Extracting playlist..."; + var playlistVideos = await VideoId.GetPlaylistVideoInfos(url, true); + if (playlistVideos.Count == 0) + { + errors.Add($"No videos found in playlist: {url}"); + failed++; + continue; + } + foreach (var video in playlistVideos) + { + VideoDownloader.QueueDownload(video); + added++; + } + } + else + { + var videoInfo = await VideoId.GetVideoId(url, true); + if (videoInfo != null) + { + VideoDownloader.QueueDownload(videoInfo); + added++; + } + else + { + errors.Add($"Could not parse: {url}"); + failed++; + } + } + } + catch (Exception ex) + { + errors.Add($"Error with {url}: {ex.Message}"); + failed++; + } + } + + if (added > 0) + ManualUrl = string.Empty; + + if (failed == 0) + StatusMessage = $"Added {added} video(s) to queue"; + else if (added == 0) + StatusMessage = string.Join("; ", errors); + else + StatusMessage = $"Added {added} video(s), {failed} failed: {string.Join("; ", errors)}"; + } + + [RelayCommand] + private void ClearQueue() + { + VideoDownloader.ClearQueue(); + StatusMessage = "Download queue cleared"; + } +} diff --git a/VRCVideoCacher/ViewModels/EditRuleViewModel.cs b/VRCVideoCacher/ViewModels/EditRuleViewModel.cs new file mode 100644 index 00000000..065dd8f8 --- /dev/null +++ b/VRCVideoCacher/ViewModels/EditRuleViewModel.cs @@ -0,0 +1,174 @@ +using System.Text.RegularExpressions; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Models; + +namespace VRCVideoCacher.ViewModels; + +public partial class EditRuleViewModel : ObservableObject +{ + [ObservableProperty] + private string _title = string.Empty; + + [ObservableProperty] + private string _name = string.Empty; + + [ObservableProperty] + private string _pattern = string.Empty; + + [ObservableProperty] + private RuleAction _selectedAction = RuleAction.Resolve; + + [ObservableProperty] + private bool _enabled = true; + + [ObservableProperty] + private bool _cache = false; + + [ObservableProperty] + private int _maxResolution = 1080; + + [ObservableProperty] + private int _maxDurationMinutes = 120; + + [ObservableProperty] + private string _redirectTarget = string.Empty; + + [ObservableProperty] + private string? _selectedIntegration = null; + + [ObservableProperty] + private string _patternError = string.Empty; + + [ObservableProperty] + private bool _isValidPattern = true; + + public RuleAction[] AvailableActions { get; } = + [ + RuleAction.Direct, + RuleAction.Resolve, + RuleAction.Redirect, + RuleAction.Rewrite, + RuleAction.Block + ]; + + /// + /// Taken from the registry rather than hardcoded, so adding an integration does not also + /// require remembering to list it here — and so a name can never drift out of sync with + /// the one the rules actually bind to. The leading null is "no integration". + /// + public string?[] AvailableIntegrations { get; } = + [null, .. Integrations.IntegrationRegistry.AvailableIntegrationNames()]; + + public int[] ResolutionOptions { get; } = [0, 720, 1080, 1440, 2160]; + + public bool IsCacheOptionVisible => SelectedAction == RuleAction.Resolve; + public bool IsCacheAction => SelectedAction == RuleAction.Resolve && Cache; + public bool IsRedirectAction => SelectedAction == RuleAction.Redirect || SelectedAction == RuleAction.Rewrite; + public string TargetUrlLabel => SelectedAction == RuleAction.Rewrite + ? Localizer.Get("RewriteTarget") + : Localizer.Get("RedirectTarget"); + + public UriRule RuleResult { get; private set; } + + public event Action? CloseRequested; + + public EditRuleViewModel(UriRule? ruleToEdit = null) + { + if (ruleToEdit != null) + { + Title = Localizer.Get("EditRuleTitle"); + RuleResult = ruleToEdit.Clone(); + Name = ruleToEdit.Name; + Pattern = ruleToEdit.Pattern; + SelectedAction = ruleToEdit.Action; + Enabled = ruleToEdit.Enabled; + Cache = ruleToEdit.Cache; + MaxResolution = ruleToEdit.MaxResolution ?? 1080; + MaxDurationMinutes = ruleToEdit.MaxDurationMinutes ?? 120; + RedirectTarget = ruleToEdit.RedirectTarget; + SelectedIntegration = ruleToEdit.Integration; + } + else + { + Title = Localizer.Get("AddRuleTitle"); + RuleResult = new UriRule(); + Name = "New Rule"; + Pattern = @"^https?://"; + SelectedAction = RuleAction.Resolve; + Enabled = true; + Cache = false; + MaxResolution = 1080; + MaxDurationMinutes = 120; + SelectedIntegration = null; + } + + ValidatePattern(); + } + + partial void OnPatternChanged(string value) + { + ValidatePattern(); + } + + partial void OnSelectedActionChanged(RuleAction value) + { + OnPropertyChanged(nameof(IsCacheOptionVisible)); + OnPropertyChanged(nameof(IsCacheAction)); + OnPropertyChanged(nameof(IsRedirectAction)); + OnPropertyChanged(nameof(TargetUrlLabel)); + } + + partial void OnCacheChanged(bool value) + { + OnPropertyChanged(nameof(IsCacheAction)); + } + + private void ValidatePattern() + { + if (string.IsNullOrWhiteSpace(Pattern)) + { + IsValidPattern = false; + PatternError = Localizer.Get("PatternCannotBeEmpty"); + return; + } + + try + { + _ = new Regex(Pattern); + IsValidPattern = true; + PatternError = string.Empty; + } + catch (Exception ex) + { + IsValidPattern = false; + PatternError = string.Format(Localizer.Get("InvalidRegex"), ex.Message); + } + } + + [RelayCommand] + private void Save() + { + ValidatePattern(); + if (!IsValidPattern) return; + + RuleResult.Name = Name; + RuleResult.Pattern = Pattern; + RuleResult.Action = SelectedAction; + RuleResult.Enabled = Enabled; + RuleResult.Cache = IsCacheAction; + RuleResult.MaxResolution = IsCacheAction ? MaxResolution : null; + RuleResult.MaxDurationMinutes = IsCacheAction ? MaxDurationMinutes : null; + RuleResult.RedirectTarget = IsRedirectAction ? RedirectTarget : string.Empty; + RuleResult.Integration = SelectedIntegration; + + CloseRequested?.Invoke(true); + } + + [RelayCommand] + private void Cancel() + { + CloseRequested?.Invoke(false); + } +} diff --git a/VRCVideoCacher/ViewModels/HistoryViewModel.cs b/VRCVideoCacher/ViewModels/HistoryViewModel.cs index 3ec680de..b5820296 100644 --- a/VRCVideoCacher/ViewModels/HistoryViewModel.cs +++ b/VRCVideoCacher/ViewModels/HistoryViewModel.cs @@ -1,299 +1,292 @@ -using System.Collections.ObjectModel; -using Avalonia.Input.Platform; -using Avalonia.Media; -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using Jeek.Avalonia.Localization; -using VRCVideoCacher.Database; -using VRCVideoCacher.Database.Models; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; -using VRCVideoCacher.YTDL; - -namespace VRCVideoCacher.ViewModels; - -public partial class HistoryItemViewModel : ViewModelBase -{ - public DateTime Timestamp { get; init; } - public string Url { get; init; } = string.Empty; - public string? Id { get; init; } - public UrlType Type { get; init; } - public string? Author { get; init; } - public bool HasAuthor => !string.IsNullOrEmpty(Author); - - private string? _title; - private string? _thumbnailUrl; - - public string DisplayTitle - { - get - { - if (!string.IsNullOrEmpty(_title)) return _title; - return Url.Length > 60 ? Url[..57] + "..." : Url; - } - } - - // Surface the human-readable id for VRDancing rows (the numerical code in the URL) - // instead of the URL hash; for YouTube show the 11-char id, otherwise fall through - // to the stored Id. - public string? DisplayId => Type == UrlType.VRDancing && !string.IsNullOrEmpty(Url) - ? ExtractVRDancingCode(Url) - : Id; - - public bool HasDisplayId => !string.IsNullOrEmpty(DisplayId); - - private static string ExtractVRDancingCode(string url) - { - var trimmed = url.TrimEnd('/'); - var idx = trimmed.LastIndexOf('/'); - return idx >= 0 && idx < trimmed.Length - 1 ? trimmed[(idx + 1)..] : trimmed; - } - - public string TypeBadge => Type switch - { - UrlType.YouTube => "YouTube", - UrlType.PyPyDance => "PyPyDance", - UrlType.VRDancing => "VRDancing", - UrlType.Hls => "HLS", - _ => "Other" - }; - - public IBrush TypeBadgeColor => Type switch - { - UrlType.YouTube => new SolidColorBrush(Color.Parse("#CC0000")), - UrlType.PyPyDance => new SolidColorBrush(Color.Parse("#4A90D9")), - UrlType.VRDancing => new SolidColorBrush(Color.Parse("#7B68EE")), - UrlType.Hls => new SolidColorBrush(Color.Parse("#2E8B57")), - _ => new SolidColorBrush(Color.Parse("#555555")) - }; - - public string? ThumbnailUrl => _thumbnailUrl; - - [ObservableProperty] - private bool _isCached; - - [ObservableProperty] - private bool _isInQueue; - - public HistoryItemViewModel(History history, VideoInfoCache? meta) - { - Timestamp = history.Timestamp.ToLocalTime(); - Url = history.Url; - Id = history.Id; - Type = history.Type; - _title = meta?.Title; - Author = meta?.Author; - UpdateStatus(); - } - - public void UpdateStatus() - { - if (Id == null) return; - - // Check if video is cached - var cachedAssets = CacheManager.GetCachedAssets(); - IsCached = cachedAssets.Keys.Any(k => Path.GetFileNameWithoutExtension(k) == Id); - - // Check if video is in download queue - var queue = VideoDownloader.GetQueueSnapshot(); - var current = VideoDownloader.GetCurrentDownload(); - var paused = VideoDownloader.GetPausedDownload(); - IsInQueue = queue.Any(q => q.VideoId == Id) - || current?.VideoId == Id - || paused?.VideoId == Id; - } - - public void SetMetadata(string? title, string? thumbnailUrl) - { - if (!string.IsNullOrEmpty(title)) - { - _title = title; - OnPropertyChanged(nameof(DisplayTitle)); - } - if (!string.IsNullOrEmpty(thumbnailUrl)) - { - _thumbnailUrl = thumbnailUrl; - OnPropertyChanged(nameof(ThumbnailUrl)); - } - } - - [ObservableProperty] - private bool _isSavingToCache; - - public bool CanSaveToCache => !IsCached && !IsInQueue && !IsSavingToCache; - - partial void OnIsCachedChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); - partial void OnIsInQueueChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); - partial void OnIsSavingToCacheChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); - - [RelayCommand] - private async Task SaveToCache() - { - if (string.IsNullOrEmpty(Url)) return; - - IsSavingToCache = true; - try - { - var videoInfo = await VideoId.GetVideoId(Url, true); - if (videoInfo != null) - { - VideoDownloader.QueueDownload(videoInfo); - UpdateStatus(); - } - } - catch (Exception ex) - { - Serilog.Log.Error(ex, "Failed to save {Url} to cache.", Url); - } - finally - { - IsSavingToCache = false; - } - } - - public async Task<(string? DisplayTitle, string? ThumbnailUrl)> LoadMetadataAsync() - { - if (Id != null) - { - // Load from DB - var videoInfo = await YouTubeMetadataService.GetVideoMetadataAsync(Id); - - if (!string.IsNullOrEmpty(videoInfo?.Title)) - { - _title = videoInfo.Title; - OnPropertyChanged(nameof(DisplayTitle)); - } - - // Load thumbnail - var thumbnailPath = ThumbnailManager.GetThumbnail(Id); - if (Id.Length == 11 && string.IsNullOrEmpty(thumbnailPath)) - thumbnailPath = await YouTubeMetadataService.GetThumbnail(Id); - - if (!string.IsNullOrEmpty(thumbnailPath)) - { - _thumbnailUrl = thumbnailPath; - OnPropertyChanged(nameof(ThumbnailUrl)); - } - } - - return (DisplayTitle, ThumbnailUrl); - } - - [RelayCommand] - private void OpenUrl() - { - try - { - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo - { - FileName = Url, - UseShellExecute = true - }); - } - catch { /* Ignore errors */ } - } - - [RelayCommand] - private async Task CopyUrl() - { - if (Avalonia.Application.Current?.ApplicationLifetime is - Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) - { - var clipboard = desktop.MainWindow?.Clipboard; - if (clipboard != null) - await clipboard.SetTextAsync(Url); - } - } -} - -public partial class HistoryViewModel : ViewModelBase -{ - [ObservableProperty] - private string _statusText = string.Empty; - - public ObservableCollection HistoryItems { get; } = []; - - public HistoryViewModel() - { - DatabaseManager.OnPlayHistoryAdded += () => Avalonia.Threading.Dispatcher.UIThread.Post(Refresh); - - // LoadMetadataAsync updates the cache, which fires this event — _isRefreshing guard prevents re-entry. - DatabaseManager.OnVideoInfoCacheUpdated += () => Avalonia.Threading.Dispatcher.UIThread.Post(Refresh); - - // Update status icons when queue or cache changes - VideoDownloader.OnQueueChanged += UpdateItemStatuses; - CacheManager.OnCacheChanged += (_, _) => UpdateItemStatuses(); - - Refresh(); - } - - private void UpdateItemStatuses() - { - Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => - { - foreach (var item in HistoryItems) - item.UpdateStatus(); - }); - } - - private bool _isRefreshing; - - [RelayCommand] - private void Refresh() - { - // Prevent infinite loop - if (_isRefreshing) - { - return; - } - _isRefreshing = true; - - var historyCache = DatabaseManager.GetVideoHistoryAsCache(distinctOnly: true); - - HistoryItems.Clear(); - foreach (var item in historyCache.OrderByDescending(h => h.Timestamp)) - { - HistoryItems.Add(item); - } - StatusText = string.Format(Localizer.Get("EntriesCountFormat"), HistoryItems.Count); - - _ = Task.Run(async () => - { - // Must always clear _isRefreshing — any unhandled exception here would otherwise - // wedge Refresh() permanently, making the history UI stop updating after a few videos. - try - { - foreach (var groupedItems in historyCache.GroupBy(h => h.Id)) - { - (string? DisplayTitle, string? ThumbnailUrl)? metadata = null; - foreach (var item in groupedItems) - { - try - { - if (metadata == null) - { - metadata = await item.LoadMetadataAsync(); - } - else - { - item.SetMetadata(metadata.Value.DisplayTitle, metadata.Value.ThumbnailUrl); - } - } - catch (Exception ex) - { - Serilog.Log.Warning(ex, "Failed to load metadata for history item {Id}", item.Id); - } - } - } - } - catch (Exception ex) - { - Serilog.Log.Error(ex, "History metadata refresh failed"); - } - finally - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => _isRefreshing = false); - } - }); - } -} +using System.Collections.ObjectModel; +using Avalonia.Input.Platform; +using Avalonia.Media; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Database; +using VRCVideoCacher.Database.Models; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using VRCVideoCacher.Integrations.YouTube; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.ViewModels; + +public partial class HistoryItemViewModel : ViewModelBase +{ + public DateTime Timestamp { get; init; } + public string Url { get; init; } = string.Empty; + public string? Id { get; init; } + public UrlType Type { get; init; } + public string? Author { get; init; } + public bool HasAuthor => !string.IsNullOrEmpty(Author); + + private string? _title; + private string? _thumbnailUrl; + + public string DisplayTitle + { + get + { + if (!string.IsNullOrEmpty(_title)) return _title; + return Url.Length > 60 ? Url[..57] + "..." : Url; + } + } + + // Surface the human-readable id for VRDancing rows (the numerical code in the URL) + // instead of the URL hash; for YouTube show the 11-char id, otherwise fall through + // to the stored Id. + public string? DisplayId => Type == UrlType.VRDancing && !string.IsNullOrEmpty(Url) + ? ExtractVRDancingCode(Url) + : Id; + + public bool HasDisplayId => !string.IsNullOrEmpty(DisplayId); + + private static string ExtractVRDancingCode(string url) + { + var trimmed = url.TrimEnd('/'); + var idx = trimmed.LastIndexOf('/'); + return idx >= 0 && idx < trimmed.Length - 1 ? trimmed[(idx + 1)..] : trimmed; + } + + public string TypeBadge => Type switch + { + UrlType.YouTube => "YouTube", + UrlType.PyPyDance => "PyPyDance", + UrlType.VRDancing => "VRDancing", + UrlType.Hls => "HLS", + _ => "Other" + }; + + public IBrush TypeBadgeColor => Type switch + { + UrlType.YouTube => new SolidColorBrush(Color.Parse("#CC0000")), + UrlType.PyPyDance => new SolidColorBrush(Color.Parse("#4A90D9")), + UrlType.VRDancing => new SolidColorBrush(Color.Parse("#7B68EE")), + UrlType.Hls => new SolidColorBrush(Color.Parse("#2E8B57")), + _ => new SolidColorBrush(Color.Parse("#555555")) + }; + + public string? ThumbnailUrl => _thumbnailUrl; + + [ObservableProperty] + private bool _isCached; + + [ObservableProperty] + private bool _isInQueue; + + public HistoryItemViewModel(History history, VideoInfoCache? meta) + { + Timestamp = history.Timestamp.ToLocalTime(); + Url = history.Url; + Id = history.Id; + Type = history.Type; + _title = meta?.Title; + Author = meta?.Author; + UpdateStatus(); + } + + public void UpdateStatus() + { + if (Id == null) return; + + // Check if video is cached + var cachedAssets = CacheManager.GetCachedAssets(); + IsCached = cachedAssets.Keys.Any(k => Path.GetFileNameWithoutExtension(k) == Id); + + // Check if video is in download queue + var queue = VideoDownloader.GetQueueSnapshot(); + var current = VideoDownloader.GetCurrentDownload(); + var paused = VideoDownloader.GetPausedDownload(); + IsInQueue = queue.Any(q => q.VideoId == Id) + || current?.VideoId == Id + || paused?.VideoId == Id; + } + + public void SetMetadata(string? title, string? thumbnailUrl) + { + if (!string.IsNullOrEmpty(title)) + { + _title = title; + OnPropertyChanged(nameof(DisplayTitle)); + } + if (!string.IsNullOrEmpty(thumbnailUrl)) + { + _thumbnailUrl = thumbnailUrl; + OnPropertyChanged(nameof(ThumbnailUrl)); + } + } + + [ObservableProperty] + private bool _isSavingToCache; + + public bool CanSaveToCache => !IsCached && !IsInQueue && !IsSavingToCache; + + partial void OnIsCachedChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); + partial void OnIsInQueueChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); + partial void OnIsSavingToCacheChanged(bool value) => OnPropertyChanged(nameof(CanSaveToCache)); + + [RelayCommand] + private async Task SaveToCache() + { + if (string.IsNullOrEmpty(Url)) return; + + IsSavingToCache = true; + try + { + var videoInfo = await VideoId.GetVideoId(Url, true); + if (videoInfo != null) + { + VideoDownloader.QueueDownload(videoInfo); + UpdateStatus(); + } + } + catch (Exception ex) + { + Serilog.Log.Error(ex, "Failed to save {Url} to cache.", Url); + } + finally + { + IsSavingToCache = false; + } + } + + public async Task<(string? DisplayTitle, string? ThumbnailUrl)> LoadMetadataAsync() + { + if (Id != null) + { + // Load from DB + var videoInfo = await YouTubeMetadataService.GetVideoMetadataAsync(Id); + + if (!string.IsNullOrEmpty(videoInfo?.Title)) + { + _title = videoInfo.Title; + OnPropertyChanged(nameof(DisplayTitle)); + } + + // Load thumbnail + var thumbnailPath = ThumbnailManager.GetThumbnail(Id); + if (Id.Length == 11 && string.IsNullOrEmpty(thumbnailPath)) + thumbnailPath = await YouTubeMetadataService.GetThumbnail(Id); + + if (!string.IsNullOrEmpty(thumbnailPath)) + { + _thumbnailUrl = thumbnailPath; + OnPropertyChanged(nameof(ThumbnailUrl)); + } + } + + return (DisplayTitle, ThumbnailUrl); + } + + [RelayCommand] + // Url is a history entry, so it originated from a VRChat world. Handing that to + // ShellExecute unchecked would launch whatever scheme it happened to name; + // Utils.OpenUrl.Open allows only http and https. + private void OpenUrl() => Utils.OpenUrl.Open(Url); + + [RelayCommand] + private async Task CopyUrl() + { + if (Avalonia.Application.Current?.ApplicationLifetime is + Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + { + var clipboard = desktop.MainWindow?.Clipboard; + if (clipboard != null) + await clipboard.SetTextAsync(Url); + } + } +} + +public partial class HistoryViewModel : ViewModelBase +{ + [ObservableProperty] + private string _statusText = string.Empty; + + public ObservableCollection HistoryItems { get; } = []; + + public HistoryViewModel() + { + DatabaseManager.OnPlayHistoryAdded += () => Avalonia.Threading.Dispatcher.UIThread.Post(Refresh); + + // LoadMetadataAsync updates the cache, which fires this event — _isRefreshing guard prevents re-entry. + DatabaseManager.OnVideoInfoCacheUpdated += () => Avalonia.Threading.Dispatcher.UIThread.Post(Refresh); + + // Update status icons when queue or cache changes + VideoDownloader.OnQueueChanged += UpdateItemStatuses; + CacheManager.OnCacheChanged += (_, _) => UpdateItemStatuses(); + + Refresh(); + } + + private void UpdateItemStatuses() + { + Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => + { + foreach (var item in HistoryItems) + item.UpdateStatus(); + }); + } + + private bool _isRefreshing; + + [RelayCommand] + private void Refresh() + { + // Prevent infinite loop + if (_isRefreshing) + { + return; + } + _isRefreshing = true; + + var historyCache = DatabaseManager.GetVideoHistoryAsCache(distinctOnly: true); + + HistoryItems.Clear(); + foreach (var item in historyCache.OrderByDescending(h => h.Timestamp)) + { + HistoryItems.Add(item); + } + StatusText = string.Format(Localizer.Get("EntriesCountFormat"), HistoryItems.Count); + + _ = Task.Run(async () => + { + // Must always clear _isRefreshing — any unhandled exception here would otherwise + // wedge Refresh() permanently, making the history UI stop updating after a few videos. + try + { + foreach (var groupedItems in historyCache.GroupBy(h => h.Id)) + { + (string? DisplayTitle, string? ThumbnailUrl)? metadata = null; + foreach (var item in groupedItems) + { + try + { + if (metadata == null) + { + metadata = await item.LoadMetadataAsync(); + } + else + { + item.SetMetadata(metadata.Value.DisplayTitle, metadata.Value.ThumbnailUrl); + } + } + catch (Exception ex) + { + Serilog.Log.Warning(ex, "Failed to load metadata for history item {Id}", item.Id); + } + } + } + } + catch (Exception ex) + { + Serilog.Log.Error(ex, "History metadata refresh failed"); + } + finally + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => _isRefreshing = false); + } + }); + } +} diff --git a/VRCVideoCacher/ViewModels/LogViewerViewModel.cs b/VRCVideoCacher/ViewModels/LogViewerViewModel.cs index 015d17a6..fe3db50d 100644 --- a/VRCVideoCacher/ViewModels/LogViewerViewModel.cs +++ b/VRCVideoCacher/ViewModels/LogViewerViewModel.cs @@ -134,10 +134,8 @@ private async Task ExportLogs() var lines = LogEntries.Select(e => $"[{e.Timestamp:HH:mm:ss} {e.Level} {e.Source}] {e.Message}"); await File.WriteAllLinesAsync(logPath, lines); - // Open file location - if (OperatingSystem.IsWindows()) - { - System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{logPath}\""); - } + // Open file location. Went through explorer.exe directly and so did nothing at all + // on Linux, where the export silently appeared to do nothing. + VRCVideoCacher.Utils.OpenUrl.RevealFile(logPath); } } diff --git a/VRCVideoCacher/ViewModels/MainWindowViewModel.cs b/VRCVideoCacher/ViewModels/MainWindowViewModel.cs index 2f157261..5229ffb5 100755 --- a/VRCVideoCacher/ViewModels/MainWindowViewModel.cs +++ b/VRCVideoCacher/ViewModels/MainWindowViewModel.cs @@ -1,181 +1,227 @@ -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; -using Jeek.Avalonia.Localization; -using VRCVideoCacher.Models; -using VRCVideoCacher.Utils; - -namespace VRCVideoCacher.ViewModels; - -public partial class MainWindowViewModel : ViewModelBase -{ - [ObservableProperty] - private ViewModelBase _currentView; - - [ObservableProperty] - private string _statusText = Localizer.Get("ServerRunning"); - - [ObservableProperty] - private string _cacheStatusText = "Cache: 0 B"; - - [ObservableProperty] - private string _title = $"VRCVideoCacherPlus v{Program.Version}"; - - [ObservableProperty] - private bool _isUpdateAvailable; - - [ObservableProperty] - private bool _isUpdatePending; - - [ObservableProperty] - private string _updateVersionText = ""; - - [ObservableProperty] - private bool _isDnsFlushPromptVisible; - - private GitHubRelease? _pendingRelease; - - public DashboardViewModel Dashboard { get; } - public SettingsViewModel Settings { get; } - public CookiesViewModel Cookies { get; } - public CacheBrowserViewModel CacheBrowser { get; } - public DownloadQueueViewModel DownloadQueue { get; } - public LogViewerViewModel LogViewer { get; } - public HistoryViewModel History { get; } - public AboutViewModel About { get; } - - public MainWindowViewModel() - { - Dashboard = new DashboardViewModel(); - Settings = new SettingsViewModel(); - Cookies = new CookiesViewModel(); - CacheBrowser = new CacheBrowserViewModel(); - DownloadQueue = new DownloadQueueViewModel(); - LogViewer = new LogViewerViewModel(); - History = new HistoryViewModel(); - About = new AboutViewModel(); - - _currentView = Dashboard; - - // Subscribe to cache changes for status bar - CacheManager.OnCacheChanged += (_, _) => UpdateCacheStatus(); - UpdateCacheStatus(); - - // Refresh localized strings when language changes - Localizer.LanguageChanged += (_, _) => StatusText = Localizer.Get("ServerRunning"); - } - - private void UpdateCacheStatus() - { - var size = CacheManager.GetTotalCacheSize(); - var maxSize = ConfigManager.Config.CacheMaxSizeInGb; - - if (maxSize > 0) - { - var maxBytes = (long)(maxSize * 1024 * 1024 * 1024); - CacheStatusText = $"Cache: {FormatSize(size)} / {FormatSize(maxBytes)}"; - } - else - { - CacheStatusText = $"Cache: {FormatSize(size)}"; - } - } - - private static string FormatSize(long bytes) - { - string[] suffixes = ["B", "KB", "MB", "GB", "TB"]; - if (bytes == 0) return "0 B"; - var mag = Math.Min((int)Math.Log(bytes, 1024), suffixes.Length - 1); - var adjustedSize = bytes / Math.Pow(1024, mag); - return $"{adjustedSize:N2} {suffixes[mag]}"; - } - - [RelayCommand] - private void NavigateToDashboard() => CurrentView = Dashboard; - - [RelayCommand] - private void NavigateToSettings() => CurrentView = Settings; - - [RelayCommand] - private void NavigateToCacheBrowser() => CurrentView = CacheBrowser; - - [RelayCommand] - private void NavigateToDownloadQueue() => CurrentView = DownloadQueue; - - [RelayCommand] - private void NavigateToCookies() => CurrentView = Cookies; - - [RelayCommand] - private void NavigateToLogViewer() => CurrentView = LogViewer; - - [RelayCommand] - private void NavigateToHistory() => CurrentView = History; - - [RelayCommand] - public void NavigateToAbout() => CurrentView = About; - - public void ShowUpdate(UpdateInfo info) - { - _pendingRelease = info.Release; - UpdateVersionText = $"Version {info.Version} is available!"; - IsUpdateAvailable = true; - } - - [RelayCommand] - private async Task ApplyUpdate() - { - if (_pendingRelease == null) return; - IsUpdatePending = true; - UpdateVersionText = "Downloading update..."; - // ApplyUpdate exits the process on success, so the failure message only shows - // when the swap or download legitimately failed. - var ok = await Updater.ApplyUpdate(_pendingRelease); - if (!ok) - { - IsUpdatePending = false; - UpdateVersionText = "Update failed. Check logs and try again."; - } - } - - [RelayCommand] - private void DismissUpdate() - { - IsUpdateAvailable = false; - } - - [RelayCommand] - private void OpenReleasesPage() - { - var url = _pendingRelease?.html_url - ?? "https://github.com/codeyumx/VRCVideoCacherPlus/releases/latest"; - try - { - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo - { - FileName = url, - UseShellExecute = true - }); - } - catch { /* ignore — best effort */ } - } - - public void CheckDnsFailure() - { - if (VideoTools.HasDnsFailureFlag()) - IsDnsFlushPromptVisible = true; - } - - [RelayCommand] - private void FlushDns() - { - VideoTools.FlushSystemDnsCache(); - VideoTools.ClearDnsFailureFlag(); - IsDnsFlushPromptVisible = false; - } - - [RelayCommand] - private void DismissDnsPrompt() - { - VideoTools.ClearDnsFailureFlag(); - IsDnsFlushPromptVisible = false; - } -} +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Models; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.ViewModels; + +public partial class MainWindowViewModel : ViewModelBase, IDisposable +{ + [ObservableProperty] + private ViewModelBase _currentView; + + [ObservableProperty] + private string _statusText = Localizer.Get("ServerRunning"); + + [ObservableProperty] + private string _cacheStatusText = "Cache: 0 B"; + + [ObservableProperty] + private string _title = $"VRCVideoCacherPlus v{Program.Version}"; + + [ObservableProperty] + private bool _isUpdateAvailable; + + [ObservableProperty] + private bool _isUpdatePending; + + [ObservableProperty] + private string _updateVersionText = ""; + + [ObservableProperty] + private bool _isDnsFlushPromptVisible; + + private GitHubRelease? _pendingRelease; + + // Built on first navigation rather than up front. All nine used to be constructed in + // this constructor, on the UI thread, before the first frame was ever drawn — each one + // querying the database, scanning the cache directory or reading config. Only the + // dashboard is needed to show the window. + // + // The window binds CurrentView and picks the view by DataTemplate on type, so nothing + // in XAML touches these properties; only the navigation commands do. + private readonly Lazy _dashboard = new(() => new DashboardViewModel()); + private readonly Lazy _nowPlaying = new(() => new NowPlayingViewModel()); + private readonly Lazy _activeConnections = new(() => new ActiveConnectionsViewModel()); + private readonly Lazy _rules = new(() => new RulesViewModel()); + private readonly Lazy _settings = new(() => new SettingsViewModel()); + private readonly Lazy _cookies = new(() => new CookiesViewModel()); + private readonly Lazy _cacheBrowser = new(() => new CacheBrowserViewModel()); + private readonly Lazy _downloadQueue = new(() => new DownloadQueueViewModel()); + private readonly Lazy _logViewer = new(() => new LogViewerViewModel()); + private readonly Lazy _history = new(() => new HistoryViewModel()); + private readonly Lazy _about = new(() => new AboutViewModel()); + + public DashboardViewModel Dashboard => _dashboard.Value; + public NowPlayingViewModel NowPlaying => _nowPlaying.Value; + public ActiveConnectionsViewModel ActiveConnections => _activeConnections.Value; + public RulesViewModel Rules => _rules.Value; + public SettingsViewModel Settings => _settings.Value; + public CookiesViewModel Cookies => _cookies.Value; + public CacheBrowserViewModel CacheBrowser => _cacheBrowser.Value; + public DownloadQueueViewModel DownloadQueue => _downloadQueue.Value; + public LogViewerViewModel LogViewer => _logViewer.Value; + public HistoryViewModel History => _history.Value; + public AboutViewModel About => _about.Value; + + public MainWindowViewModel() + { + _currentView = Dashboard; + + // Subscribe to cache changes for status bar + CacheManager.OnCacheChanged += (_, _) => UpdateCacheStatus(); + UpdateCacheStatus(); + + // Refresh localized strings when language changes + Localizer.LanguageChanged += (_, _) => StatusText = Localizer.Get("ServerRunning"); + } + + private void UpdateCacheStatus() + { + var size = CacheManager.GetTotalCacheSize(); + var maxSize = ConfigManager.Config.CacheMaxSizeInGb; + + if (maxSize > 0) + { + var maxBytes = (long)(maxSize * 1024 * 1024 * 1024); + CacheStatusText = $"Cache: {FormatSize(size)} / {FormatSize(maxBytes)}"; + } + else + { + CacheStatusText = $"Cache: {FormatSize(size)}"; + } + } + + // Second copy of this lived here; CacheStats.FormatSize is the one covered by tests. + private static string FormatSize(long bytes) => Utils.CacheStats.FormatSize(bytes); + + private async Task NavigateToAsync(ViewModelBase targetView) + { + if (CurrentView == targetView) return; + + // Guard on IsValueCreated first: reading the Rules property would construct the + // view model purely to ask whether it has unsaved changes, which defeats the point + // of deferring it. + if (_rules.IsValueCreated && ReferenceEquals(CurrentView, _rules.Value) && _rules.Value.HasChanges) + { + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var parentWindow = lifetime?.MainWindow; + await _rules.Value.CheckUnsavedChangesAsync(parentWindow); + } + + CurrentView = targetView; + } + + [RelayCommand] + private async Task NavigateToDashboard() => await NavigateToAsync(Dashboard); + + [RelayCommand] + private async Task NavigateToNowPlaying() => await NavigateToAsync(NowPlaying); + + [RelayCommand] + private async Task NavigateToActiveConnections() => await NavigateToAsync(ActiveConnections); + + [RelayCommand] + private async Task NavigateToRules() => await NavigateToAsync(Rules); + + [RelayCommand] + private async Task NavigateToSettings() => await NavigateToAsync(Settings); + + [RelayCommand] + private async Task NavigateToCacheBrowser() => await NavigateToAsync(CacheBrowser); + + [RelayCommand] + private async Task NavigateToDownloadQueue() => await NavigateToAsync(DownloadQueue); + + [RelayCommand] + private async Task NavigateToCookies() => await NavigateToAsync(Cookies); + + [RelayCommand] + private async Task NavigateToLogViewer() => await NavigateToAsync(LogViewer); + + [RelayCommand] + private async Task NavigateToHistory() => await NavigateToAsync(History); + + [RelayCommand] + public async Task NavigateToAbout() => await NavigateToAsync(About); + + public void ShowUpdate(UpdateInfo info) + { + _pendingRelease = info.Release; + UpdateVersionText = string.Format(Localizer.Get("UpdateAvailable"), info.Version); + IsUpdateAvailable = true; + } + + [RelayCommand] + private async Task ApplyUpdate() + { + if (_pendingRelease == null) return; + IsUpdatePending = true; + UpdateVersionText = Localizer.Get("UpdateDownloading"); + // ApplyUpdate exits the process on success, so the failure message only shows + // when the swap or download legitimately failed. + var ok = await Updater.ApplyUpdate(_pendingRelease); + if (!ok) + { + IsUpdatePending = false; + UpdateVersionText = Localizer.Get("UpdateFailed"); + } + } + + [RelayCommand] + private void DismissUpdate() + { + IsUpdateAvailable = false; + } + + [RelayCommand] + private void OpenReleasesPage() + { + // Through OpenUrl rather than Process.Start: html_url comes from the GitHub API + // response, and OpenUrl is what enforces the http/https allowlist. Handing an + // arbitrary string to ShellExecute does not. + OpenUrl.Open(_pendingRelease?.html_url ?? Program.LatestReleaseUrl); + } + + /// + /// Disposes the tab view models that own background work. Several of them implement + /// IDisposable and start timers or polling loops in their constructors; nothing used to + /// call this, so those kept running for the life of the process once their tab had been + /// opened even once. + /// + public void Dispose() + { + DisposeIfCreated(_activeConnections); + DisposeIfCreated(_nowPlaying); + } + + private static void DisposeIfCreated(Lazy lazy) where T : class + { + if (lazy.IsValueCreated && lazy.Value is IDisposable disposable) + disposable.Dispose(); + } + + public void CheckDnsFailure() + { + if (VideoTools.HasDnsFailureFlag()) + IsDnsFlushPromptVisible = true; + } + + [RelayCommand] + private void FlushDns() + { + VideoTools.FlushSystemDnsCache(); + VideoTools.ClearDnsFailureFlag(); + IsDnsFlushPromptVisible = false; + } + + [RelayCommand] + private void DismissDnsPrompt() + { + VideoTools.ClearDnsFailureFlag(); + IsDnsFlushPromptVisible = false; + } +} diff --git a/VRCVideoCacher/ViewModels/NowPlayingViewModel.cs b/VRCVideoCacher/ViewModels/NowPlayingViewModel.cs new file mode 100644 index 00000000..19e7ac49 --- /dev/null +++ b/VRCVideoCacher/ViewModels/NowPlayingViewModel.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input.Platform; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using VRCVideoCacher.Utils; +using VRCVideoCacher.YTDL; + +namespace VRCVideoCacher.ViewModels; + +public partial class NowPlayingViewModel : ViewModelBase, IDisposable +{ + public ObservableCollection Sessions { get; } = []; + + [ObservableProperty] + private bool _hasActiveSessions; + + private readonly DispatcherTimer _timer; + + public NowPlayingViewModel() + { + // Setup timer to tick progress bars every 1 second + _timer = new DispatcherTimer + { + Interval = TimeSpan.FromSeconds(1) + }; + _timer.Tick += (s, e) => TickProgress(); + _timer.Start(); + + ActiveStreamTracker.OnSessionsChanged += OnSessionsChangedHandler; + RefreshSessions(); + } + + private void OnSessionsChangedHandler() + { + Dispatcher.UIThread.Post(RefreshSessions); + } + + private void RefreshSessions() + { + var rawSessions = ActiveStreamTracker.GetActiveSessions(); + + // 1. Remove old sessions + var toRemove = Sessions.Where(s => rawSessions.All(r => r.ResolvedUrl != s.ResolvedUrl && r.OriginalUrl != s.OriginalUrl)).ToList(); + foreach (var item in toRemove) + { + Sessions.Remove(item); + } + + // 2. Add or update sessions + foreach (var raw in rawSessions) + { + var existing = Sessions.FirstOrDefault(s => s.ResolvedUrl == raw.ResolvedUrl || s.OriginalUrl == raw.OriginalUrl); + if (existing == null) + { + Sessions.Add(new ActiveVideoSessionViewModel(raw)); + } + else + { + existing.TriggerRefresh(); + } + } + + HasActiveSessions = Sessions.Count > 0; + } + + private void TickProgress() + { + foreach (var session in Sessions) + { + session.TriggerRefresh(); + } + } + + [RelayCommand] + private async Task SeverStream(ActiveVideoSessionViewModel? item) + { + if (item == null) return; + + if (!string.IsNullOrEmpty(item.RemoteIp)) + await ConnectionSevering.SeverAddressAsync(item.RemoteIp, allowElevation: true); + + ActiveStreamTracker.RemoveSessionByUrl(item.ResolvedUrl); + } + + [RelayCommand] + private async Task CreateRule(ActiveVideoSessionViewModel? item) + { + if (item == null) return; + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + if (lifetime?.MainWindow?.DataContext is MainWindowViewModel mainVm) + { + await mainVm.NavigateToRulesCommand.ExecuteAsync(null); + await mainVm.Rules.AddRuleWithPattern(item.OriginalUrl); + } + } + + [RelayCommand] + private async Task CopyUrl(ActiveVideoSessionViewModel? item) + { + if (item == null) return; + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var clipboard = lifetime?.MainWindow?.Clipboard; + if (clipboard != null) + { + await clipboard.SetTextAsync(item.OriginalUrl); + } + } + + public void Dispose() + { + _timer.Stop(); + ActiveStreamTracker.OnSessionsChanged -= OnSessionsChangedHandler; + } +} + +public class ActiveVideoSessionViewModel : ViewModelBase +{ + private readonly ActiveVideoSession _session; + + public ActiveVideoSessionViewModel(ActiveVideoSession session) + { + _session = session; + } + + public string? VideoId => _session.VideoId; + public string Title => _session.Title; + public string OriginalUrl => _session.OriginalUrl; + public string ResolvedUrl => _session.ResolvedUrl; + public string? RemoteIp => _session.RemoteIp; + public string Status => _session.Status; + public double? Duration => _session.Duration; + public string? ThumbnailUrl => _session.ThumbnailUrl; + + public double CurrentPosition => _session.CurrentPosition; + + public double ProgressPercentage + { + get + { + if (Duration == null || Duration == 0) return 0; + return (CurrentPosition / Duration.Value) * 100; + } + } + + public string ProgressText + { + get + { + if (Duration == null || Duration == 0) + { + if (Status == "Playing") + { + var elapsed = _session.PlaybackStartedTime.HasValue + ? (DateTime.UtcNow - _session.PlaybackStartedTime.Value) + : TimeSpan.Zero; + return $"{elapsed:mm\\:ss} / Live"; + } + return "--:--"; + } + var current = TimeSpan.FromSeconds(CurrentPosition); + var total = TimeSpan.FromSeconds(Duration.Value); + return $"{current:mm\\:ss} / {total:mm\\:ss}"; + } + } + + public bool IsPlaying => Status == "Playing"; + public bool IsLoading => Status == "Loading"; + public bool IsFailed => Status == "Failed"; + + public string StatusColor => Status switch + { + "Playing" => "#81C784", // Green + "Loading" => "#FFD54F", // Yellow + "Failed" => "#E57373", // Red + _ => "#E0E0E0" // Gray + }; + + public void TriggerRefresh() + { + OnPropertyChanged(nameof(CurrentPosition)); + OnPropertyChanged(nameof(ProgressPercentage)); + OnPropertyChanged(nameof(ProgressText)); + OnPropertyChanged(nameof(Status)); + OnPropertyChanged(nameof(IsPlaying)); + OnPropertyChanged(nameof(IsLoading)); + OnPropertyChanged(nameof(IsFailed)); + OnPropertyChanged(nameof(StatusColor)); + } +} diff --git a/VRCVideoCacher/ViewModels/RulesViewModel.cs b/VRCVideoCacher/ViewModels/RulesViewModel.cs new file mode 100644 index 00000000..a7913f11 --- /dev/null +++ b/VRCVideoCacher/ViewModels/RulesViewModel.cs @@ -0,0 +1,460 @@ +using System.Collections.ObjectModel; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Jeek.Avalonia.Localization; +using VRCVideoCacher.Models; +using VRCVideoCacher.Views; + +namespace VRCVideoCacher.ViewModels; + +public partial class RuleEntryViewModel : ObservableObject +{ + public UriRule Rule { get; } + public Action? OnEnabledChanged; + + public string Name => Rule.Name; + public string Pattern => Rule.Pattern; + public RuleAction Action => Rule.Action; + public string ActionSummary => Rule.GetActionSummary(); + public string? Integration => Rule.Integration; + public string IntegrationDisplay => string.IsNullOrEmpty(Rule.Integration) ? string.Empty : "*"; + + [ObservableProperty] + private bool _isMatched; + + private double _flashOpacity = 0.0; + private CancellationTokenSource? _flashCts; + + public string RowBackground + { + get + { + if (IsMatched) + return "#1E4D2B"; + + if (_flashOpacity > 0.0) + { + int alpha = (int)(_flashOpacity * 255); + return $"#{alpha:X2}1DB954"; + } + + return "Transparent"; + } + } + + public void TriggerFlash() + { + _flashCts?.Cancel(); + _flashCts = new CancellationTokenSource(); + var token = _flashCts.Token; + + _flashOpacity = 1.0; + OnPropertyChanged(nameof(RowBackground)); + + Task.Run(async () => + { + const int totalSteps = 40; + const int stepDelayMs = 50; + + for (int i = 1; i <= totalSteps; i++) + { + if (token.IsCancellationRequested) + return; + + try + { + await Task.Delay(stepDelayMs, token); + } + catch (TaskCanceledException) + { + return; + } + + _flashOpacity = 1.0 - ((double)i / totalSteps); + + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + OnPropertyChanged(nameof(RowBackground)); + }); + } + + _flashOpacity = 0.0; + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + OnPropertyChanged(nameof(RowBackground)); + }); + }, token); + } + + partial void OnIsMatchedChanged(bool value) + { + OnPropertyChanged(nameof(RowBackground)); + } + + public bool Enabled + { + get => Rule.Enabled; + set + { + if (Rule.Enabled != value) + { + Rule.Enabled = value; + OnPropertyChanged(); + OnEnabledChanged?.Invoke(); + } + } + } + + public RuleEntryViewModel(UriRule rule) + { + Rule = rule; + } + + public void RefreshProperties() + { + OnPropertyChanged(nameof(Name)); + OnPropertyChanged(nameof(Pattern)); + OnPropertyChanged(nameof(Action)); + OnPropertyChanged(nameof(ActionSummary)); + OnPropertyChanged(nameof(Enabled)); + OnPropertyChanged(nameof(Integration)); + OnPropertyChanged(nameof(IntegrationDisplay)); + } +} + +public partial class RulesViewModel : ViewModelBase +{ + private bool _isLoading; + + public ObservableCollection Rules { get; } = []; + + [ObservableProperty] + private string _testUrl = string.Empty; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private string _statusMessageColor = "#81C784"; + + [ObservableProperty] + private bool _hasChanges; + + public RulesViewModel() + { + ConfigManager.OnConfigChanged += LoadFromConfig; + Services.RuleEngine.OnRuleMatched += HandleRuleMatched; + LoadFromConfig(); + } + + private void HandleRuleMatched(string ruleId) + { + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + var entry = Rules.FirstOrDefault(r => r.Rule.Id == ruleId); + entry?.TriggerFlash(); + }); + } + + private RuleEntryViewModel CreateEntry(UriRule rule) + { + var entry = new RuleEntryViewModel(rule); + entry.OnEnabledChanged += () => + { + if (_isLoading) return; + EvaluateTestUrl(); + SetHasChanges(); + }; + return entry; + } + + partial void OnTestUrlChanged(string value) + { + EvaluateTestUrl(); + } + + public void EvaluateTestUrl() + { + var url = TestUrl?.Trim(); + bool foundMatch = false; + + foreach (var entry in Rules) + { + if (!foundMatch && !string.IsNullOrWhiteSpace(url) && entry.Enabled && !string.IsNullOrWhiteSpace(entry.Pattern)) + { + try + { + // Shared cache with the request path, so typing in the test box doesn't + // recompile every rule on every keystroke — and so the live matcher + // uses exactly the regex options the real evaluation does. + if (Services.RuleEngine.GetRegex(entry.Pattern).IsMatch(url)) + { + entry.IsMatched = true; + foundMatch = true; + continue; + } + } + catch + { + // Invalid regex in rule + } + } + entry.IsMatched = false; + } + } + + public void LoadFromConfig() + { + _isLoading = true; + Rules.Clear(); + + var configRules = PlusConfigManager.Config.UriRules; + if (configRules == null || configRules.Count == 0) + { + PlusConfigManager.EnsureDefaultRules(); + configRules = PlusConfigManager.Config.UriRules; + } + + // Clone on the way in. The entries used to hold the very objects stored in + // PlusConfigManager.Config.UriRules, so editing a rule or flipping its checkbox + // mutated the live config immediately — RuleEngine picked the change up before the + // user pressed Save, and "Discard" re-read those same mutated objects and appeared + // to do nothing. Working on copies is what makes the unsaved-changes guard real. + foreach (var rule in configRules) + { + Rules.Add(CreateEntry(rule.Clone())); + } + + HasChanges = false; + StatusMessage = string.Empty; + _isLoading = false; + EvaluateTestUrl(); + } + + private void SetHasChanges() + { + if (_isLoading) return; + HasChanges = true; + StatusMessage = Localizer.Get("SettingsUnsavedChanges"); + StatusMessageColor = "#FFB74D"; + } + + public void SaveToConfig() + { + // Clone on the way out too, so the entries keep their own instances and the next + // edit doesn't reach straight back into the saved config. + PlusConfigManager.Config.UriRules = Rules.Select(r => r.Rule.Clone()).ToList(); + PlusConfigManager.TrySaveConfig(); + HasChanges = false; + StatusMessage = Localizer.Get("SettingsSaved"); + StatusMessageColor = "#81C784"; + EvaluateTestUrl(); + } + + public async Task CheckUnsavedChangesAsync(Window? parentWindow) + { + if (!HasChanges) return true; + + // With no window to parent the dialog on we cannot ask, and the old code fell + // through to dialog.Confirmed == false and discarded silently. Keep the edits + // pending in the view model instead — the user can still save them later. + if (parentWindow == null) + return true; + + var message = Localizer.Get("UnsavedRulesMessage"); + var dialog = Views.PopupWindow.CreateConfirm(message, Localizer.Get("Save"), Localizer.Get("Discard")); + await dialog.ShowDialog(parentWindow); + + if (dialog.Confirmed) + { + SaveToConfig(); + } + else + { + LoadFromConfig(); + } + return true; + } + + [RelayCommand] + private async Task AddRule() + { + var editVm = new EditRuleViewModel(null); + var window = new EditRuleWindow(editVm); + + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var parentWindow = lifetime?.MainWindow; + + var result = parentWindow != null + ? await window.ShowDialog(parentWindow) + : false; + + if (result) + { + var newEntry = CreateEntry(editVm.RuleResult); + Rules.Add(newEntry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + public async Task AddRuleWithPattern(string pattern) + { + var rule = new UriRule + { + Name = "New Rule", + Pattern = pattern, + Action = RuleAction.Block, + Enabled = true + }; + var editVm = new EditRuleViewModel(rule); + var window = new EditRuleWindow(editVm); + + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var parentWindow = lifetime?.MainWindow; + + var result = parentWindow != null + ? await window.ShowDialog(parentWindow) + : false; + + if (result) + { + var newEntry = CreateEntry(editVm.RuleResult); + Rules.Add(newEntry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private async Task EditRule(RuleEntryViewModel? entry) + { + if (entry == null) return; + + var editVm = new EditRuleViewModel(entry.Rule); + var window = new EditRuleWindow(editVm); + + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + var parentWindow = lifetime?.MainWindow; + + var result = parentWindow != null + ? await window.ShowDialog(parentWindow) + : false; + + if (result) + { + entry.Rule.Name = editVm.RuleResult.Name; + entry.Rule.Pattern = editVm.RuleResult.Pattern; + entry.Rule.Action = editVm.RuleResult.Action; + entry.Rule.Enabled = editVm.RuleResult.Enabled; + entry.Rule.Cache = editVm.RuleResult.Cache; + entry.Rule.MaxResolution = editVm.RuleResult.MaxResolution; + entry.Rule.MaxDurationMinutes = editVm.RuleResult.MaxDurationMinutes; + entry.Rule.RedirectTarget = editVm.RuleResult.RedirectTarget; + entry.Rule.Integration = editVm.RuleResult.Integration; + + entry.RefreshProperties(); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void MoveRuleUp(RuleEntryViewModel? entry) + { + if (entry == null) return; + var index = Rules.IndexOf(entry); + if (index > 0) + { + Rules.RemoveAt(index); + Rules.Insert(index - 1, entry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void MoveRuleDown(RuleEntryViewModel? entry) + { + if (entry == null) return; + var index = Rules.IndexOf(entry); + if (index >= 0 && index < Rules.Count - 1) + { + Rules.RemoveAt(index); + Rules.Insert(index + 1, entry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void MoveRuleToTop(RuleEntryViewModel? entry) + { + if (entry == null) return; + var index = Rules.IndexOf(entry); + if (index > 0) + { + Rules.RemoveAt(index); + Rules.Insert(0, entry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void MoveRuleToBottom(RuleEntryViewModel? entry) + { + if (entry == null) return; + var index = Rules.IndexOf(entry); + if (index >= 0 && index < Rules.Count - 1) + { + Rules.RemoveAt(index); + Rules.Add(entry); + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void DeleteRule(RuleEntryViewModel? entry) + { + if (entry == null) return; + Rules.Remove(entry); + EvaluateTestUrl(); + SetHasChanges(); + } + + [RelayCommand] + private async Task ResetDefaultRulesAsync(Window? parentWindow) + { + var message = Localizer.Get("ConfirmResetDefaultsMessage"); + var dialog = Views.PopupWindow.CreateConfirm(message, Localizer.Get("Yes"), Localizer.Get("No")); + + if (parentWindow != null) + { + await dialog.ShowDialog(parentWindow); + } + + if (dialog.Confirmed) + { + _isLoading = true; + Rules.Clear(); + foreach (var rule in ConfigModel.GetDefaultRules()) + { + Rules.Add(CreateEntry(rule)); + } + _isLoading = false; + EvaluateTestUrl(); + SetHasChanges(); + } + } + + [RelayCommand] + private void SaveRules() + { + SaveToConfig(); + } +} diff --git a/VRCVideoCacher/ViewModels/SettingsViewModel.cs b/VRCVideoCacher/ViewModels/SettingsViewModel.cs index 44e68cc9..53fba2c3 100755 --- a/VRCVideoCacher/ViewModels/SettingsViewModel.cs +++ b/VRCVideoCacher/ViewModels/SettingsViewModel.cs @@ -47,30 +47,15 @@ public partial class SettingsViewModel : ViewModelBase [ObservableProperty] private string _cachedAssetPath = string.Empty; - [ObservableProperty] - private bool _cacheYouTube; - - [ObservableProperty] - private int _cacheYouTubeMaxResolution; - [ObservableProperty] private bool _cacheYouTubePreferVp9; // Resolution options for the dropdown public int[] ResolutionOptions { get; } = [720, 1080, 1440, 2160]; - [ObservableProperty] - private int _cacheYouTubeMaxLength; - [ObservableProperty] private float _cacheMaxSizeInGb; - [ObservableProperty] - private bool _cachePyPyDance; - - [ObservableProperty] - private bool _cacheVRDancing; - [ObservableProperty] private bool _cacheHlsPlaylists; @@ -99,9 +84,6 @@ public partial class SettingsViewModel : ViewModelBase [ObservableProperty] private bool _patchVRC; - [ObservableProperty] - private bool _redirectVRDancing; - // Updates [ObservableProperty] @@ -114,16 +96,10 @@ public partial class SettingsViewModel : ViewModelBase [ObservableProperty] private bool _startMinimized; - // Blocked URLs - public ObservableCollection BlockedUrls { get; } = []; - // Video URLs pre-cached at startup (distinct from config.PreCacheUrls, which mirrors // JSON manifests of direct file downloads and has no UI). public ObservableCollection PreCacheVideos { get; } = []; - [ObservableProperty] - private string _blockRedirect = string.Empty; - // Status [ObservableProperty] private string _statusMessage = string.Empty; @@ -165,10 +141,10 @@ private static string GetLanguageDisplayName(string code) public SettingsViewModel() { - BlockedUrls.CollectionChanged += OnUrlCollectionChanged; PreCacheVideos.CollectionChanged += OnUrlCollectionChanged; + // One file, one event. This used to subscribe to both managers and so ran + // LoadFromConfig twice for every save. ConfigManager.OnConfigChanged += LoadFromConfig; - PlusConfigManager.OnConfigChanged += LoadFromConfig; LoadFromConfig(); } @@ -182,12 +158,7 @@ private void LoadFromConfig() YtdlAdditionalArgs = config.YtdlpAdditionalArgs; YtdlDubLanguage = config.YtdlpDubLanguage; CachedAssetPath = config.CachedAssetPath; - CacheYouTube = config.CacheYouTube; - CacheYouTubeMaxResolution = config.CacheYouTubeMaxResolution; - CacheYouTubeMaxLength = config.CacheYouTubeMaxLength; CacheMaxSizeInGb = config.CacheMaxSizeInGb; - CachePyPyDance = config.CachePyPyDance; - CacheVRDancing = config.CacheVrDancing; CacheHlsPlaylists = config.CacheHlsPlaylists; CacheHlsMaxLength = config.CacheHlsMaxLength; CacheOnly = config.CacheOnly; @@ -203,14 +174,7 @@ private void LoadFromConfig() StartMinimized = config.StartMinimized; StartWithSteamVr = config.StartWithSteamVr; ErrorPopups = config.ErrorPopups; - RedirectVRDancing = config.RedirectVRDancing; AutoUpdate = config.AutoUpdateVrcVideoCacher; - BlockedUrls.Clear(); - foreach (var url in config.BlockedUrls) - { - BlockedUrls.Add(new UrlEntry(url)); - } - BlockRedirect = config.BlockRedirect; PreCacheVideos.Clear(); foreach (var url in config.PreCacheVideos) @@ -273,13 +237,8 @@ private void OnUrlEntryPropertyChanged(object? sender, PropertyChangedEventArgs partial void OnYtdlAdditionalArgsChanged(string value) => SetHasChanges(); partial void OnYtdlDubLanguageChanged(string value) => SetHasChanges(); partial void OnCachedAssetPathChanged(string value) => SetHasChanges(); - partial void OnCacheYouTubeChanged(bool value) => SetHasChanges(); - partial void OnCacheYouTubeMaxResolutionChanged(int value) => SetHasChanges(); partial void OnCacheYouTubePreferVp9Changed(bool value) => SetHasChanges(); - partial void OnCacheYouTubeMaxLengthChanged(int value) => SetHasChanges(); partial void OnCacheMaxSizeInGbChanged(float value) => SetHasChanges(); - partial void OnCachePyPyDanceChanged(bool value) => SetHasChanges(); - partial void OnCacheVRDancingChanged(bool value) => SetHasChanges(); partial void OnCacheHlsPlaylistsChanged(bool value) => SetHasChanges(); partial void OnCacheHlsMaxLengthChanged(int value) => SetHasChanges(); partial void OnCacheOnlyChanged(bool value) => SetHasChanges(); @@ -291,17 +250,21 @@ private void OnUrlEntryPropertyChanged(object? sender, PropertyChangedEventArgs partial void OnPatchVRCChanged(bool value) => SetHasChanges(); partial void OnCloseToTrayChanged(bool value) => SetHasChanges(); partial void OnStartMinimizedChanged(bool value) => SetHasChanges(); - partial void OnRedirectVRDancingChanged(bool value) => SetHasChanges(); partial void OnAutoUpdateChanged(bool value) => SetHasChanges(); partial void OnStartWithSteamVrChanged(bool value) => SetHasChanges(); partial void OnErrorPopupsChanged(bool value) => SetHasChanges(); - partial void OnBlockRedirectChanged(string value) => SetHasChanges(); [RelayCommand] private void SaveSettings() { var config = ConfigManager.Config; + // CacheManager resolves its path once at type initialisation and the web server + // serves that directory, so this one genuinely cannot be applied live — say so + // rather than appearing to have taken effect. + var cachePathChanged = config.CachedAssetPath != CachedAssetPath; + var patchSettingsChanged = config.PatchVrChat != PatchVRC || config.PatchResonite != PatchResonite; + if (config.YtdlpWebServerUrl != WebServerUrl) { config.YtdlpWebServerUrl = WebServerUrl; @@ -312,12 +275,7 @@ private void SaveSettings() config.YtdlpAdditionalArgs = YtdlAdditionalArgs; config.YtdlpDubLanguage = YtdlDubLanguage; config.CachedAssetPath = CachedAssetPath; - config.CacheYouTube = CacheYouTube; - config.CacheYouTubeMaxResolution = CacheYouTubeMaxResolution; - config.CacheYouTubeMaxLength = CacheYouTubeMaxLength; config.CacheMaxSizeInGb = CacheMaxSizeInGb; - config.CachePyPyDance = CachePyPyDance; - config.CacheVrDancing = CacheVRDancing; config.CacheHlsPlaylists = CacheHlsPlaylists; config.CacheHlsMaxLength = CacheHlsMaxLength; config.CacheOnly = CacheOnly; @@ -331,10 +289,6 @@ private void SaveSettings() config.StartMinimized = StartMinimized; config.StartWithSteamVr = StartWithSteamVr; config.ErrorPopups = ErrorPopups; - config.BlockedUrls = BlockedUrls - .Select(item => item.Url) - .ToArray(); - config.BlockRedirect = BlockRedirect; // One row may hold a whole pasted list; split it so each URL gets its own row. config.PreCacheVideos = VideoPreCache.SplitUrls(PreCacheVideos.Select(item => item.Url)); if (!config.PreCacheVideos.SequenceEqual(PreCacheVideos.Select(item => item.Url))) @@ -343,26 +297,29 @@ private void SaveSettings() foreach (var url in config.PreCacheVideos) PreCacheVideos.Add(new UrlEntry(url)); } - config.RedirectVRDancing = RedirectVRDancing; config.AutoUpdateVrcVideoCacher = AutoUpdate; // Temporarily unhook config-changed events to avoid redundant LoadFromConfig calls during save ConfigManager.OnConfigChanged -= LoadFromConfig; - PlusConfigManager.OnConfigChanged -= LoadFromConfig; try { ConfigManager.TrySaveConfig(); - PlusConfigManager.TrySaveConfig(); } finally { ConfigManager.OnConfigChanged += LoadFromConfig; - PlusConfigManager.OnConfigChanged += LoadFromConfig; } + // Patch toggles are applied straight away; they used to sit inert until the next + // launch, with nothing saying so. + if (patchSettingsChanged) + FileTools.ApplyPatchSettings(); + HasChanges = false; - StatusMessage = Localizer.Get("SettingsSaved"); - StatusMessageColor = "#81C784"; + StatusMessage = cachePathChanged + ? Localizer.Get("SettingsSavedRestartRequired") + : Localizer.Get("SettingsSaved"); + StatusMessageColor = cachePathChanged ? "#FFB74D" : "#81C784"; } [RelayCommand] @@ -373,18 +330,6 @@ private void ResetToDefaults() StatusMessageColor = "#81C784"; } - [RelayCommand] - private void AddBlockedUrl() - { - BlockedUrls.Add(new UrlEntry("https://")); - } - - [RelayCommand] - private void RemoveBlockedUrl(UrlEntry url) - { - BlockedUrls.Remove(url); - } - [RelayCommand] private void AddPreCacheVideo() { @@ -398,13 +343,10 @@ private void RemovePreCacheVideo(UrlEntry url) } [RelayCommand] - private void OpenUtilsFolder() - { - if (OperatingSystem.IsWindows()) - System.Diagnostics.Process.Start("explorer.exe", Program.UtilsPath); - else if (OperatingSystem.IsLinux()) - System.Diagnostics.Process.Start("xdg-open", Program.UtilsPath); - } + private void OpenUtilsFolder() => OpenUrl.OpenFolder(Program.UtilsPath); + + [RelayCommand] + private void OpenSettingsFolder() => OpenUrl.OpenFolder(Program.DataPath); [ObservableProperty] private bool _isRedownloading; diff --git a/VRCVideoCacher/Views/AboutView.axaml b/VRCVideoCacher/Views/AboutView.axaml index 15665cc8..b27bf6b0 100755 --- a/VRCVideoCacher/Views/AboutView.axaml +++ b/VRCVideoCacher/Views/AboutView.axaml @@ -4,6 +4,7 @@ xmlns:l="using:Jeek.Avalonia.Localization" xmlns:vm="clr-namespace:VRCVideoCacher.ViewModels" xmlns:views="clr-namespace:VRCVideoCacher.Views" + xmlns:controls="clr-namespace:VRCVideoCacher.Controls" x:Class="VRCVideoCacher.Views.AboutView" x:DataType="vm:AboutViewModel"> diff --git a/VRCVideoCacher/Views/AboutView.axaml.cs b/VRCVideoCacher/Views/AboutView.axaml.cs index ad3605ce..95edee0c 100644 --- a/VRCVideoCacher/Views/AboutView.axaml.cs +++ b/VRCVideoCacher/Views/AboutView.axaml.cs @@ -5,7 +5,7 @@ namespace VRCVideoCacher.Views; public partial class AboutView : UserControl { - private const string GithubUrl = "https://github.com/codeyumx/VRCVideoCacherPlus"; + private const string GithubUrl = Program.RepoUrl; private const string DiscordUrl = "https://discord.gg/z5kVNkmQuS"; private const string SteamUrl = "https://store.steampowered.com/app/4296960/"; diff --git a/VRCVideoCacher/Views/ActiveConnectionsView.axaml b/VRCVideoCacher/Views/ActiveConnectionsView.axaml new file mode 100644 index 00000000..3ce63a33 --- /dev/null +++ b/VRCVideoCacher/Views/ActiveConnectionsView.axaml @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VRCVideoCacher/Views/ActiveConnectionsView.axaml.cs b/VRCVideoCacher/Views/ActiveConnectionsView.axaml.cs new file mode 100644 index 00000000..ed1bd966 --- /dev/null +++ b/VRCVideoCacher/Views/ActiveConnectionsView.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace VRCVideoCacher.Views; + +public partial class ActiveConnectionsView : UserControl +{ + public ActiveConnectionsView() + { + InitializeComponent(); + } +} diff --git a/VRCVideoCacher/Views/CacheBrowserView.axaml b/VRCVideoCacher/Views/CacheBrowserView.axaml index 690fa8fa..565f8753 100644 --- a/VRCVideoCacher/Views/CacheBrowserView.axaml +++ b/VRCVideoCacher/Views/CacheBrowserView.axaml @@ -68,6 +68,9 @@ + + + + @@ -83,6 +126,49 @@ FontSize="20" FontWeight="Bold" Margin="0,10,0,0"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VRCVideoCacher/Views/DownloadQueueView.axaml b/VRCVideoCacher/Views/DownloadQueueView.axaml index f5ce095b..8d10e30a 100644 --- a/VRCVideoCacher/Views/DownloadQueueView.axaml +++ b/VRCVideoCacher/Views/DownloadQueueView.axaml @@ -48,6 +48,18 @@ IsVisible="{Binding IsDownloading}" Foreground="#1a73e8" Background="#444"/> + + + + + + diff --git a/VRCVideoCacher/Views/EditRuleWindow.axaml b/VRCVideoCacher/Views/EditRuleWindow.axaml new file mode 100644 index 00000000..ee6ea5e2 --- /dev/null +++ b/VRCVideoCacher/Views/EditRuleWindow.axaml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VRCVideoCacher/Views/NowPlayingView.axaml.cs b/VRCVideoCacher/Views/NowPlayingView.axaml.cs new file mode 100644 index 00000000..02f01363 --- /dev/null +++ b/VRCVideoCacher/Views/NowPlayingView.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace VRCVideoCacher.Views; + +public partial class NowPlayingView : UserControl +{ + public NowPlayingView() + { + InitializeComponent(); + } +} diff --git a/VRCVideoCacher/Views/PopupWindow.axaml.cs b/VRCVideoCacher/Views/PopupWindow.axaml.cs index 6a54477b..406be471 100644 --- a/VRCVideoCacher/Views/PopupWindow.axaml.cs +++ b/VRCVideoCacher/Views/PopupWindow.axaml.cs @@ -41,10 +41,7 @@ public static PopupWindow CreateConfirm(string message, string confirmLabel = "Y private void FolderPathButton_Click(object? sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(_folderPath)) return; - if (OperatingSystem.IsWindows()) - System.Diagnostics.Process.Start("explorer.exe", _folderPath); - else if (OperatingSystem.IsLinux()) - System.Diagnostics.Process.Start("xdg-open", _folderPath); + Utils.OpenUrl.OpenFolder(_folderPath); } private void OkButton_Click(object? sender, RoutedEventArgs e) diff --git a/VRCVideoCacher/Views/RulesView.axaml b/VRCVideoCacher/Views/RulesView.axaml new file mode 100644 index 00000000..62b96aa7 --- /dev/null +++ b/VRCVideoCacher/Views/RulesView.axaml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/VRCVideoCacher/Views/RulesView.axaml.cs b/VRCVideoCacher/Views/RulesView.axaml.cs new file mode 100644 index 00000000..bc1a7968 --- /dev/null +++ b/VRCVideoCacher/Views/RulesView.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace VRCVideoCacher.Views; + +public partial class RulesView : UserControl +{ + public RulesView() + { + InitializeComponent(); + } +} diff --git a/VRCVideoCacher/Views/SettingsView.axaml b/VRCVideoCacher/Views/SettingsView.axaml index 5fc0c21f..bd344d09 100755 --- a/VRCVideoCacher/Views/SettingsView.axaml +++ b/VRCVideoCacher/Views/SettingsView.axaml @@ -8,7 +8,7 @@ - + @@ -16,14 +16,21 @@ IsVisible="{Binding StatusMessage, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" Foreground="{Binding StatusMessageColor}"/> - + + - - - - - - - - - - - - - - - - - - - diff --git a/VRCVideoCacher/YTDL/ActiveStreamTracker.cs b/VRCVideoCacher/YTDL/ActiveStreamTracker.cs index 772fed7d..eef553c8 100644 --- a/VRCVideoCacher/YTDL/ActiveStreamTracker.cs +++ b/VRCVideoCacher/YTDL/ActiveStreamTracker.cs @@ -1,3 +1,9 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; + namespace VRCVideoCacher.YTDL; /// @@ -15,12 +21,19 @@ public static class ActiveStreamTracker private static readonly object Lock = new(); + private static readonly HashSet _activeVideoIps = new(); + private static readonly object IpsLock = new(); + /// - /// Tracks the expected end time of each active stream by video ID. - /// If no duration is known, the entry stores just the start time - /// and the idle buffer alone governs the delay. + /// When the stream currently being served is expected to finish. If no duration is + /// known this is just the time it started, and the idle buffer alone governs the delay. + /// + /// This was a dictionary keyed by video id, but RecordActivity cleared it on every call + /// — a new stream means the user moved on — so it never held more than one entry, and + /// the "latest end across all active streams" scan in IsIdle could only ever see that + /// one. A single field says the same thing without implying otherwise. /// - private static readonly Dictionary _expectedEndTimes = new(); + private static DateTime _expectedEndOfCurrentStream = DateTime.MinValue; /// /// Fallback: the last time any activity was recorded, used when @@ -45,15 +58,11 @@ public static void RecordActivity(string? videoId = null, double? durationSecond if (!string.IsNullOrEmpty(videoId)) { - // A new stream means the user moved on — clear previous entries - // so skipped videos don't stack their durations. - _expectedEndTimes.Clear(); - - var expectedEnd = durationSeconds > 0 + // A new stream replaces the previous one rather than stacking with it, so a + // run of skipped videos doesn't accumulate their durations. + _expectedEndOfCurrentStream = durationSeconds > 0 ? DateTime.UtcNow.AddSeconds(durationSeconds.Value) : DateTime.UtcNow; - - _expectedEndTimes[videoId] = expectedEnd; } } Task.Run(() => OnStreamingActivity?.Invoke()); @@ -70,18 +79,245 @@ public static bool IsIdle(int idleSeconds) { if (!_hasActivity) return true; - var now = DateTime.UtcNow; + // Idle = past the current video's expected end, plus the buffer. Falls back to + // the last activity timestamp when that is later, or when no duration is known. + var latestEnd = _expectedEndOfCurrentStream > _lastActivityAt + ? _expectedEndOfCurrentStream + : _lastActivityAt; + + return (DateTime.UtcNow - latestEnd).TotalSeconds >= idleSeconds; + } + } + + private static void TrackVideoUrl(string url) + { + if (string.IsNullOrEmpty(url)) return; + + // Skip local server URLs since localhost/127.0.0.1 on port 9696 is always safely severed + if (url.Contains("localhost") || url.Contains("127.0.0.1")) return; - // Find the latest expected end time across all active streams - var latestEnd = _lastActivityAt; - foreach (var endTime in _expectedEndTimes.Values) + Task.Run(async () => + { + try + { + if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + var host = uri.Host; + if (!string.IsNullOrEmpty(host)) + { + var addresses = await Dns.GetHostAddressesAsync(host); + lock (IpsLock) + { + foreach (var addr in addresses) + { + _activeVideoIps.Add(addr.ToString()); + } + } + } + } + } + catch (Exception ex) { - if (endTime > latestEnd) - latestEnd = endTime; + Serilog.Log.Debug(ex, "Failed to resolve active stream IP for URL: {Url}", url); } + }); + } + + public static HashSet GetActiveVideoIps() + { + lock (IpsLock) + { + return new HashSet(_activeVideoIps); + } + } + + public static void ClearActiveVideoIps() + { + lock (IpsLock) + { + _activeVideoIps.Clear(); + } + } + + private static readonly List _activeSessions = new(); + private static readonly object SessionsLock = new(); + + private static readonly Dictionary _urlInfoMap = new(); + private static readonly object MapLock = new(); + + public static event Action? OnSessionsChanged; + + public static void AssociateUrlInfo(string resolvedUrl, string originalUrl, string title, string? videoId, double? duration) + { + lock (MapLock) + { + var info = (title, originalUrl, videoId, duration); + if (!string.IsNullOrEmpty(resolvedUrl)) + _urlInfoMap[resolvedUrl] = info; + if (!string.IsNullOrEmpty(originalUrl)) + _urlInfoMap[originalUrl] = info; + } + + TrackVideoUrl(resolvedUrl); + TrackVideoUrl(originalUrl); - // Idle = we're past the longest video's expected end + the buffer - return (now - latestEnd).TotalSeconds >= idleSeconds; + lock (SessionsLock) + { + var updated = false; + foreach (var session in _activeSessions) + { + if ((!string.IsNullOrEmpty(videoId) && session.VideoId == videoId) || + (!string.IsNullOrEmpty(originalUrl) && session.OriginalUrl == originalUrl) || + (!string.IsNullOrEmpty(resolvedUrl) && session.ResolvedUrl == resolvedUrl)) + { + if (!string.IsNullOrEmpty(title) && (session.Title == session.OriginalUrl || session.Title == session.ResolvedUrl || string.IsNullOrEmpty(session.Title))) + { + session.Title = title; + updated = true; + } + if (duration.HasValue && !session.Duration.HasValue) + { + session.Duration = duration; + updated = true; + } + if (!string.IsNullOrEmpty(videoId) && string.IsNullOrEmpty(session.VideoId)) + { + session.VideoId = videoId; + updated = true; + } + } + } + if (updated) + { + OnSessionsChanged?.Invoke(); + } } } + + public static bool TryGetUrlInfo(string url, out (string Title, string OriginalUrl, string? VideoId, double? Duration) info) + { + lock (MapLock) + { + if (_urlInfoMap.TryGetValue(url, out info)) + return true; + + foreach (var kv in _urlInfoMap) + { + if (url.Contains(kv.Key) || kv.Key.Contains(url)) + { + info = kv.Value; + return true; + } + } + return false; + } + } + + public static void AddOrUpdateSession(ActiveVideoSession session) + { + lock (SessionsLock) + { + var existing = _activeSessions.FirstOrDefault(s => s.ResolvedUrl == session.ResolvedUrl || s.OriginalUrl == session.OriginalUrl); + if (existing != null) + { + existing.Title = session.Title; + existing.VideoId = session.VideoId; + existing.OriginalUrl = session.OriginalUrl; + existing.ResolvedUrl = session.ResolvedUrl; + existing.RemoteIp = session.RemoteIp; + existing.Status = session.Status; + existing.StartTime = session.StartTime; + existing.PlaybackStartedTime = session.PlaybackStartedTime; + existing.Duration = session.Duration; + } + else + { + _activeSessions.Add(session); + } + } + OnSessionsChanged?.Invoke(); + } + + public static void UpdateSessionStatus(string url, string status, DateTime? playbackStartedTime = null) + { + lock (SessionsLock) + { + var existing = _activeSessions.FirstOrDefault(s => s.ResolvedUrl == url || s.OriginalUrl == url); + if (existing == null && status == "Playing") + { + existing = _activeSessions.LastOrDefault(s => s.Status == "Loading"); + } + + if (existing != null) + { + existing.Status = status; + if (playbackStartedTime.HasValue) + { + existing.PlaybackStartedTime = playbackStartedTime.Value; + } + else if (status == "Playing") + { + existing.PlaybackStartedTime = DateTime.UtcNow; + } + } + } + OnSessionsChanged?.Invoke(); + } + + public static void RemoveSessionByUrl(string url) + { + lock (SessionsLock) + { + _activeSessions.RemoveAll(s => s.ResolvedUrl == url || s.OriginalUrl == url); + } + OnSessionsChanged?.Invoke(); + } + + public static void ClearAllSessions() + { + lock (SessionsLock) + { + _activeSessions.Clear(); + } + OnSessionsChanged?.Invoke(); + } + + public static List GetActiveSessions() + { + lock (SessionsLock) + { + var now = DateTime.UtcNow; + _activeSessions.RemoveAll(s => + { + if (s.Duration.HasValue && s.PlaybackStartedTime.HasValue) + { + var elapsed = (now - s.PlaybackStartedTime.Value).TotalSeconds; + return elapsed > s.Duration.Value + 10; + } + return false; + }); + return new List(_activeSessions); + } + } +} + +public class ActiveVideoSession +{ + public string? VideoId { get; set; } + public string Title { get; set; } = string.Empty; + public string OriginalUrl { get; set; } = string.Empty; + public string ResolvedUrl { get; set; } = string.Empty; + public string? RemoteIp { get; set; } + public string Status { get; set; } = string.Empty; // "Loading", "Playing", "Failed" + public DateTime StartTime { get; set; } + public DateTime? PlaybackStartedTime { get; set; } + public double? Duration { get; set; } // in seconds + + public string? ThumbnailUrl => string.IsNullOrEmpty(VideoId) || VideoId == "live" + ? null + : $"https://img.youtube.com/vi/{VideoId}/mqdefault.jpg"; + + public double CurrentPosition => Status == "Playing" && PlaybackStartedTime.HasValue + ? Math.Min(Duration ?? double.MaxValue, (DateTime.UtcNow - PlaybackStartedTime.Value).TotalSeconds) + : 0; } diff --git a/VRCVideoCacher/YTDL/SiteHandlers/ISiteHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/ISiteHandler.cs deleted file mode 100644 index 65dee8a6..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/ISiteHandler.cs +++ /dev/null @@ -1,15 +0,0 @@ -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL; - -public interface ISiteHandler -{ - // RewriteUrl runs before CanHandle for resolver type handlers. - // Direct handlers just implement CanHandle + GetVideoInfo - - bool CanHandle(Uri uri); - Task GetVideoInfo(string url, Uri uri, bool avPro); - List GetYtdlpArguments(Uri uri, bool avPro) => []; - Task RewriteUrl(string url, Uri uri) => Task.FromResult(url); - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/SiteHandlers/SiteHandlerRegistry.cs b/VRCVideoCacher/YTDL/SiteHandlers/SiteHandlerRegistry.cs deleted file mode 100644 index 873ec63e..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/SiteHandlerRegistry.cs +++ /dev/null @@ -1,72 +0,0 @@ -using VRCVideoCacher.YTDL.SiteHandlers.Sites; - -namespace VRCVideoCacher.YTDL.SiteHandlers; - -public static class SiteHandlerRegistry -{ - private static readonly List Handlers = - [ - new YouTubeHandler(), - new PyPyDanceHandler(), - new VRDancingHandler(), - new HlsHandler(), - // fallthrough last - new GenericHandler(), - ]; - - // Rewriters run first, in order, before handler resolution - private static readonly List Rewriters = - [ - new NicoVideoHandler(), // rewrites nico.ms → nicovideo.life - new YTSHandler(), // rewrites /sr/ → /yt/ - new ThirdPartyYTResolver(), // dmn.moe, u2b.cx etc → real YT url - new HlsHandler(), // Dropbox ?dl=0 → ?dl=1, GDrive /file/d//view → /uc?... - ]; - - public static async Task ApplyRewrites(string url) - { - foreach (var rewriter in Rewriters) - { - var uri = VideoId.ToUri(url); - if (uri == null) return url; - url = await rewriter.RewriteUrl(url, uri); - } - return url; - } - - public static ISiteHandler? Resolve(Uri uri) => Handlers.FirstOrDefault(h => h.CanHandle(uri)); - - /// - /// Like , but when only the GenericHandler would match, - /// performs an async content probe to detect HLS manifests served under - /// arbitrary URLs (no .m3u8 extension, unknown hosts). - /// - public static async Task ResolveAsync(string url, Uri uri) - { - var handler = Handlers.FirstOrDefault(h => h.CanHandle(uri)); - if (handler is not null and not GenericHandler) - return handler; - - // Skip the network probe for URLs that clearly aren't HLS (plain .mp4, images, etc.). - if (HlsHandler.LooksObviouslyNotHls(uri)) - return handler; - - // Skip the probe entirely when HLS caching is off — detection is only worth the - // up-to-5s GET if we're actually going to do something special with the URL. - // The flag is checked per-call (not memoized), so flipping it on takes effect on - // the next play of any URL that wasn't probed while it was off. - if (!ConfigManager.Config.CacheHlsPlaylists) - return handler; - - // LooksLikeStreamable returns true for HLS manifests AND raw progressive MPEG-TS - // streams — both are routed through HlsHandler, which surfaces the distinction - // via TryGetCachedProbe so cache-gating can apply the right rule. - if (await HlsHandler.LooksLikeStreamable(url)) - return Handlers.OfType().First(); - - return handler; // GenericHandler or null - } - - public static bool HasSpecificHandler(Uri uri) => - Handlers.Any(h => h is not GenericHandler && h.CanHandle(uri)); -} diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/GenericHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/GenericHandler.cs deleted file mode 100644 index 3c67fbc0..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/GenericHandler.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Serilog; -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class GenericHandler : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - - public bool CanHandle(Uri uri) => true; // always matches, must be last in registry - - public Task GetVideoInfo(string url, Uri uri, bool avPro) - { - var videoId = VideoId.HashUrl(url); - Log.Information("No specific handler found for URL, using generic handler: {URL}", url); - return Task.FromResult(new VideoInfo - { - VideoUrl = url, - VideoId = videoId, - UrlType = UrlType.Other, - DownloadFormat = DownloadFormat.MP4 - }); - } - - public List GetYtdlpArguments(Uri uri, bool avPro) => []; - - public Task RewriteUrl(string url, Uri uri) => Task.FromResult(url); - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/NicoVideoHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/NicoVideoHandler.cs deleted file mode 100644 index b24b1c56..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/NicoVideoHandler.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Text.RegularExpressions; -using Serilog; -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class NicoVideoHandler : ISiteHandler -{ - - private static readonly ILogger Log = Program.Logger.ForContext(); - - // Matches full nicovideo/niconico URLs - private static readonly Regex NicoID1 = new(@"^(https?)://(live|www)\.nicovideo\.jp/watch/(.+)$", RegexOptions.Compiled); - private static readonly Regex NicoID2 = new(@"^(https?)://nico\.ms/(.+)$", RegexOptions.Compiled); - - public bool CanHandle(Uri uri) => false; // rewrite only, GenericHandler picks up after - - public Task GetVideoInfo(string url, Uri uri, bool avPro) => Task.FromResult(null); - - public Task RewriteUrl(string url, Uri uri) - { - if (!uri.Host.EndsWith("nicovideo.jp") && !uri.Host.EndsWith("nico.ms")) - return Task.FromResult(url); - - var (m, group) = new[] - { - (NicoID1.Match(url), 3), - (NicoID2.Match(url), 2), - }.FirstOrDefault(x => x.Item1.Success); - - if (m?.Success != true) - return Task.FromResult(url); - - var newUrl = $"https://www.nicovideo.life/watch/{m.Groups[group].Value}"; - Log.Information("Incompatible URL, passing to external resolver: {URL}", newUrl); - return Task.FromResult(newUrl); - } - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/PyPyDanceHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/PyPyDanceHandler.cs deleted file mode 100644 index 633b32b0..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/PyPyDanceHandler.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Web; -using Serilog; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; -using VRCVideoCacher.Utils; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class PyPyDanceHandler : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - private static readonly string[] Prefixes = ["http://api.pypy.dance/video", "https://api.pypy.dance/video"]; - - public bool CanHandle(Uri uri) => Prefixes.Any(p => uri.ToString().StartsWith(p)); - - public async Task GetVideoInfo(string url, Uri uri, bool avPro) - { - try - { - using var request = new HttpRequestMessage(HttpMethod.Head, url); - using var result = await HttpUtil.HttpClient.SendAsync(request); - var videoUrl = result.RequestMessage?.RequestUri?.ToString(); - if (string.IsNullOrEmpty(videoUrl)) - { - Log.Error("Failed to get video ID from PypyDance URL: {URL} Response: {Response} - {Data}", url, result.StatusCode, await result.Content.ReadAsStringAsync()); - return null; - } - - var finalUri = new Uri(videoUrl); - var fileName = Path.GetFileName(finalUri.LocalPath); - var videoId = !fileName.Contains('.') ? fileName : fileName.Split('.')[0]; - - var query = HttpUtility.ParseQueryString(uri.Query); - var success = int.TryParse(query.Get("id"), out var idInt); - if (!success) - { - Log.Error("Failed to get video ID from PypyDance URL: {URL}", url); - return null; - } - - _ = Task.Run(async () => await PyPyDanceApiService.DownloadMetadata(idInt, videoId)); - - return new VideoInfo - { - VideoUrl = videoUrl, - VideoId = videoId, - UrlType = UrlType.PyPyDance, - DownloadFormat = DownloadFormat.MP4 - }; - } - catch - { - Log.Error("Failed to get video ID from PypyDance URL: {URL}", url); - return null; - } - } - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/ThirdPartyYTResolver.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/ThirdPartyYTResolver.cs deleted file mode 100644 index 7ec8d51a..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/ThirdPartyYTResolver.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Serilog; -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class ThirdPartyYTResolver : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - - // AllowAutoRedirect=false so we can check each hop and stop as soon as - // the destination is a URL a specific handler recognises - private static readonly HttpClient NoAutoRedirectClient = new(new HttpClientHandler { AllowAutoRedirect = false }) - { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } } - }; - - public bool CanHandle(Uri uri) => false; // rewrite only - - public Task GetVideoInfo(string url, Uri uri, bool avPro) => Task.FromResult(null); - - public async Task RewriteUrl(string url, Uri uri) - { - if (SiteHandlerRegistry.HasSpecificHandler(uri)) - return url; - - const int maxHops = 5; - var current = url; - - try - { - for (var i = 0; i < maxHops; i++) - { - using var req = new HttpRequestMessage(HttpMethod.Head, current); - using var res = await NoAutoRedirectClient.SendAsync(req); - - var location = res.Headers.Location; - if (location == null) - break; - - // Resolve relative redirects against the current URL - var next = location.IsAbsoluteUri ? location.ToString() : new Uri(new Uri(current), location).ToString(); - - if (!Uri.TryCreate(next, UriKind.Absolute, out var nextUri)) - break; - - // Stop as soon as the redirect target has a specific handler - if (SiteHandlerRegistry.HasSpecificHandler(nextUri)) - { - Log.Information("Resolved redirect: {URL} -> {Resolved}", url, next); - return next; - } - - current = next; - - var status = (int)res.StatusCode; - if (status is < 300 or >= 400) - break; - } - } - catch (HttpRequestException ex) - { - Log.Warning(ex, "Failed to follow redirects for {URL}, returning original", url); - return url; - } - - if (current != url) - { - Log.Information("Resolved redirect: {URL} -> {Resolved}", url, current); - if (Uri.TryCreate(current, UriKind.Absolute, out var finalUri) && !SiteHandlerRegistry.HasSpecificHandler(finalUri)) - Log.Warning("Resolved URL has no specific handler, will use generic: {URL}", current); - } - - return current; - } - - public List GetYtdlpArguments(Uri uri, bool avPro) => []; -} diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/VRDancingHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/VRDancingHandler.cs deleted file mode 100644 index 38025e8a..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/VRDancingHandler.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Serilog; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class VRDancingHandler : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - - private static readonly string[] Prefixes = ["https://na2.vrdancing.club", "https://eu2.vrdancing.club", "https://mpegts-beta.vrdancing.club"]; - - public bool CanHandle(Uri uri) => Prefixes.Any(p => uri.ToString().StartsWith(p)); - - public Task GetVideoInfo(string url, Uri uri, bool avPro) - { - var code = url.TrimEnd('/').Split('/').Last(); - var videoId = VideoId.HashUrl(url); - - _ = Task.Run(async () => - { - await VRDancingAPIService.DownloadMetadata(code, videoId); - }); - - return Task.FromResult(new VideoInfo - { - VideoUrl = url, - VideoId = videoId, - UrlType = UrlType.VRDancing, - DownloadFormat = DownloadFormat.MP4 - }); - } - - public List GetYtdlpArguments(Uri uri, bool avPro) => []; - - public Task RewriteUrl(string url, Uri uri) => Task.FromResult(url); - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/SiteHandlers/Sites/YTSHandler.cs b/VRCVideoCacher/YTDL/SiteHandlers/Sites/YTSHandler.cs deleted file mode 100644 index 7b536e3e..00000000 --- a/VRCVideoCacher/YTDL/SiteHandlers/Sites/YTSHandler.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Serilog; -using VRCVideoCacher.Models; - -namespace VRCVideoCacher.YTDL.SiteHandlers.Sites; - -public class YTSHandler : ISiteHandler -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - - public bool CanHandle(Uri uri) => false; // rewrite only - - public Task GetVideoInfo(string url, Uri uri, bool avPro) => Task.FromResult(null); - - public Task RewriteUrl(string url, Uri uri) - { - if (!url.StartsWith("https://dmn.moe")) - return Task.FromResult(url); - - var newUrl = url.Replace("/sr/", "/yt/"); - Log.Information("YTS URL detected, modified to: {URL}", newUrl); - return Task.FromResult(newUrl); - } - - public List GetYtdlpArguments(Uri uri, bool avPro) => []; - -} \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/VideoDownloader.cs b/VRCVideoCacher/YTDL/VideoDownloader.cs index 3b713f57..1e627d87 100644 --- a/VRCVideoCacher/YTDL/VideoDownloader.cs +++ b/VRCVideoCacher/YTDL/VideoDownloader.cs @@ -21,11 +21,28 @@ public class VideoDownloader "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/124.0.0.0 Safari/537.36"; - private static readonly HttpClient HttpClient = new() + // A cache download is an arbitrarily large file over an arbitrarily slow link, so the + // operation as a whole must not be time-boxed. HttpClient.Timeout covers reading the + // body as well as the headers even with ResponseHeadersRead, so the 100s default was + // cancelling any transfer that ran longer than that. Liveness is enforced per-read + // instead, via the stall watchdog in CopyWithStallGuardAsync. + private static readonly HttpClient HttpClient = new(new SocketsHttpHandler { - DefaultRequestHeaders = { { "User-Agent", DownloadUserAgent } } + PooledConnectionLifetime = TimeSpan.FromMinutes(2), + ConnectTimeout = TimeSpan.FromSeconds(30), + // Downloads whatever URL the resolver settled on, which ultimately came from a + // world; same address guard as the probe path. + ConnectCallback = Utils.UrlPolicy.GuardedConnectAsync, + }) + { + DefaultRequestHeaders = { { "User-Agent", DownloadUserAgent } }, + Timeout = Timeout.InfiniteTimeSpan }; + // How long a transfer may deliver no bytes at all before we give up on it. Generous + // enough to survive a CDN hiccup, short enough that a dead socket can't wedge the queue. + private static readonly TimeSpan StallTimeout = TimeSpan.FromSeconds(60); + // Per-videoId temp paths so a leftover from one download can never be glued onto // a different video's resume request. Format: _tempVideo.. private const string TempPrefix = "_tempVideo."; @@ -39,7 +56,8 @@ private static string TempPathFor(string videoId, string ext) => public static event Action? OnDownloadCompleted; public static event Action? OnDownloadPaused; public static event Action? OnQueueChanged; - public static event Action? OnDownloadProgress; // 0.0 to 100.0 + // Percent, plus transfer rate and time remaining where they are known. + public static event Action? OnDownloadProgress; // Current state (read from UI thread via Get* methods — volatile for cross-thread visibility) private static volatile VideoInfo? _currentDownload; @@ -53,10 +71,25 @@ private static string TempPathFor(string videoId, string ext) => private static Process? _currentProcess; private static CancellationTokenSource? _downloadCts; + private static int _started; + static VideoDownloader() { SweepStaleTempFiles(); ActiveStreamTracker.OnStreamingActivity += OnStreamingActivity; + } + + /// + /// Starts the download loop. Called once from startup rather than from the static + /// constructor: a type initialiser that spawns a background worker means merely + /// subscribing to one of the events on this class — which the dashboard view model does + /// while building the UI — silently starts the queue running. + /// + public static void Start() + { + if (Interlocked.Exchange(ref _started, 1) == 1) + return; + Task.Run(DownloadThread); } @@ -95,9 +128,18 @@ private static void OnStreamingActivity() private static async Task DownloadThread() { - while (true) + var shutdown = Program.ShutdownToken; + + while (!shutdown.IsCancellationRequested) { - await Task.Delay(500); + try + { + await Task.Delay(500, shutdown); + } + catch (OperationCanceledException) + { + return; + } var idleSeconds = PlusConfigManager.Config.CacheDownloadIdleSeconds; @@ -344,7 +386,10 @@ public static int GetQueueCount() var rateLimitMBs = PlusConfigManager.Config.CacheDownloadRateLimitMBs; if (rateLimitMBs > 0) - args.Add($"--limit-rate {rateLimitMBs}M"); + { + args.Add("--limit-rate"); + args.Add($"{rateLimitMBs}M"); + } using var process = new Process { @@ -360,36 +405,46 @@ public static int GetQueueCount() } }; + var evalResult = Services.RuleEngine.EvaluateUrl(videoInfo.VideoUrl); + var maxRes = evalResult.MaxResolution ?? 1080; + if (videoInfo.DownloadFormat == DownloadFormat.Webm) { var audioArg = string.IsNullOrEmpty(ConfigManager.Config.YtdlpDubLanguage) ? "+ba[acodec=opus][ext=webm]" : $"+(ba[acodec=opus][ext=webm][language={ConfigManager.Config.YtdlpDubLanguage}]/ba[acodec=opus][ext=webm])"; - args.Add($"-o \"{tempWebm}\""); - args.Add($"-f \"bv*[height<={ConfigManager.Config.CacheYouTubeMaxResolution}][vcodec~='^av01'][ext=mp4][dynamic_range='SDR']{audioArg}/bv*[height<={ConfigManager.Config.CacheYouTubeMaxResolution}][vcodec~='vp9'][ext=webm][dynamic_range='SDR']{audioArg}\""); + args.Add("-o"); + args.Add(tempWebm); + args.Add("-f"); + args.Add($"bv*[height<={maxRes}][vcodec~='^av01'][ext=mp4][dynamic_range='SDR']{audioArg}/bv*[height<={maxRes}][vcodec~='vp9'][ext=webm][dynamic_range='SDR']{audioArg}"); } else { - var maxRes = ConfigManager.Config.CacheYouTubeMaxResolution; var audioArgPotato = string.IsNullOrEmpty(ConfigManager.Config.YtdlpDubLanguage) ? "+ba[ext=m4a]" : $"+(ba[ext=m4a][language={ConfigManager.Config.YtdlpDubLanguage}]/ba[ext=m4a])"; - args.Add($"-o \"{tempMp4}\""); + args.Add("-o"); + args.Add(tempMp4); + args.Add("-f"); if (PlusConfigManager.Config.CacheYouTubePreferVp9) { // VP9+aac in mp4 — best compression, universal compatibility (20-50% smaller than h264) - args.Add($"-f \"bv*[height<={maxRes}][vcodec~='^vp9']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^(avc|h264)']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^av01'][dynamic_range='SDR']\""); + args.Add($"bv*[height<={maxRes}][vcodec~='^vp9']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^(avc|h264)']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^av01'][dynamic_range='SDR']"); } else { // h264+aac — fastest decode, widest hardware support - args.Add($"-f \"bv*[height<={maxRes}][vcodec~='^(avc|h264)']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^av01'][dynamic_range='SDR']\""); + args.Add($"bv*[height<={maxRes}][vcodec~='^(avc|h264)']{audioArgPotato}/bv*[height<={maxRes}][vcodec~='^av01'][dynamic_range='SDR']"); } - args.Add("--remux-video mp4"); + args.Add("--remux-video"); + args.Add("mp4"); } - process.StartInfo.Arguments = YtdlManager.GenerateYtdlArgs(args, $"-- \"{videoId}\""); - Log.Information("Downloading YouTube Video: {Args}", process.StartInfo.Arguments); + // "--" so a video id starting with a dash can never be read as a flag. + var arguments = YtdlManager.GenerateYtdlArgs(args, ["--", videoId]); + foreach (var argument in arguments) + process.StartInfo.ArgumentList.Add(argument); + Log.Information("Downloading YouTube Video: {Args}", string.Join(' ', arguments)); lock (StateLock) { _currentProcess = process; } @@ -447,7 +502,11 @@ public static int GetQueueCount() Log.Error("Failed to download YouTube Video: {exitCode} {URL} {error}", process.ExitCode, url, error); return (false, $"yt-dlp exited with code {process.ExitCode}"); } - Thread.Sleep(100); + + // Let yt-dlp's final rename settle before looking for the output file. Was + // Thread.Sleep, which blocks a thread-pool thread for no reason in an async method + // — the sibling HLS path already used Task.Delay here. + await Task.Delay(100); var fileName = $"{videoId}.{videoInfo.DownloadFormat.ToString().ToLower()}"; var filePath = Path.Join(CacheManager.CachePath, fileName); @@ -477,46 +536,119 @@ public static int GetQueueCount() return (false, "SkipReasonInvalidDownload"); } - File.Move(sourceTemp, filePath, overwrite: true); - CacheManager.AddToCache(fileName); + // Pinned across the publish so AddToCache's own size-budget flush cannot evict the + // file it was just told about. + using (CacheManager.PinFile(fileName)) + { + File.Move(sourceTemp, filePath, overwrite: true); + CacheManager.AddToCache(fileName); + } Log.Information("YouTube Video Downloaded: {URL}", $"{ConfigManager.Config.YtdlpWebServerUrl}/{fileName}"); return (true, null); } private static void ParseYtdlpProgress(string line) { - // yt-dlp progress lines look like: [download] 45.2% of 12.34MiB at 1.23MiB/s - if (!line.Contains('%')) return; - var idx = line.IndexOf('%'); - if (idx < 1) return; - // Walk backwards to find the start of the number - var start = idx - 1; - while (start > 0 && (char.IsDigit(line[start - 1]) || line[start - 1] == '.')) - start--; - if (double.TryParse(line[start..idx], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var percent)) - OnDownloadProgress?.Invoke(percent); + // yt-dlp reports rate and ETA itself, and it sees every byte — it writes the file. + // Taking its numbers beats re-deriving them from the lines we happen to sample. + if (YtdlpProgressParser.TryParse(line, out var progress)) + OnDownloadProgress?.Invoke(progress); } - private static async Task ThrottledCopyAsync(Stream source, Stream destination, long bytesPerSecond, long totalBytes, CancellationToken ct) + /// + /// Copies the response body to disk, optionally rate-limited, under a stall watchdog. + /// The deadline is pushed forward on every read, so a transfer that keeps making + /// progress runs as long as it needs to while one that goes silent for + /// is cancelled. HttpClient.Timeout is disabled for this + /// client, so this is the only thing between a dead socket and a wedged queue. + /// + /// Rate limit, or 0 for unlimited. + /// Expected final size on disk, including any resumed prefix. + /// + /// Bytes already present from a previous attempt. Progress is reported against the file + /// as a whole, so this has to be counted: without it a download resuming at 90% restarted + /// its progress bar from 0 and crept back up, which reads as the transfer having reset. + /// + private static async Task CopyWithStallGuardAsync( + Stream source, Stream destination, long bytesPerSecond, long totalBytes, long alreadyOnDisk, CancellationTokenSource cts) { var buffer = new byte[81920]; var stopwatch = Stopwatch.StartNew(); long totalBytesRead = 0; + var lastReportedPercent = -1.0; + + // Rate is sampled over a moving window and smoothed, rather than averaged across the + // whole transfer: an average is dominated by however the connection behaved at the + // start, so the estimate stops responding to what is happening now. + var lastSampleAt = TimeSpan.Zero; + long lastSampleBytes = 0; + double? smoothedRate = null; - int bytesRead; - while ((bytesRead = await source.ReadAsync(buffer, ct)) > 0) + while (true) { - await destination.WriteAsync(buffer.AsMemory(0, bytesRead), ct); + cts.CancelAfter(StallTimeout); + var bytesRead = await source.ReadAsync(buffer, cts.Token); + if (bytesRead <= 0) + break; + + await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cts.Token); totalBytesRead += bytesRead; + var elapsed = stopwatch.Elapsed; + var windowSeconds = (elapsed - lastSampleAt).TotalSeconds; + if (windowSeconds >= 0.5) + { + var windowRate = (totalBytesRead - lastSampleBytes) / windowSeconds; + smoothedRate = smoothedRate is null ? windowRate : (smoothedRate * 0.7) + (windowRate * 0.3); + lastSampleAt = elapsed; + lastSampleBytes = totalBytesRead; + } + if (totalBytes > 0) - OnDownloadProgress?.Invoke((double)totalBytesRead / totalBytes * 100.0); + { + // Only raise the event when the rounded percentage actually moves: this + // fired once per 80 KiB chunk, so a large file pushed thousands of + // redundant updates at the UI thread. + var percent = Math.Round((alreadyOnDisk + totalBytesRead) / (double)totalBytes * 100.0, 1); + if (percent > lastReportedPercent) + { + lastReportedPercent = percent; + + TimeSpan? eta = null; + if (smoothedRate is > 0) + { + var remaining = totalBytes - (alreadyOnDisk + totalBytesRead); + if (remaining > 0) + eta = TimeSpan.FromSeconds(remaining / smoothedRate.Value); + } + + OnDownloadProgress?.Invoke(new DownloadProgress(percent, smoothedRate, eta)); + } + } + + if (bytesPerSecond <= 0) + continue; var expectedMs = (double)totalBytesRead / bytesPerSecond * 1000; var elapsedMs = stopwatch.Elapsed.TotalMilliseconds; if (elapsedMs < expectedMs) - await Task.Delay(TimeSpan.FromMilliseconds(expectedMs - elapsedMs), ct); + await Task.Delay(TimeSpan.FromMilliseconds(expectedMs - elapsedMs), cts.Token); } + + // Disarm, so the validation and move that follow can't trip the watchdog. + cts.CancelAfter(Timeout.InfiniteTimeSpan); + } + + // A cancelled transfer is either the user's pause — which the caller reports as a pause, + // with no error — or the stall watchdog firing, which is a genuine failure and needs to + // reach the queue's status line instead of masquerading as a pause. + private static (bool Success, string? FailReason) CancelledOutcome(string url) + { + if (_pauseRequested) + return (false, null); + + Log.Warning("Download for {URL} stalled for {Seconds}s with no data; giving up.", url, StallTimeout.TotalSeconds); + return (false, "SkipReasonStalled"); } @@ -554,10 +686,14 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, request.Headers.Add("Accept", "video/*"); if (resumeFrom > 0) request.Headers.Range = new RangeHeaderValue(resumeFrom, null); - + + // Arm the watchdog for the headers too: ConnectTimeout only covers the TCP + // handshake, so a server that accepts and then says nothing would hang here. + cts.CancelAfter(StallTimeout); response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token); + cts.CancelAfter(Timeout.InfiniteTimeSpan); } - catch (OperationCanceledException) { return (false, null); } + catch (OperationCanceledException) { return CancelledOutcome(url); } catch (HttpRequestException ex) { Log.Error(ex, "Failed to start download for {URL}", url); @@ -566,65 +702,63 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, // HttpClient follows redirects automatically by default; manual handling is unnecessary. - // 416 = server says our range is beyond the file — treat as already complete long expectedTotalBytes = 0; string? responseContentType = null; - if (response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable) + + // Scoped `using` rather than a Dispose call on each of the six exit paths — one of + // which had to be added every time a new early return appeared. + using (response) { - if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.PartialContent) + // 416 = server says our range is beyond the file — treat as already complete + if (response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable) { - Log.Warning("Failed to download video: {URL} {Status}", url, response.StatusCode); - response.Dispose(); - return (false, $"HTTP {(int)response.StatusCode}"); - } + if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.PartialContent) + { + Log.Warning("Failed to download video: {URL} {Status}", url, response.StatusCode); + return (false, $"HTTP {(int)response.StatusCode}"); + } - // Reject obvious non-video bodies (HTML error pages, JSON errors served as 200, etc.) - // before they ever hit disk. The magic-byte check after download catches the rest. - responseContentType = response.Content.Headers.ContentType?.MediaType; - if (!VideoFileValidator.IsAcceptableContentType(responseContentType)) - { - Log.Warning("Skipping cache for {URL}: unexpected Content-Type {Ct}", url, responseContentType); - response.Dispose(); - VideoFileValidator.TryDelete(tempMp4); - return (false, $"unexpected content-type {responseContentType}"); - } + // Reject obvious non-video bodies (HTML error pages, JSON errors served as 200, etc.) + // before they ever hit disk. The magic-byte check after download catches the rest. + responseContentType = response.Content.Headers.ContentType?.MediaType; + if (!VideoFileValidator.IsAcceptableContentType(responseContentType)) + { + Log.Warning("Skipping cache for {URL}: unexpected Content-Type {Ct}", url, responseContentType); + VideoFileValidator.TryDelete(tempMp4); + return (false, $"unexpected content-type {responseContentType}"); + } - var contentLength = response.Content.Headers.ContentLength ?? 0; - if (contentLength > 0) - expectedTotalBytes = resumeFrom + contentLength; + var contentLength = response.Content.Headers.ContentLength ?? 0; + if (contentLength > 0) + expectedTotalBytes = resumeFrom + contentLength; - try - { - await using var stream = await response.Content.ReadAsStreamAsync(cts.Token); - var fileMode = resumeFrom > 0 ? FileMode.Append : FileMode.Create; - await using var fileStream = new FileStream(tempMp4, fileMode, FileAccess.Write, FileShare.None); + try + { + await using var stream = await response.Content.ReadAsStreamAsync(cts.Token); + var fileMode = resumeFrom > 0 ? FileMode.Append : FileMode.Create; + await using var fileStream = new FileStream(tempMp4, fileMode, FileAccess.Write, FileShare.None); - var rateLimitMBs = PlusConfigManager.Config.CacheDownloadRateLimitMBs; - if (rateLimitMBs > 0) - await ThrottledCopyAsync(stream, fileStream, rateLimitMBs * 1024L * 1024L, expectedTotalBytes, cts.Token); - else - await stream.CopyToAsync(fileStream, cts.Token); - } - catch (OperationCanceledException) - { - response.Dispose(); - return (false, null); - } - catch (IOException ex) - { - response.Dispose(); - Log.Warning("Download stream failed for {URL}: {Err}", url, ex.Message); - return (false, "network error"); - } - catch (HttpRequestException ex) - { - response.Dispose(); - Log.Warning("Download stream failed for {URL}: {Err}", url, ex.Message); - return (false, "network error"); + var rateLimitMBs = PlusConfigManager.Config.CacheDownloadRateLimitMBs; + var bytesPerSecond = rateLimitMBs > 0 ? rateLimitMBs * 1024L * 1024L : 0L; + await CopyWithStallGuardAsync(stream, fileStream, bytesPerSecond, expectedTotalBytes, resumeFrom, cts); + } + catch (OperationCanceledException) + { + return CancelledOutcome(url); + } + catch (IOException ex) + { + Log.Warning("Download stream failed for {URL}: {Err}", url, ex.Message); + return (false, "network error"); + } + catch (HttpRequestException ex) + { + Log.Warning("Download stream failed for {URL}: {Err}", url, ex.Message); + return (false, "network error"); + } } } - response.Dispose(); await Task.Delay(10); var fileName = $"{videoInfo.VideoId}.{videoInfo.DownloadFormat.ToString().ToLower()}"; @@ -668,8 +802,11 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, return (false, "SkipReasonInvalidDownload"); } - File.Move(tempMp4, filePath, overwrite: true); - CacheManager.AddToCache(fileName); + using (CacheManager.PinFile(fileName)) + { + File.Move(tempMp4, filePath, overwrite: true); + CacheManager.AddToCache(fileName); + } Log.Information("Video Downloaded: {URL}", $"{ConfigManager.Config.YtdlpWebServerUrl}/{fileName}"); return (true, null); } @@ -692,20 +829,23 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, var args = new List { "--newline", - $"-o \"{tempMp4}\"", - "--remux-video mp4", + "-o", tempMp4, + "--remux-video", "mp4", // Let yt-dlp pick native vs. ffmpeg HLS downloader — native chokes on // fMP4/CMAF (#EXT-X-MAP) playlists, ffmpeg handles those. - "--concurrent-fragments 4", + "--concurrent-fragments", "4", // CDN segment fetches can be flaky; retry the manifest a few times and // each individual segment more aggressively before giving up. - "--retries 3", - "--fragment-retries 5" + "--retries", "3", + "--fragment-retries", "5" }; var rateLimitMBs = PlusConfigManager.Config.CacheDownloadRateLimitMBs; if (rateLimitMBs > 0) - args.Add($"--limit-rate {rateLimitMBs}M"); + { + args.Add("--limit-rate"); + args.Add($"{rateLimitMBs}M"); + } using var process = new Process { @@ -721,8 +861,10 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, }, }; - process.StartInfo.Arguments = YtdlManager.GenerateYtdlArgs(args, $"\"{videoInfo.VideoUrl}\""); - Log.Information("Downloading HLS Video: {Args}", process.StartInfo.Arguments); + var arguments = YtdlManager.GenerateYtdlArgs(args, ["--", videoInfo.VideoUrl]); + foreach (var argument in arguments) + process.StartInfo.ArgumentList.Add(argument); + Log.Information("Downloading HLS Video: {Args}", string.Join(' ', arguments)); lock (StateLock) { _currentProcess = process; } @@ -782,8 +924,11 @@ private static async Task ThrottledCopyAsync(Stream source, Stream destination, return (false, "SkipReasonInvalidDownload"); } - File.Move(tempMp4, filePath, overwrite: true); - CacheManager.AddToCache(fileName); + using (CacheManager.PinFile(fileName)) + { + File.Move(tempMp4, filePath, overwrite: true); + CacheManager.AddToCache(fileName); + } Log.Information("HLS Video Downloaded: {URL}", $"{ConfigManager.Config.YtdlpWebServerUrl}/{fileName}"); // HLS has no remote thumbnail source — extract a frame from the cached MP4 so diff --git a/VRCVideoCacher/YTDL/VideoId.cs b/VRCVideoCacher/YTDL/VideoId.cs index c4fee764..081249cc 100644 --- a/VRCVideoCacher/YTDL/VideoId.cs +++ b/VRCVideoCacher/YTDL/VideoId.cs @@ -6,7 +6,8 @@ using VRCVideoCacher.Database; using VRCVideoCacher.Database.Models; using VRCVideoCacher.Models; -using VRCVideoCacher.YTDL.SiteHandlers; +using VRCVideoCacher.Utils; +using VRCVideoCacher.Integrations; using JsonSerializer = System.Text.Json.JsonSerializer; namespace VRCVideoCacher.YTDL; @@ -28,47 +29,58 @@ internal static string HashUrl(string url) .Replace("=", ""); } - private static Process GetYtdlpProcess() + /// + /// Errors that no alternative client, format or cookie state can fix. + /// + /// Every retry is another yt-dlp launch — a ~15 MB Python bundle with a second or two of + /// startup — and VRChat is blocked on the resolve the whole time. A failing video could + /// otherwise take four launches: the AVPro attempt, the non-AVPro retry, the android + /// fallback, and ApiController's own post-prefetch retry. For a deleted or private video + /// none of them was ever going to succeed. + /// + internal static bool IsTerminalFailure(string error) { - var process = new Process - { - StartInfo = - { - FileName = YtdlManager.YtdlPath, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - } - }; + if (string.IsNullOrWhiteSpace(error)) + return false; - return process; + string[] markers = + [ + "Video unavailable", + "Private video", + "This video has been removed", + "video has been removed", + "members-only", + "join this channel", + "does not exist", + "has been terminated", + "Incomplete YouTube ID", + "Unsupported URL", + "is not a valid URL", + "Video not available" + ]; + + return markers.Any(marker => error.Contains(marker, StringComparison.OrdinalIgnoreCase)); } - private static async Task<(string Output, string Error, int ExitCode)> RunYtdlpAsync(List args, string url) + private static async Task<(string Output, string Error, int ExitCode)> RunYtdlpAsync(List args, string url, bool includeCookies = true) { - var ytdlpProcess = GetYtdlpProcess(); - ytdlpProcess.StartInfo.Arguments = YtdlManager.GenerateYtdlArgs(args, $"\"{url}\""); - Log.Information("Starting yt-dlp with args: {args:l}", ytdlpProcess.StartInfo.Arguments); - ytdlpProcess.Start(); - var output = await ytdlpProcess.StandardOutput.ReadToEndAsync(); - var error = await ytdlpProcess.StandardError.ReadToEndAsync(); - await ytdlpProcess.WaitForExitAsync(); + // "--" so a URL that happens to start with a dash is never taken for a flag. + var arguments = YtdlManager.GenerateYtdlArgs(args, ["--", url], includeCookies); + Log.Information("Starting yt-dlp with args: {args:l}", string.Join(' ', arguments)); + var (output, error, exitCode) = await ProcessRunner.RunAsync(YtdlManager.YtdlPath, arguments); Log.Information("Finished yt-dlp"); - return (output.Trim(), error.Trim(), ytdlpProcess.ExitCode); + return (output, error, exitCode); } public static async Task GetVideoId(string url, bool avPro) { url = url.Trim(); - url = await SiteHandlerRegistry.ApplyRewrites(url); + url = await IntegrationRegistry.ApplyRewrites(url); var uri = ToUri(url); if (uri == null) return null; - var handler = await SiteHandlerRegistry.ResolveAsync(url, uri); + var handler = await IntegrationRegistry.ResolveAsync(url, uri, Services.RuleEngine.EvaluateUrl(url).MatchedRule); return handler == null ? null : await handler.GetVideoInfo(url, uri, avPro); } @@ -85,17 +97,32 @@ private static Process GetYtdlpProcess() if (existing?.Duration is > 0) return existing.Duration; + // Fast oEmbed lookup so a title appears immediately, ahead of the slower yt-dlp + // call below. Deliberately after the cache check: it used to run first, so every + // call made an HTTP round trip to YouTube even when the answer was already known. + // GetVideoTitleAsync caches what it finds and logs its own failures. + await Integrations.YouTube.YouTubeMetadataService.GetVideoTitleAsync(videoId); + try { var url = $"https://www.youtube.com/watch?v={videoId}"; var args = new List { "-j", - "--impersonate=\"safari\"", - "--extractor-args=\"youtube:player_client=web\"" + "--skip-download", + "--impersonate", "safari", + "--extractor-args", "youtube:player_client=web" }; - var (rawData, error, exitCode) = await RunYtdlpAsync(args, url); + var (rawData, error, exitCode) = await RunYtdlpAsync(args, url, includeCookies: true); + if ((exitCode != 0 || string.IsNullOrEmpty(rawData)) && !IsTerminalFailure(error)) + { + // Worth one retry: expired or rejected cookies make yt-dlp fail in a way a + // cookie-less request often survives. Pointless for a deleted video. + Log.Warning("Metadata fetch with cookies failed for {VideoId} ({Error}). Retrying without cookies...", videoId, error.Trim()); + (rawData, error, exitCode) = await RunYtdlpAsync(args, url, includeCookies: false); + } + if (exitCode != 0 || string.IsNullOrEmpty(rawData)) { Log.Warning("Failed to fetch metadata for {VideoId}: {Error}", videoId, error); @@ -127,13 +154,23 @@ private static Process GetYtdlpProcess() public static async Task<(string VideoId, string? SkipReason)> TryGetYouTubeVideoId(string url) { - var args = new List(); - args.Add("-j"); + var args = new List { "-j" }; - var (rawData, error, exitCode) = await RunYtdlpAsync(args, url); - if (exitCode != 0) + var (rawData, error, exitCode) = await RunYtdlpAsync(args, url, includeCookies: true); + if ((exitCode != 0 || string.IsNullOrEmpty(rawData)) && IsTerminalFailure(error)) throw new Exception($"yt-dlp metadata fetch failed: {error.Trim()}"); + if (exitCode != 0 || string.IsNullOrEmpty(rawData)) + { + Log.Warning("TryGetYouTubeVideoId with cookies failed ({Error}). Retrying without cookies...", error.Trim()); + var (fallbackData, fallbackError, fallbackExitCode) = await RunYtdlpAsync(new List { "-j" }, url, includeCookies: false); + if (fallbackExitCode != 0 || string.IsNullOrEmpty(fallbackData)) + { + throw new Exception($"yt-dlp metadata fetch failed: {fallbackError.Trim()}"); + } + rawData = fallbackData; + } + if (string.IsNullOrEmpty(rawData)) { Log.Warning("Skipping video: yt-dlp returned no metadata for {URL}", url); @@ -160,10 +197,13 @@ private static Process GetYtdlpProcess() Log.Warning("Skipping video: video is a live stream"); return (string.Empty, "SkipReasonLiveStream"); } - if (data.Duration > ConfigManager.Config.CacheYouTubeMaxLength * 60) + var evalResult = Services.RuleEngine.EvaluateUrl(url); + int maxDurationMinutes = evalResult.MaxDurationMinutes ?? 120; + + if (data.Duration > maxDurationMinutes * 60) { - Log.Warning("Skipping video: duration exceeds allowed duration ({VideoMin:F1}min > {MaxMin}min)", data.Duration / 60.0, ConfigManager.Config.CacheYouTubeMaxLength); - return (string.Empty, string.Format("SkipReasonTooLong|{0:F0}|{1}", data.Duration / 60.0, ConfigManager.Config.CacheYouTubeMaxLength)); + Log.Warning("Skipping video: duration exceeds allowed duration ({VideoMin:F1}min > {MaxMin}min)", data.Duration / 60.0, maxDurationMinutes); + return (string.Empty, string.Format("SkipReasonTooLong|{0:F0}|{1}", data.Duration / 60.0, maxDurationMinutes)); } return (data.Id, null); @@ -173,13 +213,18 @@ public static async Task GetURLResonite(string url) { var args = new List(); if (!string.IsNullOrEmpty(ConfigManager.Config.YtdlpDubLanguage)) - args.Add($"-f \"[language={ConfigManager.Config.YtdlpDubLanguage}]\""); + { + args.Add("-f"); + args.Add($"[language={ConfigManager.Config.YtdlpDubLanguage}]"); + } args.Add("--flat-playlist"); args.Add("-i"); args.Add("-J"); // --dump-single-json args.Add("-s"); - args.Add("--impersonate=\"safari\""); - args.Add("--extractor-args=\"youtube:player_client=web\""); + args.Add("--impersonate"); + args.Add("safari"); + args.Add("--extractor-args"); + args.Add("youtube:player_client=web"); var (output, error, exitCode) = await RunYtdlpAsync(args, url); if (exitCode != 0) @@ -204,25 +249,52 @@ public static async Task> GetUrl(VideoInfo videoInfo, bool a var url = videoInfo.VideoUrl; var uri = ToUri(url); - var handler = uri != null ? SiteHandlerRegistry.Resolve(uri) : null; + + // Select the handler from the type recorded on the VideoInfo rather than + // re-evaluating the rules against its URL. GetVideoInfo has already canonicalised + // that URL, so a second evaluation is both redundant and able to disagree with the + // handler that produced this record in the first place. + var handler = uri != null ? IntegrationRegistry.ResolveByUrlType(videoInfo.UrlType) : null; var args = handler?.GetYtdlpArguments(uri!, avPro) ?? []; args.Add("--get-url"); var (output, error, exitCode) = await RunYtdlpAsync(args, url); - if (exitCode == 0) // success + if (exitCode == 0 && !string.IsNullOrEmpty(output)) // success return new Tuple(output, true); if (error.Contains("Sign in to confirm you’re not a bot")) // Exact Text, do not modify. Log.Error("Fix this error by running cookie setup."); - if (error.Contains( - "Requested format is not available. Use --list-formats for a list of available formats") && avPro) + // Nothing below can help with a deleted, private or members-only video, and each + // step costs another yt-dlp launch that VRChat waits through. + if (IsTerminalFailure(error)) + { + Log.Information("Not retrying {URL}: {Error}", url, error.Trim()); + return new Tuple(error, false); + } + + if (avPro) { - Log.Warning("AVPro format request failed retrying for 360p."); + Log.Warning("AVPro format request failed retrying without AVPro."); return await GetUrl(videoInfo, false); } - return new Tuple(error, false); + + // Ultimate fallback for videos with restricted DASH/AVPro formats + Log.Warning("Standard format request failed ({Error}). Retrying with android fallback client...", error.Trim()); + var fallbackArgs = new List + { + "--get-url", + "--extractor-args", "youtube:player_client=android,web", + "-f", "b[height<=?1080]/bv*+ba/best" + }; + var (fallbackOutput, fallbackError, fallbackExitCode) = await RunYtdlpAsync(fallbackArgs, url); + if (fallbackExitCode == 0 && !string.IsNullOrEmpty(fallbackOutput)) + { + return new Tuple(fallbackOutput, true); + } + + return new Tuple(!string.IsNullOrEmpty(fallbackError) ? fallbackError : error, false); } public static bool IsYouTubePlaylist(string url) @@ -251,41 +323,33 @@ public static async Task> GetPlaylistVideoInfos(string url, bool "-j", "--ignore-config", "--no-warnings", - "--encoding utf-8" + "--encoding", "utf-8" }; if (File.Exists(YtdlManager.FfmpegPath)) - args.Add($"--ffmpeg-location \"{YtdlManager.FfmpegPath}\""); + { + args.Add("--ffmpeg-location"); + args.Add(YtdlManager.FfmpegPath); + } if (File.Exists(YtdlManager.DenoPath)) - args.Add($"--js-runtimes deno:\"{YtdlManager.DenoPath}\""); + { + args.Add("--js-runtimes"); + args.Add($"deno:{YtdlManager.DenoPath}"); + } if (Program.IsCookiesEnabledAndValid()) - args.Add($"--cookies \"{YtdlManager.CookiesPath}\""); - if (!string.IsNullOrEmpty(ConfigManager.Config.YtdlpAdditionalArgs)) - args.Add(ConfigManager.Config.YtdlpAdditionalArgs); - args.Add($"\"{url}\""); - - var process = new Process { - StartInfo = - { - FileName = YtdlManager.YtdlPath, - Arguments = string.Join(' ', args), - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - } - }; - process.Start(); - var output = await process.StandardOutput.ReadToEndAsync(); - var error = await process.StandardError.ReadToEndAsync(); - await process.WaitForExitAsync(); + args.Add("--cookies"); + args.Add(YtdlManager.CookiesPath); + } + args.AddRange(YtdlManager.SplitArguments(ConfigManager.Config.YtdlpAdditionalArgs)); + args.Add("--"); + args.Add(url); - if (process.ExitCode != 0) + var (output, error, exitCode) = await ProcessRunner.RunAsync(YtdlManager.YtdlPath, args); + + if (exitCode != 0) { - Log.Error("Failed to get playlist entries: {Error}", error.Trim()); + Log.Error("Failed to get playlist entries: {Error}", error); return results; } diff --git a/VRCVideoCacher/YTDL/VideoTools.cs b/VRCVideoCacher/YTDL/VideoTools.cs index 71f1ec14..cca07943 100644 --- a/VRCVideoCacher/YTDL/VideoTools.cs +++ b/VRCVideoCacher/YTDL/VideoTools.cs @@ -37,8 +37,11 @@ private static void ResetHttpClient() public static async Task Prefetch(string videoUrl, int maxRetryCount = 7) { - // If the URL is invalid, skip prefetching - if (string.IsNullOrWhiteSpace(videoUrl) || !Uri.IsWellFormedUriString(videoUrl, UriKind.RelativeOrAbsolute)) + // Must be absolute, not merely well-formed: RelativeOrAbsolute accepted a relative + // reference that `new Uri(...)` below then threw UriFormatException on, and the + // catch clauses here only cover HttpRequestException and TaskCanceledException — so + // it escaped into the request handler. + if (string.IsNullOrWhiteSpace(videoUrl) || !Uri.TryCreate(videoUrl, UriKind.Absolute, out var uri)) { Log.Warning("Invalid video URL provided for prefetch: {URL}", videoUrl); return false; @@ -47,7 +50,6 @@ public static async Task Prefetch(string videoUrl, int maxRetryCount = 7) try { // Determine if the URL is an M3U8 playlist - var uri = new Uri(videoUrl); var isM3U8 = uri.AbsolutePath.EndsWith(".m3u8", StringComparison.OrdinalIgnoreCase) || videoUrl.Contains("mime=application/vnd.apple.mpegurl"); // Prefetch the video URL diff --git a/VRCVideoCacher/YTDL/YtdlManager.cs b/VRCVideoCacher/YTDL/YtdlManager.cs index 95b6c66e..591b4deb 100644 --- a/VRCVideoCacher/YTDL/YtdlManager.cs +++ b/VRCVideoCacher/YTDL/YtdlManager.cs @@ -1,654 +1,838 @@ -using System.Runtime.InteropServices; -using Newtonsoft.Json; -using Serilog; -using SharpCompress.Readers; -using VRCVideoCacher.Models; -using VRCVideoCacher.Services; -using VRCVideoCacher.Utils; - -namespace VRCVideoCacher.YTDL; - -public class YtdlManager -{ - private static readonly ILogger Log = Program.Logger.ForContext(); - private static readonly HttpClient HttpClient = new() - { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } } - }; - private static readonly HttpClient DownloadHttpClient = new() - { - DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, - Timeout = TimeSpan.FromMinutes(10) - }; - public static readonly string CookiesPath; - - public static readonly string YtdlPath = - Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "yt-dlp.exe" : "yt-dlp"); - public static readonly string DenoPath = - Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "deno.exe" : "deno"); - public static readonly string FfmpegPath = - Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"); - private const string YtdlpApiUrl = "https://api.github.com/repos/yt-dlp/yt-dlp-nightly-builds/releases/latest"; - private const string FfmpegNightlyApiUrl = "https://api.github.com/repos/yt-dlp/FFmpeg-Builds/releases/latest"; - private const string FfmpegApiUrl = "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest"; - private const string DenoApiUrl = "https://api.github.com/repos/denoland/deno/releases/latest"; - private const string DenoFallBackVersionURL = "https://dl.deno.land/release-latest.txt"; - private const string DenoFallBackDownloadURL = "https://dl.deno.land/release/"; - - - static YtdlManager() - { - CookiesPath = Path.Join(Program.DataPath, "youtube_cookies.txt"); - - // try to locate in PATH - if (LaunchArgs.UseGlobalPath) - { - YtdlPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "yt-dlp.exe" : "yt-dlp") ?? - throw new FileNotFoundException("Unable to find yt-dlp"); - DenoPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "deno.exe" : "deno") ?? - throw new FileNotFoundException("Unable to find Deno runtime"); - FfmpegPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg") ?? - string.Empty; - } - - Log.Debug("Using ytdl path: {YtdlPath}", YtdlPath); - } - - public static string GenerateYtdlArgs(List args, string urlArg) - { - var globalArgs = new List - { - "--encoding utf-8", - "--ignore-config", - "--no-playlist", - "--no-warnings", - "--no-mtime", - "--no-progress" - }; - args.AddRange(globalArgs); - - if (File.Exists(FfmpegPath)) - args.Add($"--ffmpeg-location \"{FfmpegPath}\""); - - if (File.Exists(DenoPath)) - args.Add($"--js-runtimes deno:\"{DenoPath}\""); - else - Log.Error("Deno runtime not found at path: {DenoPath}", DenoPath); - - if (Program.IsCookiesEnabledAndValid()) - args.Add($"--cookies \"{CookiesPath}\""); - - if (!string.IsNullOrEmpty(ConfigManager.Config.YtdlpAdditionalArgs)) - args.Add(ConfigManager.Config.YtdlpAdditionalArgs); - - args.Add(urlArg); - return string.Join(' ', args); - } - - public static void StartYtdlUpdaterThread() - { - Task.Run(YtdlUpdaterTask); - } - - private static async Task YtdlUpdaterTask() - { - const int interval = 60 * 60 * 1000; // 1 hour - while (true) - { - await Task.Delay(interval); - try - { - await TryDownloadYtdlp(); - } - catch (Exception ex) - { - Log.Warning(ex, "YT-DLP update check failed, will retry next interval."); - } - } - // ReSharper disable once FunctionNeverReturns - } - - public static async Task TryDownloadYtdlp() - { - if (!Directory.Exists(Program.UtilsPath)) - throw new Exception("Failed to get Utils path"); - - Log.Information("Checking for YT-DLP updates..."); - try - { - using var response = await HttpClient.GetAsync(YtdlpApiUrl); - if (!response.IsSuccessStatusCode) - { - Log.Warning("Failed to check for YT-DLP updates."); - return; - } - var data = await response.Content.ReadAsStringAsync(); - var json = JsonConvert.DeserializeObject(data); - if (json == null) - { - Log.Error("Failed to parse YT-DLP update response."); - return; - } - - var currentYtdlVersion = Versions.CurrentVersion.Ytdlp; - if (!File.Exists(YtdlPath)) - { - currentYtdlVersion = "Not Installed"; - } - else if (!await CheckIfProcessStarts(YtdlPath)) - { - currentYtdlVersion = "Not Working"; - } - else - { - currentYtdlVersion = await GetYtdlpVersionFromBinary() ?? string.Empty; - } - - var latestVersion = json.tag_name; - Log.Information("YT-DLP Current: {Installed} Latest: {Latest}", currentYtdlVersion, latestVersion); - if (string.IsNullOrEmpty(latestVersion)) - { - Log.Warning("Failed to check for YT-DLP updates."); - return; - } - if (currentYtdlVersion == latestVersion) - { - Log.Information("YT-DLP is up to date."); - return; - } - Log.Information("YT-DLP is outdated. Updating..."); - - await DownloadYtdl(json); - } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) - { - Log.Warning(ex, "YT-DLP update failed due to a network error."); - Log.Information("You can manually place yt-dlp.exe (or yt-dlp on Linux) in: {UtilsPath}", Program.UtilsPath); - } - } - - private static async Task GetYtdlpVersionFromBinary() - { - try - { - using var process = new System.Diagnostics.Process(); - process.StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = YtdlPath, - Arguments = "--version", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - }; - process.Start(); - var output = await process.StandardOutput.ReadToEndAsync(); - await process.WaitForExitAsync(); - return output.Trim(); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to detect yt-dlp version from binary."); - } - return null; - } - - private static async Task GetFfmpegVersionFromBinary() - { - try - { - using var process = new System.Diagnostics.Process(); - process.StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = FfmpegPath, - Arguments = "-version", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - }; - process.Start(); - var output = await process.StandardOutput.ReadToEndAsync(); - await process.WaitForExitAsync(); - // Output: "ffmpeg version 7.1.1-full_build-www.gyan.dev ..." - var firstLine = output.Split('\n')[0].Trim(); - var parts = firstLine.Split(' '); - if (parts.Length >= 3 && parts[0] == "ffmpeg" && parts[1] == "version") - return parts[2].Split('-')[0]; // strip "-full_build-..." suffix - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to detect FFmpeg version from binary."); - } - return null; - } - - private static async Task GetDenoVersionFromBinary() - { - try - { - using var process = new System.Diagnostics.Process(); - process.StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = DenoPath, - Arguments = "--version", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - }; - process.Start(); - var output = await process.StandardOutput.ReadToEndAsync(); - await process.WaitForExitAsync(); - // Output: "deno 2.8.0\n..." - var firstLine = output.Split('\n')[0].Trim(); - var parts = firstLine.Split(' '); - if (parts.Length >= 2 && parts[0] == "deno") - return $"v{parts[1]}"; - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to detect Deno version from binary."); - } - return null; - } - - public static async Task TryDownloadDeno() - { - if (!Directory.Exists(Program.UtilsPath)) - throw new Exception("Failed to get Utils path"); - - try - { - await TryDownloadDenoInner(); - } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) - { - Log.Warning(ex, "Deno update failed due to a network error."); - Log.Information("You can manually place deno.exe (or deno on Linux) in: {UtilsPath}", Program.UtilsPath); - } - } - - private static async Task TryDownloadDenoInner() - { - using var apiResponse = await HttpClient.GetAsync(DenoApiUrl); - if (!apiResponse.IsSuccessStatusCode) - { - Log.Warning("Failed to get latest ffmpeg release: {ResponseStatusCode}", apiResponse.StatusCode); - return; - } - var data = await apiResponse.Content.ReadAsStringAsync(); - var json = JsonConvert.DeserializeObject(data); - if (json == null) - { - Log.Error("Failed to parse deno release response."); - return; - } - - var currentDenoVersion = Versions.CurrentVersion.Deno; - if (!File.Exists(DenoPath)) - { - currentDenoVersion = "Not Installed"; - } - else if (!await CheckIfProcessStarts(DenoPath)) - { - currentDenoVersion = "Not Working"; - } - else - { - currentDenoVersion = await GetDenoVersionFromBinary() ?? string.Empty; - } - - var latestVersion = json.tag_name; - Log.Information("Deno Current: {Installed} Latest: {Latest}", currentDenoVersion, latestVersion); - if (string.IsNullOrEmpty(latestVersion)) - { - Log.Warning("Failed to check for Deno updates."); - return; - } - if (currentDenoVersion == latestVersion) - { - Log.Information("Deno is up to date."); - return; - } - Log.Information("Deno is outdated. Updating..."); - - string assetName; - if (OperatingSystem.IsWindows()) - { - assetName = "deno-x86_64-pc-windows-msvc.zip"; - } - else if (OperatingSystem.IsLinux()) - { - switch (RuntimeInformation.OSArchitecture) - { - case Architecture.X64: - assetName = "deno-x86_64-unknown-linux-gnu.zip"; - break; - case Architecture.Arm64: - assetName = "deno-aarch64-unknown-linux-gnu.zip"; - break; - default: - Log.Error("Unsupported architecture {OSArchitecture}", RuntimeInformation.OSArchitecture); - return; - } - } - else - { - Log.Error("Unsupported operating system {OperatingSystem}", Environment.OSVersion); - return; - } - // deno-x86_64-pc-windows-msvc.zip -> deno-x86_64-pc-windows-msvc - var assets = json.assets.Where(asset => asset.name == assetName).ToList(); - if (assets.Count < 1) - { - Log.Error("Unable to find Deno asset {AssetName} for this platform.", assetName); - return; - } - - Log.Information("Downloading Deno..."); - var url = assets.First().browser_download_url; - - using var response = await DownloadHttpClient.GetAsync(url); - if (!response.IsSuccessStatusCode) - { - Log.Information("Failed to download deno from github attempting fallback download."); - await TryDownloadDenoFallback(assetName); - return; - } - await using var responseStream = await response.Content.ReadAsStreamAsync(); - var reader = await ReaderFactory.OpenAsyncReader(responseStream); - try - { - while (await reader.MoveToNextEntryAsync()) - { - if (reader.Entry.Key == null || reader.Entry.IsDirectory) - continue; - - Log.Debug("Extracting file {Name} ({Size} bytes)", reader.Entry.Key, reader.Entry.Size); - var path = Path.Join(Program.UtilsPath, reader.Entry.Key); - await using var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); - await using var entryStream = await reader.OpenEntryStreamAsync(); - await entryStream.CopyToAsync(outputStream); - Versions.CurrentVersion.Deno = json.tag_name; - Versions.Save(); - FileTools.MarkFileExecutable(path); - Log.Information("Deno downloaded and extracted."); - return; - } - } - finally - { - await reader.DisposeAsync(); - } - - Log.Error("Failed to extract Deno files."); - } - - private static async Task TryDownloadDenoFallback(string assetName) - { - Log.Warning("Falling back to Deno version check via text file."); - using var response = await HttpClient.GetAsync(DenoFallBackVersionURL); - if (!response.IsSuccessStatusCode) - { - Log.Warning("Failed to get latest Deno version: {ResponseStatusCode}", response.StatusCode); - return; - } - var latestVersion = (await response.Content.ReadAsStringAsync()).Trim(); - var url = $"{DenoFallBackDownloadURL}{latestVersion}/{assetName}"; - using var downloadResponse = await DownloadHttpClient.GetAsync(url); - if (!downloadResponse.IsSuccessStatusCode) - { - Log.Error("Failed to download Deno from fallback URL: {ResponseStatusCode}", downloadResponse.StatusCode); - return; - } - - await using var responseStream = await downloadResponse.Content.ReadAsStreamAsync(); - var reader = await ReaderFactory.OpenAsyncReader(responseStream); - try - { - while (await reader.MoveToNextEntryAsync()) - { - if (reader.Entry.Key == null || reader.Entry.IsDirectory) - continue; - - Log.Debug("Extracting file {Name} ({Size} bytes)", reader.Entry.Key, reader.Entry.Size); - var path = Path.Join(Program.UtilsPath, reader.Entry.Key); - await using var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); - await using var entryStream = await reader.OpenEntryStreamAsync(); - await entryStream.CopyToAsync(outputStream); - Versions.CurrentVersion.Deno = latestVersion; - Versions.Save(); - FileTools.MarkFileExecutable(path); - Log.Information("Deno downloaded and extracted."); - return; - } - } - finally - { - await reader.DisposeAsync(); - } - - Log.Error("Failed to extract Deno files from fallback download."); - } - - public static async Task TryDownloadFfmpeg() - { - if (!Directory.Exists(Program.UtilsPath)) - throw new Exception("Failed to get Utils path"); - - if (!ConfigManager.Config.CacheYouTube) - return; - - try - { - await TryDownloadFfmpegInner(); - } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) - { - Log.Warning(ex, "FFmpeg update failed due to a network error."); - Log.Information("You can manually place ffmpeg.exe (or ffmpeg on Linux) in: {UtilsPath}", Program.UtilsPath); - } - } - - private static async Task TryDownloadFfmpegInner() - { - using var apiResponse = await HttpClient.GetAsync(OperatingSystem.IsWindows() ? FfmpegApiUrl : FfmpegNightlyApiUrl); - if (!apiResponse.IsSuccessStatusCode) - { - Log.Warning("Failed to get latest ffmpeg release: {ResponseStatusCode}", apiResponse.StatusCode); - return; - } - var data = await apiResponse.Content.ReadAsStringAsync(); - var json = JsonConvert.DeserializeObject(data); - if (json == null) - { - Log.Error("Failed to parse ffmpeg release response."); - return; - } - - var currentffmpegVersion = Versions.CurrentVersion.Ffmpeg; - if (!File.Exists(FfmpegPath)) - { - currentffmpegVersion = "Not Installed"; - } - else if (!await CheckIfProcessStarts(FfmpegPath, "-version")) - { - currentffmpegVersion = "Not Working"; - } - else - { - currentffmpegVersion = await GetFfmpegVersionFromBinary() ?? string.Empty; - } - - var latestVersion = OperatingSystem.IsWindows() ? json.tag_name : json.name; - Log.Information("FFmpeg Current: {Installed} Latest: {Latest}", currentffmpegVersion, latestVersion); - if (string.IsNullOrEmpty(latestVersion)) - { - Log.Warning("Failed to check for FFmpeg updates."); - return; - } - if (currentffmpegVersion == latestVersion) - { - Log.Information("FFmpeg is up to date."); - return; - } - Log.Information("FFmpeg is outdated. Updating..."); - - string assetSuffix; - if (OperatingSystem.IsWindows()) - { - assetSuffix = "full_build-shared.zip"; - } - else if (OperatingSystem.IsLinux()) - { - switch (RuntimeInformation.OSArchitecture) - { - case Architecture.X64: - assetSuffix = "master-latest-linux64-gpl.tar.xz"; - break; - case Architecture.Arm64: - assetSuffix = "master-latest-linuxarm64-gpl.tar.xz"; - break; - default: - Log.Error("Unsupported architecture {OSArchitecture}", RuntimeInformation.OSArchitecture); - return; - } - } - else - { - Log.Error("Unsupported operating system {OperatingSystem}", Environment.OSVersion); - return; - } - var url = json.assets - .FirstOrDefault(assetVersion => assetVersion.name.EndsWith(assetSuffix, StringComparison.OrdinalIgnoreCase)) - ?.browser_download_url ?? string.Empty; - if (string.IsNullOrEmpty(url)) - { - Log.Error("Unable to find ffmpeg asset for this platform."); - return; - } - Log.Information("Downloading FFmpeg..."); - - using var response = await DownloadHttpClient.GetAsync(url); - await using var responseStream = await response.Content.ReadAsStreamAsync(); - var reader = await ReaderFactory.OpenAsyncReader(responseStream); - var success = false; - try - { - while (await reader.MoveToNextEntryAsync()) - { - if (reader.Entry.Key == null || reader.Entry.IsDirectory) - continue; - - if (!reader.Entry.Key.Contains("/bin/")) - continue; - - var fileName = Path.GetFileName(reader.Entry.Key); - Log.Debug("Extracting file {Name} ({Size} bytes)", fileName, reader.Entry.Size); - var path = Path.Join(Program.UtilsPath, fileName); - await using var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); - await using var entryStream = await reader.OpenEntryStreamAsync(); - await entryStream.CopyToAsync(outputStream); - FileTools.MarkFileExecutable(path); - success = true; - } - } - finally - { - await reader.DisposeAsync(); - } - - if (!success) - { - Log.Error("Failed to extract ffmpeg files."); - return; - } - - Versions.CurrentVersion.Ffmpeg = latestVersion; - Versions.Save(); - Log.Information("FFmpeg downloaded and extracted."); - } - - private static async Task DownloadYtdl(GitHubRelease json) - { - if (File.Exists(YtdlPath) && File.GetAttributes(YtdlPath).HasFlag(FileAttributes.ReadOnly)) - { - Log.Warning("Skipping yt-dlp download because location is unwritable."); - return; - } - - string assetName; - if (OperatingSystem.IsWindows()) - { - assetName = "yt-dlp.exe"; - } - else if (OperatingSystem.IsLinux()) - { - assetName = RuntimeInformation.OSArchitecture switch - { - Architecture.X64 => "yt-dlp_linux", - Architecture.Arm64 => "yt-dlp_linux_aarch64", - _ => throw new Exception($"Unsupported architecture {RuntimeInformation.OSArchitecture}"), - }; - } - else - { - throw new Exception($"Unsupported operating system {Environment.OSVersion}"); - } - - foreach (var assetVersion in json.assets) - { - if (assetVersion.name != assetName) - continue; - - await using var stream = await DownloadHttpClient.GetStreamAsync(assetVersion.browser_download_url); - if (string.IsNullOrEmpty(Program.UtilsPath)) - throw new Exception("Failed to get YT-DLP path"); - - // Ensure directory exists - var ytdlDir = Path.GetDirectoryName(YtdlPath); - if (!string.IsNullOrEmpty(ytdlDir)) - Directory.CreateDirectory(ytdlDir); - - await using var fileStream = new FileStream(YtdlPath, FileMode.Create, FileAccess.Write, FileShare.None); - await stream.CopyToAsync(fileStream); - Log.Information("Downloaded YT-DLP."); - FileTools.MarkFileExecutable(YtdlPath); - Versions.CurrentVersion.Ytdlp = json.tag_name; - Versions.Save(); - return; - } - throw new Exception("Failed to download YT-DLP"); - } - - private static async Task CheckIfProcessStarts(string path, string arg = "--version") - { - var processName = Path.GetFileNameWithoutExtension(path); - try - { - using var process = new System.Diagnostics.Process(); - process.StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = path, - Arguments = arg, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true - }; - process.Start(); - var output = await process.StandardOutput.ReadToEndAsync(); - var error = await process.StandardError.ReadToEndAsync(); - await process.WaitForExitAsync(); - if (process.ExitCode != 0) - { - Log.Error("Error starting {ProcessName}: {Output} {Error}", processName, output, error); - return false; - } - } - catch (Exception ex) - { - Log.Error("Exception while starting {ProcessName}: {Message}", processName, ex.Message); - return false; - } - return true; - } +using System.Diagnostics; +using System.Runtime.InteropServices; +using Serilog; +using SharpCompress.Readers; +using VRCVideoCacher.Models; +using VRCVideoCacher.Services; +using VRCVideoCacher.Utils; + +namespace VRCVideoCacher.YTDL; + +public class YtdlManager +{ + private static readonly ILogger Log = Program.Logger.ForContext(); + private static readonly HttpClient HttpClient = new() + { + DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } } + }; + private static readonly HttpClient DownloadHttpClient = new() + { + DefaultRequestHeaders = { { "User-Agent", "VRCVideoCacher" } }, + Timeout = TimeSpan.FromMinutes(10) + }; + public static readonly string CookiesPath; + + public static readonly string YtdlPath = + Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "yt-dlp.exe" : "yt-dlp"); + public static readonly string DenoPath = + Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "deno.exe" : "deno"); + public static readonly string FfmpegPath = + Path.Join(Program.UtilsPath, OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"); + private const string YtdlpApiUrl = "https://api.github.com/repos/yt-dlp/yt-dlp-nightly-builds/releases/latest"; + private const string FfmpegNightlyApiUrl = "https://api.github.com/repos/yt-dlp/FFmpeg-Builds/releases/latest"; + private const string FfmpegApiUrl = "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest"; + private const string DenoApiUrl = "https://api.github.com/repos/denoland/deno/releases/latest"; + private const string DenoFallBackVersionURL = "https://dl.deno.land/release-latest.txt"; + private const string DenoFallBackDownloadURL = "https://dl.deno.land/release/"; + + // Guards the "Deno missing" error so it is reported on transition, not per invocation. + private static int _denoMissingReported; + + + static YtdlManager() + { + CookiesPath = Path.Join(Program.DataPath, "youtube_cookies.txt"); + + // try to locate in PATH + if (LaunchArgs.UseGlobalPath) + { + YtdlPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "yt-dlp.exe" : "yt-dlp") ?? + throw new FileNotFoundException("Unable to find yt-dlp"); + DenoPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "deno.exe" : "deno") ?? + throw new FileNotFoundException("Unable to find Deno runtime"); + FfmpegPath = FileTools.LocateFile(OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg") ?? + string.Empty; + } + + Log.Debug("Using ytdl path: {YtdlPath}", YtdlPath); + } + + /// + /// Downloads an archive to a temporary file and verifies its GitHub digest before the + /// caller extracts it. Returns null when the download or the check fails. + /// + /// Buffering to disk first is the point: the archive contents get marked executable and + /// run, so they have to be verified before extraction rather than streamed straight out + /// of the socket into the utils directory. + /// + private static async Task DownloadArchiveAsync(string url, string? digest, string label) + { + var tempPath = Path.Join(Program.UtilsPath, $"_{label}.download"); + try + { + using var response = await DownloadHttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); + if (!response.IsSuccessStatusCode) + { + Log.Warning("{Label}: download failed with {StatusCode}.", label, response.StatusCode); + return null; + } + + await using (var responseStream = await response.Content.ReadAsStreamAsync()) + await using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + await responseStream.CopyToAsync(fileStream); + } + + if (await FileHash.VerifyGitHubDigestAsync(tempPath, digest, label)) + return tempPath; + } + catch + { + TryDeleteTemp(tempPath); + throw; + } + + TryDeleteTemp(tempPath); + return null; + } + + private static void TryDeleteTemp(string path) + { + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (Exception ex) + { + Log.Debug("Could not remove temporary download {Path}: {Error}", path, ex.Message); + } + } + + /// + /// Resolves an archive entry to a destination inside , + /// flattening any directory component and refusing anything that still escapes. + /// + /// Entry names come from a remote archive, and joining one straight onto a destination + /// directory is the classic zip-slip: an entry called "../../something" writes wherever + /// the process can reach. Returns null when the entry should be skipped. + /// + private static string? ResolveUtilsDestination(string entryKey) + { + var fileName = Path.GetFileName(entryKey); + if (string.IsNullOrEmpty(fileName)) + return null; + + var utilsRoot = Path.GetFullPath(Program.UtilsPath); + var destination = Path.GetFullPath(Path.Join(utilsRoot, fileName)); + + // GetFileName already strips directories; this also catches an entry literally + // named "..", which would otherwise resolve to the parent directory. + if (!destination.StartsWith(utilsRoot + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { + Log.Warning("Rejecting archive entry {Entry}: resolves outside {UtilsPath}.", entryKey, utilsRoot); + return null; + } + + return destination; + } + + /// + /// Builds the complete yt-dlp argument list. Every element is exactly one argv entry + /// and must NOT be pre-quoted — the result goes to ProcessStartInfo.ArgumentList, which + /// applies the correct platform quoting itself. + /// + /// This used to return a single concatenated command line with hand-written quotes, + /// which made the URL's own quoting the caller's problem. Exactly one call site escaped + /// it (a lone Replace("\"", "%22") in ApiController), so a URL arriving by any other + /// route — the pre-cache list, playlist expansion, the UI — could close the quote and + /// append flags of its own. yt-dlp has --exec, so that is arbitrary code execution. + /// + public static List GenerateYtdlArgs(List args, IEnumerable trailingArgs, bool includeCookies = true) + { + args.AddRange([ + "--encoding", "utf-8", + "--ignore-config", + "--no-playlist", + "--no-warnings", + "--no-mtime", + "--no-progress" + ]); + + if (File.Exists(FfmpegPath)) + { + args.Add("--ffmpeg-location"); + args.Add(FfmpegPath); + } + + if (File.Exists(DenoPath)) + { + args.Add("--js-runtimes"); + args.Add($"deno:{DenoPath}"); + Interlocked.Exchange(ref _denoMissingReported, 0); + } + else if (Interlocked.Exchange(ref _denoMissingReported, 1) == 0) + { + // Reported once per transition to missing, not once per invocation. This method + // runs for every single video request, and an error-level log raises a modal + // dialog — which, mid-session in VR, is not a small thing to do repeatedly. + Log.Error("Deno runtime not found at path: {DenoPath}", DenoPath); + } + + if (includeCookies && Program.IsCookiesEnabledAndValid()) + { + args.Add("--cookies"); + args.Add(CookiesPath); + } + + args.AddRange(SplitArguments(ConfigManager.Config.YtdlpAdditionalArgs)); + args.AddRange(trailingArgs); + return args; + } + + /// + /// Splits the user's free-form "additional arguments" setting into individual argv + /// entries, honouring double and single quotes the way a shell would. The setting is a + /// single config string, but ArgumentList needs one token per element — appending it + /// whole would pass e.g. `--retries 3` as one argument named "--retries 3". + /// + internal static List SplitArguments(string? value) + { + var result = new List(); + if (string.IsNullOrWhiteSpace(value)) + return result; + + var current = new System.Text.StringBuilder(); + var quote = '\0'; + var hasToken = false; + + foreach (var c in value) + { + if (quote != '\0') + { + if (c == quote) + quote = '\0'; + else + current.Append(c); + continue; + } + + switch (c) + { + case '"': + case '\'': + quote = c; + hasToken = true; + break; + case ' ': + case '\t': + if (hasToken) + { + result.Add(current.ToString()); + current.Clear(); + hasToken = false; + } + break; + default: + current.Append(c); + hasToken = true; + break; + } + } + + if (hasToken) + result.Add(current.ToString()); + + return result; + } + + public static void StartYtdlUpdaterThread() + { + Task.Run(YtdlUpdaterTask); + } + + private static async Task YtdlUpdaterTask() + { + var interval = TimeSpan.FromHours(1); + var token = Program.ShutdownToken; + + while (!token.IsCancellationRequested) + { + try + { + await Task.Delay(interval, token); + await TryDownloadYtdlp(); + } + catch (OperationCanceledException) + { + // Shutting down. + return; + } + catch (Exception ex) + { + Log.Warning(ex, "YT-DLP update check failed, will retry next interval."); + } + } + } + + public static async Task TryDownloadYtdlp() + { + if (!Directory.Exists(Program.UtilsPath)) + throw new Exception("Failed to get Utils path"); + + Log.Information("Checking for YT-DLP updates..."); + try + { + using var response = await HttpClient.GetAsync(YtdlpApiUrl); + if (!response.IsSuccessStatusCode) + { + Log.Warning("Failed to check for YT-DLP updates."); + return; + } + var data = await response.Content.ReadAsStringAsync(); + var json = Json.Deserialize(data); + if (json == null) + { + Log.Error("Failed to parse YT-DLP update response."); + return; + } + + var currentYtdlVersion = Versions.CurrentVersion.Ytdlp; + if (!File.Exists(YtdlPath)) + { + currentYtdlVersion = "Not Installed"; + } + else if (!await CheckIfProcessStarts(YtdlPath)) + { + currentYtdlVersion = "Not Working"; + } + else + { + currentYtdlVersion = await GetYtdlpVersionFromBinary() ?? string.Empty; + } + + var latestVersion = json.tag_name; + Log.Information("YT-DLP Current: {Installed} Latest: {Latest}", currentYtdlVersion, latestVersion); + if (string.IsNullOrEmpty(latestVersion)) + { + Log.Warning("Failed to check for YT-DLP updates."); + return; + } + if (currentYtdlVersion == latestVersion) + { + Log.Information("YT-DLP is up to date."); + return; + } + Log.Information("YT-DLP is outdated. Updating..."); + + await DownloadYtdl(json); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + Log.Warning(ex, "YT-DLP update failed due to a network error."); + Log.Information("You can manually place yt-dlp.exe (or yt-dlp on Linux) in: {UtilsPath}", Program.UtilsPath); + } + } + + private static async Task GetYtdlpVersionFromBinary() + { + try + { + var result = await ProcessRunner.RunAsync(new ProcessStartInfo + { + FileName = YtdlPath, + Arguments = "--version" + }); + return result.Output; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to detect yt-dlp version from binary."); + } + return null; + } + + private static async Task GetFfmpegVersionFromBinary() + { + try + { + var result = await ProcessRunner.RunAsync(new ProcessStartInfo + { + FileName = FfmpegPath, + Arguments = "-version" + }); + // Output: "ffmpeg version 7.1.1-full_build-www.gyan.dev ..." + var firstLine = result.Output.Split('\n')[0].Trim(); + var parts = firstLine.Split(' '); + if (parts.Length >= 3 && parts[0] == "ffmpeg" && parts[1] == "version") + return parts[2].Split('-')[0]; // strip "-full_build-..." suffix + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to detect FFmpeg version from binary."); + } + return null; + } + + private static async Task GetDenoVersionFromBinary() + { + try + { + var result = await ProcessRunner.RunAsync(new ProcessStartInfo + { + FileName = DenoPath, + Arguments = "--version" + }); + // Output: "deno 2.8.0\n..." + var firstLine = result.Output.Split('\n')[0].Trim(); + var parts = firstLine.Split(' '); + if (parts.Length >= 2 && parts[0] == "deno") + return $"v{parts[1]}"; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to detect Deno version from binary."); + } + return null; + } + + public static async Task TryDownloadDeno() + { + if (!Directory.Exists(Program.UtilsPath)) + throw new Exception("Failed to get Utils path"); + + try + { + await TryDownloadDenoInner(); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + Log.Warning(ex, "Deno update failed due to a network error."); + Log.Information("You can manually place deno.exe (or deno on Linux) in: {UtilsPath}", Program.UtilsPath); + } + } + + private static async Task TryDownloadDenoInner() + { + using var apiResponse = await HttpClient.GetAsync(DenoApiUrl); + if (!apiResponse.IsSuccessStatusCode) + { + Log.Warning("Failed to get latest ffmpeg release: {ResponseStatusCode}", apiResponse.StatusCode); + return; + } + var data = await apiResponse.Content.ReadAsStringAsync(); + var json = Json.Deserialize(data); + if (json == null) + { + Log.Error("Failed to parse deno release response."); + return; + } + + var currentDenoVersion = Versions.CurrentVersion.Deno; + if (!File.Exists(DenoPath)) + { + currentDenoVersion = "Not Installed"; + } + else if (!await CheckIfProcessStarts(DenoPath)) + { + currentDenoVersion = "Not Working"; + } + else + { + currentDenoVersion = await GetDenoVersionFromBinary() ?? string.Empty; + } + + var latestVersion = json.tag_name; + Log.Information("Deno Current: {Installed} Latest: {Latest}", currentDenoVersion, latestVersion); + if (string.IsNullOrEmpty(latestVersion)) + { + Log.Warning("Failed to check for Deno updates."); + return; + } + if (currentDenoVersion == latestVersion) + { + Log.Information("Deno is up to date."); + return; + } + Log.Information("Deno is outdated. Updating..."); + + string assetName; + if (OperatingSystem.IsWindows()) + { + assetName = "deno-x86_64-pc-windows-msvc.zip"; + } + else if (OperatingSystem.IsLinux()) + { + switch (RuntimeInformation.OSArchitecture) + { + case Architecture.X64: + assetName = "deno-x86_64-unknown-linux-gnu.zip"; + break; + case Architecture.Arm64: + assetName = "deno-aarch64-unknown-linux-gnu.zip"; + break; + default: + Log.Error("Unsupported architecture {OSArchitecture}", RuntimeInformation.OSArchitecture); + return; + } + } + else + { + Log.Error("Unsupported operating system {OperatingSystem}", Environment.OSVersion); + return; + } + // deno-x86_64-pc-windows-msvc.zip -> deno-x86_64-pc-windows-msvc + var assets = json.assets.Where(asset => asset.name == assetName).ToList(); + if (assets.Count < 1) + { + Log.Error("Unable to find Deno asset {AssetName} for this platform.", assetName); + return; + } + + Log.Information("Downloading Deno..."); + var asset = assets.First(); + + var archivePath = await DownloadArchiveAsync(asset.browser_download_url, asset.digest, "Deno"); + if (archivePath == null) + { + Log.Information("Failed to download deno from github attempting fallback download."); + await TryDownloadDenoFallback(assetName); + return; + } + + await using var responseStream = File.OpenRead(archivePath); + var reader = await ReaderFactory.OpenAsyncReader(responseStream); + try + { + while (await reader.MoveToNextEntryAsync()) + { + if (reader.Entry.Key == null || reader.Entry.IsDirectory) + continue; + + Log.Debug("Extracting file {Name} ({Size} bytes)", reader.Entry.Key, reader.Entry.Size); + var path = ResolveUtilsDestination(reader.Entry.Key); + if (path == null) + continue; + + await using (var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) + await using (var entryStream = await reader.OpenEntryStreamAsync()) + { + await entryStream.CopyToAsync(outputStream); + } + + FileTools.MarkFileExecutable(path); + Versions.CurrentVersion.Deno = json.tag_name; + Versions.Save(); + Log.Information("Deno downloaded and extracted."); + return; + } + } + finally + { + await reader.DisposeAsync(); + await responseStream.DisposeAsync(); + TryDeleteTemp(archivePath); + } + + Log.Error("Failed to extract Deno files."); + } + + private static async Task TryDownloadDenoFallback(string assetName) + { + Log.Warning("Falling back to Deno version check via text file."); + using var response = await HttpClient.GetAsync(DenoFallBackVersionURL); + if (!response.IsSuccessStatusCode) + { + Log.Warning("Failed to get latest Deno version: {ResponseStatusCode}", response.StatusCode); + return; + } + var latestVersion = (await response.Content.ReadAsStringAsync()).Trim(); + var url = $"{DenoFallBackDownloadURL}{latestVersion}/{assetName}"; + + // dl.deno.land publishes no digest, so this path is TLS-only. DownloadArchiveAsync + // logs that fact rather than letting it pass unnoticed. + var archivePath = await DownloadArchiveAsync(url, digest: null, "Deno (fallback)"); + if (archivePath == null) + { + Log.Error("Failed to download Deno from fallback URL."); + return; + } + + await using var responseStream = File.OpenRead(archivePath); + var reader = await ReaderFactory.OpenAsyncReader(responseStream); + try + { + while (await reader.MoveToNextEntryAsync()) + { + if (reader.Entry.Key == null || reader.Entry.IsDirectory) + continue; + + Log.Debug("Extracting file {Name} ({Size} bytes)", reader.Entry.Key, reader.Entry.Size); + var path = ResolveUtilsDestination(reader.Entry.Key); + if (path == null) + continue; + + await using (var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) + await using (var entryStream = await reader.OpenEntryStreamAsync()) + { + await entryStream.CopyToAsync(outputStream); + } + + FileTools.MarkFileExecutable(path); + Versions.CurrentVersion.Deno = latestVersion; + Versions.Save(); + Log.Information("Deno downloaded and extracted."); + return; + } + } + finally + { + await reader.DisposeAsync(); + await responseStream.DisposeAsync(); + TryDeleteTemp(archivePath); + } + + Log.Error("Failed to extract Deno files from fallback download."); + } + + public static async Task TryDownloadFfmpeg() + { + if (!Directory.Exists(Program.UtilsPath)) + throw new Exception("Failed to get Utils path"); + + try + { + await TryDownloadFfmpegInner(); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + Log.Warning(ex, "FFmpeg update failed due to a network error."); + Log.Information("You can manually place ffmpeg.exe (or ffmpeg on Linux) in: {UtilsPath}", Program.UtilsPath); + } + } + + private static async Task TryDownloadFfmpegInner() + { + using var apiResponse = await HttpClient.GetAsync(OperatingSystem.IsWindows() ? FfmpegApiUrl : FfmpegNightlyApiUrl); + if (!apiResponse.IsSuccessStatusCode) + { + Log.Warning("Failed to get latest ffmpeg release: {ResponseStatusCode}", apiResponse.StatusCode); + return; + } + var data = await apiResponse.Content.ReadAsStringAsync(); + var json = Json.Deserialize(data); + if (json == null) + { + Log.Error("Failed to parse ffmpeg release response."); + return; + } + + var currentffmpegVersion = Versions.CurrentVersion.Ffmpeg; + if (!File.Exists(FfmpegPath)) + { + currentffmpegVersion = "Not Installed"; + } + else if (!await CheckIfProcessStarts(FfmpegPath, "-version")) + { + currentffmpegVersion = "Not Working"; + } + else + { + currentffmpegVersion = await GetFfmpegVersionFromBinary() ?? string.Empty; + } + + var latestVersion = OperatingSystem.IsWindows() ? json.tag_name : json.name; + Log.Information("FFmpeg Current: {Installed} Latest: {Latest}", currentffmpegVersion, latestVersion); + if (string.IsNullOrEmpty(latestVersion)) + { + Log.Warning("Failed to check for FFmpeg updates."); + return; + } + if (currentffmpegVersion == latestVersion) + { + Log.Information("FFmpeg is up to date."); + return; + } + Log.Information("FFmpeg is outdated. Updating..."); + + string assetSuffix; + if (OperatingSystem.IsWindows()) + { + assetSuffix = "full_build-shared.zip"; + } + else if (OperatingSystem.IsLinux()) + { + switch (RuntimeInformation.OSArchitecture) + { + case Architecture.X64: + assetSuffix = "master-latest-linux64-gpl.tar.xz"; + break; + case Architecture.Arm64: + assetSuffix = "master-latest-linuxarm64-gpl.tar.xz"; + break; + default: + Log.Error("Unsupported architecture {OSArchitecture}", RuntimeInformation.OSArchitecture); + return; + } + } + else + { + Log.Error("Unsupported operating system {OperatingSystem}", Environment.OSVersion); + return; + } + var asset = json.assets + .FirstOrDefault(assetVersion => assetVersion.name.EndsWith(assetSuffix, StringComparison.OrdinalIgnoreCase)); + if (asset == null || string.IsNullOrEmpty(asset.browser_download_url)) + { + Log.Error("Unable to find ffmpeg asset for this platform."); + return; + } + Log.Information("Downloading FFmpeg..."); + + // Previously streamed straight into the archive reader without even checking the + // status code, so a 404 body was handed to SharpCompress as if it were an archive. + var archivePath = await DownloadArchiveAsync(asset.browser_download_url, asset.digest, "FFmpeg"); + if (archivePath == null) + return; + + await using var responseStream = File.OpenRead(archivePath); + var reader = await ReaderFactory.OpenAsyncReader(responseStream); + var success = false; + try + { + while (await reader.MoveToNextEntryAsync()) + { + if (reader.Entry.Key == null || reader.Entry.IsDirectory) + continue; + + if (!reader.Entry.Key.Contains("/bin/")) + continue; + + Log.Debug("Extracting file {Name} ({Size} bytes)", reader.Entry.Key, reader.Entry.Size); + var path = ResolveUtilsDestination(reader.Entry.Key); + if (path == null) + continue; + + await using (var outputStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) + await using (var entryStream = await reader.OpenEntryStreamAsync()) + { + await entryStream.CopyToAsync(outputStream); + } + + FileTools.MarkFileExecutable(path); + success = true; + } + } + finally + { + await reader.DisposeAsync(); + await responseStream.DisposeAsync(); + TryDeleteTemp(archivePath); + } + + if (!success) + { + Log.Error("Failed to extract ffmpeg files."); + return; + } + + Versions.CurrentVersion.Ffmpeg = latestVersion; + Versions.Save(); + Log.Information("FFmpeg downloaded and extracted."); + } + + private static async Task DownloadYtdl(GitHubRelease json) + { + if (File.Exists(YtdlPath) && File.GetAttributes(YtdlPath).HasFlag(FileAttributes.ReadOnly)) + { + Log.Warning("Skipping yt-dlp download because location is unwritable."); + return; + } + + string assetName; + if (OperatingSystem.IsWindows()) + { + assetName = "yt-dlp.exe"; + } + else if (OperatingSystem.IsLinux()) + { + assetName = RuntimeInformation.OSArchitecture switch + { + Architecture.X64 => "yt-dlp_linux", + Architecture.Arm64 => "yt-dlp_linux_aarch64", + _ => throw new Exception($"Unsupported architecture {RuntimeInformation.OSArchitecture}"), + }; + } + else + { + throw new Exception($"Unsupported operating system {Environment.OSVersion}"); + } + + foreach (var assetVersion in json.assets) + { + if (assetVersion.name != assetName) + continue; + + if (string.IsNullOrEmpty(Program.UtilsPath)) + throw new Exception("Failed to get YT-DLP path"); + + // Ensure directory exists + var ytdlDir = Path.GetDirectoryName(YtdlPath); + if (!string.IsNullOrEmpty(ytdlDir)) + Directory.CreateDirectory(ytdlDir); + + // Stage, verify, then move into place. This binary is marked executable and run + // on every video request, so an unverified body must never occupy the final + // path — not even briefly, and not even if the verification then fails. + var tempPath = YtdlPath + ".download"; + try + { + await using (var stream = await DownloadHttpClient.GetStreamAsync(assetVersion.browser_download_url)) + await using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + await stream.CopyToAsync(fileStream); + } + + if (!await FileHash.VerifyGitHubDigestAsync(tempPath, assetVersion.digest, "yt-dlp")) + throw new Exception("yt-dlp download failed its digest check."); + + File.Move(tempPath, YtdlPath, overwrite: true); + } + finally + { + TryDeleteTemp(tempPath); + } + + Log.Information("Downloaded YT-DLP."); + FileTools.MarkFileExecutable(YtdlPath); + Versions.CurrentVersion.Ytdlp = json.tag_name; + Versions.Save(); + return; + } + throw new Exception("Failed to download YT-DLP"); + } + + private static async Task CheckIfProcessStarts(string path, string arg = "--version") + { + var processName = Path.GetFileNameWithoutExtension(path); + try + { + var (output, error, exitCode) = await ProcessRunner.RunAsync(new ProcessStartInfo + { + FileName = path, + Arguments = arg + }); + if (exitCode != 0) + { + Log.Error("Error starting {ProcessName}: {Output} {Error}", processName, output, error); + return false; + } + } + catch (Exception ex) + { + Log.Error("Exception while starting {ProcessName}: {Message}", processName, ex.Message); + return false; + } + return true; + } } \ No newline at end of file diff --git a/VRCVideoCacher/YTDL/YtdlpProgressParser.cs b/VRCVideoCacher/YTDL/YtdlpProgressParser.cs new file mode 100644 index 00000000..af7caf88 --- /dev/null +++ b/VRCVideoCacher/YTDL/YtdlpProgressParser.cs @@ -0,0 +1,96 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using VRCVideoCacher.Models; + +namespace VRCVideoCacher.YTDL; + +/// +/// Reads yt-dlp's --newline progress output. +/// +/// yt-dlp already computes the transfer rate and the time remaining, and it sees every byte +/// — including the ones we never touch, since it writes the file itself. Taking its numbers +/// is both more accurate and far simpler than re-deriving them from the lines we happen to +/// sample. Lines look like: +/// +/// [download] 0.0% of 12.34MiB at Unknown B/s ETA Unknown +/// [download] 45.2% of ~ 12.34MiB at 1.23MiB/s ETA 00:12 +/// [download] 45.2% of 12.34MiB at 1.23MiB/s ETA 00:12 (frag 10/22) +/// [download] 100% of 12.34MiB in 00:05 +/// +internal static partial class YtdlpProgressParser +{ + [GeneratedRegex(@"(?\d+(?:\.\d+)?)%")] + private static partial Regex PercentPattern(); + + // "Unknown B/s" deliberately does not match: the rate is genuinely not known yet. + [GeneratedRegex(@"\bat\s+(?\d+(?:\.\d+)?)\s*(?[KMGT]?i?B)/s", RegexOptions.IgnoreCase)] + private static partial Regex RatePattern(); + + // Accepts MM:SS and HH:MM:SS. "ETA Unknown" does not match, for the same reason. + [GeneratedRegex(@"\bETA\s+(?(?:\d+:)?\d{1,2}:\d{2})\b")] + private static partial Regex EtaPattern(); + + public static bool TryParse(string line, out DownloadProgress progress) + { + progress = default; + + if (string.IsNullOrEmpty(line)) + return false; + + var percentMatch = PercentPattern().Match(line); + if (!percentMatch.Success || + !double.TryParse(percentMatch.Groups["value"].ValueSpan, NumberStyles.Float, CultureInfo.InvariantCulture, out var percent)) + return false; + + progress = new DownloadProgress(percent, ParseRate(line), ParseEta(line)); + return true; + } + + private static double? ParseRate(string line) + { + var match = RatePattern().Match(line); + if (!match.Success || + !double.TryParse(match.Groups["value"].ValueSpan, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)) + return null; + + // yt-dlp uses binary units (KiB/MiB); treat a bare K/M/G the same way. + var multiplier = match.Groups["unit"].Value.ToUpperInvariant() switch + { + "B" => 1d, + "KB" or "KIB" => 1024d, + "MB" or "MIB" => 1024d * 1024, + "GB" or "GIB" => 1024d * 1024 * 1024, + "TB" or "TIB" => 1024d * 1024 * 1024 * 1024, + _ => 1d + }; + + return value * multiplier; + } + + private static TimeSpan? ParseEta(string line) + { + var match = EtaPattern().Match(line); + if (!match.Success) + return null; + + var parts = match.Groups["eta"].Value.Split(':'); + + // Validate the fields rather than relying on the TimeSpan constructor to reject + // them: it normalises out-of-range values instead of throwing, so a malformed + // "99:99" would silently become 1h40m39s. Showing no estimate beats a wrong one. + var seconds = int.Parse(parts[^1]); + if (seconds >= 60) + return null; + + var minutes = int.Parse(parts[^2]); + if (parts.Length == 3 && minutes >= 60) + return null; + + return parts.Length switch + { + 2 => new TimeSpan(0, minutes, seconds), + 3 => new TimeSpan(int.Parse(parts[0]), minutes, seconds), + _ => null + }; + } +} diff --git a/VRCVideoCacher/manifest.vrmanifest b/VRCVideoCacher/manifest.vrmanifest index 0637336f..874e54d9 100644 --- a/VRCVideoCacher/manifest.vrmanifest +++ b/VRCVideoCacher/manifest.vrmanifest @@ -1,7 +1,7 @@ { "source" : "builtin", "applications" : [{ - "app_key" : "com.github.codeyumx.vrcvideocacherplus", + "app_key" : "com.github.bluscream.vrcvideocacherplusplus", "launch_type" : "binary", "binary_path_windows": "VRCVideoCacher.exe", "binary_path_linux": "VRCVideoCacher", @@ -9,8 +9,8 @@ "is_dashboard_overlay" : true, "strings": { "en_us": { - "name": "VRCVideoCacherPlus", - "description": "Video Player utility for VRC" + "name": "VRCVideoCacherPlusPlus", + "description": "Video Player utility for VRC (PlusPlus fork)" } } }] diff --git a/VRCVideoCacher/yt-dlp-stub.exe b/VRCVideoCacher/yt-dlp-stub.exe index bf93d94a..584933c7 100644 Binary files a/VRCVideoCacher/yt-dlp-stub.exe and b/VRCVideoCacher/yt-dlp-stub.exe differ diff --git a/build.sh b/build.sh new file mode 100755 index 00000000..9b899931 --- /dev/null +++ b/build.sh @@ -0,0 +1,444 @@ +#!/usr/bin/env bash +# Build pipeline for VRCVideoCacher. +# +# Actions are opt-in flags. They always run in the order listed below regardless of the +# order you pass them, because the dependencies only make sense one way round — there is +# no point tagging a release before the thing has been built, or pushing a commit that +# was never linted. Any action that fails aborts the rest immediately, and dotnet is run +# with warnings promoted to errors throughout. +# +# --bump raise the patch component of in VRCVideoCacher.csproj +# --lint locale check, extension check, strict compile, full test suite +# --build publish yt-dlp-stub and VRCVideoCacher for Steam (Linux x64) +# --artifacts build every release asset into dist/: the win-x64 and linux-x64 zips +# and the Chrome .crx and Firefox .xpi (implied by --release) +# --stop stop the deployed app +# --deploy rsync the publish output into the Steam directory +# --start start the deployed app through Steam and tail its log +# --restart --stop and --start together +# --commit commit the working tree (-m MESSAGE, defaults to "Release vX.Y.Z") +# and tag it X.Y.Z when --bump ran +# --push push the current branch and any tag created by --bump +# --release create the GitHub release, attaching all four assets +# +# --all everything except the local-only actions (deploy, stop, start) +# -n|--dry-run print each action instead of running the ones that change the world +# +# Running it with no arguments at all builds and deploys, which is what it always did. +# Passing any flag turns that off, so nothing gets deployed unless you asked for it. +# +# Actions run in this order, which is why --stop sits before --deploy and --start after: +# +# bump lint build artifacts stop deploy start commit push release +# +# GitHub Actions does not run on this account, so .github/workflows/ci.yml is disabled +# and its work happens here instead: --lint is the build-and-test and browser-extension +# jobs, --artifacts is the publish job. Running the workflow locally under `act` was the +# alternative and is not worth it — it wants a container runtime and a runner image to +# do what is, in the end, two dotnet publishes. +# +# Everything machine-specific is an environment variable with the author's setup as the +# default, so this is overridable rather than only working on one machine: +# +# VVC_TARGET_DIR where to deploy (default: the Steam common dir below) +# VVC_CONTAINER distrobox container (default: arch; set empty to use the host dotnet) +# VVC_TRIMMED 1 to publish trimmed (default: 0, see note further down) +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +TARGET_DIR="${VVC_TARGET_DIR:-/run/media/system/Data/Games/Steam/steamapps/common/VRCVideoCacher}" +CONTAINER_NAME="${VVC_CONTAINER-arch}" +TRIMMED="${VVC_TRIMMED:-0}" +TMP_OUT="${SCRIPT_DIR}/output_steam_linux" +DIST_DIR="${SCRIPT_DIR}/dist" +STEAM_APP_ID=4296960 +CSPROJ="${SCRIPT_DIR}/VRCVideoCacher/VRCVideoCacher.csproj" + +DO_BUMP=false +DO_LINT=false +DO_BUILD=false +DO_ARTIFACTS=false +DO_STOP=false +DO_DEPLOY=false +DO_START=false +DO_COMMIT=false +DO_PUSH=false +DO_RELEASE=false +DRY_RUN=false +COMMIT_MESSAGE="" +ARG_COUNT=$# + +while [ $# -gt 0 ]; do + case "$1" in + --bump) DO_BUMP=true ;; + --lint) DO_LINT=true ;; + --build) DO_BUILD=true ;; + --artifacts) DO_ARTIFACTS=true ;; + --stop) DO_STOP=true ;; + --deploy) DO_DEPLOY=true ;; + --start) DO_START=true ;; + --restart) DO_STOP=true; DO_START=true ;; + --commit) DO_COMMIT=true ;; + --push) DO_PUSH=true ;; + # A release is only ever the complete set of assets, so it builds them itself + # rather than trusting whatever happens to be left in dist/ from an older run. + --release) DO_RELEASE=true; DO_ARTIFACTS=true ;; + --all) + DO_BUMP=true; DO_LINT=true; DO_BUILD=true; DO_ARTIFACTS=true + DO_COMMIT=true; DO_PUSH=true; DO_RELEASE=true + ;; + -n|--dry-run) DRY_RUN=true ;; + -m|--message) + [ $# -ge 2 ] || { echo "error: $1 needs a message" >&2; exit 2; } + COMMIT_MESSAGE="$2"; shift + ;; + -m=*|--message=*) COMMIT_MESSAGE="${1#*=}" ;; + -h|--help) sed -n '2,45p' "$0" | sed 's/^# \?//'; exit 0 ;; + *) echo "Unknown argument: $1" >&2; exit 2 ;; + esac + shift +done + +# Backwards compatibility: bare ./build.sh is a deploy. Keyed on there being no arguments +# at all rather than on "no action flags selected", so that a flag which selects no action +# can never fall through to here and deploy something nobody asked to deploy. +if [ "$ARG_COUNT" -eq 0 ]; then + DO_BUILD=true + DO_DEPLOY=true +fi + +step() { echo; echo "=== $* ==="; } +fail() { echo "error: $*" >&2; exit 1; } + +# Guards a command that changes something outside this working tree. +run() { + if [ "$DRY_RUN" = true ]; then + echo "[dry-run] $*" + return 0 + fi + "$@" +} + +# Run dotnet inside the container when one is configured, otherwise straight on the host. +dotnet_run() { + if [ -n "${CONTAINER_NAME}" ]; then + distrobox enter "${CONTAINER_NAME}" -- dotnet "$@" + else + dotnet "$@" + fi +} + +read_version() { + sed -n 's:.*\(.*\).*:\1:p' "$CSPROJ" | head -n 1 +} + +VERSION="$(read_version)" +[ -n "$VERSION" ] || fail "could not read from ${CSPROJ}" + +# yt-dlp-stub.exe rebuilds non-deterministically: identical content, different bytes. Left +# alone it lands in every release commit as meaningless churn. Recorded here so it can be +# restored before committing — but only when it was already clean, so a genuine change to +# the stub is never silently discarded. +STUB="VRCVideoCacher/yt-dlp-stub.exe" +STUB_WAS_CLEAN=false +git -C "$SCRIPT_DIR" diff --quiet -- "$STUB" 2>/dev/null && STUB_WAS_CLEAN=true + +# A release is always the same four files. Checked as a set rather than trusted, +# because the .crx silently does not get built when npx is unavailable — which would +# otherwise produce a release quietly missing the Chrome download. +RELEASE_ASSETS=() +require_assets() { + local missing=0 + local found + RELEASE_ASSETS=() + for pattern in \ + "VRCVideoCacher-win-x64.zip" \ + "VRCVideoCacher-linux-x64.zip" \ + "VRCVideoCacherPlusPlus-chrome-*.crx" \ + "VRCVideoCacherPlusPlus-firefox-*.xpi" + do + found=$(find "${DIST_DIR}" -maxdepth 1 -name "$pattern" -print -quit 2>/dev/null || true) + if [ -z "$found" ]; then + printf ' MISSING %s\n' "$pattern" >&2 + missing=1 + else + RELEASE_ASSETS+=("$found") + printf ' %-6s %s\n' "$(du -h "$found" | cut -f1)" "$(basename "$found")" + fi + done + [ "$missing" -eq 0 ] || fail "dist/ is missing release assets" +} + +require_clean_tree() { + git -C "$SCRIPT_DIR" diff --quiet && git -C "$SCRIPT_DIR" diff --cached --quiet \ + || fail "working tree is dirty; commit or stash first" +} + +# --- bump ------------------------------------------------------------------------------- +# Versioning is YEAR.MONTH.RELEASE, so rolling into a new month restarts the counter +# rather than carrying the old month's patch number forward. +if [ "$DO_BUMP" = true ]; then + step "Bumping version (currently ${VERSION})" + + IFS='.' read -r OLD_YEAR OLD_MONTH OLD_PATCH <<< "$VERSION" + NOW_YEAR="$(date +%Y)" + NOW_MONTH="$(date +%-m)" + + if [ "$OLD_YEAR" = "$NOW_YEAR" ] && [ "$OLD_MONTH" = "$NOW_MONTH" ]; then + NEW_VERSION="${NOW_YEAR}.${NOW_MONTH}.$((OLD_PATCH + 1))" + else + NEW_VERSION="${NOW_YEAR}.${NOW_MONTH}.0" + fi + + if [ "$DRY_RUN" = true ]; then + echo "[dry-run] ${VERSION} -> ${NEW_VERSION}" + else + # Anchored on the exact old value so this cannot touch a PackageReference Version. + sed -i "s:${VERSION}:${NEW_VERSION}:" "$CSPROJ" + [ "$(read_version)" = "$NEW_VERSION" ] || fail "version bump did not apply" + echo "${VERSION} -> ${NEW_VERSION}" + fi + VERSION="$NEW_VERSION" +fi + +# Tags in this repo are bare versions (2026.8.21), while release *titles* carry the v +# (v2026.8.21). Keep both conventions — tagging v2026.8.22 next to 2026.8.21 would split +# the history in two and break `releases/latest` ordering. +TAG="${VERSION}" +RELEASE_TITLE="v${VERSION}" + +# --- lint ------------------------------------------------------------------------------- +if [ "$DO_LINT" = true ]; then + step "Checking locales" + python3 "${SCRIPT_DIR}/scripts/lint-locales.py" || fail "locale check failed" + + step "Checking browser extension" + "${SCRIPT_DIR}/BrowserExtension/build.sh" --check || fail "browser extension check failed" + + step "Compiling with warnings as errors" + dotnet_run build "${SCRIPT_DIR}/VRCVideoCacher.sln" -c Release -warnaserror \ + || fail "build produced warnings or errors" + + step "Running tests" + dotnet_run test "${SCRIPT_DIR}/VRCVideoCacher.Tests/VRCVideoCacher.Tests.csproj" -c Release \ + || fail "tests failed" +fi + +# --- build ------------------------------------------------------------------------------ +if [ "$DO_BUILD" = true ]; then + step "Building yt-dlp-stub" + dotnet_run publish "${SCRIPT_DIR}/yt-dlp-stub/yt-dlp-stub.csproj" -c Release -r win-x64 -warnaserror + cp "${SCRIPT_DIR}/yt-dlp-stub/bin/Release/net10.0/win-x64/publish/yt-dlp-stub.exe" "${SCRIPT_DIR}/VRCVideoCacher/" + + # Deploying loose files rather than a single trimmed binary keeps local iteration fast + # and makes stack traces readable. It does mean this path does not exercise trimming — + # CI's publish job does that, and VVC_TRIMMED=1 reproduces it here when you need to. + step "Building VRCVideoCacher for Steam (Linux x64, trimmed=${TRIMMED}, v${VERSION})" + rm -rf "${TMP_OUT}" + dotnet_run publish "$CSPROJ" \ + -c SteamRelease \ + -r linux-x64 \ + -o "${TMP_OUT}" \ + --self-contained true \ + -warnaserror \ + -p:PublishSingleFile=false \ + -p:PublishTrimmed="$([ "${TRIMMED}" = "1" ] && echo true || echo false)" +fi + +# --- artifacts -------------------------------------------------------------------------- +# The publish job from ci.yml, run here because Actions does not run on this account. +# Worth keeping distinct from --build: this is Release, trimmed and single-file per the +# csproj, which is the only configuration that exercises the trimmer. A Debug or loose +# build cannot reproduce the trimmer removing something only reflection reaches. +if [ "$DO_ARTIFACTS" = true ]; then + command -v zip >/dev/null || fail "zip is not installed; cannot package artifacts" + + rm -rf "${DIST_DIR}" + mkdir -p "${DIST_DIR}" + + step "Packaging browser extensions" + # Also re-runs the shared-file drift check, so this cannot ship a chrome/ and a + # firefox/ that have silently diverged. + "${SCRIPT_DIR}/BrowserExtension/build.sh" || fail "packaging the browser extensions failed" + + for RID in win-x64 linux-x64; do + step "Publishing ${RID} (Release, trimmed, v${VERSION})" + OUT="${SCRIPT_DIR}/out/${RID}" + rm -rf "${OUT}" + dotnet_run publish "$CSPROJ" -c Release -r "${RID}" -o "${OUT}" -warnaserror \ + || fail "publishing ${RID} failed" + + ZIP="${DIST_DIR}/VRCVideoCacher-${RID}.zip" + (cd "${OUT}" && zip -qr "${ZIP}" .) || fail "packaging ${RID} failed" + done + + step "Release assets" + require_assets +fi + +# --- stop ------------------------------------------------------------------------------- +if [ "$DO_STOP" = true ]; then + step "Stopping VRCVideoCacher" + # Match the deployed binary by full path. A bare `pkill -f VRCVideoCacher` also matches + # this script, an editor with the project open, or a shell sitting in the source tree. + if [ "$DRY_RUN" = true ]; then + # Not just `run pkill`: the wait-and-verify below would then poll a process that + # was never signalled and report a failure to stop something nobody stopped. + echo "[dry-run] pkill -f ^${TARGET_DIR}/VRCVideoCacher" + elif pgrep -f "^${TARGET_DIR}/VRCVideoCacher" >/dev/null; then + # SIGTERM first so the shutdown token fires and the loops unwind; SIGKILL only if + # it is still there afterwards. + pkill -f "^${TARGET_DIR}/VRCVideoCacher" || true + for _ in $(seq 1 10); do + pgrep -f "^${TARGET_DIR}/VRCVideoCacher" >/dev/null || break + sleep 1 + done + if pgrep -f "^${TARGET_DIR}/VRCVideoCacher" >/dev/null; then + echo "Still running after 10s, sending SIGKILL." + pkill -9 -f "^${TARGET_DIR}/VRCVideoCacher" || true + sleep 1 + fi + pgrep -f "^${TARGET_DIR}/VRCVideoCacher" >/dev/null \ + && fail "could not stop VRCVideoCacher" || echo "Stopped." + else + echo "Not running." + fi +fi + +# --- deploy ----------------------------------------------------------------------------- +if [ "$DO_DEPLOY" = true ]; then + [ -d "${TMP_OUT}" ] || fail "nothing to deploy: ${TMP_OUT} does not exist (run --build)" + + step "Deploying to ${TARGET_DIR}" + run mkdir -p "${TARGET_DIR}" + run rsync -av --delete --exclude='CachedAssets' --exclude='logs' "${TMP_OUT}/" "${TARGET_DIR}/" + echo "=== Deployment Complete ===" +fi + +# --- start ------------------------------------------------------------------------------ +if [ "$DO_START" = true ]; then + step "Starting VRCVideoCacher" + if [ "$DRY_RUN" = true ]; then + echo "[dry-run] steam steam://rungameid/${STEAM_APP_ID}" + else + (nohup steam "steam://rungameid/${STEAM_APP_ID}" >/dev/null 2>&1 \ + || nohup xdg-open "steam://rungameid/${STEAM_APP_ID}" >/dev/null 2>&1 &) + + # Steam takes its time, and how long varies. Poll rather than sleeping a fixed + # five seconds and declaring failure — that reported a crash on every slow launch. + for _ in $(seq 1 30); do + pgrep -f "^${TARGET_DIR}/VRCVideoCacher" >/dev/null && break + sleep 1 + done + + PIDS=$(pgrep -f "^${TARGET_DIR}/VRCVideoCacher" || true) + if [ -z "${PIDS}" ]; then + CRASH_REPORT="${XDG_CONFIG_HOME:-${HOME}/.config}/VRCVideoCacher/CRASH_REPORT.txt" + if [ -f "${CRASH_REPORT}" ]; then + step "CRASH_REPORT.txt (check the timestamp — it may predate this run)" + cat "${CRASH_REPORT}" + fi + fail "VRCVideoCacher did not start within 30s" + fi + + echo "Running (PIDs: ${PIDS})" + sleep 3 + LOG_DIR="${XDG_CONFIG_HOME:-${HOME}/.config}/VRCVideoCacher/Logs" + LOG_FILE=$(ls -t "${LOG_DIR}"/VRCVideoCacher*.log 2>/dev/null | head -n 1 || true) + if [ -n "${LOG_FILE}" ] && [ -f "${LOG_FILE}" ]; then + step "Last 25 log lines (${LOG_FILE})" + tail -n 25 "${LOG_FILE}" + fi + fi +fi + +# --- commit ----------------------------------------------------------------------------- +if [ "$DO_COMMIT" = true ]; then + step "Committing" + if [ "$STUB_WAS_CLEAN" = true ] && ! git -C "$SCRIPT_DIR" diff --quiet -- "$STUB"; then + echo "Discarding rebuilt ${STUB} (byte churn, no content change)." + run git -C "$SCRIPT_DIR" checkout -- "$STUB" + fi + + if git -C "$SCRIPT_DIR" diff --quiet && git -C "$SCRIPT_DIR" diff --cached --quiet; then + echo "Nothing to commit." + else + MESSAGE="${COMMIT_MESSAGE:-Release ${RELEASE_TITLE}}" + run git -C "$SCRIPT_DIR" add -A + run git -C "$SCRIPT_DIR" commit -m "$MESSAGE" || fail "commit failed" + fi + + if [ "$DO_BUMP" = true ]; then + if git -C "$SCRIPT_DIR" rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then + echo "Tag ${TAG} already exists, leaving it alone." + else + run git -C "$SCRIPT_DIR" tag -a "$TAG" -m "$TAG" || fail "could not create tag ${TAG}" + fi + fi +fi + +# --- push ------------------------------------------------------------------------------- +if [ "$DO_PUSH" = true ]; then + step "Pushing" + # Uncommitted work would be silently left behind by a push that appears to succeed. + [ "$DRY_RUN" = true ] || require_clean_tree + BRANCH="$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD)" + run git -C "$SCRIPT_DIR" push origin "$BRANCH" || fail "push failed" + if git -C "$SCRIPT_DIR" rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then + run git -C "$SCRIPT_DIR" push origin "$TAG" || fail "pushing tag ${TAG} failed" + fi +fi + +# --- release ---------------------------------------------------------------------------- +if [ "$DO_RELEASE" = true ]; then + step "Creating GitHub release ${TAG}" + command -v gh >/dev/null || fail "gh is not installed; cannot create a release" + + # `gh release create` creates a draft, uploads, then publishes. Interrupted partway — + # a 100MB upload is not quick — it leaves a draft behind, and a plain "already exists" + # check then blocks every retry with nothing to do about it. Resume instead. + RESUME_DRAFT=false + if gh release view "$TAG" >/dev/null 2>&1; then + if [ "$(gh release view "$TAG" --json isDraft -q .isDraft)" = "true" ]; then + echo "Found an unfinished draft for ${TAG}; resuming it." + RESUME_DRAFT=true + else + fail "release ${TAG} already exists and is published" + fi + fi + + # The tag has to be on the remote first or gh will create one from whatever the + # default branch happens to point at. + if [ "$DRY_RUN" = false ] && ! git -C "$SCRIPT_DIR" ls-remote --exit-code --tags origin "$TAG" >/dev/null 2>&1; then + fail "tag ${TAG} is not on origin; run --push first" + fi + + # Attaching the assets is the whole point now that no CI job uploads them. + # Exactly the four named assets. A glob over dist/ would also sweep up the + # extension .zip byproducts the .crx and .xpi are made from, and a release listing + # six downloads where two are duplicates of the other two is just confusing. + require_assets + + if [ "$RESUME_DRAFT" = true ]; then + # --clobber so a half-finished asset from the interrupted run is replaced. + run gh release upload "$TAG" --clobber "${RELEASE_ASSETS[@]}" \ + || fail "uploading the release assets failed" + run gh release edit "$TAG" --draft=false \ + || fail "publishing the draft failed" + else + run gh release create "$TAG" \ + --title "$RELEASE_TITLE" \ + --generate-notes \ + "${RELEASE_ASSETS[@]}" \ + || fail "creating the release failed" + fi + + # gh exits before GitHub finishes processing large uploads, and an asset stuck in + # "starting" is a broken download link on a published release. + if [ "$DRY_RUN" = false ]; then + UPLOADED=$(gh release view "$TAG" --json assets -q '[.assets[]|select(.state=="uploaded")]|length') + [ "$UPLOADED" = "${#RELEASE_ASSETS[@]}" ] \ + || fail "only ${UPLOADED}/${#RELEASE_ASSETS[@]} assets finished uploading" + echo "Published ${TAG} with ${UPLOADED} assets." + fi +fi diff --git a/docs/screenshots/cookie-refresh.png b/docs/screenshots/cookie-refresh.png deleted file mode 100644 index ee61bc9c..00000000 Binary files a/docs/screenshots/cookie-refresh.png and /dev/null differ diff --git a/docs/screenshots/download-settings.png b/docs/screenshots/download-settings.png deleted file mode 100644 index 8078a2ee..00000000 Binary files a/docs/screenshots/download-settings.png and /dev/null differ diff --git a/docs/screenshots/main-info.png b/docs/screenshots/main-info.png deleted file mode 100644 index 7e464273..00000000 Binary files a/docs/screenshots/main-info.png and /dev/null differ diff --git a/scripts/lint-locales.py b/scripts/lint-locales.py new file mode 100755 index 00000000..4bb63601 --- /dev/null +++ b/scripts/lint-locales.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +""" +Locale linter for VRCVideoCacher/Languages/*.loc.json. + +English is the fallback, which is exactly why translation problems are invisible at +runtime: a missing key silently renders the English string, an empty one silently +renders nothing at all, and a key nobody references any more just sits there being +translated into eight languages forever. This turns all of that into a build failure. + +Checks, all fatal: + + missing a key en.loc.json has that a translation does not + unexpected a key a translation has that en.loc.json does not + empty a value that is empty or only whitespace + untranslated a value byte-identical to the English one. Two escape hatches, kept + apart on purpose: + locale-allow-identical.txt intentional — proper nouns, brand names, + anything that is the same word everywhere + locale-untranslated.txt known debt, listed as lang:Key. This file + is meant to shrink; the linter fails if an + entry is stale so finishing a translation + forces the line to be deleted. + unused a key defined in English that no .cs or .axaml file references + +Written in Python rather than bash because every one of these needs real JSON +parsing, and `jq` is not something the build can assume is installed. + + scripts/lint-locales.py report and exit non-zero on any problem + scripts/lint-locales.py --list-identical print keys that are identical to English, + in allowlist format, and exit 0 +""" + +import json +import pathlib +import re +import sys + +ROOT = pathlib.Path(__file__).resolve().parent.parent +LANG_DIR = ROOT / "VRCVideoCacher" / "Languages" +ALLOW_IDENTICAL = ROOT / "scripts" / "locale-allow-identical.txt" +UNTRANSLATED_BASELINE = ROOT / "scripts" / "locale-untranslated.txt" +SOURCE_DIRS = [ROOT / "VRCVideoCacher"] + +# Deliberately looser than Localizer.Get("Key"): keys are routinely produced in one +# place and resolved in another — VideoDownloader returns a bare "SkipReasonBotCheck", +# and VideoId builds "SkipReasonTooLong|{0:F0}|{1}" — so a precise pattern reports all +# of those as dead. A whole-word search over the source text is used instead. It errs +# towards calling a key used, which is the right direction: an unused-key report that +# cannot be trusted is worse than one that occasionally misses something. +def is_referenced(key, text): + return re.search(rf"\b{re.escape(key)}\b", text) is not None + + +def load(path): + with path.open(encoding="utf-8") as handle: + return json.load(handle) + + +def load_list(path): + if not path.exists(): + return set() + entries = set() + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.split("#", 1)[0].strip() + if line: + entries.add(line) + return entries + + +def referenced_keys(keys): + """The subset of `keys` mentioned anywhere in the source tree.""" + remaining = set(keys) + found = set() + for source_dir in SOURCE_DIRS: + for pattern in ("**/*.cs", "**/*.axaml"): + for path in source_dir.glob(pattern): + if not remaining: + return found + as_posix = path.as_posix() + if "/obj/" in as_posix or "/bin/" in as_posix: + continue + text = path.read_text(encoding="utf-8", errors="replace") + hits = {key for key in remaining if is_referenced(key, text)} + found |= hits + remaining -= hits + return found + + +def main(): + english_path = LANG_DIR / "en.loc.json" + english = load(english_path) + translations = sorted(p for p in LANG_DIR.glob("*.loc.json") if p != english_path) + + def language_of(path): + return path.name.removesuffix(".loc.json") + + if "--list-identical" in sys.argv: + for path in translations: + data = load(path) + for key in sorted(k for k, v in data.items() if k in english and v == english[k]): + print(f"{language_of(path)}:{key}") + return 0 + + allow_identical = load_list(ALLOW_IDENTICAL) + baseline = load_list(UNTRANSLATED_BASELINE) + still_identical = set() + problems = [] + + def report(path, kind, detail): + problems.append(f"{path.relative_to(ROOT)}: {kind}: {detail}") + + for key, value in english.items(): + if not str(value).strip(): + report(english_path, "empty", key) + + used = referenced_keys(english) + for key in sorted(set(english) - used): + report(english_path, "unused", f"{key} is not referenced by any .cs or .axaml file") + + for path in translations: + data = load(path) + + for key in sorted(set(english) - set(data)): + report(path, "missing", key) + for key in sorted(set(data) - set(english)): + report(path, "unexpected", f"{key} is not defined in en.loc.json") + + for key, value in data.items(): + if not str(value).strip(): + report(path, "empty", key) + elif key in english and value == english[key] and key not in allow_identical: + entry = f"{language_of(path)}:{key}" + still_identical.add(entry) + if entry not in baseline: + report(path, "untranslated", f'{key} is identical to English ("{value}")') + + for stale in sorted(baseline - still_identical): + report( + UNTRANSLATED_BASELINE, + "stale", + f"{stale} is translated now (or gone) — delete this line", + ) + + if problems: + print(f"Locale check FAILED with {len(problems)} problem(s):\n", file=sys.stderr) + for problem in problems: + print(f" {problem}", file=sys.stderr) + print( + "\nA value that is legitimately the same in every language (a proper noun, a" + "\nunit, a command name) belongs in scripts/locale-allow-identical.txt." + "\nA translation that is simply not written yet belongs in" + "\nscripts/locale-untranslated.txt as lang:Key — run --list-identical to" + "\nregenerate that list.", + file=sys.stderr, + ) + return 1 + + print(f"Locale check passed: {len(english)} keys across {len(translations) + 1} languages.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/locale-allow-identical.txt b/scripts/locale-allow-identical.txt new file mode 100644 index 00000000..6b0b95cf --- /dev/null +++ b/scripts/locale-allow-identical.txt @@ -0,0 +1,10 @@ +# Keys whose value is legitimately identical to English in every language. +# Brand names, product names and borrowed technical terms. The linter will not +# report these as untranslated. +# +# This is not the place for a translation that simply has not been written yet — +# that goes in locale-untranslated.txt, which is meant to shrink over time. + +Chrome +Firefox +VRCVideoCacherPlus diff --git a/scripts/locale-untranslated.txt b/scripts/locale-untranslated.txt new file mode 100644 index 00000000..d77d0934 --- /dev/null +++ b/scripts/locale-untranslated.txt @@ -0,0 +1,64 @@ +# Known translation debt: values still identical to English, as lang:Key. +# +# Generated with: scripts/lint-locales.py --list-identical +# +# This file exists so the build fails on *new* untranslated strings without being +# blocked by the ones already here. It is meant to shrink, never grow: translate a +# string, delete its line. The linter fails on a stale entry, so finishing a +# translation forces the line to go. + +it:Cache +it:CacheDownloadIdleSeconds +it:CacheDownloadIdleSecondsTooltip +it:CacheDownloadRateLimit +it:CacheDownloadRateLimitTooltip +it:CacheHlsPlaylists +it:ConfirmClearCacheFormat +it:ConfirmClearCacheTitle +it:CookiesDisabledWarning +it:CookiesHelpBeta +it:CookiesHelpLegacy +it:CookiesRefreshHeader +it:CookiesRequestRefresh +it:CookiesRequestRefreshTooltip +it:CookiesStatusDisabled +it:CookiesStatusMissing +it:CookiesStatusPresent +it:CookiesStatusVerifying +it:CookiesStatusWorking +it:CookiesVerifyNow +it:Dashboard +it:Debug +it:DownloadCompleted +it:DownloadFailed +it:DownloadSkipped +it:Info +it:Logs +it:ManualCookiesExpired +it:ManualCookiesWrongFormat +it:No +it:OpenUtilsFolder +it:OpenYouTubeWith +it:PasteCookiesManually +it:PatchResonite +it:PatchVRChat +it:RedownloadComplete +it:RedownloadFailed +it:RedownloadUtils +it:RedownloadingUtils +it:SaveCookies +it:SkipReasonBotCheck +it:SkipReasonFileExists +it:SkipReasonFileNotFound +it:SkipReasonFormatUnavailable +it:SkipReasonLiveStream +it:SkipReasonNoMetadata +it:SkipReasonParseFailed +it:SkipReasonPrivateVideo +it:SkipReasonTooLong +it:SkipReasonUnsupportedUrl +it:SkipReasonVideoUnavailable +it:TrayMinimizeNotice +it:UseBetaExtension +it:UseBetaExtensionTooltip +it:Yes diff --git a/t.db b/t.db new file mode 100644 index 00000000..06c01707 Binary files /dev/null and b/t.db differ