mailscanner.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "log"
  29. "os"
  30. "sync"
  31. "git.semlanik.org/semlanik/gostfix/common"
  32. config "git.semlanik.org/semlanik/gostfix/config"
  33. db "git.semlanik.org/semlanik/gostfix/db"
  34. utils "git.semlanik.org/semlanik/gostfix/utils"
  35. fsnotify "github.com/fsnotify/fsnotify"
  36. )
  37. const (
  38. SignalReconfigure = iota
  39. )
  40. type MailScanner struct {
  41. watcher *fsnotify.Watcher
  42. emailMaps map[string]string
  43. storage *db.Storage
  44. signalChannel chan int
  45. notifiers []common.Notifier
  46. notifiersLock sync.Mutex
  47. }
  48. func NewMailScanner() (ms *MailScanner) {
  49. watcher, err := fsnotify.NewWatcher()
  50. if err != nil {
  51. log.Fatal(err)
  52. return
  53. }
  54. storage, err := db.NewStorage()
  55. if err != nil {
  56. log.Fatal(err)
  57. return
  58. }
  59. if !utils.DirectoryExists(config.ConfigInstance().AttachmentsPath) {
  60. err = os.Mkdir(config.ConfigInstance().AttachmentsPath, 0755)
  61. if err != nil {
  62. log.Fatal(err)
  63. return
  64. }
  65. }
  66. ms = &MailScanner{
  67. watcher: watcher,
  68. storage: storage,
  69. signalChannel: make(chan int),
  70. notifiers: []common.Notifier{},
  71. }
  72. return
  73. }
  74. func (ms *MailScanner) Reconfigure() {
  75. ms.signalChannel <- SignalReconfigure
  76. }
  77. func (ms *MailScanner) checkEmailRegistred(email string) bool {
  78. emails, err := ms.storage.GetAllEmails()
  79. if err != nil {
  80. return false
  81. }
  82. for _, e := range emails {
  83. if email == e {
  84. return true
  85. }
  86. }
  87. return false
  88. }
  89. func (ms *MailScanner) reconfigure() {
  90. var err error
  91. ms.emailMaps, err = ms.storage.ReadEmailMaps()
  92. if err != nil {
  93. log.Fatal(err.Error())
  94. }
  95. for mailbox, mailPath := range ms.emailMaps {
  96. if !utils.FileExists(mailPath) {
  97. file, err := os.Create(mailPath)
  98. if err != nil {
  99. fmt.Printf("Unable to create mailbox for watching %s\n", err)
  100. continue
  101. }
  102. file.Close()
  103. }
  104. mails := ms.readMailFile(mailPath)
  105. for _, mail := range mails {
  106. ms.storage.SaveMail(mailbox, common.Inbox, mail, false)
  107. }
  108. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  109. err := ms.watcher.Add(mailPath)
  110. if err != nil {
  111. fmt.Printf("Unable to add mailbox for watching\n")
  112. } else {
  113. fmt.Printf("Add mail file %s for watching\n", mailPath)
  114. }
  115. }
  116. }
  117. func (ms *MailScanner) Run() {
  118. go func() {
  119. ms.reconfigure()
  120. for {
  121. select {
  122. case signal := <-ms.signalChannel:
  123. switch signal {
  124. case SignalReconfigure:
  125. ms.reconfigure()
  126. }
  127. case event, ok := <-ms.watcher.Events:
  128. if !ok {
  129. return
  130. }
  131. if event.Op&fsnotify.Write == fsnotify.Write {
  132. log.Println("iNotify write")
  133. mailPath := event.Name
  134. mailbox := ""
  135. for k, v := range ms.emailMaps {
  136. if v == mailPath {
  137. mailbox = k
  138. }
  139. }
  140. if mailbox != "" {
  141. mails := ms.readMailFile(mailPath)
  142. if len(mails) > 0 {
  143. ms.notifyMailboxUpdate(mailbox)
  144. }
  145. for _, mail := range mails {
  146. ms.storage.SaveMail(mailbox, common.Inbox, mail, false)
  147. ms.notifyNewMail(mailbox, *mail)
  148. }
  149. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  150. } else {
  151. log.Printf("Invalid path update triggered: %s", mailPath)
  152. }
  153. }
  154. case err, ok := <-ms.watcher.Errors:
  155. if !ok {
  156. return
  157. }
  158. log.Println("error:", err)
  159. }
  160. }
  161. }()
  162. }
  163. func (ms *MailScanner) Stop() {
  164. defer ms.watcher.Close()
  165. }
  166. func (ms *MailScanner) readMailFile(mailPath string) (mails []*common.Mail) {
  167. log.Println("Read mail file")
  168. defer log.Println("Exit read mail file")
  169. if !utils.FileExists(mailPath) {
  170. return nil
  171. }
  172. file, err := utils.OpenAndLockWait(mailPath)
  173. if err != nil {
  174. return nil
  175. }
  176. defer file.CloseAndUnlock()
  177. mails = parseFile(file)
  178. if len(mails) > 0 {
  179. file.Truncate(0)
  180. }
  181. return mails
  182. }
  183. func (ms *MailScanner) RegisterNotifier(notifier common.Notifier) {
  184. if notifier != nil {
  185. ms.notifiersLock.Lock()
  186. defer ms.notifiersLock.Unlock()
  187. ms.notifiers = append(ms.notifiers, notifier)
  188. }
  189. }
  190. func (ms *MailScanner) notifyNewMail(email string, mail common.Mail) {
  191. ms.notifiersLock.Lock()
  192. defer ms.notifiersLock.Unlock()
  193. for _, notifier := range ms.notifiers {
  194. notifier.NotifyNewMail(email, mail)
  195. }
  196. }
  197. func (ms *MailScanner) notifyMailboxUpdate(email string) {
  198. ms.notifiersLock.Lock()
  199. defer ms.notifiersLock.Unlock()
  200. for _, notifier := range ms.notifiers {
  201. notifier.NotifyMaiboxUpdate(email)
  202. }
  203. }