core.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // package core is the collection of re-usable functions that primarily provides data (DB / CRUD) operations
  2. // to the app. For instance, creating and mutating objects like lists, subscribers etc.
  3. // All such methods return an echo.HTTPError{} (which implements error.error) that can be directly returned
  4. // as a response to HTTP handlers without further processing.
  5. package core
  6. import (
  7. "bytes"
  8. "fmt"
  9. "log"
  10. "regexp"
  11. "strings"
  12. "github.com/jmoiron/sqlx"
  13. "github.com/knadh/listmonk/internal/i18n"
  14. "github.com/knadh/listmonk/models"
  15. "github.com/lib/pq"
  16. )
  17. const (
  18. SortAsc = "asc"
  19. SortDesc = "desc"
  20. )
  21. // Core represents the listmonk core with all shared, global functions.
  22. type Core struct {
  23. h *Hooks
  24. constants Constants
  25. i18n *i18n.I18n
  26. db *sqlx.DB
  27. q *models.Queries
  28. log *log.Logger
  29. }
  30. // Constants represents constant config.
  31. type Constants struct {
  32. SendOptinConfirmation bool
  33. BounceActions map[string]struct {
  34. Count int
  35. Action string
  36. }
  37. }
  38. // Hooks contains external function hooks that are required by the core package.
  39. type Hooks struct {
  40. SendOptinConfirmation func(models.Subscriber, []int) (int, error)
  41. }
  42. // Opt contains the controllers required to start the core.
  43. type Opt struct {
  44. Constants Constants
  45. I18n *i18n.I18n
  46. DB *sqlx.DB
  47. Queries *models.Queries
  48. Log *log.Logger
  49. }
  50. var (
  51. regexFullTextQuery = regexp.MustCompile(`\s+`)
  52. regexpSpaces = regexp.MustCompile(`[\s]+`)
  53. campQuerySortFields = []string{"name", "status", "created_at", "updated_at"}
  54. subQuerySortFields = []string{"email", "status", "name", "created_at", "updated_at"}
  55. listQuerySortFields = []string{"name", "status", "created_at", "updated_at", "subscriber_count"}
  56. )
  57. // New returns a new instance of the core.
  58. func New(o *Opt, h *Hooks) *Core {
  59. return &Core{
  60. h: h,
  61. constants: o.Constants,
  62. i18n: o.I18n,
  63. db: o.DB,
  64. q: o.Queries,
  65. log: o.Log,
  66. }
  67. }
  68. // Given an error, pqErrMsg will try to return pq error details
  69. // if it's a pq error.
  70. func pqErrMsg(err error) string {
  71. if err, ok := err.(*pq.Error); ok {
  72. if err.Detail != "" {
  73. return fmt.Sprintf("%s. %s", err, err.Detail)
  74. }
  75. }
  76. return err.Error()
  77. }
  78. // makeSearchQuery cleans an optional search string and prepares the
  79. // query SQL statement (string interpolated) and returns the
  80. // search query string along with the SQL expression.
  81. func makeSearchQuery(searchStr, orderBy, order, query string, querySortFields []string) (string, string) {
  82. if searchStr != "" {
  83. searchStr = `%` + string(regexFullTextQuery.ReplaceAll([]byte(searchStr), []byte("&"))) + `%`
  84. }
  85. // Sort params.
  86. if !strSliceContains(orderBy, querySortFields) {
  87. orderBy = "created_at"
  88. }
  89. if order != SortAsc && order != SortDesc {
  90. order = SortDesc
  91. }
  92. query = strings.ReplaceAll(query, "%order%", orderBy+" "+order)
  93. return searchStr, query
  94. }
  95. // strSliceContains checks if a string is present in the string slice.
  96. func strSliceContains(str string, sl []string) bool {
  97. for _, s := range sl {
  98. if s == str {
  99. return true
  100. }
  101. }
  102. return false
  103. }
  104. // normalizeTags takes a list of string tags and normalizes them by
  105. // lower casing and removing all special characters except for dashes.
  106. func normalizeTags(tags []string) []string {
  107. var (
  108. out []string
  109. dash = []byte("-")
  110. )
  111. for _, t := range tags {
  112. rep := regexpSpaces.ReplaceAll(bytes.TrimSpace([]byte(t)), dash)
  113. if len(rep) > 0 {
  114. out = append(out, string(rep))
  115. }
  116. }
  117. return out
  118. }
  119. // sanitizeSQLExp does basic sanitisation on arbitrary
  120. // SQL query expressions coming from the frontend.
  121. func sanitizeSQLExp(q string) string {
  122. if len(q) == 0 {
  123. return ""
  124. }
  125. q = strings.TrimSpace(q)
  126. // Remove semicolon suffix.
  127. if q[len(q)-1] == ';' {
  128. q = q[:len(q)-1]
  129. }
  130. return q
  131. }
  132. // strHasLen checks if the given string has a length within min-max.
  133. func strHasLen(str string, min, max int) bool {
  134. return len(str) >= min && len(str) <= max
  135. }