Thumbnail

rani/matterbridge.git

Clone URL: https://git.buni.party/rani/matterbridge.git

Viewing file on branch master

1package bmattermost
2
3import (
4 "net/http"
5 "strings"
6
7 "github.com/matterbridge-org/matterbridge/bridge/config"
8 "github.com/matterbridge-org/matterbridge/bridge/helper"
9 "github.com/matterbridge-org/matterbridge/matterhook"
10 "github.com/matterbridge/matterclient"
11 "github.com/mattermost/mattermost/server/public/model"
12)
13
14func (b *Bmattermost) doConnectWebhookBind() error {
15 switch {
16 case b.GetString("WebhookURL") != "":
17 b.Log.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)")
18 b.mh = matterhook.New(b.GetString("WebhookURL"),
19 matterhook.Config{
20 InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
21 BindAddress: b.GetString("WebhookBindAddress"),
22 })
23 case b.GetString("Token") != "":
24 b.Log.Info("Connecting using token (sending)")
25 err := b.apiLogin()
26 if err != nil {
27 return err
28 }
29 case b.GetString("Login") != "":
30 b.Log.Info("Connecting using login/password (sending)")
31 err := b.apiLogin()
32 if err != nil {
33 return err
34 }
35 default:
36 b.Log.Info("Connecting using webhookbindaddress (receiving)")
37 b.mh = matterhook.New(b.GetString("WebhookURL"),
38 matterhook.Config{
39 InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
40 BindAddress: b.GetString("WebhookBindAddress"),
41 })
42 }
43 return nil
44}
45
46func (b *Bmattermost) doConnectWebhookURL() error {
47 b.Log.Info("Connecting using webhookurl (sending)")
48 b.mh = matterhook.New(b.GetString("WebhookURL"),
49 matterhook.Config{
50 InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
51 DisableServer: true,
52 })
53 if b.GetString("Token") != "" {
54 b.Log.Info("Connecting using token (receiving)")
55 err := b.apiLogin()
56 if err != nil {
57 return err
58 }
59 } else if b.GetString("Login") != "" {
60 b.Log.Info("Connecting using login/password (receiving)")
61 err := b.apiLogin()
62 if err != nil {
63 return err
64 }
65 }
66 return nil
67}
68
69//nolint:wrapcheck
70func (b *Bmattermost) apiLogin() error {
71 password := b.GetString("Password")
72 if b.GetString("Token") != "" {
73 password = "token=" + b.GetString("Token")
74 }
75
76 b.mc = matterclient.New(b.GetString("Login"), password, b.GetString("Team"), b.GetString("Server"), "")
77 if b.GetBool("debug") {
78 b.mc.SetLogLevel("debug")
79 }
80 b.mc.SkipTLSVerify = b.GetBool("SkipTLSVerify")
81 b.mc.SkipVersionCheck = b.GetBool("SkipVersionCheck")
82 b.mc.NoTLS = b.GetBool("NoTLS")
83 b.Log.Infof("Connecting %s (team: %s) on %s", b.GetString("Login"), b.GetString("Team"), b.GetString("Server"))
84
85 if err := b.mc.Login(); err != nil {
86 return err
87 }
88
89 b.Log.Info("Connection succeeded")
90 b.TeamID = b.mc.GetTeamID()
91 return nil
92}
93
94// replaceAction replace the message with the correct action (/me) code
95func (b *Bmattermost) replaceAction(text string) (string, bool) {
96 if strings.HasPrefix(text, "*") && strings.HasSuffix(text, "*") {
97 return strings.ReplaceAll(text, "*", ""), true
98 }
99 return text, false
100}
101
102func (b *Bmattermost) cacheAvatar(msg *config.Message) (string, error) {
103 fi := msg.Extra["file"][0].(config.FileInfo)
104 /* if we have a sha we have successfully uploaded the file to the media server,
105 so we can now cache the sha */
106 if fi.SHA != "" {
107 b.Log.Debugf("Added %s to %s in avatarMap", fi.SHA, msg.UserID)
108 b.avatarMap[msg.UserID] = fi.SHA
109 }
110 return "", nil
111}
112
113// sendWebhook uses the configured WebhookURL to send the message
114func (b *Bmattermost) sendWebhook(msg config.Message) (string, error) {
115 // skip events
116 if msg.Event != "" {
117 return "", nil
118 }
119
120 if b.GetBool("PrefixMessagesWithNick") {
121 msg.Text = msg.Username + msg.Text
122 }
123
124 if msg.Extra != nil {
125 // this sends a message only if we received a config.EVENT_FILE_FAILURE_SIZE
126 for _, rmsg := range helper.HandleExtra(&msg, b.General) {
127 rmsg := rmsg // scopelint
128 iconURL := config.GetIconURL(&rmsg, b.GetString("iconurl"))
129 matterMessage := matterhook.OMessage{
130 IconURL: iconURL,
131 Channel: rmsg.Channel,
132 UserName: rmsg.Username,
133 Text: rmsg.Text,
134 Props: make(map[string]interface{}),
135 }
136 matterMessage.Props["matterbridge_"+b.uuid] = true
137 if err := b.mh.Send(matterMessage); err != nil {
138 b.Log.Errorf("sendWebhook failed: %s ", err)
139 }
140 }
141
142 // webhook doesn't support file uploads, so we add the url manually
143 if len(msg.Extra["file"]) > 0 {
144 for _, f := range msg.Extra["file"] {
145 fi := f.(config.FileInfo)
146 if fi.URL != "" {
147 msg.Text += " " + fi.URL
148 }
149 }
150 }
151 }
152
153 iconURL := config.GetIconURL(&msg, b.GetString("iconurl"))
154 matterMessage := matterhook.OMessage{
155 IconURL: iconURL,
156 Channel: msg.Channel,
157 UserName: msg.Username,
158 Text: msg.Text,
159 Props: make(map[string]interface{}),
160 }
161 if msg.Avatar != "" {
162 matterMessage.IconURL = msg.Avatar
163 }
164 matterMessage.Props["matterbridge_"+b.uuid] = true
165 err := b.mh.Send(matterMessage)
166 if err != nil {
167 b.Log.Info(err)
168 return "", err
169 }
170 return "", nil
171}
172
173// skipMessages returns true if this message should not be handled
174//
175//nolint:gocyclo,cyclop
176func (b *Bmattermost) skipMessage(message *matterclient.Message) bool {
177 // Handle join/leave
178 skipJoinMessageTypes := map[string]struct{}{
179 "system_join_leave": {}, // deprecated for system_add_to_channel
180 "system_leave_channel": {}, // deprecated for system_remove_from_channel
181 "system_join_channel": {},
182 "system_add_to_channel": {},
183 "system_remove_from_channel": {},
184 "system_add_to_team": {},
185 "system_remove_from_team": {},
186 }
187
188 // dirty hack to efficiently check if this element is in the map without writing a contains func
189 // can be replaced with native slice.contains with go 1.21
190 if _, ok := skipJoinMessageTypes[message.Type]; ok {
191 if b.GetBool("nosendjoinpart") {
192 return true
193 }
194
195 channelName := b.getChannelName(message.Post.ChannelId)
196 if channelName == "" {
197 channelName = message.Channel
198 }
199
200 b.Log.Debugf("Sending JOIN_LEAVE event from %s to gateway", b.Account)
201 b.Remote <- config.Message{
202 Username: "system",
203 Text: message.Text,
204 Channel: channelName,
205 Account: b.Account,
206 Event: config.EventJoinLeave,
207 }
208 return true
209 }
210
211 // Handle edited messages
212 if (message.Raw.EventType() == model.WebsocketEventPostEdited) && b.GetBool("EditDisable") {
213 return true
214 }
215
216 // Ignore non-post messages
217 if message.Post == nil {
218 b.Log.Debugf("ignoring nil message.Post: %#v", message)
219 return true
220 }
221
222 // Ignore messages sent from matterbridge
223 if message.Post.Props != nil {
224 if _, ok := message.Post.Props["matterbridge_"+b.uuid].(bool); ok {
225 b.Log.Debug("sent by matterbridge, ignoring")
226 return true
227 }
228 }
229
230 // Ignore messages sent from a user logged in as the bot
231 if b.mc.User.Username == message.Username {
232 b.Log.Debug("message from same user as bot, ignoring")
233 return true
234 }
235
236 // if the message has reactions don't repost it (for now, until we can correlate reaction with message)
237 if message.Post.HasReactions {
238 return true
239 }
240
241 // ignore messages from other teams than ours
242 if message.Raw.GetData()["team_id"].(string) != b.TeamID {
243 b.Log.Debug("message from other team, ignoring")
244 return true
245 }
246
247 // only handle posted, edited or deleted events
248 if !(message.Raw.EventType() == "posted" || message.Raw.EventType() == model.WebsocketEventPostEdited ||
249 message.Raw.EventType() == model.WebsocketEventPostDeleted) {
250 return true
251 }
252 return false
253}
254
255func (b *Bmattermost) getVersion() string {
256 proto := "https"
257
258 if b.GetBool("notls") {
259 proto = "http"
260 }
261
262 resp, err := http.Get(proto + "://" + b.GetString("server"))
263 if err != nil {
264 b.Log.Error("failed getting version")
265 return ""
266 }
267
268 defer resp.Body.Close()
269
270 return resp.Header.Get("X-Version-Id")
271}
272
273func (b *Bmattermost) getChannelID(name string) string {
274 idcheck := strings.Split(name, "ID:")
275 if len(idcheck) > 1 {
276 return idcheck[1]
277 }
278
279 return b.mc.GetChannelID(name, b.TeamID)
280}
281
282func (b *Bmattermost) getChannelName(id string) string {
283 b.channelsMutex.RLock()
284 defer b.channelsMutex.RUnlock()
285
286 for _, c := range b.channelInfoMap {
287 if c.Name == "ID:"+id {
288 // if we have ID: specified in our gateway configuration return this
289 return c.Name
290 }
291 }
292
293 return ""
294}
295