forked from micromdm/micromdm
/
event.go
63 lines (55 loc) · 1.49 KB
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package command
import (
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"github.com/micromdm/micromdm/mdm/mdm"
"github.com/micromdm/micromdm/platform/command/internal/commandproto"
)
type Event struct {
ID string
Time time.Time
Payload *mdm.CommandPayload
DeviceUDID string
}
// NewEvent returns an Event with a unique ID and the current time.
func NewEvent(payload *mdm.CommandPayload, udid string) *Event {
event := Event{
ID: uuid.New().String(),
Time: time.Now().UTC(),
Payload: payload,
DeviceUDID: udid,
}
return &event
}
// MarshalEvent serializes an event to a protocol buffer wire format.
func MarshalEvent(e *Event) ([]byte, error) {
payloadBytes, err := mdm.MarshalCommandPayload(e.Payload)
if err != nil {
return nil, err
}
return proto.Marshal(&commandproto.Event{
Id: e.ID,
Time: e.Time.UnixNano(),
PayloadBytes: payloadBytes,
DeviceUdid: e.DeviceUDID,
})
}
// UnmarshalEvent parses a protocol buffer representation of data into
// the Event.
func UnmarshalEvent(data []byte, e *Event) error {
var pb commandproto.Event
if err := proto.Unmarshal(data, &pb); err != nil {
return errors.Wrap(err, "unmarshal pb Event")
}
var payload mdm.CommandPayload
if err := mdm.UnmarshalCommandPayload(pb.PayloadBytes, &payload); err != nil {
return err
}
e.ID = pb.Id
e.DeviceUDID = pb.DeviceUdid
e.Time = time.Unix(0, pb.Time).UTC()
e.Payload = &payload
return nil
}