mailbox.go 8.9 KB

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