webnotifier.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 web
  26. import (
  27. "encoding/json"
  28. "fmt"
  29. "log"
  30. "net/http"
  31. "sync"
  32. "git.semlanik.org/semlanik/gostfix/common"
  33. "github.com/gorilla/websocket"
  34. )
  35. type webNotification struct {
  36. Type string `json:"type"`
  37. Data interface{} `json:"data"`
  38. }
  39. type websocketChannel struct {
  40. connection *websocket.Conn
  41. channel chan interface{}
  42. }
  43. type webNotifier struct {
  44. server *Server
  45. notifiers map[string]*websocketChannel
  46. notifiersLock sync.Mutex
  47. }
  48. func NewWebNotifier() *webNotifier {
  49. return &webNotifier{
  50. notifiers: make(map[string]*websocketChannel),
  51. }
  52. }
  53. func (wn *webNotifier) NotifyMaiboxUpdate(email string, stats []common.FolderStat) {
  54. if channel, ok := wn.getNotifier(email); ok {
  55. channel.channel <- stats
  56. }
  57. }
  58. func (wn *webNotifier) NotifyNewMail(email string, m common.MailMetadata) {
  59. if channel, ok := wn.getNotifier(email); ok {
  60. channel.channel <- &m
  61. }
  62. //TODO: this functionality needs JS support to create new mails from templates
  63. }
  64. var upgrader = websocket.Upgrader{
  65. ReadBufferSize: 1024,
  66. WriteBufferSize: 1024,
  67. }
  68. func (wn *webNotifier) handleNotifierRequest(w http.ResponseWriter, r *http.Request, email string) {
  69. fmt.Printf("New web socket session start %s\n", email)
  70. conn, err := upgrader.Upgrade(w, r, nil)
  71. if err != nil {
  72. log.Printf("Could not upgrade websocket %s\n", err)
  73. http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
  74. return
  75. }
  76. c := &websocketChannel{
  77. connection: conn,
  78. channel: make(chan interface{}, 10),
  79. }
  80. wn.addNotifier(email, c)
  81. conn.SetCloseHandler(func(code int, text string) error {
  82. fmt.Printf("Web socket session end %s\n", email)
  83. wn.removeNotifier(email)
  84. conn.Close()
  85. return nil
  86. })
  87. go wn.handleNotifications(c)
  88. }
  89. func (wn *webNotifier) handleNotifications(c *websocketChannel) {
  90. for {
  91. select {
  92. case data := <-c.channel:
  93. var err error = nil
  94. var out []byte
  95. if newMail, ok := data.(*common.MailMetadata); ok {
  96. out, err = json.Marshal(&webNotification{
  97. Type: "mail",
  98. Data: &struct {
  99. Folder string `json:"folder"`
  100. HTML string `json:"html"`
  101. }{
  102. Folder: newMail.Folder,
  103. HTML: wn.server.templater.ExecuteMailList([]*common.MailMetadata{newMail}),
  104. },
  105. })
  106. } else if stats, ok := data.([]common.FolderStat); ok {
  107. out, err = json.Marshal(&webNotification{
  108. Type: "stats",
  109. Data: stats,
  110. })
  111. }
  112. if err != nil {
  113. log.Printf("Unable to marshal notification data %v\n", err)
  114. } else {
  115. err = c.connection.WriteMessage(websocket.TextMessage, out)
  116. if err != nil {
  117. log.Println(err.Error())
  118. return
  119. }
  120. }
  121. }
  122. }
  123. }
  124. func (wn *webNotifier) getNotifier(email string) (channel *websocketChannel, ok bool) {
  125. wn.notifiersLock.Lock()
  126. defer wn.notifiersLock.Unlock()
  127. channel, ok = wn.notifiers[email]
  128. return
  129. }
  130. func (wn *webNotifier) addNotifier(email string, channel *websocketChannel) {
  131. wn.notifiersLock.Lock()
  132. defer wn.notifiersLock.Unlock()
  133. wn.notifiers[email] = channel
  134. }
  135. func (wn *webNotifier) removeNotifier(email string) {
  136. wn.notifiersLock.Lock()
  137. defer wn.notifiersLock.Unlock()
  138. delete(wn.notifiers, email)
  139. }