-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.go
65 lines (54 loc) · 1.31 KB
/
adapter.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
package lxlib
import (
"encoding/json"
"github.com/lxbot/lxlib/v2/common"
"github.com/lxbot/lxlib/v2/lxtypes"
)
type Adapter struct {
common *common.LxCommon
eventCh *chan *lxtypes.Event
messageCh *chan *lxtypes.Message
}
func NewAdapter() (*Adapter, *chan *lxtypes.Message) {
messageCh := make(chan *lxtypes.Message)
eventCh := make(chan *lxtypes.Event)
c := common.NewLxCommon()
adapter := &Adapter{
common: c,
eventCh: &eventCh,
messageCh: &messageCh,
}
go c.Listen(&eventCh)
go adapter.listen()
adapter.Raw(lxtypes.NewEvent(lxtypes.ReadyEvent, lxtypes.ReadyEventPayload{
Mode: lxtypes.StdIOMode,
Endpoint: "",
}))
return adapter, &messageCh
}
func (this *Adapter) listen() {
for {
eventPtr := <-*this.eventCh
switch eventPtr.Event {
case lxtypes.OutgoingMessageEvent:
json := eventPtr.Payload.(json.RawMessage)
payload, err := common.FromJSON(json)
if err != nil {
common.ErrorLog(err)
continue
}
message, err := lxtypes.NewLXMessage(payload)
if err != nil {
common.ErrorLog(err)
continue
}
*this.messageCh <- message
}
}
}
func (this *Adapter) Raw(event *lxtypes.Event) {
go this.common.Send(event)
}
func (this *Adapter) Send(message *lxtypes.Message) {
go this.common.Send(lxtypes.NewEvent(lxtypes.IncomingMessageEvent, message))
}