mailbox.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. "crypto/md5"
  28. "crypto/tls"
  29. "encoding/hex"
  30. "encoding/json"
  31. "fmt"
  32. "html"
  33. template "html/template"
  34. "log"
  35. "net/http"
  36. "net/smtp"
  37. "strconv"
  38. "strings"
  39. "time"
  40. common "git.semlanik.org/semlanik/gostfix/common"
  41. "git.semlanik.org/semlanik/gostfix/config"
  42. )
  43. func (s *Server) handleMailbox(w http.ResponseWriter, user, email string) {
  44. fmt.Fprint(w, s.templater.ExecuteIndex(&struct {
  45. Folders template.HTML
  46. MailNew template.HTML
  47. Version template.HTML
  48. }{
  49. MailNew: template.HTML(s.templater.ExecuteNewMail("")),
  50. Folders: "Folders",
  51. Version: common.Version,
  52. }))
  53. }
  54. func (s *Server) handleMailboxRequest(path, user string, mailbox int, w http.ResponseWriter, r *http.Request) {
  55. log.Printf("Handle mailbox %s", path)
  56. emails, err := s.storage.GetEmails(user)
  57. if err != nil || len(emails) <= 0 {
  58. s.error(http.StatusInternalServerError, "Unable to access mailbox", w)
  59. return
  60. }
  61. if len(emails) <= mailbox {
  62. if path == "" {
  63. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  64. } else {
  65. s.error(http.StatusInternalServerError, "Unable to access mailbox", w)
  66. }
  67. return
  68. }
  69. switch path {
  70. case "":
  71. s.handleMailbox(w, user, emails[mailbox])
  72. case "folders":
  73. s.handleFolders(w, user, emails[mailbox])
  74. case "folderStat":
  75. s.handleFolderStat(w, r, user, emails[mailbox])
  76. case "statusLine":
  77. s.handleStatusLine(w, user, emails[mailbox])
  78. case "mailList":
  79. s.handleMailList(w, r, user, emails[mailbox])
  80. case "sendNewMail":
  81. s.handleNewMail(w, r, user, emails[mailbox])
  82. case "notifierSubscribe":
  83. s.Notifier.handleNotifierRequest(w, r, emails[mailbox])
  84. default:
  85. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  86. }
  87. }
  88. func (s *Server) handleFolders(w http.ResponseWriter, user, email string) {
  89. folders := s.storage.GetFolders(email)
  90. out, err := json.Marshal(&struct {
  91. Folders []*common.Folder `json:"folders"`
  92. Html string `json:"html"`
  93. }{
  94. Folders: folders,
  95. Html: s.templater.ExecuteFolders(s.storage.GetFolders(email)),
  96. })
  97. if err != nil {
  98. s.error(http.StatusInternalServerError, "Could not fetch folder list", w)
  99. }
  100. w.Write(out)
  101. }
  102. func (s *Server) handleFolderStat(w http.ResponseWriter, r *http.Request, user, email string) {
  103. unread, total, err := s.storage.GetEmailStats(user, email, s.extractFolder(email, r))
  104. if err != nil {
  105. s.error(http.StatusInternalServerError, "Couldn't read mailbox stat", w)
  106. return
  107. }
  108. out, err := json.Marshal(&struct {
  109. Total int `json:"total"`
  110. Unread int `json:"unread"`
  111. }{
  112. Total: total,
  113. Unread: unread,
  114. })
  115. if err != nil {
  116. s.error(http.StatusInternalServerError, "Couldn't parse mailbox stat", w)
  117. return
  118. }
  119. w.Write(out)
  120. }
  121. func (s *Server) handleMailList(w http.ResponseWriter, r *http.Request, user, email string) {
  122. folder := s.extractFolder(email, r)
  123. page, err := strconv.Atoi(r.FormValue("page"))
  124. if err != nil {
  125. page = 0
  126. }
  127. _, total, err := s.storage.GetEmailStats(user, email, folder)
  128. if err != nil {
  129. s.error(http.StatusInternalServerError, "Couldn't read email database", w)
  130. return
  131. }
  132. mailList, err := s.storage.GetMailList(user, email, folder, common.Frame{Skip: int32(50 * page), Limit: 50})
  133. if err != nil {
  134. s.error(http.StatusInternalServerError, "Couldn't read email database", w)
  135. return
  136. }
  137. out, err := json.Marshal(&struct {
  138. Total int `json:"total"`
  139. Html string `json:"html"`
  140. }{
  141. Total: total,
  142. Html: s.templater.ExecuteMailList(mailList),
  143. })
  144. if err != nil {
  145. s.error(http.StatusInternalServerError, "Could not perform maillist", w)
  146. return
  147. }
  148. w.Write(out)
  149. }
  150. func (s *Server) handleStatusLine(w http.ResponseWriter, user, email string) {
  151. info, err := s.storage.GetUserInfo(user)
  152. if err != nil {
  153. s.error(http.StatusInternalServerError, "Could not read user info", w)
  154. return
  155. }
  156. type EmailIndexes struct {
  157. Index int
  158. Email string
  159. }
  160. emails, err := s.storage.GetEmails(user)
  161. emailsIndexes := []EmailIndexes{}
  162. k := 0
  163. for i, existingEmail := range emails {
  164. emailsIndexes = append(emailsIndexes, EmailIndexes{i, existingEmail})
  165. if existingEmail == email {
  166. k = i
  167. }
  168. }
  169. emailsIndexes = emailsIndexes[:k+copy(emailsIndexes[k:], emailsIndexes[k+1:])]
  170. if err != nil {
  171. s.error(http.StatusInternalServerError, "Could not read user info", w)
  172. return
  173. }
  174. emailHash := md5.Sum([]byte(strings.Trim(email, "\t ")))
  175. fmt.Fprint(w, s.templater.ExecuteStatusLine(&struct {
  176. Name string
  177. Email string
  178. EmailHash string
  179. EmailsIndexes []EmailIndexes
  180. }{
  181. Name: info.FullName,
  182. Email: email,
  183. EmailHash: hex.EncodeToString(emailHash[:]),
  184. EmailsIndexes: emailsIndexes,
  185. }))
  186. }
  187. func (s *Server) extractFolder(email string, r *http.Request) string {
  188. folder := r.FormValue("folder")
  189. folders := s.storage.GetFolders(email)
  190. ok := false
  191. for _, existFolder := range folders {
  192. if folder == existFolder.Name {
  193. ok = true
  194. break
  195. }
  196. }
  197. if !ok {
  198. folder = common.Inbox
  199. }
  200. return folder
  201. }
  202. func (s *Server) handleNewMail(w http.ResponseWriter, r *http.Request, user, email string) {
  203. rawMail := &common.Mail{
  204. Header: &common.MailHeader{
  205. From: email,
  206. To: r.FormValue("to"),
  207. Cc: r.FormValue("cc"),
  208. Bcc: r.FormValue("bcc"),
  209. Date: time.Now().Unix(),
  210. Subject: r.FormValue("subject"),
  211. },
  212. Body: &common.MailBody{
  213. PlainText: html.EscapeString(r.FormValue("body")),
  214. },
  215. }
  216. resultEmail := s.templater.ExecuteMail(&struct {
  217. From string
  218. Subject string
  219. Date template.HTML
  220. To string
  221. Body template.HTML
  222. }{
  223. From: rawMail.Header.From,
  224. To: rawMail.Header.To,
  225. Subject: rawMail.Header.Subject,
  226. Date: template.HTML(time.Unix(rawMail.Header.Date, 0).Format(time.RFC1123Z)),
  227. Body: template.HTML(rawMail.Body.PlainText),
  228. })
  229. host := config.ConfigInstance().MyDomain
  230. server := host + ":25"
  231. _, token := s.extractAuth(w, r)
  232. auth := smtp.PlainAuth("token", user, token, host)
  233. tlsconfig := &tls.Config{
  234. InsecureSkipVerify: true,
  235. ServerName: host,
  236. }
  237. client, err := smtp.Dial(server)
  238. if err != nil {
  239. s.error(http.StatusInternalServerError, "Unable to send message", w)
  240. log.Printf("Dial %s \n", err)
  241. return
  242. }
  243. err = client.StartTLS(tlsconfig)
  244. if err != nil {
  245. s.error(http.StatusInternalServerError, "Unable to send message", w)
  246. log.Printf("StartTLS %s \n", err)
  247. return
  248. }
  249. err = client.Auth(auth)
  250. if err != nil {
  251. s.error(http.StatusInternalServerError, "Unable to send message", w)
  252. log.Printf("Auth %s \n", err)
  253. return
  254. }
  255. err = client.Mail(email)
  256. if err != nil {
  257. s.error(http.StatusInternalServerError, "Unable to send message", w)
  258. log.Printf("Mail %s \n", err)
  259. return
  260. }
  261. err = client.Rcpt(rawMail.Header.To)
  262. if err != nil {
  263. s.error(http.StatusInternalServerError, "Unable to send message", w)
  264. log.Println(err)
  265. return
  266. }
  267. mailWriter, err := client.Data()
  268. if err != nil {
  269. s.error(http.StatusInternalServerError, "Unable to send message", w)
  270. log.Println(err)
  271. return
  272. }
  273. _, err = mailWriter.Write([]byte(resultEmail))
  274. if err != nil {
  275. s.error(http.StatusInternalServerError, "Unable to send message", w)
  276. log.Println(err)
  277. return
  278. }
  279. err = mailWriter.Close()
  280. if err != nil {
  281. s.error(http.StatusInternalServerError, "Unable to send message", w)
  282. log.Println(err)
  283. return
  284. }
  285. client.Quit()
  286. s.storage.SaveMail(email, common.Sent, rawMail, true)
  287. w.WriteHeader(http.StatusOK)
  288. w.Write([]byte{0})
  289. }