Skip to content

Instantly share code, notes, and snippets.

@DegenCoden
Created October 20, 2021 20:27
Show Gist options
  • Save DegenCoden/d29d995c1dd920c845a9b774b0a43eb4 to your computer and use it in GitHub Desktop.
Save DegenCoden/d29d995c1dd920c845a9b774b0a43eb4 to your computer and use it in GitHub Desktop.
wt.sh - watch torrents
#! /usr/bin/env bash
for p in btfs curl fusermount fzf jq xdg-open; do
command -v "$p" 2>&1 > /dev/null || {
echo >&2 "Dependency $p not found.";
exit 1;
}
done
function usage() {
echo ""
echo "█▁█▁█ ▔█▔ | Watch Torrents"
echo " Utility for searching for, downloading, and streaming torrents."
echo ""
echo "Usage: $0 QUERY"
echo ""
echo " QUERY - Search query sent to the search engine."
echo ""
exit 1
}
if [ $# -eq 0 ]; then usage; fi
TRACKERS=(
"http://nyaa.tracker.wf:7777/announce"
"udp://exodus.desync.com:6969/announce"
"udp://open.stealth.si:80/announce"
"udp://tracker.coppersurfer.tk:6969/announce"
"udp://tracker.internetwarriors.net:1337"
"udp://tracker.opentrackr.org:1337/announce"
)
quitIfZero () { if [[ -z "$1" ]]; then exit 1; fi; }
# $1 / stdin - XT Hash [https://en.wikipedia.org/wiki/Magnet_URI_scheme]
magnetLink () {
INPUT="$([[ -p /dev/stdin ]] && cat - || echo "$1")"
quitIfZero "$INPUT"
TRACKER_PARAMS=$(for t in "${TRACKERS[@]}"; do printf -- '&tr=%s' "$t"; done)
printf "magnet:?xt=urn:btih:%s%s\n" "$INPUT" "$TRACKER_PARAMS"
}
# $1 / stdin - Search query
torrentSearch () {
INPUT="$([[ -p /dev/stdin ]] && cat - || echo "$1")"
quitIfZero "$INPUT"
curl -s -G --data-urlencode "q=$INPUT" \
"https://torrent-paradise.ml/api/search" \
| jq -c 'sort_by(.s)|reverse[]'
}
# stdin - Lines of JSON
selectTorrent () {
cat - \
| jq -r '[.id, .text, .s, .l]|@tsv' \
| fzf --delimiter='\t' --with-nth=2,3,4 \
| cut -f1
}
# stdin - Lines of file paths
selectFile () {
cat - | fzf
}
# $1 - Download directory
# $2 - Fuse mount location
# $3 / stdin - Magnet link
btfsMount () {
INPUT="$([[ -p /dev/stdin ]] && cat - || echo "$3")"
quitIfZero "$1"
quitIfZero "$2"
quitIfZero "$INPUT"
btfs --data-directory="$1" "$INPUT" "$2"
while [[ -z "$(ls "$2")" ]]; do sleep 0.1; done
}
# $1 / stdin - File
watch () {
INPUT="$([[ -p /dev/stdin ]] && cat - || echo "$1")"
quitIfZero "$INPUT"
xdg-open "$INPUT"
}
D=$(mktemp -d)
mkdir "$D/mnt"
mkdir "$D/dl"
trap '{ fusermount -u $D/mnt 2> /dev/null; rm -rf $D; }' EXIT
torrentSearch "$1" \
| selectTorrent \
| magnetLink \
| btfsMount "$D/dl" "$D/mnt" \
&& find "$D/mnt" -type f \
| selectFile \
| watch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment