device.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package stats
  7. import (
  8. "time"
  9. "github.com/syncthing/syncthing/internal/db"
  10. )
  11. const (
  12. lastSeenKey = "lastSeen"
  13. connDurationKey = "lastConnDuration"
  14. )
  15. type DeviceStatistics struct {
  16. LastSeen time.Time `json:"lastSeen"`
  17. LastConnectionDurationS float64 `json:"lastConnectionDurationS"`
  18. }
  19. type DeviceStatisticsReference struct {
  20. kv *db.Typed
  21. }
  22. func NewDeviceStatisticsReference(kv *db.Typed) *DeviceStatisticsReference {
  23. return &DeviceStatisticsReference{
  24. kv: kv,
  25. }
  26. }
  27. func (s *DeviceStatisticsReference) GetLastSeen() (time.Time, error) {
  28. t, ok, err := s.kv.Time(lastSeenKey)
  29. if err != nil {
  30. return time.Time{}, err
  31. } else if !ok {
  32. // The default here is 1970-01-01 as opposed to the default
  33. // time.Time{} from s.ns
  34. return time.Unix(0, 0), nil
  35. }
  36. return t, nil
  37. }
  38. func (s *DeviceStatisticsReference) GetLastConnectionDuration() (time.Duration, error) {
  39. d, ok, err := s.kv.Int64(connDurationKey)
  40. if err != nil {
  41. return 0, err
  42. } else if !ok {
  43. return 0, nil
  44. }
  45. return time.Duration(d), nil
  46. }
  47. func (s *DeviceStatisticsReference) WasSeen() error {
  48. return s.kv.PutTime(lastSeenKey, time.Now().Truncate(time.Second))
  49. }
  50. func (s *DeviceStatisticsReference) LastConnectionDuration(d time.Duration) error {
  51. return s.kv.PutInt64(connDurationKey, d.Nanoseconds())
  52. }
  53. func (s *DeviceStatisticsReference) GetStatistics() (DeviceStatistics, error) {
  54. lastSeen, err := s.GetLastSeen()
  55. if err != nil {
  56. return DeviceStatistics{}, err
  57. }
  58. lastConnDuration, err := s.GetLastConnectionDuration()
  59. if err != nil {
  60. return DeviceStatistics{}, err
  61. }
  62. return DeviceStatistics{
  63. LastSeen: lastSeen,
  64. LastConnectionDurationS: lastConnDuration.Seconds(),
  65. }, nil
  66. }