From anonymous, 1 Year ago, written in Bash.
Embed
  1. #!/bin/bash
  2.  
  3. TMPDIR="${TMPDIR:-/tmp}" # TODO: Make it portable.
  4.  
  5. # Usage: error msg need_print_usage
  6. # Prints "error: $msg" to stderr and exits with status 1.
  7. # If need_print_usage is not empty then it also calls print_usage.
  8. error() {
  9.   echo "error: $1" >&2
  10.   [ "$2" ] && print_usage
  11.   exit 1
  12. }
  13.  
  14. print_usage() {
  15.   cat <<EOF
  16. Usage: $(basename "$0") [options] url
  17.  
  18. Open internet video at specified url with your favorite player.
  19.  
  20. It uses youtube-dl internally.
  21.  
  22. Options:
  23.   -h, --help            Show this message and exit.
  24.  
  25.   -F, --list-formats    List available formats for the video and exit.
  26.  
  27.   -f, --format FORMAT   Choose format for the video. See youtube-dl
  28.                         documentation for details on FORMAT.
  29.  
  30.   -d, --with-download   Download the video into the temporary directory
  31.                         then open it. Good for slow internet connection.
  32.  
  33. Environment variables:
  34.  
  35.   PLAYER                If defined then the specified player is used.
  36.                         Default is "$player".
  37.  
  38. EOF
  39. }
  40.  
  41. # ---- MAIN ----
  42.  
  43. watch() {
  44.   direct_urls="$(
  45.    if [ "$format" ]; then
  46.      youtube-dl --get-url --format "$format" "$url"
  47.    else
  48.      youtube-dl --get-url "$url"
  49.    fi
  50.  )" && \
  51.   { [ "$(echo "$direct_urls" | wc --lines)" == 1 ] || error "there are separate URLs for video and audio stream"; } && \
  52.   exec "$player" "$direct_urls"
  53. }
  54.  
  55. list_formats() {
  56.   exec youtube-dl --list-formats "$url"
  57. }
  58.  
  59. download_then_watch() {
  60.   cd "$TMPDIR"
  61.   if [ "$format" ]; then
  62.     exec youtube-dl \
  63.       --no-part --no-continue --format "$format" --exec "$player {}" "$url"
  64.   else
  65.     exec youtube-dl \
  66.       --no-part --no-continue --exec "$player {}" "$url"
  67.   fi
  68. }
  69.  
  70. player="${PLAYER:-smplayer}"
  71. action="watch"
  72. format=""
  73. url=""
  74. while true; do
  75.   case "$1" in
  76.     -h|--help)
  77.       print_usage
  78.       exit
  79.       ;;
  80.     -F|--list-formats)
  81.       action="list_formats"
  82.       shift
  83.       ;;
  84.     -f|--format)
  85.       format="$2"
  86.       shift; shift
  87.       ;;
  88.     -d|--with-download)
  89.       action="download_then_watch"
  90.       shift
  91.       ;;
  92.     -*)
  93.       error "unknown option \`$1\'" usage
  94.       ;;
  95.     *)
  96.       url="$1"
  97.       shift
  98.       break
  99.       ;;
  100.   esac
  101. done
  102. [ "$url" ] || error "url not specified" usage
  103. [ -z "$1" ] || error "invalid command line" usage
  104. $action
  105.