mailbox.go 9.0 KB

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