watchyt/watchyt.sh

90 lines
2.6 KiB
Bash
Executable File

#!/bin/sh
# watchyt - a simple shell script for finding and watching youtube videos
# Copyright (C) 2020 Christian Ulrich
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
max_results=${2:-10}
line_index=0
title=""
id=""
uploader=""
duration=""
video_titles=()
video_urls=()
mkdir -p "$HOME/.local/share/watchyt"
cd "$HOME/.local/share/watchyt"
mkfifo youtube_dl_output
youtube-dl --get-title --get-filename -o '%(id)s;%(duration)d;%(upload_date)s;%(uploader)s' ytsearch${max_results}:"$1" 2>/dev/null > youtube_dl_output &
while read line
do
case $line_index in
0)
title="$line"
;;
1)
id=$(echo "$line" | cut -d ';' -f 1)
duration=$(echo "$line" | cut -d ';' -f 2)
upload_date=$(echo "$line" | cut -d ';' -f 3)
uploader=$(echo "$line" | cut -d ';' -f 4)
video_titles+=( "$title" )
video_urls+=( "https://youtube.com/watch?v=$id" )
duration_minutes=$(( duration / 60 ))
duration_seconds=$(( duration % 60 ))
upload_date_formatted=$(date -d"$upload_date" +%d/%m/%Y)
entry_index=${#video_urls[@]}
echo "$(printf "%2d" $entry_index)) $title [$duration_minutes:$(printf "%02d" $duration_seconds)]"
echo " uploaded by \"$uploader\" on $upload_date_formatted"
echo ""
;;
esac
line_index=$(( line_index + 1))
line_index=$(( line_index % 2 ))
done < youtube_dl_output
rm youtube_dl_output
video_count="${#video_urls}"
if [ "$video_count" -eq "0" ]
then
echo "no videos found"
exit 0
fi
echo -n "please select video: "
read selection
case $selection in
(*[!0-9]*|'')
echo "invalid selection"
exit 1
;;
(*)
if [ "$selection" -gt $(( video_count )) ]
then
echo "invalid selection"
exit 2
fi
video_url="${video_urls[$(( selection - 1 ))]}"
youtube-dl --restrict-filenames -o '%(title)s.%(ext)s' "$video_url"
filename=$(youtube-dl -s --get-filename --restrict-filenames -o '%(title)s' "$video_url")
echo "filename: $filename"
vlc "$filename".* 2>/dev/null
;;
esac