icon.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package service
  2. import (
  3. "context"
  4. "sort"
  5. "strings"
  6. "sync"
  7. "time"
  8. "go-common/app/interface/main/web/model"
  9. resmdl "go-common/app/service/main/resource/model"
  10. "go-common/library/log"
  11. )
  12. const (
  13. _iconFixType = "fix"
  14. )
  15. // IndexIcon get index icons
  16. func (s *Service) IndexIcon() (res *model.IndexIcon) {
  17. return s.indexIcon
  18. }
  19. func fmtIndexIcon(icons []*resmdl.IndexIcon) {
  20. for _, v := range icons {
  21. v.Icon = strings.Replace(v.Icon, "http://", "//", 1)
  22. }
  23. }
  24. func (s *Service) randomIndexIcon(icons []*resmdl.IndexIcon) (icon *model.IndexIcon) {
  25. var (
  26. item *resmdl.IndexIcon
  27. total, weight int
  28. )
  29. length := len(icons)
  30. if length == 0 {
  31. return new(model.IndexIcon)
  32. }
  33. for _, v := range icons {
  34. if v.Weight == 0 {
  35. total++
  36. } else {
  37. total += v.Weight
  38. }
  39. }
  40. if total == length {
  41. item = icons[s.r.Intn(length)]
  42. return &model.IndexIcon{ID: item.ID, Title: item.Title, Links: item.Links, Icon: item.Icon, Weight: item.Weight}
  43. }
  44. randWeight := s.r.Intn(total)
  45. for _, v := range icons {
  46. if v.Weight == 0 {
  47. weight++
  48. } else {
  49. weight += v.Weight
  50. }
  51. if weight > randWeight {
  52. item = v
  53. break
  54. }
  55. }
  56. return &model.IndexIcon{ID: item.ID, Title: item.Title, Links: item.Links, Icon: item.Icon, Weight: item.Weight}
  57. }
  58. func (s *Service) indexIconproc() {
  59. var (
  60. data map[string][]*resmdl.IndexIcon
  61. icons []*resmdl.IndexIcon
  62. ok bool
  63. err error
  64. mutex = sync.RWMutex{}
  65. )
  66. go func() {
  67. for {
  68. if data, err = s.res.IndexIcon(context.Background()); err != nil {
  69. log.Error("s.res.IndexIcon error(%v)", err)
  70. time.Sleep(time.Second)
  71. continue
  72. }
  73. mutex.Lock()
  74. icons, ok = data[_iconFixType]
  75. mutex.Unlock()
  76. if ok {
  77. if len(icons) == 0 {
  78. log.Error("s.res.IndexIcon data error")
  79. time.Sleep(time.Second)
  80. continue
  81. } else {
  82. sort.Slice(icons, func(i, j int) bool { return icons[i].Weight > icons[j].Weight })
  83. fmtIndexIcon(icons)
  84. }
  85. } else {
  86. log.Error("s.res.IndexIcon data error")
  87. time.Sleep(time.Second)
  88. continue
  89. }
  90. time.Sleep(time.Duration(s.c.WEB.PullOnlineInterval))
  91. }
  92. }()
  93. for {
  94. mutex.RLock()
  95. tempIcons := make([]*resmdl.IndexIcon, len(icons))
  96. copy(tempIcons, icons)
  97. mutex.RUnlock()
  98. s.indexIcon = s.randomIndexIcon(tempIcons)
  99. time.Sleep(500 * time.Millisecond)
  100. }
  101. }