Mine is self-contained, though I like your way to use the mailcap entry… I'll look this out later.
I cleaned up mine a bit. The cool stuff about it (I think) is that you can pipe
data to it and open it. Not only URIs:
Code:
curl -s 'https://random.tld/image.png' | plumb -s
This would cache the file locally, and open it with the according mime entry.
Here is the full script:
Code:
#!/bin/sh
#
# open things from uri
cachedir=$HOME/.cache/plumber
usage() {
echo "usage: $(basename $0) [-h] [uri]" >&2
}
peekmime() {
curl -sSfL "$1" | cut -b-16 | file -ib - | cut -d\; -f1
}
# return a uri to a local file (download if necessary)
localuri() {
local="$1"
if [ ! -f "$1" ]; then
tmp=$(mktemp)
curl -o $tmp -sSfL "$1"
local=$(cachefile "$tmp" "${mime##*/}")
rm $tmp
fi
printf '%s\n' "$local"
}
# copy file to cache
cachefile() {
mkdir -p $cachedir
hash=$(sha256sum "$1"|cut -d' ' -f1)
cp "$1" $cachedir/${hash}.$2
printf '%s/%s.%s\n' "$cachedir" "$hash" "$2"
}
# prompt for a command to open uri
prompt() {
dmenu_path | dmenu -p "$1" -l 8
}
clip="$(xsel -o 2>/dev/null)"
while getopts "hs" OPT; do
case $OPT in
s) slurp=$(mktemp -p $cachedir) ;;
h) usage; exit 0 ;;
*) usage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
# fallback to clipboard when not uri given
uri="${1:-$clip}"
# special arg "-" read uri(s) from stdin
if [ "$uri" = "-" ]; then
cat | xargs -P$(nproc) -n1 $0
fi
# can read file _content_ from stdin, then process it
if [ -n "$slurp" ]; then
cat > $slurp
uri="$slurp"
fi
[ -z "$uri" ] && exit 1
if [ -f "$uri" ]; then
mime=$(file -ib "$uri" | cut -d\; -f1)
else
proto="${uri%%:*}"
case $proto in
mailto) mime='application/x-mail' ;;
magnet) mime='application/x-bittorrent' ;;
*) mime="$(peekmime $uri)" ;;
esac
fi
if [ -n "$slurp" ]; then
uri="$(cachefile $slurp ${mime##*/})"
rm "$slurp"
fi
case "$mime" in
text/html) exec firefox "$uri" ;;
video/*) exec mplayer -cache 512 "$uri" ;;
image/gif) exec mplayer -loop 0 $(localuri "$uri") ;;
image/*) exec meh $(localuri "$uri") ;;
text/*) exec st -e less $(localuri "$uri") ;;
application/x-mail) exec st -e mutt $uri ;;
application/x-bittorrent) exec st -e rtorrent $uri ;;
*) exec $(prompt) "$uri" ;;
esac