1
0

lastPlayedSong was made into lastPlayedSongs. Now it retrieves up to n songs from a log.

This commit is contained in:
Alexander Andreev 2022-08-30 02:29:11 +04:00
parent df67314f2a
commit 0620f82940
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

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