Share your file-opener script - Programming On Unix

Users browsing this thread: 1 Guest(s)
z3bra
Grey Hair Nixers
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


Messages In This Thread
Share your file-opener script - by seninha - 30-05-2020, 07:40 PM
RE: Share your file/link-opener script - by z3bra - 31-05-2020, 03:55 AM
RE: Share your file/link-opener script - by venam - 31-05-2020, 04:12 AM
RE: Share your file-opener script - by jkl - 10-02-2021, 03:40 PM
RE: Share your file-opener script - by neeasade - 13-02-2021, 12:16 PM
RE: Share your file-opener script - by venam - 07-03-2022, 02:47 AM