models.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. package models
  2. import (
  3. "bytes"
  4. "database/sql/driver"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "html/template"
  9. "net/textproto"
  10. "regexp"
  11. "strings"
  12. txttpl "text/template"
  13. "time"
  14. "github.com/jmoiron/sqlx"
  15. "github.com/jmoiron/sqlx/types"
  16. "github.com/lib/pq"
  17. "github.com/yuin/goldmark"
  18. "github.com/yuin/goldmark/extension"
  19. "github.com/yuin/goldmark/parser"
  20. "github.com/yuin/goldmark/renderer/html"
  21. null "gopkg.in/volatiletech/null.v6"
  22. )
  23. // Enum values for various statuses.
  24. const (
  25. // Subscriber.
  26. SubscriberStatusEnabled = "enabled"
  27. SubscriberStatusDisabled = "disabled"
  28. SubscriberStatusBlockListed = "blocklisted"
  29. // Subscription.
  30. SubscriptionStatusUnconfirmed = "unconfirmed"
  31. SubscriptionStatusConfirmed = "confirmed"
  32. SubscriptionStatusUnsubscribed = "unsubscribed"
  33. // Campaign.
  34. CampaignStatusDraft = "draft"
  35. CampaignStatusScheduled = "scheduled"
  36. CampaignStatusRunning = "running"
  37. CampaignStatusPaused = "paused"
  38. CampaignStatusFinished = "finished"
  39. CampaignStatusCancelled = "cancelled"
  40. CampaignTypeRegular = "regular"
  41. CampaignTypeOptin = "optin"
  42. CampaignContentTypeRichtext = "richtext"
  43. CampaignContentTypeHTML = "html"
  44. CampaignContentTypeMarkdown = "markdown"
  45. CampaignContentTypePlain = "plain"
  46. // List.
  47. ListTypePrivate = "private"
  48. ListTypePublic = "public"
  49. ListOptinSingle = "single"
  50. ListOptinDouble = "double"
  51. // User.
  52. UserTypeSuperadmin = "superadmin"
  53. UserTypeUser = "user"
  54. UserStatusEnabled = "enabled"
  55. UserStatusDisabled = "disabled"
  56. // BaseTpl is the name of the base template.
  57. BaseTpl = "base"
  58. // ContentTpl is the name of the compiled message.
  59. ContentTpl = "content"
  60. // Headers attached to e-mails for bounce tracking.
  61. EmailHeaderSubscriberUUID = "X-Listmonk-Subscriber"
  62. EmailHeaderCampaignUUID = "X-Listmonk-Campaign"
  63. // Standard e-mail headers.
  64. EmailHeaderDate = "Date"
  65. EmailHeaderFrom = "From"
  66. EmailHeaderSubject = "Subject"
  67. EmailHeaderMessageId = "Message-Id"
  68. EmailHeaderDeliveredTo = "Delivered-To"
  69. EmailHeaderReceived = "Received"
  70. BounceTypeHard = "hard"
  71. BounceTypeSoft = "soft"
  72. BounceTypeComplaint = "complaint"
  73. // Templates.
  74. TemplateTypeCampaign = "campaign"
  75. TemplateTypeTx = "tx"
  76. )
  77. // Headers represents an array of string maps used to represent SMTP, HTTP headers etc.
  78. // similar to url.Values{}
  79. type Headers []map[string]string
  80. // regTplFunc represents contains a regular expression for wrapping and
  81. // substituting a Go template function from the user's shorthand to a full
  82. // function call.
  83. type regTplFunc struct {
  84. regExp *regexp.Regexp
  85. replace string
  86. }
  87. var regTplFuncs = []regTplFunc{
  88. // Regular expression for matching {{ TrackLink "http://link.com" }} in the template
  89. // and substituting it with {{ Track "http://link.com" . }} (the dot context)
  90. // before compilation. This is to make linking easier for users.
  91. {
  92. regExp: regexp.MustCompile("{{(\\s+)?TrackLink(\\s+)?(.+?)(\\s+)?}}"),
  93. replace: `{{ TrackLink $3 . }}`,
  94. },
  95. // Convert the shorthand https://google.com@TrackLink to {{ TrackLink ... }}.
  96. // This is for WYSIWYG editors that encode and break quotes {{ "" }} when inserted
  97. // inside <a href="{{ TrackLink "https://these-quotes-break" }}>.
  98. {
  99. regExp: regexp.MustCompile(`(https?://.+?)@TrackLink`),
  100. replace: `{{ TrackLink "$1" . }}`,
  101. },
  102. {
  103. regExp: regexp.MustCompile(`{{(\s+)?(TrackView|UnsubscribeURL|ManageURL|OptinURL|MessageURL)(\s+)?}}`),
  104. replace: `{{ $2 . }}`,
  105. },
  106. }
  107. // AdminNotifCallback is a callback function that's called
  108. // when a campaign's status changes.
  109. type AdminNotifCallback func(subject string, data interface{}) error
  110. // PageResults is a generic HTTP response container for paginated results of list of items.
  111. type PageResults struct {
  112. Results interface{} `json:"results"`
  113. Query string `json:"query"`
  114. Total int `json:"total"`
  115. PerPage int `json:"per_page"`
  116. Page int `json:"page"`
  117. }
  118. // Base holds common fields shared across models.
  119. type Base struct {
  120. ID int `db:"id" json:"id"`
  121. CreatedAt null.Time `db:"created_at" json:"created_at"`
  122. UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
  123. }
  124. // User represents an admin user.
  125. type User struct {
  126. Base
  127. Email string `json:"email"`
  128. Name string `json:"name"`
  129. Password string `json:"-"`
  130. Type string `json:"type"`
  131. Status string `json:"status"`
  132. }
  133. // Subscriber represents an e-mail subscriber.
  134. type Subscriber struct {
  135. Base
  136. UUID string `db:"uuid" json:"uuid"`
  137. Email string `db:"email" json:"email" form:"email"`
  138. Name string `db:"name" json:"name" form:"name"`
  139. Attribs JSON `db:"attribs" json:"attribs"`
  140. Status string `db:"status" json:"status"`
  141. Lists types.JSONText `db:"lists" json:"lists"`
  142. }
  143. type subLists struct {
  144. SubscriberID int `db:"subscriber_id"`
  145. Lists types.JSONText `db:"lists"`
  146. }
  147. // Subscription represents a list attached to a subscriber.
  148. type Subscription struct {
  149. List
  150. SubscriptionStatus null.String `db:"subscription_status" json:"subscription_status"`
  151. SubscriptionCreatedAt null.String `db:"subscription_created_at" json:"subscription_created_at"`
  152. Meta json.RawMessage `db:"meta" json:"meta"`
  153. }
  154. // SubscriberExportProfile represents a subscriber's collated data in JSON for export.
  155. type SubscriberExportProfile struct {
  156. Email string `db:"email" json:"-"`
  157. Profile json.RawMessage `db:"profile" json:"profile,omitempty"`
  158. Subscriptions json.RawMessage `db:"subscriptions" json:"subscriptions,omitempty"`
  159. CampaignViews json.RawMessage `db:"campaign_views" json:"campaign_views,omitempty"`
  160. LinkClicks json.RawMessage `db:"link_clicks" json:"link_clicks,omitempty"`
  161. }
  162. // JSON is is the wrapper for reading and writing arbitrary JSONB fields from the DB.
  163. type JSON map[string]interface{}
  164. // StringIntMap is used to define DB Scan()s.
  165. type StringIntMap map[string]int
  166. // Subscribers represents a slice of Subscriber.
  167. type Subscribers []Subscriber
  168. // SubscriberExport represents a subscriber record that is exported to raw data.
  169. type SubscriberExport struct {
  170. Base
  171. UUID string `db:"uuid" json:"uuid"`
  172. Email string `db:"email" json:"email"`
  173. Name string `db:"name" json:"name"`
  174. Attribs string `db:"attribs" json:"attribs"`
  175. Status string `db:"status" json:"status"`
  176. }
  177. // List represents a mailing list.
  178. type List struct {
  179. Base
  180. UUID string `db:"uuid" json:"uuid"`
  181. Name string `db:"name" json:"name"`
  182. Type string `db:"type" json:"type"`
  183. Optin string `db:"optin" json:"optin"`
  184. Tags pq.StringArray `db:"tags" json:"tags"`
  185. Description string `db:"description" json:"description"`
  186. SubscriberCount int `db:"-" json:"subscriber_count"`
  187. SubscriberCounts StringIntMap `db:"subscriber_statuses" json:"subscriber_statuses"`
  188. SubscriberID int `db:"subscriber_id" json:"-"`
  189. // This is only relevant when querying the lists of a subscriber.
  190. SubscriptionStatus string `db:"subscription_status" json:"subscription_status,omitempty"`
  191. SubscriptionCreatedAt null.Time `db:"subscription_created_at" json:"subscription_created_at,omitempty"`
  192. SubscriptionUpdatedAt null.Time `db:"subscription_updated_at" json:"subscription_updated_at,omitempty"`
  193. // Pseudofield for getting the total number of subscribers
  194. // in searches and queries.
  195. Total int `db:"total" json:"-"`
  196. }
  197. // Campaign represents an e-mail campaign.
  198. type Campaign struct {
  199. Base
  200. CampaignMeta
  201. UUID string `db:"uuid" json:"uuid"`
  202. Type string `db:"type" json:"type"`
  203. Name string `db:"name" json:"name"`
  204. Subject string `db:"subject" json:"subject"`
  205. FromEmail string `db:"from_email" json:"from_email"`
  206. Body string `db:"body" json:"body"`
  207. AltBody null.String `db:"altbody" json:"altbody"`
  208. SendAt null.Time `db:"send_at" json:"send_at"`
  209. Status string `db:"status" json:"status"`
  210. ContentType string `db:"content_type" json:"content_type"`
  211. Tags pq.StringArray `db:"tags" json:"tags"`
  212. Headers Headers `db:"headers" json:"headers"`
  213. TemplateID int `db:"template_id" json:"template_id"`
  214. Messenger string `db:"messenger" json:"messenger"`
  215. Archive bool `db:"archive" json:"archive"`
  216. ArchiveTemplateID int `db:"archive_template_id" json:"archive_template_id"`
  217. ArchiveMeta json.RawMessage `db:"archive_meta" json:"archive_meta"`
  218. // TemplateBody is joined in from templates by the next-campaigns query.
  219. TemplateBody string `db:"template_body" json:"-"`
  220. ArchiveTemplateBody string `db:"archive_template_body" json:"-"`
  221. Tpl *template.Template `json:"-"`
  222. SubjectTpl *txttpl.Template `json:"-"`
  223. AltBodyTpl *template.Template `json:"-"`
  224. // List of media (attachment) IDs obtained from the next-campaign query
  225. // while sending a campaign.
  226. MediaIDs pq.Int64Array `json:"-" db:"media_id"`
  227. // Fetched bodies of the attachments.
  228. Attachments []Attachment `json:"-" db:"-"`
  229. // Pseudofield for getting the total number of subscribers
  230. // in searches and queries.
  231. Total int `db:"total" json:"-"`
  232. }
  233. // CampaignMeta contains fields tracking a campaign's progress.
  234. type CampaignMeta struct {
  235. CampaignID int `db:"campaign_id" json:"-"`
  236. Views int `db:"views" json:"views"`
  237. Clicks int `db:"clicks" json:"clicks"`
  238. Bounces int `db:"bounces" json:"bounces"`
  239. // This is a list of {list_id, name} pairs unlike Subscriber.Lists[]
  240. // because lists can be deleted after a campaign is finished, resulting
  241. // in null lists data to be returned. For that reason, campaign_lists maintains
  242. // campaign-list associations with a historical record of id + name that persist
  243. // even after a list is deleted.
  244. Lists types.JSONText `db:"lists" json:"lists"`
  245. Media types.JSONText `db:"media" json:"media"`
  246. StartedAt null.Time `db:"started_at" json:"started_at"`
  247. ToSend int `db:"to_send" json:"to_send"`
  248. Sent int `db:"sent" json:"sent"`
  249. }
  250. type CampaignStats struct {
  251. ID int `db:"id" json:"id"`
  252. Status string `db:"status" json:"status"`
  253. ToSend int `db:"to_send" json:"to_send"`
  254. Sent int `db:"sent" json:"sent"`
  255. Started null.Time `db:"started_at" json:"started_at"`
  256. UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
  257. Rate int `json:"rate"`
  258. NetRate int `json:"net_rate"`
  259. }
  260. type CampaignAnalyticsCount struct {
  261. CampaignID int `db:"campaign_id" json:"campaign_id"`
  262. Count int `db:"count" json:"count"`
  263. Timestamp time.Time `db:"timestamp" json:"timestamp"`
  264. }
  265. type CampaignAnalyticsLink struct {
  266. URL string `db:"url" json:"url"`
  267. Count int `db:"count" json:"count"`
  268. }
  269. // Campaigns represents a slice of Campaigns.
  270. type Campaigns []Campaign
  271. // Template represents a reusable e-mail template.
  272. type Template struct {
  273. Base
  274. Name string `db:"name" json:"name"`
  275. // Subject is only for type=tx.
  276. Subject string `db:"subject" json:"subject"`
  277. Type string `db:"type" json:"type"`
  278. Body string `db:"body" json:"body,omitempty"`
  279. IsDefault bool `db:"is_default" json:"is_default"`
  280. // Only relevant to tx (transactional) templates.
  281. SubjectTpl *txttpl.Template `json:"-"`
  282. Tpl *template.Template `json:"-"`
  283. }
  284. // Bounce represents a single bounce event.
  285. type Bounce struct {
  286. ID int `db:"id" json:"id"`
  287. Type string `db:"type" json:"type"`
  288. Source string `db:"source" json:"source"`
  289. Meta json.RawMessage `db:"meta" json:"meta"`
  290. CreatedAt time.Time `db:"created_at" json:"created_at"`
  291. // One of these should be provided.
  292. Email string `db:"email" json:"email,omitempty"`
  293. SubscriberUUID string `db:"subscriber_uuid" json:"subscriber_uuid,omitempty"`
  294. SubscriberID int `db:"subscriber_id" json:"subscriber_id,omitempty"`
  295. CampaignUUID string `db:"campaign_uuid" json:"campaign_uuid,omitempty"`
  296. Campaign *json.RawMessage `db:"campaign" json:"campaign"`
  297. // Pseudofield for getting the total number of bounces
  298. // in searches and queries.
  299. Total int `db:"total" json:"-"`
  300. }
  301. // Message is the message pushed to a Messenger.
  302. type Message struct {
  303. From string
  304. To []string
  305. Subject string
  306. ContentType string
  307. Body []byte
  308. AltBody []byte
  309. Headers textproto.MIMEHeader
  310. Attachments []Attachment
  311. Subscriber Subscriber
  312. // Campaign is generally the same instance for a large number of subscribers.
  313. Campaign *Campaign
  314. // Messenger is the messenger backend to use: email|postback.
  315. Messenger string
  316. }
  317. // Attachment represents a file or blob attachment that can be
  318. // sent along with a message by a Messenger.
  319. type Attachment struct {
  320. Name string
  321. Header textproto.MIMEHeader
  322. Content []byte
  323. }
  324. // TxMessage represents an e-mail campaign.
  325. type TxMessage struct {
  326. SubscriberEmails []string `json:"subscriber_emails"`
  327. SubscriberIDs []int `json:"subscriber_ids"`
  328. // Deprecated.
  329. SubscriberEmail string `json:"subscriber_email"`
  330. SubscriberID int `json:"subscriber_id"`
  331. TemplateID int `json:"template_id"`
  332. Data map[string]interface{} `json:"data"`
  333. FromEmail string `json:"from_email"`
  334. Headers Headers `json:"headers"`
  335. ContentType string `json:"content_type"`
  336. Messenger string `json:"messenger"`
  337. // File attachments added from multi-part form data.
  338. Attachments []Attachment `json:"-"`
  339. Subject string `json:"-"`
  340. Body []byte `json:"-"`
  341. Tpl *template.Template `json:"-"`
  342. SubjectTpl *txttpl.Template `json:"-"`
  343. }
  344. // markdown is a global instance of Markdown parser and renderer.
  345. var markdown = goldmark.New(
  346. goldmark.WithParserOptions(
  347. parser.WithAutoHeadingID(),
  348. ),
  349. goldmark.WithRendererOptions(
  350. html.WithXHTML(),
  351. html.WithUnsafe(),
  352. ),
  353. goldmark.WithExtensions(
  354. extension.Table,
  355. extension.Strikethrough,
  356. extension.TaskList,
  357. ),
  358. )
  359. // GetIDs returns the list of subscriber IDs.
  360. func (subs Subscribers) GetIDs() []int {
  361. IDs := make([]int, len(subs))
  362. for i, c := range subs {
  363. IDs[i] = c.ID
  364. }
  365. return IDs
  366. }
  367. // LoadLists lazy loads the lists for all the subscribers
  368. // in the Subscribers slice and attaches them to their []Lists property.
  369. func (subs Subscribers) LoadLists(stmt *sqlx.Stmt) error {
  370. var sl []subLists
  371. err := stmt.Select(&sl, pq.Array(subs.GetIDs()))
  372. if err != nil {
  373. return err
  374. }
  375. if len(subs) != len(sl) {
  376. return errors.New("campaign stats count does not match")
  377. }
  378. for i, s := range sl {
  379. if s.SubscriberID == subs[i].ID {
  380. subs[i].Lists = s.Lists
  381. }
  382. }
  383. return nil
  384. }
  385. // Value returns the JSON marshalled SubscriberAttribs.
  386. func (s JSON) Value() (driver.Value, error) {
  387. return json.Marshal(s)
  388. }
  389. // Scan unmarshals JSONB from the DB.
  390. func (s JSON) Scan(src interface{}) error {
  391. if src == nil {
  392. s = make(JSON)
  393. return nil
  394. }
  395. if data, ok := src.([]byte); ok {
  396. return json.Unmarshal(data, &s)
  397. }
  398. return fmt.Errorf("could not not decode type %T -> %T", src, s)
  399. }
  400. // Scan unmarshals JSONB from the DB.
  401. func (s StringIntMap) Scan(src interface{}) error {
  402. if src == nil {
  403. s = make(StringIntMap)
  404. return nil
  405. }
  406. if data, ok := src.([]byte); ok {
  407. return json.Unmarshal(data, &s)
  408. }
  409. return fmt.Errorf("could not not decode type %T -> %T", src, s)
  410. }
  411. // GetIDs returns the list of campaign IDs.
  412. func (camps Campaigns) GetIDs() []int {
  413. IDs := make([]int, len(camps))
  414. for i, c := range camps {
  415. IDs[i] = c.ID
  416. }
  417. return IDs
  418. }
  419. // LoadStats lazy loads campaign stats onto a list of campaigns.
  420. func (camps Campaigns) LoadStats(stmt *sqlx.Stmt) error {
  421. var meta []CampaignMeta
  422. if err := stmt.Select(&meta, pq.Array(camps.GetIDs())); err != nil {
  423. return err
  424. }
  425. if len(camps) != len(meta) {
  426. return errors.New("campaign stats count does not match")
  427. }
  428. for i, c := range meta {
  429. if c.CampaignID == camps[i].ID {
  430. camps[i].Lists = c.Lists
  431. camps[i].Views = c.Views
  432. camps[i].Clicks = c.Clicks
  433. camps[i].Bounces = c.Bounces
  434. camps[i].Media = c.Media
  435. }
  436. }
  437. return nil
  438. }
  439. // CompileTemplate compiles a campaign body template into its base
  440. // template and sets the resultant template to Campaign.Tpl.
  441. func (c *Campaign) CompileTemplate(f template.FuncMap) error {
  442. // If the subject line has a template string, compile it.
  443. if strings.Contains(c.Subject, "{{") {
  444. subj := c.Subject
  445. for _, r := range regTplFuncs {
  446. subj = r.regExp.ReplaceAllString(subj, r.replace)
  447. }
  448. var txtFuncs map[string]interface{} = f
  449. subjTpl, err := txttpl.New(ContentTpl).Funcs(txtFuncs).Parse(subj)
  450. if err != nil {
  451. return fmt.Errorf("error compiling subject: %v", err)
  452. }
  453. c.SubjectTpl = subjTpl
  454. }
  455. // Compile the base template.
  456. body := c.TemplateBody
  457. for _, r := range regTplFuncs {
  458. body = r.regExp.ReplaceAllString(body, r.replace)
  459. }
  460. baseTPL, err := template.New(BaseTpl).Funcs(f).Parse(body)
  461. if err != nil {
  462. return fmt.Errorf("error compiling base template: %v", err)
  463. }
  464. // If the format is markdown, convert Markdown to HTML.
  465. if c.ContentType == CampaignContentTypeMarkdown {
  466. var b bytes.Buffer
  467. if err := markdown.Convert([]byte(c.Body), &b); err != nil {
  468. return err
  469. }
  470. body = b.String()
  471. } else {
  472. body = c.Body
  473. }
  474. // Compile the campaign message.
  475. for _, r := range regTplFuncs {
  476. body = r.regExp.ReplaceAllString(body, r.replace)
  477. }
  478. msgTpl, err := template.New(ContentTpl).Funcs(f).Parse(body)
  479. if err != nil {
  480. return fmt.Errorf("error compiling message: %v", err)
  481. }
  482. out, err := baseTPL.AddParseTree(ContentTpl, msgTpl.Tree)
  483. if err != nil {
  484. return fmt.Errorf("error inserting child template: %v", err)
  485. }
  486. c.Tpl = out
  487. if strings.Contains(c.AltBody.String, "{{") {
  488. b := c.AltBody.String
  489. for _, r := range regTplFuncs {
  490. b = r.regExp.ReplaceAllString(b, r.replace)
  491. }
  492. bTpl, err := template.New(ContentTpl).Funcs(f).Parse(b)
  493. if err != nil {
  494. return fmt.Errorf("error compiling alt plaintext message: %v", err)
  495. }
  496. c.AltBodyTpl = bTpl
  497. }
  498. return nil
  499. }
  500. // ConvertContent converts a campaign's body from one format to another,
  501. // for example, Markdown to HTML.
  502. func (c *Campaign) ConvertContent(from, to string) (string, error) {
  503. body := c.Body
  504. for _, r := range regTplFuncs {
  505. body = r.regExp.ReplaceAllString(body, r.replace)
  506. }
  507. // If the format is markdown, convert Markdown to HTML.
  508. var out string
  509. if from == CampaignContentTypeMarkdown &&
  510. (to == CampaignContentTypeHTML || to == CampaignContentTypeRichtext) {
  511. var b bytes.Buffer
  512. if err := markdown.Convert([]byte(c.Body), &b); err != nil {
  513. return out, err
  514. }
  515. out = b.String()
  516. } else {
  517. return out, errors.New("unknown formats to convert")
  518. }
  519. return out, nil
  520. }
  521. // Compile compiles a template body and subject (only for tx templates) and
  522. // caches the templat references to be executed later.
  523. func (t *Template) Compile(f template.FuncMap) error {
  524. tpl, err := template.New(BaseTpl).Funcs(f).Parse(t.Body)
  525. if err != nil {
  526. return fmt.Errorf("error compiling transactional template: %v", err)
  527. }
  528. t.Tpl = tpl
  529. // If the subject line has a template string, compile it.
  530. if strings.Contains(t.Subject, "{{") {
  531. subj := t.Subject
  532. subjTpl, err := txttpl.New(BaseTpl).Funcs(txttpl.FuncMap(f)).Parse(subj)
  533. if err != nil {
  534. return fmt.Errorf("error compiling subject: %v", err)
  535. }
  536. t.SubjectTpl = subjTpl
  537. }
  538. return nil
  539. }
  540. func (m *TxMessage) Render(sub Subscriber, tpl *Template) error {
  541. data := struct {
  542. Subscriber Subscriber
  543. Tx *TxMessage
  544. }{sub, m}
  545. // Render the body.
  546. b := bytes.Buffer{}
  547. if err := tpl.Tpl.ExecuteTemplate(&b, BaseTpl, data); err != nil {
  548. return err
  549. }
  550. m.Body = make([]byte, b.Len())
  551. copy(m.Body, b.Bytes())
  552. b.Reset()
  553. // If the subject is also a template, render that.
  554. if tpl.SubjectTpl != nil {
  555. if err := tpl.SubjectTpl.ExecuteTemplate(&b, BaseTpl, data); err != nil {
  556. return err
  557. }
  558. m.Subject = b.String()
  559. b.Reset()
  560. } else {
  561. m.Subject = tpl.Subject
  562. }
  563. return nil
  564. }
  565. // FirstName splits the name by spaces and returns the first chunk
  566. // of the name that's greater than 2 characters in length, assuming
  567. // that it is the subscriber's first name.
  568. func (s Subscriber) FirstName() string {
  569. for _, s := range strings.Split(s.Name, " ") {
  570. if len(s) > 2 {
  571. return s
  572. }
  573. }
  574. return s.Name
  575. }
  576. // LastName splits the name by spaces and returns the last chunk
  577. // of the name that's greater than 2 characters in length, assuming
  578. // that it is the subscriber's last name.
  579. func (s Subscriber) LastName() string {
  580. chunks := strings.Split(s.Name, " ")
  581. for i := len(chunks) - 1; i >= 0; i-- {
  582. chunk := chunks[i]
  583. if len(chunk) > 2 {
  584. return chunk
  585. }
  586. }
  587. return s.Name
  588. }
  589. // Scan implements the sql.Scanner interface.
  590. func (h *Headers) Scan(src interface{}) error {
  591. var b []byte
  592. switch src := src.(type) {
  593. case []byte:
  594. b = src
  595. case string:
  596. b = []byte(src)
  597. case nil:
  598. return nil
  599. }
  600. if err := json.Unmarshal(b, h); err != nil {
  601. return err
  602. }
  603. return nil
  604. }
  605. // Value implements the driver.Valuer interface.
  606. func (h Headers) Value() (driver.Value, error) {
  607. if h == nil {
  608. return nil, nil
  609. }
  610. if n := len(h); n > 0 {
  611. b, err := json.Marshal(h)
  612. if err != nil {
  613. return nil, err
  614. }
  615. return b, nil
  616. }
  617. return "[]", nil
  618. }