db.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 db
  26. import (
  27. "context"
  28. "crypto/sha1"
  29. "encoding/hex"
  30. "errors"
  31. "fmt"
  32. "log"
  33. "os"
  34. "strings"
  35. "sync"
  36. "time"
  37. common "git.semlanik.org/semlanik/gostfix/common"
  38. "git.semlanik.org/semlanik/gostfix/utils"
  39. "github.com/semlanik/berkeleydb"
  40. bcrypt "golang.org/x/crypto/bcrypt"
  41. bson "go.mongodb.org/mongo-driver/bson"
  42. "go.mongodb.org/mongo-driver/bson/primitive"
  43. mongo "go.mongodb.org/mongo-driver/mongo"
  44. options "go.mongodb.org/mongo-driver/mongo/options"
  45. config "git.semlanik.org/semlanik/gostfix/config"
  46. )
  47. type StuctNotifiers struct {
  48. notifiers []common.Notifier
  49. notifiersLock sync.Mutex
  50. }
  51. var notifiers StuctNotifiers = StuctNotifiers{
  52. notifiers: []common.Notifier{},
  53. }
  54. type Storage struct {
  55. db *mongo.Database
  56. usersCollection *mongo.Collection
  57. tokensCollection *mongo.Collection
  58. emailsCollection *mongo.Collection
  59. allEmailsCollection *mongo.Collection
  60. }
  61. func qualifiedMailCollection(user string) string {
  62. sum := sha1.Sum([]byte(user))
  63. return "mb" + hex.EncodeToString(sum[:])
  64. }
  65. func NewStorage() (s *Storage, err error) {
  66. fullUrl := "mongodb://"
  67. if config.ConfigInstance().MongoUser != "" {
  68. fullUrl += config.ConfigInstance().MongoUser
  69. if config.ConfigInstance().MongoPassword != "" {
  70. fullUrl += ":" + config.ConfigInstance().MongoPassword
  71. }
  72. fullUrl += "@"
  73. }
  74. fullUrl += config.ConfigInstance().MongoAddress
  75. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  76. if err != nil {
  77. return nil, err
  78. }
  79. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  80. defer cancel()
  81. err = client.Connect(ctx)
  82. if err != nil {
  83. return nil, err
  84. }
  85. db := client.Database("gostfix")
  86. index := mongo.IndexModel{
  87. Keys: bson.M{
  88. "user": 1,
  89. },
  90. Options: options.Index().SetUnique(true),
  91. }
  92. collections, err := db.ListCollectionNames(context.Background(), bson.D{})
  93. if err != nil {
  94. log.Fatal(err)
  95. }
  96. createAllEmails := true
  97. for _, collection := range collections {
  98. if collection == "allEmails" {
  99. createAllEmails = false
  100. }
  101. log.Println(collection)
  102. }
  103. if createAllEmails {
  104. unwindStage := bson.D{{"$unwind", bson.D{{"path", "$email"}}}}
  105. groupStage := bson.D{{"$group", bson.D{{"_id", "null"}, {"emails", bson.D{{"$addToSet", "$email"}}}}}}
  106. pipeline := mongo.Pipeline{unwindStage, groupStage}
  107. err = db.CreateView(context.Background(), "allEmails", "emails", pipeline)
  108. if err != nil {
  109. log.Fatal(err)
  110. }
  111. }
  112. s = &Storage{
  113. db: db,
  114. usersCollection: db.Collection("users"),
  115. tokensCollection: db.Collection("tokens"),
  116. emailsCollection: db.Collection("emails"),
  117. allEmailsCollection: db.Collection("allEmails"),
  118. }
  119. //Initial database setup
  120. s.usersCollection.Indexes().CreateOne(context.Background(), index)
  121. s.tokensCollection.Indexes().CreateOne(context.Background(), index)
  122. s.emailsCollection.Indexes().CreateOne(context.Background(), index)
  123. return
  124. }
  125. func (s *Storage) AddUser(user, password, fullName string) error {
  126. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  127. if err != nil {
  128. return err
  129. }
  130. hashString := string(hash)
  131. userInfo := bson.M{
  132. "user": user,
  133. "password": hashString,
  134. "fullName": fullName,
  135. }
  136. _, err = s.usersCollection.InsertOne(context.Background(), userInfo)
  137. if err != nil {
  138. return err
  139. }
  140. err = s.addEmail(user, user, true)
  141. if err != nil {
  142. s.usersCollection.DeleteOne(context.Background(), bson.M{"user": user})
  143. return err
  144. }
  145. return nil
  146. }
  147. func (s *Storage) UpdateUser(user, password, fullName string) error {
  148. userInfo := bson.M{}
  149. if len(password) > 0 && len(password) < 128 {
  150. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  151. if err != nil {
  152. return err
  153. }
  154. hashString := string(hash)
  155. userInfo["password"] = hashString
  156. }
  157. if len(fullName) > 0 && len(fullName) < 128 && utils.RegExpUtilsInstance().FullNameChecker.MatchString(fullName) {
  158. userInfo["fullName"] = fullName
  159. }
  160. if len(userInfo) > 0 {
  161. _, err := s.usersCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": userInfo})
  162. if err != nil {
  163. return err
  164. }
  165. }
  166. return nil
  167. }
  168. func (s *Storage) AddEmail(user string, email string) error {
  169. return s.addEmail(user, email, false)
  170. }
  171. func (s *Storage) addEmail(user string, email string, upsert bool) error {
  172. result := struct {
  173. User string
  174. }{}
  175. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  176. if err != nil {
  177. return err
  178. }
  179. emails, err := s.GetAllEmails()
  180. if err != nil {
  181. return err
  182. }
  183. for _, existingEmail := range emails {
  184. if existingEmail == email {
  185. return errors.New("Email exists")
  186. }
  187. }
  188. emailParts := strings.Split(email, "@")
  189. if len(emailParts) != 2 {
  190. return errors.New("Invalid email format")
  191. }
  192. db, err := berkeleydb.NewDB()
  193. if err != nil {
  194. log.Fatal(err)
  195. }
  196. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  197. if err != nil {
  198. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  199. }
  200. defer db.Close()
  201. err = db.Put(email, emailParts[1]+"/"+emailParts[0])
  202. if err != nil {
  203. return errors.New("Unable to add email to maps" + err.Error())
  204. }
  205. _, err = s.emailsCollection.UpdateOne(context.Background(),
  206. bson.M{"user": user},
  207. bson.M{"$addToSet": bson.M{"email": email}},
  208. options.Update().SetUpsert(upsert))
  209. return err
  210. }
  211. func (s *Storage) RemoveEmail(user string, email string) error {
  212. log.Printf("User %s removes email %s", user, email)
  213. result := s.emailsCollection.FindOne(context.Background(), bson.M{
  214. "user": user,
  215. "email": email,
  216. })
  217. if result.Err() != nil {
  218. return result.Err()
  219. }
  220. db, err := berkeleydb.NewDB()
  221. if err != nil {
  222. log.Fatal(err)
  223. }
  224. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  225. if err != nil {
  226. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  227. }
  228. defer db.Close()
  229. err = db.Delete(email)
  230. if err != nil {
  231. return errors.New("Unable to remove email from maps" + err.Error())
  232. }
  233. err = s.cleanupAttachments(user, email)
  234. if err != nil {
  235. log.Printf("Unable to cleanup attachments for %s %s\n", email, err)
  236. }
  237. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  238. mailsCollection.DeleteMany(context.Background(), bson.M{"email": email})
  239. _, err = s.emailsCollection.UpdateOne(context.Background(),
  240. bson.M{"user": user},
  241. bson.M{"$pull": bson.M{"email": email}})
  242. return err
  243. }
  244. func (s *Storage) SaveMail(email, folder string, m *common.Mail, read bool) error {
  245. user := &struct {
  246. User string
  247. }{}
  248. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(user)
  249. mailsCollection := s.db.Collection(qualifiedMailCollection(user.User))
  250. result, err := mailsCollection.InsertOne(context.Background(), &struct {
  251. Email string
  252. Mail *common.Mail
  253. Folder string
  254. Read bool
  255. Trash bool
  256. }{
  257. Email: email,
  258. Mail: m,
  259. Folder: folder,
  260. Read: read,
  261. Trash: false,
  262. }, options.InsertOne().SetBypassDocumentValidation(true))
  263. if err != nil {
  264. return err
  265. }
  266. mail := *m //deep copy for multithreading
  267. s.notifyNewMail(email, common.MailMetadata{
  268. Id: result.InsertedID.(primitive.ObjectID).Hex(),
  269. Read: false,
  270. Trash: false,
  271. Folder: folder,
  272. User: user.User,
  273. Mail: &mail,
  274. })
  275. stats, err := s.GetEmailStats(user.User, email, folder)
  276. if err == nil {
  277. s.notifyMailboxUpdate(email, []common.FolderStat{stats})
  278. }
  279. return nil
  280. }
  281. func (s *Storage) DeleteMail(user string, mailId string) error {
  282. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  283. oId, err := primitive.ObjectIDFromHex(mailId)
  284. if err != nil {
  285. return err
  286. }
  287. var result common.MailMetadata
  288. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(&result)
  289. if err != nil {
  290. return err
  291. }
  292. for _, attachment := range result.Mail.Body.Attachments {
  293. removeAttachment(attachment.Id)
  294. }
  295. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  296. stats, errTemp := s.GetEmailStats(user, result.Email, common.Trash)
  297. if errTemp == nil {
  298. s.notifyMailboxUpdate(result.Email, []common.FolderStat{stats})
  299. }
  300. return err
  301. }
  302. func (s *Storage) GetMailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  303. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  304. matchFilter := bson.M{"email": email}
  305. if folder == common.Trash {
  306. matchFilter["$or"] = bson.A{
  307. bson.M{"trash": true},
  308. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  309. }
  310. } else {
  311. matchFilter["folder"] = folder
  312. matchFilter["$or"] = bson.A{
  313. bson.M{"trash": false},
  314. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  315. }
  316. }
  317. request := bson.A{
  318. bson.M{"$match": matchFilter},
  319. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  320. }
  321. if frame.Skip > 0 {
  322. request = append(request, bson.M{"$skip": frame.Skip})
  323. }
  324. fmt.Printf("Trying limit number of mails: %v\n", frame)
  325. if frame.Limit > 0 {
  326. fmt.Printf("Limit number of mails: %v\n", frame)
  327. request = append(request, bson.M{"$limit": frame.Limit})
  328. }
  329. cur, err := mailsCollection.Aggregate(context.Background(), request)
  330. if err != nil {
  331. log.Println(err.Error())
  332. return nil, err
  333. }
  334. var headers []*common.MailMetadata
  335. for cur.Next(context.Background()) {
  336. result := &common.MailMetadata{}
  337. err = cur.Decode(result)
  338. if err != nil {
  339. log.Printf("Unable to read database mail record: %s", err)
  340. continue
  341. }
  342. // fmt.Printf("Add mail: %s", result.Id)
  343. headers = append(headers, result)
  344. }
  345. // fmt.Printf("Mails read from database: %v", headers)
  346. return headers, nil
  347. }
  348. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  349. result := &common.UserInfo{}
  350. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  351. return result, err
  352. }
  353. func (s *Storage) GetEmailStats(user string, email string, folder string) (stat common.FolderStat, err error) {
  354. stat = common.FolderStat{
  355. Folder: folder,
  356. }
  357. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  358. matchFilter := bson.M{"email": email}
  359. if folder == common.Trash {
  360. matchFilter["$or"] = bson.A{
  361. bson.M{"trash": true},
  362. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  363. }
  364. } else {
  365. matchFilter["folder"] = folder
  366. matchFilter["$or"] = bson.A{
  367. bson.M{"trash": false},
  368. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  369. }
  370. }
  371. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "total"}})
  372. if err == nil && cur.Next(context.Background()) {
  373. cur.Decode(&stat)
  374. } else {
  375. return
  376. }
  377. matchFilter["read"] = false
  378. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "unread"}})
  379. if err == nil && cur.Next(context.Background()) {
  380. cur.Decode(&stat)
  381. } else {
  382. return
  383. }
  384. return
  385. }
  386. func (s *Storage) GetMail(user string, id string) (metadata *common.MailMetadata, err error) {
  387. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  388. oId, err := primitive.ObjectIDFromHex(id)
  389. if err != nil {
  390. return nil, err
  391. }
  392. metadata = &common.MailMetadata{
  393. Mail: common.NewMail(),
  394. }
  395. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(metadata)
  396. if err != nil {
  397. return nil, err
  398. }
  399. return metadata, nil
  400. }
  401. func (s *Storage) SetRead(user string, id string, read bool) error {
  402. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  403. oId, err := primitive.ObjectIDFromHex(id)
  404. if err != nil {
  405. return err
  406. }
  407. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  408. s.notifyMailboxUpdateForMail(user, id)
  409. return err
  410. }
  411. func (s *Storage) UpdateMail(user string, id string, mailMap interface{}) error {
  412. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  413. oId, err := primitive.ObjectIDFromHex(id)
  414. if err != nil {
  415. return err
  416. }
  417. fromFolder := ""
  418. metadata, err := s.GetMail(user, id)
  419. if err == nil {
  420. if metadata.Trash {
  421. fromFolder = common.Trash
  422. } else {
  423. fromFolder = metadata.Folder
  424. }
  425. } else {
  426. log.Printf("Unable to get mail info to update folder statistics %s", err)
  427. }
  428. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": mailMap})
  429. s.notifyMailboxUpdateForMail(user, id, fromFolder)
  430. return err
  431. }
  432. func (s *Storage) GetUsers() (users []string, err error) {
  433. return nil, nil
  434. }
  435. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  436. result := &struct {
  437. Email []string
  438. }{}
  439. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  440. if err != nil {
  441. return nil, err
  442. }
  443. return result.Email, nil
  444. }
  445. func (s *Storage) GetAllEmails() (emails []string, err error) {
  446. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  447. if cur.Next(context.Background()) {
  448. result := struct {
  449. Emails []string
  450. }{}
  451. err = cur.Decode(&result)
  452. if err == nil {
  453. return result.Emails, nil
  454. }
  455. }
  456. return nil, err
  457. }
  458. func (s *Storage) CheckEmailExists(email string) bool {
  459. result := s.allEmailsCollection.FindOne(context.Background(), bson.M{"emails": email})
  460. return result.Err() == nil
  461. }
  462. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  463. folders = []*common.Folder{
  464. {Name: common.Inbox, Custom: false},
  465. {Name: common.Sent, Custom: false},
  466. {Name: common.Trash, Custom: false},
  467. {Name: common.Spam, Custom: false},
  468. }
  469. return
  470. }
  471. func (s *Storage) ReadEmailMaps() (map[string]string, error) {
  472. registredEmails, err := s.GetAllEmails()
  473. if err != nil {
  474. return nil, err
  475. }
  476. mailPath := config.ConfigInstance().VMailboxBase
  477. mapsFile := config.ConfigInstance().VMailboxMaps
  478. db, err := berkeleydb.NewDB()
  479. if err != nil {
  480. log.Fatal(err)
  481. }
  482. if !utils.FileExists(config.ConfigInstance().VMailboxMaps) {
  483. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, berkeleydb.DbCreate)
  484. } else {
  485. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, berkeleydb.DbRdOnly)
  486. }
  487. if err != nil {
  488. return nil, errors.New("Unable to open virtual mailbox maps " + mapsFile + " " + err.Error())
  489. }
  490. defer db.Close()
  491. cursor, err := db.Cursor()
  492. if err != nil {
  493. return nil, errors.New("Unable to read virtual mailbox maps " + mapsFile + " " + err.Error())
  494. }
  495. emailMaps := make(map[string]string)
  496. for true {
  497. email, path, dberr := cursor.GetNext()
  498. if dberr != nil {
  499. break
  500. }
  501. found := false
  502. for _, registredEmail := range registredEmails {
  503. if email == registredEmail {
  504. found = true
  505. }
  506. }
  507. if !found {
  508. return nil, errors.New("Found non-registred mailbox <" + email + "> in mail maps. Database has inconsistancy")
  509. }
  510. emailMaps[email] = mailPath + "/" + path
  511. }
  512. for _, registredEmail := range registredEmails {
  513. if _, exists := emailMaps[registredEmail]; !exists {
  514. return nil, errors.New("Found existing mailbox <" + registredEmail + "> in database. Mail maps has inconsistancy")
  515. }
  516. }
  517. return emailMaps, nil
  518. }
  519. func removeAttachment(attachmentId string) error {
  520. attachmentPath := config.ConfigInstance().AttachmentsPath + "/" + attachmentId
  521. err := os.Remove(attachmentPath)
  522. if err != nil {
  523. log.Printf("Unable to remove attachment file: %s. Database inconsistency", attachmentPath)
  524. }
  525. return err
  526. }
  527. func (s *Storage) cleanupAttachments(user, email string) error {
  528. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  529. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{
  530. bson.M{"$match": bson.M{"email": email}},
  531. bson.M{"$project": bson.M{"mail.body.attachments": 1}},
  532. bson.M{"$unwind": "$mail.body.attachments"},
  533. bson.M{"$replaceRoot": bson.M{"newRoot": "$mail.body.attachments"}},
  534. })
  535. if err != nil {
  536. return err
  537. }
  538. for cur.Next(context.Background()) {
  539. var attachment common.AttachmentHeader
  540. err = cur.Decode(&attachment)
  541. if err != nil {
  542. log.Printf("Unable to decode attachment")
  543. }
  544. removeAttachment(attachment.Id)
  545. }
  546. return nil
  547. }
  548. func (s *Storage) CheckAttachment(user, attachment string) bool {
  549. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  550. result := mailsCollection.FindOne(context.Background(), bson.M{"mail.body.attachments.id": attachment})
  551. return result.Err() == nil
  552. }
  553. func (s *Storage) RegisterNotifier(notifier common.Notifier) {
  554. if notifier != nil {
  555. notifiers.notifiersLock.Lock()
  556. defer notifiers.notifiersLock.Unlock()
  557. notifiers.notifiers = append(notifiers.notifiers, notifier)
  558. }
  559. }
  560. func (s *Storage) notifyNewMail(email string, mail common.MailMetadata) {
  561. notifiers.notifiersLock.Lock()
  562. defer notifiers.notifiersLock.Unlock()
  563. for _, notifier := range notifiers.notifiers {
  564. notifier.NotifyNewMail(email, mail)
  565. }
  566. }
  567. func (s *Storage) notifyMailboxUpdate(email string, stats []common.FolderStat) {
  568. notifiers.notifiersLock.Lock()
  569. defer notifiers.notifiersLock.Unlock()
  570. for _, notifier := range notifiers.notifiers {
  571. notifier.NotifyMaiboxUpdate(email, stats)
  572. }
  573. }
  574. func (s *Storage) notifyMailboxUpdateForMail(user, id string, folders ...string) {
  575. metadata, err := s.GetMail(user, id)
  576. if err != nil {
  577. log.Printf("Unable to get mail metadata to update mailbox stat %v\n", err)
  578. return
  579. }
  580. if metadata.Trash {
  581. folders = append(folders, common.Trash)
  582. }
  583. var stats []common.FolderStat
  584. stat, err := s.GetEmailStats(user, metadata.Email, metadata.Folder)
  585. stats = append(stats, stat)
  586. for _, folder := range folders {
  587. if folder == metadata.Folder {
  588. continue
  589. }
  590. stat, err = s.GetEmailStats(user, metadata.Email, folder)
  591. if err == nil {
  592. stats = append(stats, stat)
  593. } else {
  594. log.Printf("Unable to update mailbox stat %v\n", err)
  595. }
  596. }
  597. s.notifyMailboxUpdate(metadata.Email, stats)
  598. }