moin (1396B)
1 #!/bin/sh 2 3 APIURI="https://www.googleapis.com/youtube/v3" 4 VIDURI="https://youtube.com/embed" 5 PLAYER="mpv" 6 PLAYER_OPTS="-vo null --quiet" 7 8 ytapi() { 9 apikey="$1" 10 cmd="$2" 11 params="$3" 12 wget -qO - "$APIURI/$cmd?key=$apikey&part=contentDetails&$params" 13 } 14 15 ytplrand() { 16 apikey="$1" 17 listid="$2" 18 maxres=50 19 data="$(ytapi "$apikey" "playlists" "id=$listid")" 20 nitems="$(echo "$data" |grep itemCount |cut -d: -f2)" 21 [ -z "$nitems" ] && return 22 choose="$(shuf -i 1-"$nitems" -n1)" 23 page="$(echo "1 + ($choose - 1) / $maxres" |bc)" 24 item="$(echo "$choose - (($page-1) * $maxres)" |bc)" 25 pagetok="" 26 27 # browse the pages until reach the item (that's the way YouTube works) 28 for p in $(seq $page); do 29 [ $p -gt 1 ] && pagetok="&pageToken=$(echo $data|grep nextPageToken |cut -d: -f2)" 30 data="$(ytapi "$apikey" "playlistItems" "playlistId=$listid&maxResults=${maxres}${pagetok}")" 31 done 32 echo "$(echo "$data" |grep videoId |head -n $item |tail -1 |cut -d: -f2 |tr -cd "[:alnum:]_-")" 33 } 34 35 main() { 36 apikey="$1" 37 listid="$2" 38 39 if [ -z "$apikey" -o -z "$listid" ]; then 40 echo "Usage: "$(basename "$0")" <API key> <playlist ID>" 41 exit 1 42 fi 43 pgrep -a "$PLAYER" >/dev/null && exit 1 44 rv=1 45 while [ $rv -ne 0 ]; do 46 songid="$(ytplrand "$apikey" "$listid")" 47 [ -z "$songid" ] && echo "$(basename "$0"): no song ID found" && break 48 "$PLAYER" $PLAYER_OPTS "$VIDURI/$songid" 49 #rv=$? 50 rv=0 51 done 52 } 53 54 main "$@"