utils.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "github.com/jmoiron/sqlx"
  16. "github.com/knadh/goyesql"
  17. "github.com/labstack/echo"
  18. "github.com/lib/pq"
  19. )
  20. const tmpFilePrefix = "listmonk"
  21. var (
  22. // This matches filenames, sans extensions, of the format
  23. // filename_(number). The number is incremented in case
  24. // new file uploads conflict with existing filenames
  25. // on the filesystem.
  26. fnameRegexp, _ = regexp.Compile(`(.+?)_([0-9]+)$`)
  27. // This replaces all special characters
  28. tagRegexp, _ = regexp.Compile(`[^a-z0-9\-\s]`)
  29. tagRegexpSpaces, _ = regexp.Compile(`[\s]+`)
  30. )
  31. // ScanToStruct prepares a given set of Queries and assigns the resulting
  32. // *sql.Stmt statements to the fields of a given struct, matching based on the name
  33. // in the `query` tag in the struct field names.
  34. func scanQueriesToStruct(obj interface{}, q goyesql.Queries, db *sqlx.DB) error {
  35. ob := reflect.ValueOf(obj)
  36. if ob.Kind() == reflect.Ptr {
  37. ob = ob.Elem()
  38. }
  39. if ob.Kind() != reflect.Struct {
  40. return fmt.Errorf("Failed to apply SQL statements to struct. Non struct type: %T", ob)
  41. }
  42. // Go through every field in the struct and look for it in the Args map.
  43. for i := 0; i < ob.NumField(); i++ {
  44. f := ob.Field(i)
  45. if f.IsValid() {
  46. if tag := ob.Type().Field(i).Tag.Get("query"); tag != "" && tag != "-" {
  47. // Extract the value of the `query` tag.
  48. var (
  49. tg = strings.Split(tag, ",")
  50. name string
  51. )
  52. if len(tg) == 2 {
  53. if tg[0] != "-" && tg[0] != "" {
  54. name = tg[0]
  55. }
  56. } else {
  57. name = tg[0]
  58. }
  59. // Query name found in the field tag is not in the map.
  60. if _, ok := q[name]; !ok {
  61. return fmt.Errorf("query '%s' not found in query map", name)
  62. }
  63. if !f.CanSet() {
  64. return fmt.Errorf("query field '%s' is unexported", ob.Type().Field(i).Name)
  65. }
  66. switch f.Type().String() {
  67. case "string":
  68. // Unprepared SQL query.
  69. f.Set(reflect.ValueOf(q[name].Query))
  70. case "*sqlx.Stmt":
  71. // Prepared query.
  72. stmt, err := db.Preparex(q[name].Query)
  73. if err != nil {
  74. return fmt.Errorf("Error preparing query '%s': %v", name, err)
  75. }
  76. f.Set(reflect.ValueOf(stmt))
  77. }
  78. }
  79. }
  80. }
  81. return nil
  82. }
  83. // uploadFile is a helper function on top of echo.Context for processing file uploads.
  84. // It allows copying a single file given the incoming file field name.
  85. // If the upload directory dir is empty, the file is copied to the system's temp directory.
  86. // If name is empty, the incoming file's name along with a small random hash is used.
  87. // When a slice of MIME types is given, the uploaded file's MIME type is validated against the list.
  88. func uploadFile(key string, dir, name string, mimes []string, c echo.Context) (string, error) {
  89. file, err := c.FormFile(key)
  90. if err != nil {
  91. return "", echo.NewHTTPError(http.StatusBadRequest,
  92. fmt.Sprintf("Invalid file uploaded: %v", err))
  93. }
  94. // Check MIME type.
  95. if len(mimes) > 0 {
  96. var (
  97. typ = file.Header.Get("Content-type")
  98. ok = false
  99. )
  100. for _, m := range mimes {
  101. if typ == m {
  102. ok = true
  103. break
  104. }
  105. }
  106. if !ok {
  107. return "", echo.NewHTTPError(http.StatusBadRequest,
  108. fmt.Sprintf("Unsupported file type (%s) uploaded.", typ))
  109. }
  110. }
  111. src, err := file.Open()
  112. if err != nil {
  113. return "", err
  114. }
  115. defer src.Close()
  116. // There's no upload directory. Use a tempfile.
  117. var out *os.File
  118. if dir == "" {
  119. o, err := ioutil.TempFile("", tmpFilePrefix)
  120. if err != nil {
  121. return "", echo.NewHTTPError(http.StatusInternalServerError,
  122. fmt.Sprintf("Error copying uploaded file: %v", err))
  123. }
  124. out = o
  125. name = o.Name()
  126. } else {
  127. // There's no explicit name. Use the one posted in the HTTP request.
  128. if name == "" {
  129. name = strings.TrimSpace(file.Filename)
  130. if name == "" {
  131. name, _ = generateRandomString(10)
  132. }
  133. }
  134. name = assertUniqueFilename(dir, name)
  135. o, err := os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)
  136. if err != nil {
  137. return "", echo.NewHTTPError(http.StatusInternalServerError,
  138. fmt.Sprintf("Error copying uploaded file: %v", err))
  139. }
  140. out = o
  141. }
  142. defer out.Close()
  143. if _, err = io.Copy(out, src); err != nil {
  144. return "", echo.NewHTTPError(http.StatusInternalServerError,
  145. fmt.Sprintf("Error copying uploaded file: %v", err))
  146. }
  147. return name, nil
  148. }
  149. // Given an error, pqErrMsg will try to return pq error details
  150. // if it's a pq error.
  151. func pqErrMsg(err error) string {
  152. if err, ok := err.(*pq.Error); ok {
  153. if err.Detail != "" {
  154. return fmt.Sprintf("%s. %s", err, err.Detail)
  155. }
  156. }
  157. return err.Error()
  158. }
  159. // generateRandomString generates a cryptographically random, alphanumeric string of length n.
  160. func generateRandomString(n int) (string, error) {
  161. const dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  162. var bytes = make([]byte, n)
  163. if _, err := rand.Read(bytes); err != nil {
  164. return "", err
  165. }
  166. for k, v := range bytes {
  167. bytes[k] = dictionary[v%byte(len(dictionary))]
  168. }
  169. return string(bytes), nil
  170. }
  171. // assertUniqueFilename takes a file path and check if it exists on the disk. If it doesn't,
  172. // it returns the same name and if it does, it adds a small random hash to the filename
  173. // and returns that.
  174. func assertUniqueFilename(dir, fileName string) string {
  175. var (
  176. ext = filepath.Ext(fileName)
  177. base = fileName[0 : len(fileName)-len(ext)]
  178. num = 0
  179. )
  180. for {
  181. // There's no name conflict.
  182. if _, err := os.Stat(filepath.Join(dir, fileName)); os.IsNotExist(err) {
  183. return fileName
  184. }
  185. // Does the name match the _(num) syntax?
  186. r := fnameRegexp.FindAllStringSubmatch(fileName, -1)
  187. if len(r) == 1 && len(r[0]) == 3 {
  188. num, _ = strconv.Atoi(r[0][2])
  189. }
  190. num++
  191. fileName = fmt.Sprintf("%s_%d%s", base, num, ext)
  192. }
  193. }
  194. // normalizeTags takes a list of string tags and normalizes them by
  195. // lowercasing and removing all special characters except for dashes.
  196. func normalizeTags(tags []string) []string {
  197. var (
  198. out []string
  199. space = []byte(" ")
  200. dash = []byte("-")
  201. )
  202. for _, t := range tags {
  203. rep := bytes.TrimSpace(tagRegexp.ReplaceAll(bytes.ToLower([]byte(t)), space))
  204. rep = tagRegexpSpaces.ReplaceAll(rep, dash)
  205. if len(rep) > 0 {
  206. out = append(out, string(rep))
  207. }
  208. }
  209. return out
  210. }
  211. // makeErrorTpl takes error details and returns an errorTpl
  212. // with the error details applied to be rendered in an HTML view.
  213. func makeErrorTpl(pageTitle, heading, desc string) errorTpl {
  214. if heading == "" {
  215. heading = pageTitle
  216. }
  217. err := errorTpl{}
  218. err.Title = pageTitle
  219. err.ErrorTitle = heading
  220. err.ErrorMessage = desc
  221. return err
  222. }