💾 Archived View for tilde.club › ~filip › tech › script › ytfeed › ytfeed captured on 2023-07-22 at 17:30:55.

View Raw

More Information

⬅️ Previous capture (2022-07-16)

-=-=-=-=-=-=-

#!/usr/bin/env bash

printhelp(){
    echo "Render YouTube channel feeds into Gemtext."
    echo "Usage:"
    echo "  $0 <CHANNEL_ID> | <CHANNEL_ID-CHANNEL_TITLE TSV FILE> [ <FLAG> ]"
    echo "  $0 -h"
    echo "<FLAG>:"
    echo "  -n  - only the newest entry"
    echo "  -l  - URLs only"
    echo "  -ln - only the newest URL"
}

xml2links(){
# Parameter: channel_id flag
    channel_id="$1"
    flag="$2"
    first_line=0
    first_title=0
    first_link=0
    while read xml_line; do
        if (( first_line == 0 )); then
            [[ "$xml_line" == "<!DOCTYPE html>" ]] && echo "Channel does not exist!" && exit
            first_line=1
        fi
        title_re='<title>(.*)</title>'
        [[ $xml_line =~ $title_re ]] && title="${BASH_REMATCH[1]}"
        link_re='^<link rel="alternate" href="(.*)"/>'
        [[ $xml_line =~ $link_re ]] && link="${BASH_REMATCH[1]}"
        if [[ "$link" != "" ]]; then
            if (( first_title == 0 )); then
                l_flag_re='^-l.*'
                [[ $flag =~ $l_flag_re ]] || echo "# $title (Channel ID: $channel_id)"
                link=""
                first_title=1
            else
                case $flag in
                    -n)
                        echo "=>$link $title"
                        break
                    ;;
                    -l)
                        echo "$link"
                        link=""
                    ;;
                    -ln)
                        echo "$link"
                        link=""
                        break
                    ;;
                    *)
                        echo "=>$link $title"
                        link=""
                    ;;
                esac
            fi
        fi
    done < <(curl "https://www.youtube.com/feeds/videos.xml?channel_id=$channel_id" 2>/dev/null)
}

flags=("" "-n" "-l" "-ln")
[[ "$1" == "-h" ]] && printhelp && exit
if [[ "${flags[@]}" =~ $2 ]]; then
    if [[ -f "$1" ]]; then
        while read line; do
            channel_id=$(echo "$line" | cut -f1)
            xml2links "$channel_id" "$2"
        done < "$1"
    else
        xml2links "$1" "$2"
    fi
else
    echo "Invalid flag! Use -h for help."
fi