mailscanner.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package scanner
  26. import (
  27. "fmt"
  28. ioutil "io/ioutil"
  29. "log"
  30. utils "../utils"
  31. fsnotify "github.com/fsnotify/fsnotify"
  32. )
  33. type MailScanner struct {
  34. watcher *fsnotify.Watcher
  35. }
  36. func NewMailScanner(mailPath string) (ms *MailScanner) {
  37. fmt.Printf("Add mail folder %s for watching\n", mailPath)
  38. watcher, err := fsnotify.NewWatcher()
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. ms = &MailScanner{
  43. watcher: watcher,
  44. }
  45. files, err := ioutil.ReadDir(mailPath)
  46. if err != nil {
  47. log.Fatal(err)
  48. }
  49. for _, f := range files {
  50. fullPath := mailPath + "/" + f.Name()
  51. if utils.FileExists(fullPath) {
  52. fmt.Printf("Add mail file %s for watching\n", fullPath)
  53. watcher.Add(fullPath)
  54. }
  55. }
  56. return
  57. }
  58. func (ms *MailScanner) Run() {
  59. go func() {
  60. for {
  61. select {
  62. case event, ok := <-ms.watcher.Events:
  63. if !ok {
  64. return
  65. }
  66. if event.Op&fsnotify.Write == fsnotify.Write {
  67. log.Println("New email for", event.Name)
  68. }
  69. case err, ok := <-ms.watcher.Errors:
  70. if !ok {
  71. return
  72. }
  73. log.Println("error:", err)
  74. }
  75. }
  76. }()
  77. }
  78. func (ms *MailScanner) Stop() {
  79. defer ms.watcher.Close()
  80. }