1
0

Added mutex for lastPlayedCache.

This commit is contained in:
Alexander Andreev 2022-04-01 20:44:32 +04:00
parent d3ffd01e0a
commit 21995ea4cd
Signed by: Arav
GPG Key ID: 1327FE8A374CC86F

View File

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