diff --git a/cmd/dwelling-radio/main.go b/cmd/dwelling-radio/main.go index fbcf055..e696a3d 100644 --- a/cmd/dwelling-radio/main.go +++ b/cmd/dwelling-radio/main.go @@ -51,10 +51,11 @@ func main() { } defer logErr.Close() - if err := radio.IcecastWatchPlaylist(config.Icecast.Playlist, config.ListLastNSongs); err != nil { + playlistWatcher := radio.NewPlaylistLogWatcher() + if err := playlistWatcher.Watch(config.Icecast.Playlist, config.ListLastNSongs); err != nil { logErr.Fatalln(err) } - defer radio.IcecastWatchClose() + defer playlistWatcher.Close() hand := handlers.NewRadioHandlers(config, logErr) srv := server.NewHttpServer() diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index 1511954..a2b28cb 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -166,35 +166,45 @@ func icecastLastPlayedSongs(playlistPath string, n int) ([]Song, error) { return songs, nil } -var playlistWatcher watcher.InotifyWatcher -var playlistChanged chan uint32 = make(chan uint32) +type PlaylistLogWatcher struct { + watcher *watcher.InotifyWatcher + changed chan uint32 +} -func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { - playlistWatcher, err := watcher.NewInotifyWatcher() +func NewPlaylistLogWatcher() *PlaylistLogWatcher { + return &PlaylistLogWatcher{changed: make(chan uint32)} +} + +func (pw *PlaylistLogWatcher) Watch(playlistPath string, n int) (err error) { + if pw.watcher != nil { + pw.watcher.Close() + } + + pw.watcher, err = watcher.NewInotifyWatcher() if err != nil { return errors.Wrap(err, "cannot instantiate inotify watcher") } - err = playlistWatcher.AddWatch(playlistPath, watcher.ModIgnMask) + err = pw.watcher.AddWatch(playlistPath, watcher.ModIgnMask) if err != nil { return errors.Wrap(err, "cannot set a playlist to watch") } - playlistWatcher.WatchForMask(playlistChanged, watcher.ModIgnMask) + pw.watcher.WatchForMask(pw.changed, watcher.ModIgnMask) go func() { for { select { - case mask := <-playlistChanged: + case mask := <-pw.changed: if mask&syscall.IN_MODIFY > 0 { lastPlayedCacheMutex.Lock() - if songs, err := icecastLastPlayedSongs(playlistPath, lastNSongs); err == nil { + if songs, err := icecastLastPlayedSongs(playlistPath, n); err == nil { lastPlayedCache = songs } lastPlayedCacheMutex.Unlock() } else if mask&syscall.IN_IGNORED > 0 { - playlistWatcher.Close() - IcecastWatchPlaylist(playlistPath, lastNSongs) + pw.Close() + pw.Watch(playlistPath, n) return } } @@ -204,6 +214,6 @@ func IcecastWatchPlaylist(playlistPath string, lastNSongs int) error { return nil } -func IcecastWatchClose() { - playlistWatcher.Close() +func (pw *PlaylistLogWatcher) Close() { + pw.watcher.Close() }