Timestamp.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package SystemInfo
  2. import (
  3. pb "AudioPlayer/gRPC_Model"
  4. "context"
  5. "os/exec"
  6. "strings"
  7. "time"
  8. )
  9. type TimeGRpcServer struct {
  10. pb.UnimplementedTimeServer
  11. }
  12. func (s *TimeGRpcServer) GetTime(ctx context.Context, in *pb.Empty) (*pb.Timestamp, error) {
  13. now := time.Now()
  14. return &pb.Timestamp{
  15. Seconds: now.Unix(),
  16. }, nil
  17. }
  18. func (s *TimeGRpcServer) SetTime(ctx context.Context, ts *pb.Timestamp) (*pb.Empty, error) {
  19. t := time.Unix(ts.Seconds, 0).Format(time.DateTime)
  20. _, err := exec.Command("timedatectl", "set-time", t).Output()
  21. if err != nil {
  22. return &pb.Empty{}, err
  23. }
  24. return &pb.Empty{}, nil
  25. }
  26. func Bool2String(b bool) string {
  27. if b {
  28. return "true"
  29. }
  30. return "false"
  31. }
  32. func (s *TimeGRpcServer) AutoSet(ctx context.Context, ts *pb.StateSwitch) (*pb.Empty, error) {
  33. _, err := exec.CommandContext(ctx, "timedatectl", "set-ntp", Bool2String(ts.State)).Output()
  34. if err != nil {
  35. return nil, err
  36. }
  37. return &pb.Empty{}, nil
  38. }
  39. func (s *TimeGRpcServer) AutoSetState(ctx context.Context, ts *pb.Empty) (*pb.StateSwitch, error) {
  40. out, err := exec.CommandContext(ctx, "timedatectl", "status").Output()
  41. return &pb.StateSwitch{State: strings.Contains(string(out), "NTP service: active")}, err
  42. }