models.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. package models
  2. import (
  3. "bytes"
  4. "database/sql/driver"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "html/template"
  9. "regexp"
  10. "strings"
  11. "time"
  12. "github.com/jmoiron/sqlx"
  13. "github.com/jmoiron/sqlx/types"
  14. "github.com/lib/pq"
  15. "github.com/yuin/goldmark"
  16. "github.com/yuin/goldmark/extension"
  17. "github.com/yuin/goldmark/renderer/html"
  18. null "gopkg.in/volatiletech/null.v6"
  19. )
  20. // Enum values for various statuses.
  21. const (
  22. // Subscriber.
  23. SubscriberStatusEnabled = "enabled"
  24. SubscriberStatusDisabled = "disabled"
  25. SubscriberStatusBlockListed = "blocklisted"
  26. // Subscription.
  27. SubscriptionStatusUnconfirmed = "unconfirmed"
  28. SubscriptionStatusConfirmed = "confirmed"
  29. SubscriptionStatusUnsubscribed = "unsubscribed"
  30. // Campaign.
  31. CampaignStatusDraft = "draft"
  32. CampaignStatusScheduled = "scheduled"
  33. CampaignStatusRunning = "running"
  34. CampaignStatusPaused = "paused"
  35. CampaignStatusFinished = "finished"
  36. CampaignStatusCancelled = "cancelled"
  37. CampaignTypeRegular = "regular"
  38. CampaignTypeOptin = "optin"
  39. CampaignContentTypeRichtext = "richtext"
  40. CampaignContentTypeHTML = "html"
  41. CampaignContentTypeMarkdown = "markdown"
  42. CampaignContentTypePlain = "plain"
  43. // List.
  44. ListTypePrivate = "private"
  45. ListTypePublic = "public"
  46. ListOptinSingle = "single"
  47. ListOptinDouble = "double"
  48. // User.
  49. UserTypeSuperadmin = "superadmin"
  50. UserTypeUser = "user"
  51. UserStatusEnabled = "enabled"
  52. UserStatusDisabled = "disabled"
  53. // BaseTpl is the name of the base template.
  54. BaseTpl = "base"
  55. // ContentTpl is the name of the compiled message.
  56. ContentTpl = "content"
  57. // Headers attached to e-mails for bounce tracking.
  58. EmailHeaderSubscriberUUID = "X-Listmonk-Subscriber"
  59. EmailHeaderCampaignUUID = "X-Listmonk-Campaign"
  60. BounceTypeHard = "hard"
  61. BounceTypeSoft = "soft"
  62. )
  63. // regTplFunc represents contains a regular expression for wrapping and
  64. // substituting a Go template function from the user's shorthand to a full
  65. // function call.
  66. type regTplFunc struct {
  67. regExp *regexp.Regexp
  68. replace string
  69. }
  70. // Regular expression for matching {{ Track "http://link.com" }} in the template
  71. // and substituting it with {{ Track "http://link.com" .Campaign.UUID .Subscriber.UUID }}
  72. // before compilation. This string gimmick is to make linking easier for users.
  73. var regTplFuncs = []regTplFunc{
  74. regTplFunc{
  75. regExp: regexp.MustCompile("{{(\\s+)?TrackLink\\s+?(\"|`)(.+?)(\"|`)(\\s+)?}}"),
  76. replace: `{{ TrackLink "$3" . }}`,
  77. },
  78. regTplFunc{
  79. regExp: regexp.MustCompile(`{{(\s+)?(TrackView|UnsubscribeURL|OptinURL|MessageURL)(\s+)?}}`),
  80. replace: `{{ $2 . }}`,
  81. },
  82. }
  83. // AdminNotifCallback is a callback function that's called
  84. // when a campaign's status changes.
  85. type AdminNotifCallback func(subject string, data interface{}) error
  86. // Base holds common fields shared across models.
  87. type Base struct {
  88. ID int `db:"id" json:"id"`
  89. CreatedAt null.Time `db:"created_at" json:"created_at"`
  90. UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
  91. }
  92. // User represents an admin user.
  93. type User struct {
  94. Base
  95. Email string `json:"email"`
  96. Name string `json:"name"`
  97. Password string `json:"-"`
  98. Type string `json:"type"`
  99. Status string `json:"status"`
  100. }
  101. // Subscriber represents an e-mail subscriber.
  102. type Subscriber struct {
  103. Base
  104. UUID string `db:"uuid" json:"uuid"`
  105. Email string `db:"email" json:"email"`
  106. Name string `db:"name" json:"name"`
  107. Attribs SubscriberAttribs `db:"attribs" json:"attribs"`
  108. Status string `db:"status" json:"status"`
  109. Lists types.JSONText `db:"lists" json:"lists"`
  110. }
  111. type subLists struct {
  112. SubscriberID int `db:"subscriber_id"`
  113. Lists types.JSONText `db:"lists"`
  114. }
  115. // SubscriberAttribs is the map of key:value attributes of a subscriber.
  116. type SubscriberAttribs map[string]interface{}
  117. // Subscribers represents a slice of Subscriber.
  118. type Subscribers []Subscriber
  119. // SubscriberExport represents a subscriber record that is exported to raw data.
  120. type SubscriberExport struct {
  121. Base
  122. UUID string `db:"uuid" json:"uuid"`
  123. Email string `db:"email" json:"email"`
  124. Name string `db:"name" json:"name"`
  125. Attribs string `db:"attribs" json:"attribs"`
  126. Status string `db:"status" json:"status"`
  127. }
  128. // List represents a mailing list.
  129. type List struct {
  130. Base
  131. UUID string `db:"uuid" json:"uuid"`
  132. Name string `db:"name" json:"name"`
  133. Type string `db:"type" json:"type"`
  134. Optin string `db:"optin" json:"optin"`
  135. Tags pq.StringArray `db:"tags" json:"tags"`
  136. SubscriberCount int `db:"subscriber_count" json:"subscriber_count"`
  137. SubscriberID int `db:"subscriber_id" json:"-"`
  138. // This is only relevant when querying the lists of a subscriber.
  139. SubscriptionStatus string `db:"subscription_status" json:"subscription_status,omitempty"`
  140. // Pseudofield for getting the total number of subscribers
  141. // in searches and queries.
  142. Total int `db:"total" json:"-"`
  143. }
  144. // Campaign represents an e-mail campaign.
  145. type Campaign struct {
  146. Base
  147. CampaignMeta
  148. UUID string `db:"uuid" json:"uuid"`
  149. Type string `db:"type" json:"type"`
  150. Name string `db:"name" json:"name"`
  151. Subject string `db:"subject" json:"subject"`
  152. FromEmail string `db:"from_email" json:"from_email"`
  153. Body string `db:"body" json:"body"`
  154. AltBody null.String `db:"altbody" json:"altbody"`
  155. SendAt null.Time `db:"send_at" json:"send_at"`
  156. Status string `db:"status" json:"status"`
  157. ContentType string `db:"content_type" json:"content_type"`
  158. Tags pq.StringArray `db:"tags" json:"tags"`
  159. TemplateID int `db:"template_id" json:"template_id"`
  160. Messenger string `db:"messenger" json:"messenger"`
  161. // TemplateBody is joined in from templates by the next-campaigns query.
  162. TemplateBody string `db:"template_body" json:"-"`
  163. Tpl *template.Template `json:"-"`
  164. SubjectTpl *template.Template `json:"-"`
  165. AltBodyTpl *template.Template `json:"-"`
  166. // Pseudofield for getting the total number of subscribers
  167. // in searches and queries.
  168. Total int `db:"total" json:"-"`
  169. }
  170. // CampaignMeta contains fields tracking a campaign's progress.
  171. type CampaignMeta struct {
  172. CampaignID int `db:"campaign_id" json:"-"`
  173. Views int `db:"views" json:"views"`
  174. Clicks int `db:"clicks" json:"clicks"`
  175. Bounces int `db:"bounces" json:"bounces"`
  176. // This is a list of {list_id, name} pairs unlike Subscriber.Lists[]
  177. // because lists can be deleted after a campaign is finished, resulting
  178. // in null lists data to be returned. For that reason, campaign_lists maintains
  179. // campaign-list associations with a historical record of id + name that persist
  180. // even after a list is deleted.
  181. Lists types.JSONText `db:"lists" json:"lists"`
  182. StartedAt null.Time `db:"started_at" json:"started_at"`
  183. ToSend int `db:"to_send" json:"to_send"`
  184. Sent int `db:"sent" json:"sent"`
  185. }
  186. // Campaigns represents a slice of Campaigns.
  187. type Campaigns []Campaign
  188. // Template represents a reusable e-mail template.
  189. type Template struct {
  190. Base
  191. Name string `db:"name" json:"name"`
  192. Body string `db:"body" json:"body,omitempty"`
  193. IsDefault bool `db:"is_default" json:"is_default"`
  194. }
  195. // Bounce represents a single bounce event.
  196. type Bounce struct {
  197. ID int `db:"id" json:"id"`
  198. Type string `db:"type" json:"type"`
  199. Source string `db:"source" json:"source"`
  200. Meta json.RawMessage `db:"meta" json:"meta"`
  201. CreatedAt time.Time `db:"created_at" json:"created_at"`
  202. // One of these should be provided.
  203. Email string `db:"email" json:"email,omitempty"`
  204. SubscriberUUID string `db:"subscriber_uuid" json:"subscriber_uuid,omitempty"`
  205. SubscriberID int `db:"subscriber_id" json:"subscriber_id,omitempty"`
  206. CampaignUUID string `db:"campaign_uuid" json:"campaign_uuid,omitempty"`
  207. Campaign *json.RawMessage `db:"campaign" json:"campaign"`
  208. // Pseudofield for getting the total number of bounces
  209. // in searches and queries.
  210. Total int `db:"total" json:"-"`
  211. }
  212. // markdown is a global instance of Markdown parser and renderer.
  213. var markdown = goldmark.New(
  214. goldmark.WithRendererOptions(
  215. html.WithXHTML(),
  216. html.WithUnsafe(),
  217. ),
  218. goldmark.WithExtensions(
  219. extension.Table,
  220. extension.Strikethrough,
  221. extension.TaskList,
  222. ),
  223. )
  224. // GetIDs returns the list of subscriber IDs.
  225. func (subs Subscribers) GetIDs() []int {
  226. IDs := make([]int, len(subs))
  227. for i, c := range subs {
  228. IDs[i] = c.ID
  229. }
  230. return IDs
  231. }
  232. // LoadLists lazy loads the lists for all the subscribers
  233. // in the Subscribers slice and attaches them to their []Lists property.
  234. func (subs Subscribers) LoadLists(stmt *sqlx.Stmt) error {
  235. var sl []subLists
  236. err := stmt.Select(&sl, pq.Array(subs.GetIDs()))
  237. if err != nil {
  238. return err
  239. }
  240. if len(subs) != len(sl) {
  241. return errors.New("campaign stats count does not match")
  242. }
  243. for i, s := range sl {
  244. if s.SubscriberID == subs[i].ID {
  245. subs[i].Lists = s.Lists
  246. }
  247. }
  248. return nil
  249. }
  250. // Value returns the JSON marshalled SubscriberAttribs.
  251. func (s SubscriberAttribs) Value() (driver.Value, error) {
  252. return json.Marshal(s)
  253. }
  254. // Scan unmarshals JSON into SubscriberAttribs.
  255. func (s SubscriberAttribs) Scan(src interface{}) error {
  256. if data, ok := src.([]byte); ok {
  257. return json.Unmarshal(data, &s)
  258. }
  259. return fmt.Errorf("Could not not decode type %T -> %T", src, s)
  260. }
  261. // GetIDs returns the list of campaign IDs.
  262. func (camps Campaigns) GetIDs() []int {
  263. IDs := make([]int, len(camps))
  264. for i, c := range camps {
  265. IDs[i] = c.ID
  266. }
  267. return IDs
  268. }
  269. // LoadStats lazy loads campaign stats onto a list of campaigns.
  270. func (camps Campaigns) LoadStats(stmt *sqlx.Stmt) error {
  271. var meta []CampaignMeta
  272. if err := stmt.Select(&meta, pq.Array(camps.GetIDs())); err != nil {
  273. return err
  274. }
  275. if len(camps) != len(meta) {
  276. return errors.New("campaign stats count does not match")
  277. }
  278. for i, c := range meta {
  279. if c.CampaignID == camps[i].ID {
  280. camps[i].Lists = c.Lists
  281. camps[i].Views = c.Views
  282. camps[i].Clicks = c.Clicks
  283. camps[i].Bounces = c.Bounces
  284. }
  285. }
  286. return nil
  287. }
  288. // CompileTemplate compiles a campaign body template into its base
  289. // template and sets the resultant template to Campaign.Tpl.
  290. func (c *Campaign) CompileTemplate(f template.FuncMap) error {
  291. // Compile the base template.
  292. body := c.TemplateBody
  293. for _, r := range regTplFuncs {
  294. body = r.regExp.ReplaceAllString(body, r.replace)
  295. }
  296. baseTPL, err := template.New(BaseTpl).Funcs(f).Parse(body)
  297. if err != nil {
  298. return fmt.Errorf("error compiling base template: %v", err)
  299. }
  300. // If the format is markdown, convert Markdown to HTML.
  301. if c.ContentType == CampaignContentTypeMarkdown {
  302. var b bytes.Buffer
  303. if err := markdown.Convert([]byte(c.Body), &b); err != nil {
  304. return err
  305. }
  306. body = b.String()
  307. } else {
  308. body = c.Body
  309. }
  310. // Compile the campaign message.
  311. for _, r := range regTplFuncs {
  312. body = r.regExp.ReplaceAllString(body, r.replace)
  313. }
  314. msgTpl, err := template.New(ContentTpl).Funcs(f).Parse(body)
  315. if err != nil {
  316. return fmt.Errorf("error compiling message: %v", err)
  317. }
  318. out, err := baseTPL.AddParseTree(ContentTpl, msgTpl.Tree)
  319. if err != nil {
  320. return fmt.Errorf("error inserting child template: %v", err)
  321. }
  322. c.Tpl = out
  323. // If the subject line has a template string, compile it.
  324. if strings.Contains(c.Subject, "{{") {
  325. subj := c.Subject
  326. for _, r := range regTplFuncs {
  327. subj = r.regExp.ReplaceAllString(subj, r.replace)
  328. }
  329. subjTpl, err := template.New(ContentTpl).Funcs(f).Parse(subj)
  330. if err != nil {
  331. return fmt.Errorf("error compiling subject: %v", err)
  332. }
  333. c.SubjectTpl = subjTpl
  334. }
  335. if strings.Contains(c.AltBody.String, "{{") {
  336. b := c.AltBody.String
  337. for _, r := range regTplFuncs {
  338. b = r.regExp.ReplaceAllString(b, r.replace)
  339. }
  340. bTpl, err := template.New(ContentTpl).Funcs(f).Parse(b)
  341. if err != nil {
  342. return fmt.Errorf("error compiling alt plaintext message: %v", err)
  343. }
  344. c.AltBodyTpl = bTpl
  345. }
  346. return nil
  347. }
  348. // ConvertContent converts a campaign's body from one format to another,
  349. // for example, Markdown to HTML.
  350. func (c *Campaign) ConvertContent(from, to string) (string, error) {
  351. body := c.Body
  352. for _, r := range regTplFuncs {
  353. body = r.regExp.ReplaceAllString(body, r.replace)
  354. }
  355. // If the format is markdown, convert Markdown to HTML.
  356. var out string
  357. if from == CampaignContentTypeMarkdown &&
  358. (to == CampaignContentTypeHTML || to == CampaignContentTypeRichtext) {
  359. var b bytes.Buffer
  360. if err := markdown.Convert([]byte(c.Body), &b); err != nil {
  361. return out, err
  362. }
  363. out = b.String()
  364. } else {
  365. return out, errors.New("unknown formats to convert")
  366. }
  367. return out, nil
  368. }
  369. // FirstName splits the name by spaces and returns the first chunk
  370. // of the name that's greater than 2 characters in length, assuming
  371. // that it is the subscriber's first name.
  372. func (s Subscriber) FirstName() string {
  373. for _, s := range strings.Split(s.Name, " ") {
  374. if len(s) > 2 {
  375. return s
  376. }
  377. }
  378. return s.Name
  379. }
  380. // LastName splits the name by spaces and returns the last chunk
  381. // of the name that's greater than 2 characters in length, assuming
  382. // that it is the subscriber's last name.
  383. func (s Subscriber) LastName() string {
  384. chunks := strings.Split(s.Name, " ")
  385. for i := len(chunks) - 1; i >= 0; i-- {
  386. chunk := chunks[i]
  387. if len(chunk) > 2 {
  388. return chunk
  389. }
  390. }
  391. return s.Name
  392. }