models.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package models
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "regexp"
  8. "strings"
  9. "github.com/jmoiron/sqlx"
  10. "github.com/jmoiron/sqlx/types"
  11. "github.com/lib/pq"
  12. null "gopkg.in/volatiletech/null.v6"
  13. )
  14. // Enum values for various statuses.
  15. const (
  16. // Subscriber.
  17. SubscriberStatusEnabled = "enabled"
  18. SubscriberStatusDisabled = "disabled"
  19. SubscriberStatusBlackListed = "blacklisted"
  20. // Campaign.
  21. CampaignStatusDraft = "draft"
  22. CampaignStatusScheduled = "scheduled"
  23. CampaignStatusRunning = "running"
  24. CampaignStatusPaused = "paused"
  25. CampaignStatusFinished = "finished"
  26. CampaignStatusCancelled = "cancelled"
  27. // List.
  28. ListTypePrivate = "private"
  29. ListTypePublic = "public"
  30. // User.
  31. UserTypeSuperadmin = "superadmin"
  32. UserTypeUser = "user"
  33. UserStatusEnabled = "enabled"
  34. UserStatusDisabled = "disabled"
  35. // BaseTpl is the name of the base template.
  36. BaseTpl = "base"
  37. // ContentTpl is the name of the compiled message.
  38. ContentTpl = "content"
  39. )
  40. // Regular expression for matching {{ Track "http://link.com" }} in the template
  41. // and substituting it with {{ Track "http://link.com" .Campaign.UUID .Subscriber.UUID }}
  42. // before compilation. This string gimmick is to make linking easier for users.
  43. var (
  44. regexpLinkTag = regexp.MustCompile(`{{(\s+)?TrackLink\s+?"(.+?)"(\s+)?}}`)
  45. regexpLinkTagReplace = `{{ TrackLink "$2" .Campaign.UUID .Subscriber.UUID }}`
  46. regexpViewTag = regexp.MustCompile(`{{(\s+)?TrackView(\s+)?}}`)
  47. regexpViewTagReplace = `{{ TrackView .Campaign.UUID .Subscriber.UUID }}`
  48. )
  49. // Base holds common fields shared across models.
  50. type Base struct {
  51. ID int `db:"id" json:"id"`
  52. CreatedAt null.Time `db:"created_at" json:"created_at"`
  53. UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
  54. }
  55. // User represents an admin user.
  56. type User struct {
  57. Base
  58. Email string `json:"email"`
  59. Name string `json:"name"`
  60. Password string `json:"-"`
  61. Type string `json:"type"`
  62. Status string `json:"status"`
  63. }
  64. // Subscriber represents an e-mail subscriber.
  65. type Subscriber struct {
  66. Base
  67. UUID string `db:"uuid" json:"uuid"`
  68. Email string `db:"email" json:"email"`
  69. Name string `db:"name" json:"name"`
  70. Attribs SubscriberAttribs `db:"attribs" json:"attribs"`
  71. Status string `db:"status" json:"status"`
  72. CampaignIDs pq.Int64Array `db:"campaigns" json:"-"`
  73. Lists []List `json:"lists"`
  74. }
  75. // SubscriberAttribs is the map of key:value attributes of a subscriber.
  76. type SubscriberAttribs map[string]interface{}
  77. // Subscribers represents a slice of Subscriber.
  78. type Subscribers []Subscriber
  79. // List represents a mailing list.
  80. type List struct {
  81. Base
  82. UUID string `db:"uuid" json:"uuid"`
  83. Name string `db:"name" json:"name"`
  84. Type string `db:"type" json:"type"`
  85. Tags pq.StringArray `db:"tags" json:"tags"`
  86. SubscriberCount int `db:"subscriber_count" json:"subscriber_count"`
  87. SubscriberID int `db:"subscriber_id" json:"-"`
  88. // This is only relevant when querying the lists of a subscriber.
  89. SubscriptionStatus string `db:"subscription_status" json:"subscription_status,omitempty"`
  90. }
  91. // Campaign represents an e-mail campaign.
  92. type Campaign struct {
  93. Base
  94. CampaignMeta
  95. UUID string `db:"uuid" json:"uuid"`
  96. Name string `db:"name" json:"name"`
  97. Subject string `db:"subject" json:"subject"`
  98. FromEmail string `db:"from_email" json:"from_email"`
  99. Body string `db:"body" json:"body,omitempty"`
  100. SendAt null.Time `db:"send_at" json:"send_at"`
  101. Status string `db:"status" json:"status"`
  102. ContentType string `db:"content_type" json:"content_type"`
  103. Tags pq.StringArray `db:"tags" json:"tags"`
  104. TemplateID int `db:"template_id" json:"template_id"`
  105. MessengerID string `db:"messenger" json:"messenger"`
  106. Lists types.JSONText `json:"lists"`
  107. // TemplateBody is joined in from templates by the next-campaigns query.
  108. TemplateBody string `db:"template_body" json:"-"`
  109. Tpl *template.Template `json:"-"`
  110. }
  111. // CampaignMeta contains fields tracking a campaign's progress.
  112. type CampaignMeta struct {
  113. StartedAt null.Time `db:"started_at" json:"started_at"`
  114. ToSend int `db:"to_send" json:"to_send"`
  115. Sent int `db:"sent" json:"sent"`
  116. }
  117. // Campaigns represents a slice of Campaign.
  118. type Campaigns []Campaign
  119. // Media represents an uploaded media item.
  120. type Media struct {
  121. ID int `db:"id" json:"id"`
  122. UUID string `db:"uuid" json:"uuid"`
  123. Filename string `db:"filename" json:"filename"`
  124. Width int `db:"width" json:"width"`
  125. Height int `db:"height" json:"height"`
  126. CreatedAt null.Time `db:"created_at" json:"created_at"`
  127. ThumbURI string `json:"thumb_uri"`
  128. URI string `json:"uri"`
  129. }
  130. // Template represents a reusable e-mail template.
  131. type Template struct {
  132. Base
  133. Name string `db:"name" json:"name"`
  134. Body string `db:"body" json:"body,omitempty"`
  135. IsDefault bool `db:"is_default" json:"is_default"`
  136. }
  137. // LoadLists lazy loads the lists for all the subscribers
  138. // in the Subscribers slice and attaches them to their []Lists property.
  139. func (subs Subscribers) LoadLists(stmt *sqlx.Stmt) error {
  140. var (
  141. lists []List
  142. subIDs = make([]int, len(subs))
  143. )
  144. for i := 0; i < len(subs); i++ {
  145. subIDs[i] = subs[i].ID
  146. subs[i].Lists = make([]List, 0)
  147. }
  148. err := stmt.Select(&lists, pq.Array(subIDs))
  149. if err != nil {
  150. return err
  151. }
  152. // Loop through each list and attach it to the subscribers by ID.
  153. for _, l := range lists {
  154. for i := 0; i < len(subs); i++ {
  155. if l.SubscriberID == subs[i].ID {
  156. subs[i].Lists = append(subs[i].Lists, l)
  157. }
  158. }
  159. }
  160. return nil
  161. }
  162. // Value returns the JSON marshalled SubscriberAttribs.
  163. func (s SubscriberAttribs) Value() (driver.Value, error) {
  164. return json.Marshal(s)
  165. }
  166. // Scan unmarshals JSON into SubscriberAttribs.
  167. func (s SubscriberAttribs) Scan(src interface{}) error {
  168. if data, ok := src.([]byte); ok {
  169. return json.Unmarshal(data, &s)
  170. }
  171. return fmt.Errorf("Could not not decode type %T -> %T", src, s)
  172. }
  173. // CompileTemplate compiles a campaign body template into its base
  174. // template and sets the resultant template to Campaign.Tpl
  175. func (c *Campaign) CompileTemplate(f template.FuncMap) error {
  176. // Compile the base template.
  177. t := regexpLinkTag.ReplaceAllString(c.TemplateBody, regexpLinkTagReplace)
  178. t = regexpViewTag.ReplaceAllString(t, regexpViewTagReplace)
  179. baseTPL, err := template.New(BaseTpl).Funcs(f).Parse(t)
  180. if err != nil {
  181. return fmt.Errorf("error compiling base template: %v", err)
  182. }
  183. // Compile the campaign message.
  184. t = regexpLinkTag.ReplaceAllString(c.Body, regexpLinkTagReplace)
  185. t = regexpViewTag.ReplaceAllString(t, regexpViewTagReplace)
  186. msgTpl, err := template.New(ContentTpl).Funcs(f).Parse(t)
  187. if err != nil {
  188. return fmt.Errorf("error compiling message: %v", err)
  189. }
  190. out, err := baseTPL.AddParseTree(ContentTpl, msgTpl.Tree)
  191. if err != nil {
  192. return fmt.Errorf("error inserting child template: %v", err)
  193. }
  194. c.Tpl = out
  195. return nil
  196. }
  197. // FirstName splits the name by spaces and returns the first chunk
  198. // of the name that's greater than 2 characters in length, assuming
  199. // that it is the subscriber's first name.
  200. func (s *Subscriber) FirstName() string {
  201. for _, s := range strings.Split(s.Name, " ") {
  202. if len(s) > 2 {
  203. return s
  204. }
  205. }
  206. return s.Name
  207. }
  208. // LastName splits the name by spaces and returns the last chunk
  209. // of the name that's greater than 2 characters in length, assuming
  210. // that it is the subscriber's last name.
  211. func (s *Subscriber) LastName() string {
  212. chunks := strings.Split(s.Name, " ")
  213. for i := len(chunks) - 1; i >= 0; i-- {
  214. chunk := chunks[i]
  215. if len(chunk) > 2 {
  216. return chunk
  217. }
  218. }
  219. return s.Name
  220. }