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.

avatar.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "crypto/md5"
  7. "fmt"
  8. "net/url"
  9. "strings"
  10. "code.gitea.io/gitea/modules/cache"
  11. "code.gitea.io/gitea/modules/setting"
  12. )
  13. // EmailHash represents a pre-generated hash map
  14. type EmailHash struct {
  15. Hash string `xorm:"pk varchar(32)"`
  16. Email string `xorm:"UNIQUE NOT NULL"`
  17. }
  18. // GetEmailForHash converts a provided md5sum to the email
  19. func GetEmailForHash(md5Sum string) (string, error) {
  20. return cache.GetString("Avatar:"+md5Sum, func() (string, error) {
  21. emailHash := EmailHash{
  22. Hash: strings.ToLower(strings.TrimSpace(md5Sum)),
  23. }
  24. _, err := x.Get(&emailHash)
  25. return emailHash.Email, err
  26. })
  27. }
  28. // AvatarLink returns an avatar link for a provided email
  29. func AvatarLink(email string) string {
  30. lowerEmail := strings.ToLower(strings.TrimSpace(email))
  31. sum := fmt.Sprintf("%x", md5.Sum([]byte(lowerEmail)))
  32. _, _ = cache.GetString("Avatar:"+sum, func() (string, error) {
  33. emailHash := &EmailHash{
  34. Email: lowerEmail,
  35. Hash: sum,
  36. }
  37. // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors
  38. sess := x.NewSession()
  39. defer sess.Close()
  40. if err := sess.Begin(); err != nil {
  41. // we don't care about any DB problem just return the lowerEmail
  42. return lowerEmail, nil
  43. }
  44. _, _ = sess.Insert(emailHash)
  45. if err := sess.Commit(); err != nil {
  46. // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
  47. return lowerEmail, nil
  48. }
  49. return lowerEmail, nil
  50. })
  51. return setting.AppSubURL + "/avatar/" + url.PathEscape(sum)
  52. }