all repos — breadsite @ 65ec84fd4e55ea87d7147c6a5717d04c235aae00

Unnamed repository; edit this file 'description' to name the repository.

backend/nowPlaying.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"
)

type musicCache struct {
	expires time.Time
	content PlayingInfo
}

var music_handler_Cache musicCache

func music_cache_handler(music_handler_Cache *musicCache, expiry_time time.Duration) PlayingInfo {
	e := music_handler_Cache.content == PlayingInfo{}
	if time.Now().After(music_handler_Cache.expires) || e{
		log.Println("cache expired")
		music_handler_Cache.content = getInfo()
		music_handler_Cache.expires = time.Now().Add(expiry_time)
	}
	log.Println("returning cached result")
	return music_handler_Cache.content
}

func nowPlayingHandler(w http.ResponseWriter, r *http.Request) {
	playingInfo := music_cache_handler(&music_handler_Cache, time.Second * 60)

	// v := reflect.ValueOf(playingInfo)
	// k := v.Type()
	// for i := range v.NumField() {
	// 	log.Printf("%s: %s\n", k.Field(i).Name, v.Field(i))
	// }

	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "*")

	var response string

	if playingInfo.playing {
		response = fmt.Sprintf(
			`
				<a class='nowPlaying' href=%s>
					<h3>Now Playing:</h3>
					<div class='songInfo'>
						<img class='coverImg' src='%s' alt='%s'>
						<div class='metadata'>
							<p class='recordingName'>%s</p>
							<p class='artistName'>~ %s</p>
							<p class='releaseName'>%s</p>
						</div>
					</div>
				</a>
			`,
			playingInfo.recordingUrl,
			playingInfo.coverUrl,
			strings.ReplaceAll(
				fmt.Sprintf("%s - %s", playingInfo.recordingName, playingInfo.artistName),
				`'`,
				"",
			),
			playingInfo.recordingName,
			playingInfo.artistName,
			playingInfo.releaseName,
		)
	} else {
		response = "<h3 class='nowPlaying offline'>nothing is playing...</h3>"
	}
	fmt.Fprintf(w, response)
}