This repository has been archived by the owner on Jul 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadapter.go
332 lines (285 loc) · 8.14 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Package mattermost implements a mattermost adapter for the joe bot library.
package mattermost
import (
"context"
"fmt"
"net/url"
"strings"
"sync"
"github.com/go-joe/joe/reactions"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/go-joe/joe"
"github.com/mattermost/mattermost-server/model"
)
//
//const bufsz = 10
// BotAdapter implements a joe.Adapter that reads and writes messages to and
// from Mattermost.
type BotAdapter struct {
context context.Context
logger *zap.Logger
user *model.User
team *model.Team
api mattermostAPI
rooms map[string]*model.Channel
roomsMu sync.RWMutex
roomNamesFromIDs map[string]string
}
// Config contains the configuration of a BotAdapter.
type Config struct {
Token string
Team string
ServerURL *url.URL
Name string
Logger *zap.Logger
}
type mattermostAPI interface {
CreatePost(post *model.Post) (*model.Post, *model.Response)
SaveReaction(reaction *model.Reaction) (*model.Reaction, *model.Response)
GetMe(etag string) (*model.User, *model.Response)
EventStream() chan *model.WebSocketEvent
GetChannelByName(channelName, teamId string, etag string) (*model.Channel, *model.Response)
GetChannel(channelId, etag string) (*model.Channel, *model.Response)
GetTeamByName(name, etag string) (*model.Team, *model.Response)
Close() error
}
//Adapter returns a new mattermost Adapter as joe.Module.
func Adapter(token, serverURL, teamName string, opts ...Option) joe.Module {
return joe.ModuleFunc(func(joeConf *joe.Config) error {
conf, err := newConf(token, serverURL, teamName, joeConf, opts)
if err != nil {
return err
}
a, err := NewAdapter(joeConf.Context, conf)
if err != nil {
return err
}
joeConf.SetAdapter(a)
return nil
})
}
func newConf(token, serverURL, teamName string, joeConf *joe.Config, opts []Option) (Config, error) {
u, err := url.Parse(serverURL)
if err != nil {
return Config{}, err
}
conf := Config{Token: token, ServerURL: u, Name: joeConf.Name, Team: teamName}
for _, opt := range opts {
err := opt(&conf)
if err != nil {
return conf, err
}
}
if conf.Logger == nil {
conf.Logger = joeConf.Logger("mattermost")
}
return conf, nil
}
// NewAdapter creates a new *BotAdapter that connects to mattermost. Note that you
// will usually configure the mattermost adapter as joe.Module (i.e. using the
// Adapter function of this package).
func NewAdapter(ctx context.Context, conf Config) (*BotAdapter, error) {
uri := conf.ServerURL.String()
wsURL, _ := url.Parse(uri)
wsURL.Scheme = "wss"
wsClient, err := model.NewWebSocketClient4(wsURL.String(), conf.Token)
if err != nil {
return nil, err
}
client := &mmClient{
Client4: model.NewAPIv4Client(conf.ServerURL.String()),
wsClient: wsClient,
}
client.SetToken(conf.Token)
return newAdapter(ctx, client, conf)
}
func newAdapter(ctx context.Context, client mattermostAPI, conf Config) (*BotAdapter, error) {
user, response := client.GetMe("")
if response.Error != nil {
return nil, errors.Wrapf(response.Error, "error getting self")
}
a := &BotAdapter{
context: ctx,
logger: conf.Logger,
user: user,
api: client,
rooms: make(map[string]*model.Channel),
roomNamesFromIDs: make(map[string]string),
}
if team, response := client.GetTeamByName(conf.Team, ""); response.Error != nil {
a.logger.Error("unable to find team, are you sure the bot is a member?",
zap.String("team", conf.Team),
zap.Error(response.Error),
)
return nil, errors.Wrapf(response.Error, "unable to find team '%s', are you sure the bot is a member?", conf.Team)
} else {
a.team = team
}
if a.logger == nil {
a.logger = zap.NewNop()
}
a.logger.Info("Connected to mattermost API",
zap.String("url", conf.ServerURL.String()),
zap.String("username", a.user.Username),
zap.String("id", a.user.Id),
zap.String("team", a.team.Name),
)
return a, nil
}
// RegisterAt implements the joe.Adapter interface by emitting the mattermost API
// events to the given brain.
func (a *BotAdapter) RegisterAt(brain *joe.Brain) {
go a.handleEvents(brain)
}
func (a *BotAdapter) handleEvents(brain *joe.Brain) {
evts := a.api.EventStream()
waitloop:
for evts != nil {
select {
case evt, ok := <-evts:
if !ok {
evts = nil
continue
}
switch evt.Event {
case model.WEBSOCKET_EVENT_POSTED:
a.handleMessageEvent(evt, brain)
default:
}
case <-a.context.Done():
break waitloop
}
}
}
func (a *BotAdapter) handleMessageEvent(msg *model.WebSocketEvent, brain *joe.Brain) {
post := model.PostFromJson(strings.NewReader(msg.Data["post"].(string)))
if post == nil {
a.logger.Error("Unable to parse post", zap.String("data", msg.Data["post"].(string)))
return
}
// Short-circuit for our own messages
if post.UserId == a.user.Id {
return
}
channel := a.roomsByID(post.ChannelId)
if channel == nil {
return
}
direct := channel.Type == model.CHANNEL_DIRECT
// check if we have a DM, or standard channel post
selfLink := a.userLink(a.user.Username)
if !direct && !strings.Contains(post.Message, selfLink) {
// Message isn't for us, exiting
return
}
text := strings.TrimSpace(strings.TrimPrefix(post.Message, selfLink))
brain.Emit(joe.ReceiveMessageEvent{
Text: text,
Channel: channel.Name,
AuthorID: post.UserId,
Data: post,
ID: post.Id,
})
}
func (a *BotAdapter) roomsByID(rid string) *model.Channel {
a.roomsMu.RLock()
roomName, ok := a.roomNamesFromIDs[rid]
a.roomsMu.RUnlock()
if ok {
return a.roomsByName(roomName)
}
a.roomsMu.Lock()
defer a.roomsMu.Unlock()
ch, resp := a.api.GetChannel(rid, "")
if resp.Error != nil {
a.logger.Error("Received error from GetChannel",
zap.String("rid", rid),
zap.Error(resp.Error),
)
return nil
}
a.rooms[ch.Name] = ch
a.roomNamesFromIDs[rid] = ch.Name
return ch
}
func (a *BotAdapter) roomsByName(name string) *model.Channel {
a.roomsMu.RLock()
room, ok := a.rooms[name]
a.roomsMu.RUnlock()
if ok {
return room
}
a.roomsMu.Lock()
defer a.roomsMu.Unlock()
// It's possible the room was filled in by another thread while waiting
// for write lock.
room, ok = a.rooms[name]
if ok {
return room
}
ch, resp := a.api.GetChannelByName(name, a.team.Id, "")
if resp.Error != nil {
a.logger.Error("Received error from GetChannelByName",
zap.String("name", name),
zap.Error(resp.Error),
)
return nil
}
a.rooms[name] = ch
return ch
}
// Send implements joe.Adapter by sending all received text messages to the
// given mattermost channel name.
func (a *BotAdapter) Send(text, channelName string) error {
room := a.roomsByName(channelName)
if room == nil {
a.logger.Error("Could not send message, channel not found",
zap.String("channelName", channelName),
)
return fmt.Errorf("could not send message, channel '%s' not found", channelName)
}
p := &model.Post{Message: text, ChannelId: room.Id}
a.logger.Info("Sending message to channel",
zap.String("channelName", channelName),
// do not leak actual message content since it might be sensitive
)
_, resp := a.api.CreatePost(p)
if resp.Error != nil {
a.logger.Error("unable to create post", zap.Error(resp.Error))
return errors.Wrap(resp.Error, "unable to create post")
}
return nil
}
// Close disconnects the adapter from the mattermost API.
func (a *BotAdapter) Close() error {
return a.api.Close()
}
// userLink takes a username and returns the formatting necessary to link it.
func (a *BotAdapter) userLink(username string) string {
return fmt.Sprintf("@%s", username)
}
//
//// newMessage creates basic message with an ID, a RoomID, and a Msg
//// Takes channel and text
//func (a *BotAdapter) newMessage(channel *models.Channel, text string) *models.Message {
// return &models.Message{
// ID: a.idgen.ID(),
// RoomID: channel.ID,
// Msg: text,
// User: a.user,
// }
//}
//
func (a *BotAdapter) React(r reactions.Reaction, msg joe.Message) error {
react := &model.Reaction{
PostId: msg.ID,
EmojiName: r.Shortcode,
UserId: a.user.Id,
}
_, resp := a.api.SaveReaction(react)
if resp.Error != nil {
return errors.Wrapf(resp.Error, "Error reacting to message: msg: %s, reaction: %s", msg.ID, r.Shortcode)
}
return nil
}