mailbox.go 8.4 KB

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