first commit
This commit is contained in:
60
watcher/watcher.go
Normal file
60
watcher/watcher.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package watcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.savin.nyc/alex/go-iar-notificator/bus"
|
||||
"github.com/fsnotify/fsnotify"
|
||||
)
|
||||
|
||||
const (
|
||||
EventNewMP3 = "new_mp3" // Event name for new MP3 detection
|
||||
)
|
||||
|
||||
func WatchDirectory(ctx context.Context, dirToWatch string, eb *bus.CustomEventBus, logger *slog.Logger) {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
logger.Error("Failed to create directory watcher", "error", err)
|
||||
return
|
||||
}
|
||||
defer watcher.Close()
|
||||
|
||||
// Ensure the directory exists
|
||||
if err := os.MkdirAll(dirToWatch, os.ModePerm); err != nil {
|
||||
logger.Error("Failed to create watched directory", "error", err, "dir", dirToWatch)
|
||||
return
|
||||
}
|
||||
|
||||
if err := watcher.Add(dirToWatch); err != nil {
|
||||
logger.Error("Failed to add watch on directory", "error", err, "dir", dirToWatch)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Info("Watching directory for MP3 files", "dir", dirToWatch)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
logger.Info("Stopping directory watcher")
|
||||
return
|
||||
case event, ok := <-watcher.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// Trigger on file creation or write (e.g., when saved)
|
||||
if (event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Write == fsnotify.Write) &&
|
||||
filepath.Ext(event.Name) == ".mp3" {
|
||||
logger.Info("Detected new or saved MP3 file", "path", event.Name)
|
||||
eb.Publish(EventNewMP3, event.Name)
|
||||
}
|
||||
case err, ok := <-watcher.Errors:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
logger.Error("Directory watcher error", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user