models.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 "$3" .Campaign.UUID .Subscriber.UUID }}`
  46. regexpViewTag = regexp.MustCompile(`{{(\s+)?TrackView(\s+)?}}`)
  47. regexpViewTagReplace = `{{ TrackView .Campaign.UUID .Subscriber.UUID }}`
  48. )
  49. // AdminNotifCallback is a callback function that's called
  50. // when a campaign's status changes.
  51. type AdminNotifCallback func(subject string, data map[string]interface{}) error
  52. // Base holds common fields shared across models.
  53. type Base struct {
  54. ID int `db:"id" json:"id"`
  55. CreatedAt null.Time `db:"created_at" json:"created_at"`
  56. UpdatedAt null.Time `db:"updated_at" json:"updated_at"`
  57. }
  58. // User represents an admin user.
  59. type User struct {
  60. Base
  61. Email string `json:"email"`
  62. Name string `json:"name"`
  63. Password string `json:"-"`
  64. Type string `json:"type"`
  65. Status string `json:"status"`
  66. }
  67. // Subscriber represents an e-mail subscriber.
  68. type Subscriber struct {
  69. Base
  70. UUID string `db:"uuid" json:"uuid"`
  71. Email string `db:"email" json:"email"`
  72. Name string `db:"name" json:"name"`
  73. Attribs SubscriberAttribs `db:"attribs" json:"attribs"`
  74. Status string `db:"status" json:"status"`
  75. CampaignIDs pq.Int64Array `db:"campaigns" json:"-"`
  76. Lists []List `json:"lists"`
  77. // Pseudofield for getting the total number of subscribers
  78. // in searches and queries.
  79. Total int `db:"total" json:"-"`
  80. }
  81. // SubscriberAttribs is the map of key:value attributes of a subscriber.
  82. type SubscriberAttribs map[string]interface{}
  83. // Subscribers represents a slice of Subscriber.
  84. type Subscribers []Subscriber
  85. // List represents a mailing list.
  86. type List struct {
  87. Base
  88. UUID string `db:"uuid" json:"uuid"`
  89. Name string `db:"name" json:"name"`
  90. Type string `db:"type" json:"type"`
  91. Tags pq.StringArray `db:"tags" json:"tags"`
  92. SubscriberCount int `db:"subscriber_count" json:"subscriber_count"`
  93. SubscriberID int `db:"subscriber_id" json:"-"`
  94. // This is only relevant when querying the lists of a subscriber.
  95. SubscriptionStatus string `db:"subscription_status" json:"subscription_status,omitempty"`
  96. }
  97. // Campaign represents an e-mail campaign.
  98. type Campaign struct {
  99. Base
  100. CampaignMeta
  101. UUID string `db:"uuid" json:"uuid"`
  102. Name string `db:"name" json:"name"`
  103. Subject string `db:"subject" json:"subject"`
  104. FromEmail string `db:"from_email" json:"from_email"`
  105. Body string `db:"body" json:"body,omitempty"`
  106. SendAt null.Time `db:"send_at" json:"send_at"`
  107. Status string `db:"status" json:"status"`
  108. ContentType string `db:"content_type" json:"content_type"`
  109. Tags pq.StringArray `db:"tags" json:"tags"`
  110. TemplateID int `db:"template_id" json:"template_id"`
  111. MessengerID string `db:"messenger" json:"messenger"`
  112. Lists types.JSONText `json:"lists"`
  113. View int `db:"views" json:"views"`
  114. Clicks int `db:"clicks" json:"clicks"`
  115. // TemplateBody is joined in from templates by the next-campaigns query.
  116. TemplateBody string `db:"template_body" json:"-"`
  117. Tpl *template.Template `json:"-"`
  118. // Pseudofield for getting the total number of subscribers
  119. // in searches and queries.
  120. Total int `db:"total" json:"-"`
  121. }
  122. // CampaignMeta contains fields tracking a campaign's progress.
  123. type CampaignMeta struct {
  124. StartedAt null.Time `db:"started_at" json:"started_at"`
  125. ToSend int `db:"to_send" json:"to_send"`
  126. Sent int `db:"sent" json:"sent"`
  127. }
  128. // Campaigns represents a slice of Campaign.
  129. type Campaigns []Campaign
  130. // Media represents an uploaded media item.
  131. type Media struct {
  132. ID int `db:"id" json:"id"`
  133. UUID string `db:"uuid" json:"uuid"`
  134. Filename string `db:"filename" json:"filename"`
  135. Width int `db:"width" json:"width"`
  136. Height int `db:"height" json:"height"`
  137. CreatedAt null.Time `db:"created_at" json:"created_at"`
  138. ThumbURI string `json:"thumb_uri"`
  139. URI string `json:"uri"`
  140. }
  141. // Template represents a reusable e-mail template.
  142. type Template struct {
  143. Base
  144. Name string `db:"name" json:"name"`
  145. Body string `db:"body" json:"body,omitempty"`
  146. IsDefault bool `db:"is_default" json:"is_default"`
  147. }
  148. // LoadLists lazy loads the lists for all the subscribers
  149. // in the Subscribers slice and attaches them to their []Lists property.
  150. func (subs Subscribers) LoadLists(stmt *sqlx.Stmt) error {
  151. var (
  152. lists []List
  153. subIDs = make([]int, len(subs))
  154. )
  155. for i := 0; i < len(subs); i++ {
  156. subIDs[i] = subs[i].ID
  157. subs[i].Lists = make([]List, 0)
  158. }
  159. err := stmt.Select(&lists, pq.Array(subIDs))
  160. if err != nil {
  161. return err
  162. }
  163. // Loop through each list and attach it to the subscribers by ID.
  164. for _, l := range lists {
  165. for i := 0; i < len(subs); i++ {
  166. if l.SubscriberID == subs[i].ID {
  167. subs[i].Lists = append(subs[i].Lists, l)
  168. }
  169. }
  170. }
  171. return nil
  172. }
  173. // Value returns the JSON marshalled SubscriberAttribs.
  174. func (s SubscriberAttribs) Value() (driver.Value, error) {
  175. return json.Marshal(s)
  176. }
  177. // Scan unmarshals JSON into SubscriberAttribs.
  178. func (s SubscriberAttribs) Scan(src interface{}) error {
  179. if data, ok := src.([]byte); ok {
  180. return json.Unmarshal(data, &s)
  181. }
  182. return fmt.Errorf("Could not not decode type %T -> %T", src, s)
  183. }
  184. // CompileTemplate compiles a campaign body template into its base
  185. // template and sets the resultant template to Campaign.Tpl.
  186. func (c *Campaign) CompileTemplate(f template.FuncMap) error {
  187. // Compile the base template.
  188. t := regexpLinkTag.ReplaceAllString(c.TemplateBody, regexpLinkTagReplace)
  189. t = regexpViewTag.ReplaceAllString(t, regexpViewTagReplace)
  190. baseTPL, err := template.New(BaseTpl).Funcs(f).Parse(t)
  191. if err != nil {
  192. return fmt.Errorf("error compiling base template: %v", err)
  193. }
  194. // Compile the campaign message.
  195. t = regexpLinkTag.ReplaceAllString(c.Body, regexpLinkTagReplace)
  196. t = regexpViewTag.ReplaceAllString(t, regexpViewTagReplace)
  197. msgTpl, err := template.New(ContentTpl).Funcs(f).Parse(t)
  198. if err != nil {
  199. return fmt.Errorf("error compiling message: %v", err)
  200. }
  201. out, err := baseTPL.AddParseTree(ContentTpl, msgTpl.Tree)
  202. if err != nil {
  203. return fmt.Errorf("error inserting child template: %v", err)
  204. }
  205. c.Tpl = out
  206. return nil
  207. }
  208. // FirstName splits the name by spaces and returns the first chunk
  209. // of the name that's greater than 2 characters in length, assuming
  210. // that it is the subscriber's first name.
  211. func (s *Subscriber) FirstName() string {
  212. for _, s := range strings.Split(s.Name, " ") {
  213. if len(s) > 2 {
  214. return s
  215. }
  216. }
  217. return s.Name
  218. }
  219. // LastName splits the name by spaces and returns the last chunk
  220. // of the name that's greater than 2 characters in length, assuming
  221. // that it is the subscriber's last name.
  222. func (s *Subscriber) LastName() string {
  223. chunks := strings.Split(s.Name, " ")
  224. for i := len(chunks) - 1; i >= 0; i-- {
  225. chunk := chunks[i]
  226. if len(chunk) > 2 {
  227. return chunk
  228. }
  229. }
  230. return s.Name
  231. }