Created
March 15, 2022 18:54
-
-
Save Joshix-1/d948eb751d79e6d231c42654c0c090cd to your computer and use it in GitHub Desktop.
Search for videos with the YouTube API in the terminal to watch your favourite videos in mpv.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# change this key: | |
API_KEY="" | |
CACHE_DIR="$HOME/.cache/yt-search" | |
DEFAULT_COMMAND="mpv '%s'" | |
if [ -z "$API_KEY" ]; then | |
echo "Please input an API key in the script." | |
echo "https://developers.google.com/youtube/registering_an_application" | |
exit | |
fi | |
VIDEO_URL="https://www.youtube.com/watch?v=%s" | |
API_URL="https://www.googleapis.com/youtube/v3/search?q=%s&key=$API_KEY&type=video&part=snippet" | |
mkdir -p "$CACHE_DIR" | |
query=$(echo "$1" | sed "s/'/%27/g" | sed 's/"/%22/g' | sed "s/ /+/g" | sed "s/&/%26/g" | sed "s|/|%2F|g") | |
if [ -z "$query" ]; then | |
echo -n "Input Query: " | |
read query | |
fi | |
if [ -n "$query" ]; then | |
CACHE_FILE="$CACHE_DIR/$query" | |
if [ -f "$CACHE_FILE" ];then | |
echo "Using cached result." | |
result=$(cat "$CACHE_FILE") | |
fi | |
fi | |
if [ -z "$result" ]; then | |
result=$(curl -s $(printf "$API_URL" "$query")) | |
error=$(echo "$result" | jq ".error" | sed "s/^null$//g") | |
if [ -z "$error" ]; then | |
if [ -n "$query" ]; then | |
echo "$result" > "$CACHE_FILE" | |
else | |
echo "Unable to cache empty query." | |
fi | |
else | |
echo "API responded with error. Do not cache result." | |
echo "$error" | |
exit | |
fi | |
fi | |
snippets=$(echo "$result" | jq -c ".items[].snippet") | |
count=$(echo "$result" | jq ".items | length") | |
echo "Found $count videos:" | |
echo "$snippets" | awk -F '|' '{printf "[%s] ", NR; print $s | "jq .title"; close("jq .title"); printf "Description: "; print $s | "jq .description"; close("jq .description"); printf "Channel: "; print $s | "jq .channelTitle"; close("jq .channelTitle"); printf "Published At: "; print $s | "jq .publishedAt"; close("jq .publishedAt")}' | |
echo -n "Input index [1]: " | |
read input | |
if [ -z "$input" ]; then | |
input="1" | |
fi | |
input=$(expr "$input" - 1) | |
video_id=$(echo "$result" | jq ".items[$input].id.videoId" | sed 's/^"//g' | sed 's/"$//g') | |
url=$(printf "$VIDEO_URL" "$video_id") | |
echo "Using $url" | |
echo -n "Command to run [$DEFAULT_COMMAND]: " | |
read command | |
if [ -z "$command" ]; then | |
command="$DEFAULT_COMMAND" | |
fi | |
if [ "0" = $(echo "$command" | grep -c "%s") ]; then | |
command="$command '%s'" | |
fi | |
command=$(printf "$command" "$url") | |
echo "Running: $command" | |
sh -c "$command" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment