core.go 3.5 KB

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