The new Ripple frontend.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

profbackground.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "fmt"
  4. "image"
  5. "image/jpeg"
  6. "os"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/nfnt/resize"
  12. )
  13. var hexColourRegex = regexp.MustCompile("^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$")
  14. func profBackground(c *gin.Context) {
  15. ctx := getContext(c)
  16. if ctx.User.ID == 0 {
  17. resp403(c)
  18. return
  19. }
  20. var m message = successMessage{T(c, "Your profile background has been saved.")}
  21. defer func() {
  22. addMessage(c, m)
  23. getSession(c).Save()
  24. c.Redirect(302, "/settings/profbackground")
  25. }()
  26. if ok, _ := CSRF.Validate(ctx.User.ID, c.PostForm("csrf")); !ok {
  27. m = errorMessage{T(c, "Your session has expired. Please try redoing what you were trying to do.")}
  28. return
  29. }
  30. t := c.Param("type")
  31. switch t {
  32. case "0":
  33. db.Exec("DELETE FROM profile_backgrounds WHERE uid = ?", ctx.User.ID)
  34. case "1":
  35. // image
  36. file, _, err := c.Request.FormFile("value")
  37. if err != nil {
  38. m = errorMessage{T(c, "An error occurred.")}
  39. return
  40. }
  41. img, _, err := image.Decode(file)
  42. if err != nil {
  43. m = errorMessage{T(c, "An error occurred.")}
  44. return
  45. }
  46. img = resize.Thumbnail(2496, 1404, img, resize.Bilinear)
  47. f, err := os.Create(fmt.Sprintf("static/profbackgrounds/%d.jpg", ctx.User.ID))
  48. defer f.Close()
  49. if err != nil {
  50. m = errorMessage{T(c, "An error occurred.")}
  51. c.Error(err)
  52. return
  53. }
  54. err = jpeg.Encode(f, img, &jpeg.Options{
  55. Quality: 88,
  56. })
  57. if err != nil {
  58. m = errorMessage{T(c, "We were not able to save your profile background.")}
  59. c.Error(err)
  60. return
  61. }
  62. saveProfileBackground(ctx, 1, fmt.Sprintf("%d.jpg?%d", ctx.User.ID, time.Now().Unix()))
  63. case "2":
  64. // solid colour
  65. col := strings.ToLower(c.PostForm("value"))
  66. // verify it's valid
  67. if !hexColourRegex.MatchString(col) {
  68. m = errorMessage{T(c, "Colour is invalid")}
  69. return
  70. }
  71. saveProfileBackground(ctx, 2, col)
  72. }
  73. }
  74. func saveProfileBackground(ctx context, t int, val string) {
  75. db.Exec(`INSERT INTO profile_backgrounds(uid, time, type, value)
  76. VALUES (?, ?, ?, ?)
  77. ON DUPLICATE KEY UPDATE
  78. time = VALUES(time),
  79. type = VALUES(type),
  80. value = VALUES(value)
  81. `, ctx.User.ID, time.Now().Unix(), t, val)
  82. }