core.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. MaxBounceCount int
  34. BounceAction string
  35. }
  36. // Hooks contains external function hooks that are required by the core package.
  37. type Hooks struct {
  38. SendOptinConfirmation func(models.Subscriber, []int) (int, error)
  39. }
  40. // Opt contains the controllers required to start the core.
  41. type Opt struct {
  42. Constants Constants
  43. I18n *i18n.I18n
  44. DB *sqlx.DB
  45. Queries *models.Queries
  46. Log *log.Logger
  47. }
  48. var (
  49. regexFullTextQuery = regexp.MustCompile(`\s+`)
  50. regexpSpaces = regexp.MustCompile(`[\s]+`)
  51. querySortFields = []string{"name", "status", "created_at", "updated_at"}
  52. )
  53. // New returns a new instance of the core.
  54. func New(o *Opt, h *Hooks) *Core {
  55. return &Core{
  56. h: h,
  57. constants: o.Constants,
  58. i18n: o.I18n,
  59. db: o.DB,
  60. q: o.Queries,
  61. log: o.Log,
  62. }
  63. }
  64. // Given an error, pqErrMsg will try to return pq error details
  65. // if it's a pq error.
  66. func pqErrMsg(err error) string {
  67. if err, ok := err.(*pq.Error); ok {
  68. if err.Detail != "" {
  69. return fmt.Sprintf("%s. %s", err, err.Detail)
  70. }
  71. }
  72. return err.Error()
  73. }
  74. // makeSearchQuery cleans an optional search string and prepares the
  75. // query SQL statement (string interpolated) and returns the
  76. // search query string along with the SQL expression.
  77. func makeSearchQuery(searchStr, orderBy, order, query string) (string, string) {
  78. if searchStr != "" {
  79. searchStr = `%` + string(regexFullTextQuery.ReplaceAll([]byte(searchStr), []byte("&"))) + `%`
  80. }
  81. // Sort params.
  82. if !strSliceContains(orderBy, querySortFields) {
  83. orderBy = "created_at"
  84. }
  85. if order != SortAsc && order != SortDesc {
  86. order = SortDesc
  87. }
  88. query = strings.ReplaceAll(query, "%order%", orderBy+" "+order)
  89. return searchStr, query
  90. }
  91. // strSliceContains checks if a string is present in the string slice.
  92. func strSliceContains(str string, sl []string) bool {
  93. for _, s := range sl {
  94. if s == str {
  95. return true
  96. }
  97. }
  98. return false
  99. }
  100. // normalizeTags takes a list of string tags and normalizes them by
  101. // lower casing and removing all special characters except for dashes.
  102. func normalizeTags(tags []string) []string {
  103. var (
  104. out []string
  105. dash = []byte("-")
  106. )
  107. for _, t := range tags {
  108. rep := regexpSpaces.ReplaceAll(bytes.TrimSpace([]byte(t)), dash)
  109. if len(rep) > 0 {
  110. out = append(out, string(rep))
  111. }
  112. }
  113. return out
  114. }
  115. // sanitizeSQLExp does basic sanitisation on arbitrary
  116. // SQL query expressions coming from the frontend.
  117. func sanitizeSQLExp(q string) string {
  118. if len(q) == 0 {
  119. return ""
  120. }
  121. q = strings.TrimSpace(q)
  122. // Remove semicolon suffix.
  123. if q[len(q)-1] == ';' {
  124. q = q[:len(q)-1]
  125. }
  126. return q
  127. }
  128. // strHasLen checks if the given string has a length within min-max.
  129. func strHasLen(str string, min, max int) bool {
  130. return len(str) >= min && len(str) <= max
  131. }