diff --git a/packages/beatsaber-oneclick/beatsaber-oneclick.sh b/packages/beatsaber-oneclick/beatsaber-oneclick.sh new file mode 100644 index 0000000..835c633 --- /dev/null +++ b/packages/beatsaber-oneclick/beatsaber-oneclick.sh @@ -0,0 +1,134 @@ +# Forwards a Beat Saber OneClick link to the Steam Frame, where BSManager downloads it, +# and keeps a desktop notification up to date until the install is done. +# Usage: beatsaber-oneclick +# $remote_script (remote.sh) is set by the package. + +host=${1:?usage: beatsaber-oneclick } +url=${2:?usage: beatsaber-oneclick } +api=https://api.beatsaver.com + +# One notification, updated in place +notification_id= +notify() { + local id + if id=$(notify-send --print-id ${notification_id:+--replace-id="$notification_id"} \ + --app-name="Beat Saber OneClick" --icon=input-gaming "$@"); then + notification_id=$id + fi +} + +# Only forward the OneClick schemes, and only plain URL characters, since the URL +# ends up in a remote shell command line. +if [[ ! $url =~ ^(beatsaver|bsplaylist|web\+bsmap|modelsaber):// ]] || + [[ ! $url =~ ^[A-Za-z0-9+.:/?#\&=%_~@!,\;-]+$ ]]; then + notify --urgency=critical "Not a OneClick link" "$url" + exit 1 +fi + +fetch() { + curl -sfL --max-time 20 "$@" +} + +# Look up what the link installs, to know which map folders to watch for. If that +# fails, the link is still sent, just without tracking. +ids=() +label=$url +playlist= +case $url in +beatsaver://* | web+bsmap://*) + ref=${url#*://} + ref=${ref%%[/?#]*} + if [[ $url == beatsaver://* ]]; then + map=$(fetch "$api/maps/id/$ref") || map= + else + map=$(fetch "$api/maps/hash/$ref") || map= + fi + if [[ -n $map ]]; then + ids=("$(jq -r '.id | ascii_downcase' <<<"$map")") + label=$(jq -r '"\(.metadata.songName) – \(.metadata.levelAuthorName)"' <<<"$map") + fi + ;; +bsplaylist://playlist/*) + playlist=1 + label="Playlist" + if bplist=$(fetch "${url#bsplaylist://playlist/}"); then + label=$(jq -r '.playlistTitle // "Playlist"' <<<"$bplist") + # Entries with a key need no lookup; resolve the rest by hash, 50 at a time + mapfile -t ids < <(jq -r '.songs[] | .key // empty | ascii_downcase' <<<"$bplist") + mapfile -t hashes < <(jq -r '.songs[] | select(.key == null) | .hash // empty | ascii_downcase' <<<"$bplist") + for ((i = 0; i < ${#hashes[@]}; i += 50)); do + batch=$( + IFS=, + echo "${hashes[*]:i:50}" + ) + if found=$(fetch "$api/maps/hash/$batch"); then + # A single hash returns the map itself instead of a hash → map object + mapfile -t -O "${#ids[@]}" ids < <(jq -r 'if has("id") then .id else (.[] | select(. != null) | .id) end | ascii_downcase' <<<"$found") + fi + done + fi + ;; +esac + +notify "Sending to Steam Frame…" "$label" + +total=${#ids[@]} +done_count=0 +new=0 +already=0 +missing=0 +last_error= +stderr_file=$(mktemp) +trap 'rm -f "$stderr_file"' EXIT + +exec {events}< <(ssh -T -o BatchMode=yes -o ConnectTimeout=5 "$host" \ + bash -s -- "$(printf '%q' "$url")" "${ids[@]}" <"$remote_script" 2>"$stderr_file") +ssh_pid=$! + +while IFS= read -r -u "$events" event; do + case $event in + received) + notify "Downloading on Steam Frame…" "$label" + ;; + "done "*) + done_count=$((done_count + 1)) + if ((total > 1)); then + notify "Downloading on Steam Frame… $done_count/$total" "$label" + fi + ;; + "error "*) + last_error=${event#error } + ;; + "result "*" new") new=$((new + 1)) ;; + "result "*" already") already=$((already + 1)) ;; + "result "*" missing") missing=$((missing + 1)) ;; + esac +done + +if ! wait "$ssh_pid"; then + err=$(tr -d '\r' <"$stderr_file" | grep -v 'X11 forwarding' || true) + notify --urgency=critical "Couldn't send to Steam Frame" "${err:-ssh failed}" + exit 1 +fi + +failure_hint=${last_error:-BSManager didn\'t finish within 2 minutes. Check it on the Frame.} + +if ((total == 0)); then + notify "Sent to Steam Frame" "$label"$'\n(Not tracked: couldn\'t look it up on BeatSaver.)' +elif [[ -z $playlist ]]; then + if ((new > 0)); then + notify "Installed on Steam Frame" "$label" + elif ((already > 0)); then + notify "Already on Steam Frame" "$label" + else + notify --urgency=critical "Not installed on Steam Frame" "$label"$'\n'"$failure_hint" + fi +else + summary="$label: $new new, $already already there" + if ((missing > 0)); then + notify --urgency=critical "Playlist partly installed on Steam Frame" \ + "$summary, $missing failed"$'\n'"$failure_hint" + else + notify "Playlist installed on Steam Frame" "$summary" + fi +fi diff --git a/packages/beatsaber-oneclick/default.nix b/packages/beatsaber-oneclick/default.nix new file mode 100644 index 0000000..3ee7e80 --- /dev/null +++ b/packages/beatsaber-oneclick/default.nix @@ -0,0 +1,25 @@ +{ + writeShellApplication, + openssh, + libnotify, + curl, + jq, +}: + +# Forwards Beat Saber OneClick links (BeatSaver, BeatLeader, ScoreSaber, playlists) +# to a Steam Frame over SSH and opens them there, so BSManager on the Frame does the +# download, and shows the install progress as a notification. +# Usage: beatsaber-oneclick +writeShellApplication { + name = "beatsaber-oneclick"; + runtimeInputs = [ + openssh + libnotify + curl + jq + ]; + text = '' + remote_script=${./remote.sh} + '' + + builtins.readFile ./beatsaber-oneclick.sh; +} diff --git a/packages/beatsaber-oneclick/remote.sh b/packages/beatsaber-oneclick/remote.sh new file mode 100644 index 0000000..1eef7ff --- /dev/null +++ b/packages/beatsaber-oneclick/remote.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash +# Runs on the Steam Frame (piped over SSH): opens a OneClick link in the graphical +# session, so the Frame's own handler (BSManager) downloads and installs it. +# +# Usage: remote.sh [...] +# +# With map ids, it then watches BSManager's log and map folders until those maps are +# installed, and reports on stdout, one event per line: +# received BSManager got the link +# downloading BSManager started downloading a map +# done the map's folder was (re)written and is complete +# error BSManager logged an error (may be unrelated) +# result new|already|missing +set -euo pipefail + +url=$1 +shift +ids=("$@") +uid=$(id -u) + +# BSManager's default locations (installation folder not changed) +bsm=$HOME/.local/share/BSManager +logs=$HOME/.config/bs-manager/logs + +# Give up when nothing has happened for this long (BSManager may need to start first) +timeout=120 +# With maps that were already installed, finish once BSManager is quiet for this long +quiet=10 + +for id in "${ids[@]}"; do + if [[ ! $id =~ ^[0-9a-f]+$ ]]; then + echo "Invalid map id: $id" >&2 + exit 1 + fi +done + +# An SSH session has no display. Borrow the display variables from a process in +# the graphical session, preferring the Steam client. +session_env() { + local pid env + for pid in $(pgrep -u "$uid" -x steam || true) $(pgrep -u "$uid"); do + env=$(tr '\0' '\n' <"/proc/$pid/environ" 2>/dev/null) || continue + if grep -qE '^(DISPLAY|WAYLAND_DISPLAY)=' <<<"$env"; then + printf '%s\n' "$env" + return 0 + fi + done + return 1 +} + +if ! env=$(session_env); then + echo "No graphical session found on the Frame (is it signed in?)" >&2 + exit 1 +fi + +while IFS= read -r line; do + export "${line?}" +done < <(grep -E '^(DISPLAY|WAYLAND_DISPLAY|XAUTHORITY|XDG_CURRENT_DESKTOP|XDG_SESSION_TYPE|DBUS_SESSION_BUS_ADDRESS)=' <<<"$env") + +opener= +for candidate in gio xdg-open kde-open; do + if command -v "$candidate" >/dev/null; then + opener=$candidate + break + fi +done +if [[ -z $opener ]]; then + echo "No gio, xdg-open or kde-open on the Frame" >&2 + exit 1 +fi +open_cmd=("$opener") +[[ $opener == gio ]] && open_cmd+=(open) + +map_dirs=("$bsm"/BSInstances/*/"Beat Saber_Data"/CustomLevels "$bsm"/SharedContent/SharedMaps/CustomLevels) + +# Prints " " over a map's folders in all instances, +# or "none". Change time (not mtime), as extracting may keep the zip's mtimes. +map_state() { + local d f t s newest=0 size=0 found= + for d in "${map_dirs[@]}"; do + for f in "$d/$1 ("*; do + [[ -d $f ]] || continue + found=1 + t=$(find "$f" -printf '%C@\n' | sort -n | tail -n1) + t=${t%.*} + ((t > newest)) && newest=$t + s=$(du -sb "$f" | cut -f1) + size=$((size + s)) + done + done + if [[ -n $found ]]; then echo "$newest $size"; else echo none; fi +} + +# BSManager log lines written since we started. Continuation lines (stack traces) +# don't start with a timestamp and are left out. +log_since_start() { + find "$logs" -name '*.log' -newermt "@$start" -print0 2>/dev/null | + xargs -0r cat | + awk -v s="[$start_log" 'substr($0, 1, 20) >= s' +} + +declare -A pre state prev +for id in "${ids[@]}"; do + pre[$id]=$(map_state "$id") + state[$id]=pending + prev[$id]= +done + +start=$(date +%s) +start_log=$(date -d "@$start" '+%Y-%m-%d %H:%M:%S') + +# gio comes first: xdg-open (generic mode) mangles the quoted path in BSManager's Exec line. +# Run it in its own scope, detached from this SSH session: if BSManager isn't running +# yet, the handler starts it, and it must outlive the connection. Output goes to the +# journal: journalctl --user -t beatsaber-oneclick +systemd-run --user --scope --collect --quiet \ + setsid -f systemd-cat -t beatsaber-oneclick "${open_cmd[@]}" "$url" \ + /dev/null 2>&1 + +((${#ids[@]} > 0)) || exit 0 + +received= +errors_seen=0 +last_activity=$start +while :; do + sleep 1 + now=$(date +%s) + lines=$(log_since_start) + + if [[ -z $received ]] && grep -q 'DEEP-LINK RECEIVED' <<<"$lines"; then + received=1 + last_activity=$now + echo received + fi + + mapfile -t errors < <(grep -F '[error]' <<<"$lines" || true) + for err in "${errors[@]:errors_seen}"; do + echo "error ${err#*\[error\] }" + done + errors_seen=${#errors[@]} + + waiting=0 + all_done=1 + for id in "${ids[@]}"; do + [[ ${state[$id]} == installed ]] && continue + all_done= + + if [[ ${state[$id]} == pending ]] && grep -qF " $id https://" <<<"$lines"; then + state[$id]=downloading + last_activity=$now + echo "downloading $id" + fi + + # Done once the folder changed since we started and stayed the same for a second + cur=$(map_state "$id") + if [[ $cur != none ]] && ((${cur%% *} >= start)); then + if [[ $cur == "${prev[$id]}" ]]; then + state[$id]=installed + last_activity=$now + echo "done $id" + continue + fi + prev[$id]=$cur + last_activity=$now + fi + + # Maps that weren't installed yet, or are being downloaded, are worth waiting for + if [[ ${state[$id]} == downloading || ${pre[$id]} == none ]]; then + waiting=$((waiting + 1)) + fi + done + + [[ -n $all_done ]] && break + [[ -n $received ]] && ((waiting == 0 && now - last_activity >= quiet)) && break + ((now - last_activity >= timeout)) && break +done + +for id in "${ids[@]}"; do + if [[ ${state[$id]} == installed ]]; then + echo "result $id new" + elif [[ ${pre[$id]} != none ]]; then + echo "result $id already" + else + echo "result $id missing" + fi +done