GraphQL API and utilities for the rpdata project
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.

84 lines
1.5 KiB

  1. package log
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/globalsign/mgo/bson"
  6. )
  7. var scheduleCharacterUpdate = func() func() {
  8. var mutex sync.Mutex
  9. var scheduled bool
  10. return func() {
  11. mutex.Lock()
  12. if !scheduled {
  13. go func() {
  14. time.Sleep(time.Second * 60)
  15. // If another comes along in the next 2-3 seconds, it should schedule a new
  16. // round to avoid a character only appearing in half their logs.
  17. mutex.Lock()
  18. scheduled = false
  19. mutex.Unlock()
  20. UpdateAllCharacters()
  21. }()
  22. scheduled = true
  23. }
  24. mutex.Unlock()
  25. }
  26. }()
  27. // ScheduleCharacterUpdate schedules a full update within the minute.
  28. // Subsequent calls within that time will not schedule anything. Even
  29. // if the operation takes a few seconds at most, it need not be ran often.
  30. func ScheduleCharacterUpdate() {
  31. scheduleCharacterUpdate()
  32. }
  33. // UpdateCharacters is a shorthand for getting a log and updaing its characters
  34. func UpdateCharacters(logID string) error {
  35. log, err := FindID(logID)
  36. if err != nil {
  37. return err
  38. }
  39. return log.UpdateCharacters()
  40. }
  41. // UpdateAllCharacters updates character list on all logs. This should
  42. // be done if one or more characters failed to be added.
  43. func UpdateAllCharacters() (updated int, err error) {
  44. updated = 0
  45. err = clearUnknownNicks()
  46. if err != nil {
  47. return
  48. }
  49. iter := iterLogs(bson.M{}, 0)
  50. err = iter.Err()
  51. if err != nil {
  52. return
  53. }
  54. log := Log{}
  55. for iter.Next(&log) {
  56. err = log.UpdateCharacters()
  57. if err != nil {
  58. return
  59. }
  60. updated++
  61. }
  62. err = iter.Err()
  63. if err != nil {
  64. return
  65. }
  66. return
  67. }