mailscanner.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "fmt"
  4. ioutil "io/ioutil"
  5. "log"
  6. fsnotify "github.com/fsnotify/fsnotify"
  7. )
  8. type MailScanner struct {
  9. watcher *fsnotify.Watcher
  10. }
  11. // func fileExists(filename string) bool {
  12. // info, err := os.Stat(filename)
  13. // if os.IsNotExist(err) {
  14. // return false
  15. // }
  16. // return err == nil && !info.IsDir() && info != nil
  17. // }
  18. func NewMailScanner(mailPath string) (ms *MailScanner) {
  19. fmt.Printf("Add mail folder %s for watching\n", mailPath)
  20. watcher, err := fsnotify.NewWatcher()
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. ms = &MailScanner{
  25. watcher: watcher,
  26. }
  27. files, err := ioutil.ReadDir(mailPath)
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. for _, f := range files {
  32. fullPath := mailPath + "/" + f.Name()
  33. if fileExists(fullPath) {
  34. fmt.Printf("Add mail file %s for watching\n", fullPath)
  35. watcher.Add(fullPath)
  36. }
  37. }
  38. return
  39. }
  40. func (ms *MailScanner) Run() {
  41. go func() {
  42. for {
  43. select {
  44. case event, ok := <-ms.watcher.Events:
  45. if !ok {
  46. return
  47. }
  48. if event.Op&fsnotify.Write == fsnotify.Write {
  49. log.Println("New email for", event.Name)
  50. }
  51. case err, ok := <-ms.watcher.Errors:
  52. if !ok {
  53. return
  54. }
  55. log.Println("error:", err)
  56. }
  57. }
  58. }()
  59. }