templates.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "strconv"
  8. "github.com/knadh/listmonk/models"
  9. "github.com/labstack/echo"
  10. )
  11. const (
  12. // tplTag is the template tag that should be present in a template
  13. // as the placeholder for campaign bodies.
  14. tplTag = `{{ template "content" . }}`
  15. dummyTpl = `
  16. <p>Hi there</p>
  17. <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et elit ac elit sollicitudin condimentum non a magna. Sed tempor mauris in facilisis vehicula. Aenean nisl urna, accumsan ac tincidunt vitae, interdum cursus massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam varius turpis et turpis lacinia placerat. Aenean id ligula a orci lacinia blandit at eu felis. Phasellus vel lobortis lacus. Suspendisse leo elit, luctus sed erat ut, venenatis fermentum ipsum. Donec bibendum neque quis.</p>
  18. <h3>Sub heading</h3>
  19. <p>Nam luctus dui non placerat mattis. Morbi non accumsan orci, vel interdum urna. Duis faucibus id nunc ut euismod. Curabitur et eros id erat feugiat fringilla in eget neque. Aliquam accumsan cursus eros sed faucibus.</p>
  20. <p>Here is a link to <a href="https://listmonk.app" target="_blank">listmonk</a>.</p>`
  21. )
  22. var (
  23. regexpTplTag = regexp.MustCompile(`{{(\s+)?template\s+?"content"(\s+)?\.(\s+)?}}`)
  24. )
  25. // handleGetTemplates handles retrieval of templates.
  26. func handleGetTemplates(c echo.Context) error {
  27. var (
  28. app = c.Get("app").(*App)
  29. out []models.Template
  30. id, _ = strconv.Atoi(c.Param("id"))
  31. single = false
  32. noBody, _ = strconv.ParseBool(c.QueryParam("no_body"))
  33. )
  34. // Fetch one list.
  35. if id > 0 {
  36. single = true
  37. }
  38. err := app.queries.GetTemplates.Select(&out, id, noBody)
  39. if err != nil {
  40. return echo.NewHTTPError(http.StatusInternalServerError,
  41. app.i18n.Ts("globals.messages.errorFetching",
  42. "name", "{globals.terms.templates}", "error", pqErrMsg(err)))
  43. }
  44. if single && len(out) == 0 {
  45. return echo.NewHTTPError(http.StatusBadRequest,
  46. app.i18n.Ts("globals.messages.notFound", "name", "{globals.terms.template}"))
  47. }
  48. if len(out) == 0 {
  49. return c.JSON(http.StatusOK, okResp{[]struct{}{}})
  50. } else if single {
  51. return c.JSON(http.StatusOK, okResp{out[0]})
  52. }
  53. return c.JSON(http.StatusOK, okResp{out})
  54. }
  55. // handlePreviewTemplate renders the HTML preview of a template.
  56. func handlePreviewTemplate(c echo.Context) error {
  57. var (
  58. app = c.Get("app").(*App)
  59. id, _ = strconv.Atoi(c.Param("id"))
  60. body = c.FormValue("body")
  61. tpls []models.Template
  62. )
  63. if body != "" {
  64. if !regexpTplTag.MatchString(body) {
  65. return echo.NewHTTPError(http.StatusBadRequest,
  66. app.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
  67. }
  68. } else {
  69. if id < 1 {
  70. return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
  71. }
  72. err := app.queries.GetTemplates.Select(&tpls, id, false)
  73. if err != nil {
  74. return echo.NewHTTPError(http.StatusInternalServerError,
  75. app.i18n.Ts("globals.messages.errorFetching",
  76. "name", "{globals.terms.templates}", "error", pqErrMsg(err)))
  77. }
  78. if len(tpls) == 0 {
  79. return echo.NewHTTPError(http.StatusBadRequest,
  80. app.i18n.Ts("globals.messages.notFound", "name", "{globals.terms.template}"))
  81. }
  82. body = tpls[0].Body
  83. }
  84. // Compile the template.
  85. camp := models.Campaign{
  86. UUID: dummyUUID,
  87. Name: app.i18n.T("templates.dummyName"),
  88. Subject: app.i18n.T("templates.dummySubject"),
  89. FromEmail: "dummy-campaign@listmonk.app",
  90. TemplateBody: body,
  91. Body: dummyTpl,
  92. }
  93. if err := camp.CompileTemplate(app.manager.TemplateFuncs(&camp)); err != nil {
  94. return echo.NewHTTPError(http.StatusBadRequest,
  95. app.i18n.Ts("templates.errorCompiling", "error", err.Error()))
  96. }
  97. // Render the message body.
  98. msg, err := app.manager.NewCampaignMessage(&camp, dummySubscriber)
  99. if err != nil {
  100. return echo.NewHTTPError(http.StatusBadRequest,
  101. app.i18n.Ts("templates.errorRendering", "error", err.Error()))
  102. }
  103. return c.HTML(http.StatusOK, string(msg.Body()))
  104. }
  105. // handleCreateTemplate handles template creation.
  106. func handleCreateTemplate(c echo.Context) error {
  107. var (
  108. app = c.Get("app").(*App)
  109. o = models.Template{}
  110. )
  111. if err := c.Bind(&o); err != nil {
  112. return err
  113. }
  114. if err := validateTemplate(o, app); err != nil {
  115. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  116. }
  117. // Insert and read ID.
  118. var newID int
  119. if err := app.queries.CreateTemplate.Get(&newID,
  120. o.Name,
  121. o.Body); err != nil {
  122. return echo.NewHTTPError(http.StatusInternalServerError,
  123. app.i18n.Ts("globals.messages.errorCreating",
  124. "name", "{globals.terms.template}", "error", pqErrMsg(err)))
  125. }
  126. // Hand over to the GET handler to return the last insertion.
  127. return handleGetTemplates(copyEchoCtx(c, map[string]string{
  128. "id": fmt.Sprintf("%d", newID),
  129. }))
  130. }
  131. // handleUpdateTemplate handles template modification.
  132. func handleUpdateTemplate(c echo.Context) error {
  133. var (
  134. app = c.Get("app").(*App)
  135. id, _ = strconv.Atoi(c.Param("id"))
  136. )
  137. if id < 1 {
  138. return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
  139. }
  140. var o models.Template
  141. if err := c.Bind(&o); err != nil {
  142. return err
  143. }
  144. if err := validateTemplate(o, app); err != nil {
  145. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  146. }
  147. res, err := app.queries.UpdateTemplate.Exec(id, o.Name, o.Body)
  148. if err != nil {
  149. return echo.NewHTTPError(http.StatusInternalServerError,
  150. app.i18n.Ts("globals.messages.errorUpdating",
  151. "name", "{globals.terms.template}", "error", pqErrMsg(err)))
  152. }
  153. if n, _ := res.RowsAffected(); n == 0 {
  154. return echo.NewHTTPError(http.StatusBadRequest,
  155. app.i18n.Ts("globals.messages.notFound", "name", "{globals.terms.template}"))
  156. }
  157. return handleGetTemplates(c)
  158. }
  159. // handleTemplateSetDefault handles template modification.
  160. func handleTemplateSetDefault(c echo.Context) error {
  161. var (
  162. app = c.Get("app").(*App)
  163. id, _ = strconv.Atoi(c.Param("id"))
  164. )
  165. if id < 1 {
  166. return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
  167. }
  168. _, err := app.queries.SetDefaultTemplate.Exec(id)
  169. if err != nil {
  170. return echo.NewHTTPError(http.StatusInternalServerError,
  171. app.i18n.Ts("globals.messages.errorUpdating",
  172. "name", "{globals.terms.template}", "error", pqErrMsg(err)))
  173. }
  174. return handleGetTemplates(c)
  175. }
  176. // handleDeleteTemplate handles template deletion.
  177. func handleDeleteTemplate(c echo.Context) error {
  178. var (
  179. app = c.Get("app").(*App)
  180. id, _ = strconv.Atoi(c.Param("id"))
  181. )
  182. if id < 1 {
  183. return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidID"))
  184. }
  185. var delID int
  186. err := app.queries.DeleteTemplate.Get(&delID, id)
  187. if err != nil {
  188. return echo.NewHTTPError(http.StatusInternalServerError,
  189. app.i18n.Ts("globals.messages.errorDeleting",
  190. "name", "{globals.terms.template}", "error", pqErrMsg(err)))
  191. }
  192. if delID == 0 {
  193. return echo.NewHTTPError(http.StatusBadRequest,
  194. app.i18n.T("templates.cantDeleteDefault"))
  195. }
  196. return c.JSON(http.StatusOK, okResp{true})
  197. }
  198. // validateTemplate validates template fields.
  199. func validateTemplate(o models.Template, app *App) error {
  200. if !strHasLen(o.Name, 1, stdInputMaxLen) {
  201. return errors.New(app.i18n.T("campaigns.fieldInvalidName"))
  202. }
  203. if !regexpTplTag.MatchString(o.Body) {
  204. return echo.NewHTTPError(http.StatusBadRequest,
  205. app.i18n.Ts("templates.placeholderHelp", "placeholder", tplTag))
  206. }
  207. return nil
  208. }