diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index 80128f4..a8c8ea5 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -18,7 +18,7 @@ const ( IcecastPlaylistDateFormat = "02/Jan/2006:15:04:05 -0700" SongTimeFormat = "2006 15:04-0700" - bufferSize = 8192 + bufferSize = 32768 ) var ( @@ -92,7 +92,12 @@ func IcecastLastPlayedSongs(lastNSongs int, playlistPath string) ([]Song, error) } } - return make([]Song, 0), nil + songs, err := lastPlayedSongs(playlistPath, lastNSongs) + if err != nil { + return make([]Song, 0), err + } + + return songs, nil } func IcecastLastSong(playlistPath string) (Song, error) { @@ -104,15 +109,16 @@ func IcecastLastSong(playlistPath string) (Song, error) { } } - song, err := lastPlayedSong(playlistPath) + song, err := lastPlayedSongs(playlistPath, 1) if err != nil { return Song{}, err } - return *song, nil + return song[0], nil } -func lastPlayedSong(playlistPath string) (*Song, error) { +func lastPlayedSongs(playlistPath string, n int) ([]Song, error) { + songs := make([]Song, n) buf := make([]byte, bufferSize) playlist, err := os.Open(playlistPath) @@ -140,14 +146,24 @@ func lastPlayedSong(playlistPath string) (*Song, error) { return nil, nil } - fields := bytes.Split(lines[len(lines)-3], []byte("|")) + if len(lines) < n { + n = len(lines) + } - tim, _ := time.Parse(IcecastPlaylistDateFormat, string(fields[0])) + lines = lines[len(lines)-n-3 : len(lines)-3] - return &Song{ - Time: tim.Format(SongTimeFormat), - Listeners: string(fields[2]), - Song: string(fields[3])}, nil + for _, line := range lines { + fields := bytes.Split(line, []byte("|")) + + tim, _ := time.Parse(IcecastPlaylistDateFormat, string(fields[0])) + + songs = append(songs, Song{ + Time: tim.Format(SongTimeFormat), + Listeners: string(fields[2]), + Song: string(fields[3])}) + } + + return songs, nil } var playlistWatcher watcher.InotifyWatcher @@ -172,11 +188,8 @@ func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { case mask := <-playlistFired: if mask&syscall.IN_MODIFY > 0 { lastPlayedCacheMutex.Lock() - if song, err := lastPlayedSong(playlistPath); err == nil { - lastPlayedCache = append(lastPlayedCache, *song) - if len(lastPlayedCache) > lastNSongs { - lastPlayedCache = lastPlayedCache[1:] - } + if songs, err := lastPlayedSongs(playlistPath, lastNSongs); err == nil { + lastPlayedCache = songs } lastPlayedCacheMutex.Unlock() } else if mask&syscall.IN_IGNORED > 0 {