scripts

random scripts
git clone https://git.parazyd.org/scripts
Log | Files | Refs

ydl (1365B)


      1 #!/bin/sh
      2 #
      3 # download the audio track of the first result of a youtube search
      4 # and add it to MPD library (will end up with a .mp3, for tags)
      5 
      6 MPD_DOWNLOAD_DIR=$PWD
      7 
      8 usage() {
      9     echo "`basename $0` [-h] <query>"
     10 }
     11 
     12 ys() {
     13         num=3
     14         regex='^.*<a href="\(/watch[^"]*\)"[^>]*>\([^<]*\)</a>.*$'
     15         output='\2 - http://youtube.com\1'
     16 
     17         while getopts "hn:tu" OPT; do
     18             case  $OPT in
     19                 n) num=$OPTARG;;
     20                 t) output='\2';;
     21                 u) output='http://youtube.com\1';;
     22                 h) usage long; exit 0;;
     23                 *) usage; exit 1;;
     24             esac
     25         done
     26 
     27         shift $((OPTIND - 1))
     28 
     29         query=$(echo $@ | tr ' ' '+')
     30         url="https://www.youtube.com/results?search_query=${query}"
     31 
     32         curl -s "$url" | sed -n "s,$regex,$output,p" | sed ${num}q
     33 }
     34 
     35 # don't process if no argument given
     36 test $# -eq 0 && usage && exit 1
     37 
     38 # you can either pass MULTIPLE search terms or a SINGLE url
     39 test $# -gt 1 && uri=$(ys -n1 -u $@) || uri=$1
     40 
     41 # give up if we got no uri
     42 if test -z "$uri"; then
     43     echo "no result found"
     44     exit 1
     45 fi
     46 
     47 # change to target dir if it exists
     48 test -d $MPD_DOWNLOAD_DIR && cd $MPD_DOWNLOAD_DIR
     49 
     50 # download and extract audio track
     51 youtube-dl -q -x -o '%(title)s.%(ext)s' "$uri"
     52 
     53 # update mpd lib if running
     54 pgrep mpd >/dev/null 2>&1&& mpc -q update
     55 
     56 exit 0