A webmail client. Forked from https://git.sr.ht/~migadu/alps
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

303 řádky
6.5 KiB

  1. package koushin
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "mime"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "time"
  10. imapclient "github.com/emersion/go-imap/client"
  11. "github.com/labstack/echo/v4"
  12. )
  13. const cookieName = "koushin_session"
  14. type Server struct {
  15. imap struct {
  16. host string
  17. tls bool
  18. insecure bool
  19. pool *ConnPool
  20. }
  21. smtp struct {
  22. host string
  23. tls bool
  24. insecure bool
  25. }
  26. }
  27. func (s *Server) parseIMAPURL(imapURL string) error {
  28. u, err := url.Parse(imapURL)
  29. if err != nil {
  30. return fmt.Errorf("failed to parse IMAP server URL: %v", err)
  31. }
  32. s.imap.host = u.Host
  33. switch u.Scheme {
  34. case "imap":
  35. // This space is intentionally left blank
  36. case "imaps":
  37. s.imap.tls = true
  38. case "imap+insecure":
  39. s.imap.insecure = true
  40. default:
  41. return fmt.Errorf("unrecognized IMAP URL scheme: %s", u.Scheme)
  42. }
  43. return nil
  44. }
  45. func (s *Server) parseSMTPURL(smtpURL string) error {
  46. u, err := url.Parse(smtpURL)
  47. if err != nil {
  48. return fmt.Errorf("failed to parse SMTP server URL: %v", err)
  49. }
  50. s.smtp.host = u.Host
  51. switch u.Scheme {
  52. case "smtp":
  53. // This space is intentionally left blank
  54. case "smtps":
  55. s.smtp.tls = true
  56. case "smtp+insecure":
  57. s.smtp.insecure = true
  58. default:
  59. return fmt.Errorf("unrecognized SMTP URL scheme: %s", u.Scheme)
  60. }
  61. return nil
  62. }
  63. func NewServer(imapURL, smtpURL string) (*Server, error) {
  64. s := &Server{}
  65. if err := s.parseIMAPURL(imapURL); err != nil {
  66. return nil, err
  67. }
  68. s.imap.pool = NewConnPool()
  69. if smtpURL != "" {
  70. if err := s.parseSMTPURL(smtpURL); err != nil {
  71. return nil, err
  72. }
  73. }
  74. return s, nil
  75. }
  76. type context struct {
  77. echo.Context
  78. server *Server
  79. conn *imapclient.Client
  80. }
  81. var aLongTimeAgo = time.Unix(233431200, 0)
  82. func (c *context) setToken(token string) {
  83. cookie := http.Cookie{
  84. Name: cookieName,
  85. Value: token,
  86. HttpOnly: true,
  87. // TODO: domain, secure
  88. }
  89. if token == "" {
  90. cookie.Expires = aLongTimeAgo // unset the cookie
  91. }
  92. c.SetCookie(&cookie)
  93. }
  94. func handleLogin(ectx echo.Context) error {
  95. ctx := ectx.(*context)
  96. username := ctx.FormValue("username")
  97. password := ctx.FormValue("password")
  98. if username != "" && password != "" {
  99. conn, err := ctx.server.connectIMAP()
  100. if err != nil {
  101. return err
  102. }
  103. if err := conn.Login(username, password); err != nil {
  104. conn.Logout()
  105. return ctx.Render(http.StatusOK, "login.html", nil)
  106. }
  107. token, err := ctx.server.imap.pool.Put(conn)
  108. if err != nil {
  109. return fmt.Errorf("failed to put connection in pool: %v", err)
  110. }
  111. ctx.setToken(token)
  112. return ctx.Redirect(http.StatusFound, "/mailbox/INBOX")
  113. }
  114. return ctx.Render(http.StatusOK, "login.html", nil)
  115. }
  116. func handleGetPart(ctx *context, raw bool) error {
  117. mboxName := ctx.Param("mbox")
  118. uid, err := parseUid(ctx.Param("uid"))
  119. if err != nil {
  120. return echo.NewHTTPError(http.StatusBadRequest, err)
  121. }
  122. partPathString := ctx.QueryParam("part")
  123. partPath, err := parsePartPath(partPathString)
  124. if err != nil {
  125. return echo.NewHTTPError(http.StatusBadRequest, err)
  126. }
  127. msg, part, err := getMessagePart(ctx.conn, mboxName, uid, partPath)
  128. if err != nil {
  129. return err
  130. }
  131. mimeType, _, err := part.Header.ContentType()
  132. if err != nil {
  133. return fmt.Errorf("failed to parse part Content-Type: %v", err)
  134. }
  135. if len(partPath) == 0 {
  136. mimeType = "message/rfc822"
  137. }
  138. if raw {
  139. disp, dispParams, _ := part.Header.ContentDisposition()
  140. filename := dispParams["filename"]
  141. if !strings.EqualFold(mimeType, "text/plain") || strings.EqualFold(disp, "attachment") {
  142. dispParams := make(map[string]string)
  143. if filename != "" {
  144. dispParams["filename"] = filename
  145. }
  146. disp := mime.FormatMediaType("attachment", dispParams)
  147. ctx.Response().Header().Set("Content-Disposition", disp)
  148. }
  149. return ctx.Stream(http.StatusOK, mimeType, part.Body)
  150. }
  151. var body string
  152. if strings.HasPrefix(strings.ToLower(mimeType), "text/") {
  153. b, err := ioutil.ReadAll(part.Body)
  154. if err != nil {
  155. return fmt.Errorf("failed to read part body: %v", err)
  156. }
  157. body = string(b)
  158. }
  159. return ctx.Render(http.StatusOK, "message.html", map[string]interface{}{
  160. "Mailbox": ctx.conn.Mailbox(),
  161. "Message": msg,
  162. "Body": body,
  163. "PartPath": partPathString,
  164. })
  165. }
  166. func handleCompose(ectx echo.Context) error {
  167. ctx := ectx.(*context)
  168. return ctx.Render(http.StatusOK, "compose.html", nil)
  169. }
  170. func New(imapURL, smtpURL string) *echo.Echo {
  171. e := echo.New()
  172. s, err := NewServer(imapURL, smtpURL)
  173. if err != nil {
  174. e.Logger.Fatal(err)
  175. }
  176. e.HTTPErrorHandler = func(err error, c echo.Context) {
  177. code := http.StatusInternalServerError
  178. if he, ok := err.(*echo.HTTPError); ok {
  179. code = he.Code
  180. } else {
  181. c.Logger().Error(err)
  182. }
  183. // TODO: hide internal errors
  184. c.String(code, err.Error())
  185. }
  186. e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  187. return func(ectx echo.Context) error {
  188. ctx := &context{Context: ectx, server: s}
  189. cookie, err := ctx.Cookie(cookieName)
  190. if err == http.ErrNoCookie {
  191. // Require auth for all pages except /login
  192. if ctx.Path() == "/login" {
  193. return next(ctx)
  194. } else {
  195. return ctx.Redirect(http.StatusFound, "/login")
  196. }
  197. } else if err != nil {
  198. return err
  199. }
  200. ctx.conn, err = ctx.server.imap.pool.Get(cookie.Value)
  201. if err == ErrSessionExpired {
  202. ctx.setToken("")
  203. return ctx.Redirect(http.StatusFound, "/login")
  204. } else if err != nil {
  205. return err
  206. }
  207. return next(ctx)
  208. }
  209. })
  210. e.Renderer, err = loadTemplates()
  211. if err != nil {
  212. e.Logger.Fatal("Failed to load templates:", err)
  213. }
  214. e.GET("/mailbox/:mbox", func(ectx echo.Context) error {
  215. ctx := ectx.(*context)
  216. mailboxes, err := listMailboxes(ctx.conn)
  217. if err != nil {
  218. return err
  219. }
  220. msgs, err := listMessages(ctx.conn, ctx.Param("mbox"))
  221. if err != nil {
  222. return err
  223. }
  224. return ctx.Render(http.StatusOK, "mailbox.html", map[string]interface{}{
  225. "Mailbox": ctx.conn.Mailbox(),
  226. "Mailboxes": mailboxes,
  227. "Messages": msgs,
  228. })
  229. })
  230. e.GET("/message/:mbox/:uid", func(ectx echo.Context) error {
  231. ctx := ectx.(*context)
  232. return handleGetPart(ctx, false)
  233. })
  234. e.GET("/message/:mbox/:uid/raw", func(ectx echo.Context) error {
  235. ctx := ectx.(*context)
  236. return handleGetPart(ctx, true)
  237. })
  238. e.GET("/login", handleLogin)
  239. e.POST("/login", handleLogin)
  240. e.GET("/logout", func(ectx echo.Context) error {
  241. ctx := ectx.(*context)
  242. if err := ctx.conn.Logout(); err != nil {
  243. return fmt.Errorf("failed to logout: %v", err)
  244. }
  245. ctx.setToken("")
  246. return ctx.Redirect(http.StatusFound, "/login")
  247. })
  248. e.GET("/compose", handleCompose)
  249. e.POST("/compose", handleCompose)
  250. e.Static("/assets", "public/assets")
  251. return e
  252. }