-
Notifications
You must be signed in to change notification settings - Fork 1
/
openmessaging_message_event_typing.go
92 lines (84 loc) · 2.21 KB
/
openmessaging_message_event_typing.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package gcloudcx
import (
"encoding/json"
"time"
"github.com/gildas/go-errors"
)
// OpenMessageTypingEvent is a typing event sent or received by the Open Messaging API
type OpenMessageTypingEvent struct {
IsTyping bool `json:"-"`
Duration time.Duration `json:"-"`
}
func init() {
openMessageEventRegistry.Add(OpenMessageTypingEvent{})
}
// GetType returns the type of this event
//
// implements core.TypeCarrier
func (event OpenMessageTypingEvent) GetType() string {
return "Typing"
}
// MarshalJSON marshals this into JSON
//
// implements json.Marshaler
func (event OpenMessageTypingEvent) MarshalJSON() (data []byte, err error) {
if !event.IsTyping || event.Duration > 0 {
type TypingInfo struct {
Type string `json:"type"`
Duration int `json:"duration"`
}
newTypingInfo := func(isTyping bool, duration time.Duration) TypingInfo {
if !isTyping {
return TypingInfo{
Type: "On",
Duration: int(duration.Milliseconds()),
}
}
return TypingInfo{
Type: "Off",
Duration: int(duration.Milliseconds()),
}
}
data, err = json.Marshal(struct {
Type string `json:"eventType"`
Typing TypingInfo `json:"typing"`
}{
Type: event.GetType(),
Typing: newTypingInfo(event.IsTyping, event.Duration),
})
} else {
data, err = json.Marshal(struct {
Type string `json:"eventType"`
}{
Type: event.GetType(),
})
}
return data, errors.JSONMarshalError.Wrap(err)
}
// UnmarshalJSON unmarshals JSON into this
//
// implements json.Unmarshaler
func (event *OpenMessageTypingEvent) UnmarshalJSON(payload []byte) (err error) {
type surrogate OpenMessageTypingEvent
var inner struct {
surrogate
Type string `json:"eventType"`
Typing *struct {
Type string `json:"type"`
Duration int `json:"duration"`
} `json:"typing"`
}
if err = json.Unmarshal(payload, &inner); errors.Is(err, errors.JSONUnmarshalError) {
return err
} else if err != nil {
return errors.JSONUnmarshalError.Wrap(err)
}
*event = OpenMessageTypingEvent(inner.surrogate)
if inner.Typing != nil {
event.IsTyping = inner.Typing.Type == "On"
event.Duration = time.Duration(inner.Typing.Duration) * time.Millisecond
} else {
event.IsTyping = true
}
return nil
}