utils.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "fmt"
  6. "log"
  7. "mime/multipart"
  8. "net/http"
  9. "reflect"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "github.com/disintegration/imaging"
  14. "github.com/jmoiron/sqlx"
  15. "github.com/knadh/goyesql"
  16. "github.com/labstack/echo"
  17. "github.com/lib/pq"
  18. )
  19. var (
  20. // This replaces all special characters
  21. tagRegexp = regexp.MustCompile(`[^a-z0-9\-\s]`)
  22. tagRegexpSpaces = regexp.MustCompile(`[\s]+`)
  23. )
  24. // ScanToStruct prepares a given set of Queries and assigns the resulting
  25. // *sql.Stmt statements to the fields of a given struct, matching based on the name
  26. // in the `query` tag in the struct field names.
  27. func scanQueriesToStruct(obj interface{}, q goyesql.Queries, db *sqlx.DB) error {
  28. ob := reflect.ValueOf(obj)
  29. if ob.Kind() == reflect.Ptr {
  30. ob = ob.Elem()
  31. }
  32. if ob.Kind() != reflect.Struct {
  33. return fmt.Errorf("Failed to apply SQL statements to struct. Non struct type: %T", ob)
  34. }
  35. // Go through every field in the struct and look for it in the Args map.
  36. for i := 0; i < ob.NumField(); i++ {
  37. f := ob.Field(i)
  38. if f.IsValid() {
  39. if tag := ob.Type().Field(i).Tag.Get("query"); tag != "" && tag != "-" {
  40. // Extract the value of the `query` tag.
  41. var (
  42. tg = strings.Split(tag, ",")
  43. name string
  44. )
  45. if len(tg) == 2 {
  46. if tg[0] != "-" && tg[0] != "" {
  47. name = tg[0]
  48. }
  49. } else {
  50. name = tg[0]
  51. }
  52. // Query name found in the field tag is not in the map.
  53. if _, ok := q[name]; !ok {
  54. return fmt.Errorf("query '%s' not found in query map", name)
  55. }
  56. if !f.CanSet() {
  57. return fmt.Errorf("query field '%s' is unexported", ob.Type().Field(i).Name)
  58. }
  59. switch f.Type().String() {
  60. case "string":
  61. // Unprepared SQL query.
  62. f.Set(reflect.ValueOf(q[name].Query))
  63. case "*sqlx.Stmt":
  64. // Prepared query.
  65. stmt, err := db.Preparex(q[name].Query)
  66. if err != nil {
  67. return fmt.Errorf("Error preparing query '%s': %v", name, err)
  68. }
  69. f.Set(reflect.ValueOf(stmt))
  70. }
  71. }
  72. }
  73. }
  74. return nil
  75. }
  76. // validateMIME is a helper function to validate uploaded file's MIME type
  77. // against the slice of MIME types is given.
  78. func validateMIME(typ string, mimes []string) (ok bool) {
  79. if len(mimes) > 0 {
  80. var (
  81. ok = false
  82. )
  83. for _, m := range mimes {
  84. if typ == m {
  85. ok = true
  86. break
  87. }
  88. }
  89. if !ok {
  90. return false
  91. }
  92. }
  93. return true
  94. }
  95. // generateFileName appends the incoming file's name with a small random hash.
  96. func generateFileName(fName string) string {
  97. name := strings.TrimSpace(fName)
  98. if name == "" {
  99. name, _ = generateRandomString(10)
  100. }
  101. return name
  102. }
  103. // createThumbnail reads the file object and returns a smaller image
  104. func createThumbnail(file *multipart.FileHeader) (*bytes.Reader, error) {
  105. src, err := file.Open()
  106. if err != nil {
  107. return nil, err
  108. }
  109. defer src.Close()
  110. img, err := imaging.Decode(src)
  111. if err != nil {
  112. return nil, echo.NewHTTPError(http.StatusInternalServerError,
  113. fmt.Sprintf("Error decoding image: %v", err))
  114. }
  115. t := imaging.Resize(img, thumbnailSize, 0, imaging.Lanczos)
  116. // Encode the image into a byte slice as PNG.
  117. var buf bytes.Buffer
  118. err = imaging.Encode(&buf, t, imaging.PNG)
  119. if err != nil {
  120. log.Fatal(err)
  121. }
  122. return bytes.NewReader(buf.Bytes()), nil
  123. }
  124. // Given an error, pqErrMsg will try to return pq error details
  125. // if it's a pq error.
  126. func pqErrMsg(err error) string {
  127. if err, ok := err.(*pq.Error); ok {
  128. if err.Detail != "" {
  129. return fmt.Sprintf("%s. %s", err, err.Detail)
  130. }
  131. }
  132. return err.Error()
  133. }
  134. // normalizeTags takes a list of string tags and normalizes them by
  135. // lowercasing and removing all special characters except for dashes.
  136. func normalizeTags(tags []string) []string {
  137. var (
  138. out []string
  139. space = []byte(" ")
  140. dash = []byte("-")
  141. )
  142. for _, t := range tags {
  143. rep := bytes.TrimSpace(tagRegexp.ReplaceAll(bytes.ToLower([]byte(t)), space))
  144. rep = tagRegexpSpaces.ReplaceAll(rep, dash)
  145. if len(rep) > 0 {
  146. out = append(out, string(rep))
  147. }
  148. }
  149. return out
  150. }
  151. // makeMsgTpl takes a page title, heading, and message and returns
  152. // a msgTpl that can be rendered as a HTML view. This is used for
  153. // rendering arbitrary HTML views with error and success messages.
  154. func makeMsgTpl(pageTitle, heading, msg string) msgTpl {
  155. if heading == "" {
  156. heading = pageTitle
  157. }
  158. err := msgTpl{}
  159. err.Title = pageTitle
  160. err.MessageTitle = heading
  161. err.Message = msg
  162. return err
  163. }
  164. // parseStringIDs takes a slice of numeric string IDs and
  165. // parses each number into an int64 and returns a slice of the
  166. // resultant values.
  167. func parseStringIDs(s []string) ([]int64, error) {
  168. vals := make([]int64, 0, len(s))
  169. for _, v := range s {
  170. i, err := strconv.ParseInt(v, 10, 64)
  171. if err != nil {
  172. return nil, err
  173. }
  174. if i < 1 {
  175. return nil, fmt.Errorf("%d is not a valid ID", i)
  176. }
  177. vals = append(vals, i)
  178. }
  179. return vals, nil
  180. }
  181. // generateRandomString generates a cryptographically random, alphanumeric string of length n.
  182. func generateRandomString(n int) (string, error) {
  183. const dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  184. var bytes = make([]byte, n)
  185. if _, err := rand.Read(bytes); err != nil {
  186. return "", err
  187. }
  188. for k, v := range bytes {
  189. bytes[k] = dictionary[v%byte(len(dictionary))]
  190. }
  191. return string(bytes), nil
  192. }