2
0

status.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package manager
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "time"
  8. . "github.com/tuna/tunasync/internal"
  9. )
  10. type mirrorStatus struct {
  11. Name string
  12. Status SyncStatus
  13. LastUpdate time.Time
  14. Upstream string
  15. Size string // approximate size
  16. }
  17. func (s mirrorStatus) MarshalJSON() ([]byte, error) {
  18. m := map[string]interface{}{
  19. "name": s.Name,
  20. "status": s.Status,
  21. "last_update": s.LastUpdate.Format("2006-01-02 15:04:05"),
  22. "last_update_ts": fmt.Sprintf("%d", s.LastUpdate.Unix()),
  23. "size": s.Size,
  24. "upstream": s.Upstream,
  25. }
  26. return json.Marshal(m)
  27. }
  28. func (s *mirrorStatus) UnmarshalJSON(v []byte) error {
  29. var m map[string]interface{}
  30. err := json.Unmarshal(v, &m)
  31. if err != nil {
  32. return err
  33. }
  34. if name, ok := m["name"]; ok {
  35. if s.Name, ok = name.(string); !ok {
  36. return errors.New("name should be a string")
  37. }
  38. } else {
  39. return errors.New("key `name` does not exist in the json")
  40. }
  41. if upstream, ok := m["upstream"]; ok {
  42. if s.Upstream, ok = upstream.(string); !ok {
  43. return errors.New("upstream should be a string")
  44. }
  45. } else {
  46. return errors.New("key `upstream` does not exist in the json")
  47. }
  48. if size, ok := m["size"]; ok {
  49. if s.Size, ok = size.(string); !ok {
  50. return errors.New("size should be a string")
  51. }
  52. } else {
  53. return errors.New("key `size` does not exist in the json")
  54. }
  55. // tricky: status
  56. if status, ok := m["status"]; ok {
  57. if ss, ok := status.(string); ok {
  58. err := json.Unmarshal([]byte(`"`+ss+`"`), &(s.Status))
  59. if err != nil {
  60. return err
  61. }
  62. } else {
  63. return errors.New("status should be a string")
  64. }
  65. } else {
  66. return errors.New("key `status` does not exist in the json")
  67. }
  68. // tricky: last update
  69. if lastUpdate, ok := m["last_update_ts"]; ok {
  70. if sts, ok := lastUpdate.(string); ok {
  71. ts, err := strconv.Atoi(sts)
  72. if err != nil {
  73. return fmt.Errorf("last_update_ts should be a interger, got: %s", sts)
  74. }
  75. s.LastUpdate = time.Unix(int64(ts), 0)
  76. } else {
  77. return fmt.Errorf("last_update_ts should be a string of integer, got: %s", lastUpdate)
  78. }
  79. } else {
  80. return errors.New("key `last_update_ts` does not exist in the json")
  81. }
  82. return nil
  83. }