-
Notifications
You must be signed in to change notification settings - Fork 138
/
main.go
201 lines (186 loc) · 5.25 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package devzatapi
import (
"context"
"github.com/quackduck/devzat/plugin"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"time"
)
type Message struct {
Room,
From,
Data,
DMTo string
}
type CmdCall struct {
Room,
From,
Args string
}
type Session struct {
conn *grpc.ClientConn
pluginClient plugin.PluginClient
ErrorChan chan error
}
// NewSession connects to the Devzat server and creates a session. The address should be in the form of "host:port".
func NewSession(address string, token string) (*Session, error) {
backoffConfig := backoff.DefaultConfig
backoffConfig.Multiplier = 1.1
conn, err := grpc.Dial(address,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithStreamInterceptor(
func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token)
return streamer(ctx, desc, cc, method, opts...)
},
),
grpc.WithUnaryInterceptor(
func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token)
return invoker(ctx, method, req, reply, cc, opts...)
},
),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
grpc.WithConnectParams(grpc.ConnectParams{Backoff: backoffConfig, MinConnectTimeout: time.Second * 20}),
)
if err != nil {
return nil, err
}
return &Session{conn: conn, pluginClient: plugin.NewPluginClient(conn), ErrorChan: make(chan error)}, nil
}
// Close closes the session.
func (s *Session) Close() error {
return s.conn.Close()
}
// RegisterListener allows for message monitoring and intercepting/editing.
// Set middleware to true to intercept and edit messages.
// Set once to true to unregister the listener after the first message is received.
// Set regex to a valid regex string to only receive messages that match the regex.
//
// messageChan will receive messages that match the regex.
// middlewareResponseChan is used to send back the edited message. You must send a response if middleware is true
// even if you don't edit the message.
// See example/main.go for correct usage of this function.
func (s *Session) RegisterListener(middleware, once bool, regex string) (messageChan chan Message, middlewareResponseChan chan string, err error) {
var client plugin.Plugin_RegisterListenerClient
setup := func() error {
client, err = s.pluginClient.RegisterListener(context.Background())
if err != nil {
return err
}
pointerRegex := ®ex
if regex == "" {
pointerRegex = nil
}
err = client.Send(&plugin.ListenerClientData{Data: &plugin.ListenerClientData_Listener{Listener: &plugin.Listener{
Middleware: &middleware,
Once: &once,
Regex: pointerRegex,
}}})
if err != nil {
return err
}
return nil
}
err = setup()
if err != nil {
return
}
messageChan = make(chan Message)
var e *plugin.Event
go func() {
for {
e, err = client.Recv()
if err != nil {
if isErrEOF(err) {
// set up new stream
err = setup()
if err == nil {
continue
}
}
s.ErrorChan <- err
continue
}
messageChan <- Message{Room: e.Room, From: e.From, Data: e.Msg}
}
}()
if !middleware {
return
}
middlewareResponseChan = make(chan string)
go func() {
for {
response := <-middlewareResponseChan
err := client.Send(&plugin.ListenerClientData{Data: &plugin.ListenerClientData_Response{Response: &plugin.MiddlewareResponse{Msg: &response}}})
if err != nil {
if isErrEOF(err) {
// set up new stream
err = setup()
if err == nil {
continue
}
}
s.ErrorChan <- err
continue
}
}
}()
return
}
func (s *Session) SendMessage(m Message) error {
if m.Data == "" {
return nil
}
fromPtr := &m.From
if m.From == "" {
fromPtr = nil
}
dmToPtr := &m.DMTo
if m.DMTo == "" {
dmToPtr = nil
}
_, err := s.pluginClient.SendMessage(context.Background(), &plugin.Message{
Room: m.Room,
From: fromPtr,
Msg: m.Data,
EphemeralTo: dmToPtr,
})
return err
}
// RegisterCmd registers a command.
// onCmd is called when the command is used.
// If onCmd returns true, the client stops listening for command usages.
func (s *Session) RegisterCmd(name, argsInfo, info string, onCmd func(CmdCall, error)) error {
client, err := s.pluginClient.RegisterCmd(context.Background(), &plugin.CmdDef{
Name: name,
ArgsInfo: argsInfo,
Info: info,
})
if err != nil {
return err
}
go func() {
for {
i, err := client.Recv()
if err != nil {
if isErrEOF(err) {
// set up new stream
client, err = s.pluginClient.RegisterCmd(context.Background(), &plugin.CmdDef{Name: name, ArgsInfo: argsInfo, Info: info})
if err == nil {
continue
}
}
i = &plugin.CmdInvocation{}
}
onCmd(CmdCall{Room: i.Room, From: i.From, Args: i.Args}, err)
}
}()
return nil
}
func isErrEOF(err error) bool {
//return errors.Is(err, io.EOF)
return err.Error() == "rpc error: code = Unavailable desc = error reading from server: EOF"
}