#!/usr/bin/bash

:<< 'COMMENT'
I threw this together for conky, to display may media. Add this line to your .conkrc file:

${execi 5 /home/mitch/bin/now-playing|fmt -45}

and that is it.

http://crn.hopto.org Enjoy!
COMMENT

# Function to clean HTML entities and tags
clean_html() {
    # 1. Decode common HTML entities (&amp; -> &, &lt; -> <, etc.)
    # 2. Strip any remaining HTML tags (<tag> -> empty)
    # 3. Squeeze multiple spaces into one
    sed -e 's/&amp;/\&/g' \
        -e 's/&lt;/</g' \
        -e 's/&gt;/>/g' \
        -e 's/&nbsp;/ /g' \
        -e 's/&#39;/'\''/g' \
        -e 's/&quot;/"/g' \
        -e 's/<[^>]*>//g' | \
    tr -s ' '
}

# Get status
STATUS=$(playerctl status 2>/dev/null)

if [ -z "$STATUS" ]; then
    echo "Silence..."
    exit 0
fi

#echo "Status: $STATUS"

# Attempt to get Artist and Title
ARTIST=$(playerctl metadata --format '{{ artist }}' 2>/dev/null)
TITLE=$(playerctl metadata --format '{{ title }}' 2>/dev/null)

if [ -n "$ARTIST" ] && [ -n "$TITLE" ]; then
    # Clean HTML from metadata if present
    ARTIST_CLEAN=$(echo "$ARTIST" | clean_html)
    TITLE_CLEAN=$(echo "$TITLE" | clean_html)
    echo "$ARTIST_CLEAN - $TITLE_CLEAN" |sed -e 's/-/ /g' -e 's/.*/\L&/; s/[a-z]*/\u&/g' -e 's/\/.*\//: /g' -e 's/ \+/ /g' -e 's/\.Mp3//' -e 's/\.Mp4//'

else
    # Fallback: Get the URL
    URL=$(playerctl metadata --format '{{ xesam:url }}' 2>/dev/null)
    
    if [ -n "$URL" ]; then
        if [[ "$URL" == file://* ]]; then
            FILEPATH="${URL#file://}"
            FILENAME=$(basename "$FILEPATH")
            # Clean HTML from filename
            #FILENAME_CLEAN=$(echo "$FILENAME" | clean_html)
decoded=$(echo -e "$(echo "$FILENAME" | sed 's/+/ /g; s/%\([0-9a-fA-F][0-9a-fA-F]\)/\\x\1/g')")
echo "${decoded%.*}"  |sed -e 's/-/ /g' -e 's/.*/\L&/; s/[a-z]*/\u&/g'
            #echo "Now Playing: $FILENAME_CLEAN"
        else
            # Clean HTML from stream URL if necessary
            URL_CLEAN=$(echo "$URL" | clean_html)
            echo "Now Playing: $URL_CLEAN"
        fi
    else
        WEB="$(playerctl metadata xesam:title)"
        echo "${WEB}"|sed -e 's/-/ /g' -e 's/.*/\L&/; s/[a-z]*/\u&/g' -e 's/\/.*\//: /g'
    fi
fi   
