core.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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. return searchStr, fmt.Sprintf(query, orderBy, order)
  89. }
  90. // strSliceContains checks if a string is present in the string slice.
  91. func strSliceContains(str string, sl []string) bool {
  92. for _, s := range sl {
  93. if s == str {
  94. return true
  95. }
  96. }
  97. return false
  98. }
  99. // normalizeTags takes a list of string tags and normalizes them by
  100. // lower casing and removing all special characters except for dashes.
  101. func normalizeTags(tags []string) []string {
  102. var (
  103. out []string
  104. dash = []byte("-")
  105. )
  106. for _, t := range tags {
  107. rep := regexpSpaces.ReplaceAll(bytes.TrimSpace([]byte(t)), dash)
  108. if len(rep) > 0 {
  109. out = append(out, string(rep))
  110. }
  111. }
  112. return out
  113. }
  114. // sanitizeSQLExp does basic sanitisation on arbitrary
  115. // SQL query expressions coming from the frontend.
  116. func sanitizeSQLExp(q string) string {
  117. if len(q) == 0 {
  118. return ""
  119. }
  120. q = strings.TrimSpace(q)
  121. // Remove semicolon suffix.
  122. if q[len(q)-1] == ';' {
  123. q = q[:len(q)-1]
  124. }
  125. return q
  126. }
  127. // strHasLen checks if the given string has a length within min-max.
  128. func strHasLen(str string, min, max int) bool {
  129. return len(str) >= min && len(str) <= max
  130. }