Skip to content

Instantly share code, notes, and snippets.

@cleanhands
Created February 14, 2025 00:41
Show Gist options
  • Select an option

  • Save cleanhands/4aac0dc62b3a52e324120f1294e2b833 to your computer and use it in GitHub Desktop.

Select an option

Save cleanhands/4aac0dc62b3a52e324120f1294e2b833 to your computer and use it in GitHub Desktop.
Bash script for downloading books from Anna's Archive using CLI (requires: xq aria2c)
#!/usr/bin/env bash
set -euo pipefail
url="${1}"
prot="${url%%:*}"
link="${url#$prot://}"
domain="${link%%/*}"
link="${link#$domain}"
tmpdir="$(mktemp -d)"
trap 'rm -rf -- "$tmpdir"' EXIT
page="$(curl -sf "$url" | perl -0777 -pe 's/<script.*?script>//gs' | sed 's#</em>##g')"
md5=$(xq -e '//span[text()="AA Record ID"]/following-sibling::span' <<< "$page")
md5=${md5#md5:}
output_name=$(xq -e '//span[text()="Filepath"]/following-sibling::span' <<< "$page")
if [[ -n $output_name ]]; then
output_name=${output_name##*/}
output_name=${output_name##*\\}
else
output_name=$(xq -e '//main/div/div[2]' <<< "$page" | cut -d ',' -f 2)
output_name="${output_name#"${output_name%%[![:space:]]*}"}"
output_name=$(xq -e '//main/div/div[3]/text()' <<< "$page")$output_name
fi
torrent_url="${prot}://${domain}$(xq -e '//div[@id="md5-panel-downloads"]/ul/li/div/a[2]/@href' <<< "$page")"
torrent_name=$(xq -e '//div[@id="md5-panel-downloads"]/ul/li/div/text()[3]' <<< "$page" | sed -E 's/[^“]+“([^”]+)”/\1/')
curl -s -o "torrent" --output-dir "$tmpdir" "$torrent_url"
index=$(aria2c --show-files "$tmpdir/torrent" | grep "$torrent_name" | cut -d '|' -f 1)
aria2c --summary-interval=0 --auto-file-renaming=false --seed-time=0 --check-integrity=true --select-file=$index --dir="$tmpdir" "$tmpdir/torrent"
find "$tmpdir" -name "$torrent_name" -exec mv -vn {} "./$output_name" \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment