diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index db3bd42..7fe8c2c 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -7,6 +7,7 @@ import ( "net/http" "os/exec" "strings" + "sync" "time" "github.com/pkg/errors" @@ -65,19 +66,27 @@ func IcecastGetStatus(icecastURL string) (*IcecastStatus, error) { } func IcecastLastPlayedSongs(lastNSongs int, playlistPath string) ([]Song, error) { - if lpcLen := len(lastPlayedCache); lpcLen > 0 { - if lastNSongs > lpcLen { - lastNSongs = lpcLen + { + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() + if lpcLen := len(lastPlayedCache); lpcLen > 0 { + if lastNSongs > lpcLen { + lastNSongs = lpcLen + } + return lastPlayedCache[lpcLen-lastNSongs:], nil } - return lastPlayedCache[lpcLen-lastNSongs:], nil } return lastPlayedSongs(lastNSongs, playlistPath) } func IcecastLastSong(playlistPath string) (Song, error) { - if lpcLen := len(lastPlayedCache); lpcLen > 0 { - return lastPlayedCache[lpcLen-1], nil + { + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() + if lpcLen := len(lastPlayedCache); lpcLen > 0 { + return lastPlayedCache[lpcLen-1], nil + } } songs, err := lastPlayedSongs(1, playlistPath) @@ -121,6 +130,7 @@ func lastPlayedSongs(lastNSongs int, playlistPath string) ([]Song, error) { var playlistWatcher watcher.InotifyWatcher var playlistFired chan uint32 var lastPlayedCache []Song +var lastPlayedCacheMutex sync.Mutex func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { playlistWatcher, err := watcher.NewInotifyWatcher() @@ -141,6 +151,8 @@ func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { for { select { case <-playlistFired: + lastPlayedCacheMutex.Lock() + defer lastPlayedCacheMutex.Unlock() songs, err := lastPlayedSongs(lastNSongs, playlistPath) if err == nil && len(songs) > 0 { lastPlayedCache = songs