-
Notifications
You must be signed in to change notification settings - Fork 19
/
matrix.go
448 lines (405 loc) · 15.5 KB
/
matrix.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main
import (
"fmt"
"strconv"
"strings"
"time"
skype "github.com/kelaresg/go-skypeapi"
"github.com/kelaresg/matrix-skype/database"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/patch"
"maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
)
type MatrixHandler struct {
bridge *Bridge
as *appservice.AppService
log maulogger.Logger
cmd *CommandHandler
}
func NewMatrixHandler(bridge *Bridge) *MatrixHandler {
handler := &MatrixHandler{
bridge: bridge,
as: bridge.AS,
log: bridge.Log.Sub("Matrix"),
cmd: NewCommandHandler(bridge),
}
bridge.EventProcessor.On(event.EventMessage, handler.HandleMessage)
bridge.EventProcessor.On(event.EventEncrypted, handler.HandleEncrypted)
bridge.EventProcessor.On(event.EventSticker, handler.HandleMessage)
bridge.EventProcessor.On(event.EventRedaction, handler.HandleRedaction)
bridge.EventProcessor.On(event.StateMember, handler.HandleMembership)
bridge.EventProcessor.On(event.StateRoomName, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateRoomAvatar, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateTopic, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateEncryption, handler.HandleEncryption)
return handler
}
func (mx *MatrixHandler) HandleEncryption(evt *event.Event) {
if evt.Content.AsEncryption().Algorithm != id.AlgorithmMegolmV1 {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if portal != nil && !portal.Encrypted {
mx.log.Debugfln("%s enabled encryption in %s", evt.Sender, evt.RoomID)
portal.Encrypted = true
portal.Update()
}
}
func (mx *MatrixHandler) joinAndCheckMembers(evt *event.Event, intent *appservice.IntentAPI) *mautrix.RespJoinedMembers {
resp, err := intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("JoinRoomByID err, retry in 5 seconds", err)
time.Sleep(5 * time.Second)
resp, err = intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("JoinRoomByID err, retry again in 5 seconds", err)
time.Sleep(5 * time.Second)
resp, err = intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("Failed to join room %s as %s with invite from %s: %v", evt.RoomID, intent.UserID, evt.Sender, err)
return nil
}
}
}
members, err := intent.JoinedMembers(resp.RoomID)
if err != nil {
mx.log.Debugfln("Failed to get members in room %s after accepting invite from %s as %s: %v", resp.RoomID, evt.Sender, intent.UserID, err)
_, _ = intent.LeaveRoom(resp.RoomID)
return nil
}
if len(members.Joined) < 2 {
mx.log.Debugln("Leaving empty room", resp.RoomID, "after accepting invite from", evt.Sender, "as", intent.UserID)
_, _ = intent.LeaveRoom(resp.RoomID)
return nil
}
return members
}
func (mx *MatrixHandler) HandleBotInvite(evt *event.Event) {
intent := mx.as.BotIntent()
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil {
return
}
members := mx.joinAndCheckMembers(evt, intent)
if members == nil {
return
}
if !user.Whitelisted {
_, _ = intent.SendNotice(evt.RoomID, "You are not whitelisted to use this bridge.\n"+
"If you're the owner of this bridge, see the bridge.permissions section in your config file.")
_, _ = intent.LeaveRoom(evt.RoomID)
return
}
if evt.RoomID == mx.bridge.Config.Bridge.Relaybot.ManagementRoom {
_, _ = intent.SendNotice(evt.RoomID, "This is the relaybot management room. Send `!wa help` to get a list of commands.")
mx.log.Debugln("Joined relaybot management room", evt.RoomID, "after invite from", evt.Sender)
return
}
hasPuppets := false
for mxid, _ := range members.Joined {
if mxid == intent.UserID || mxid == evt.Sender {
continue
} else if _, ok := mx.bridge.ParsePuppetMXID(mxid); ok {
hasPuppets = true
continue
}
mx.log.Debugln("Leaving multi-user room", evt.RoomID, "after accepting invite from", evt.Sender)
_, _ = intent.SendNotice(evt.RoomID, "This bridge is user-specific, please don't invite me into rooms with other users.")
_, _ = intent.LeaveRoom(evt.RoomID)
return
}
if !hasPuppets && (len(user.ManagementRoom) == 0 || evt.Content.AsMember().IsDirect) {
user.SetManagementRoom(evt.RoomID)
_, _ = intent.SendNotice(user.ManagementRoom, "This room has been registered as your bridge management/status room. Send `help` to get a list of commands.")
mx.log.Debugln(evt.RoomID, "registered as a management room with", evt.Sender)
}
}
func (mx *MatrixHandler) handlePrivatePortal(roomID id.RoomID, inviter *User, puppet *Puppet, key database.PortalKey) {
portal := mx.bridge.GetPortalByJID(key)
if len(portal.MXID) == 0 {
mx.createPrivatePortalFromInvite(roomID, inviter, puppet, portal)
return
}
err := portal.MainIntent().EnsureInvited(portal.MXID, inviter.MXID)
if err != nil {
mx.log.Warnfln("Failed to invite %s to existing private chat portal %s with %s: %v. Redirecting portal to new room...", inviter.MXID, portal.MXID, puppet.JID, err)
mx.createPrivatePortalFromInvite(roomID, inviter, puppet, portal)
return
}
intent := puppet.DefaultIntent()
_, _ = intent.SendNotice(roomID, fmt.Sprintf("You already have a private chat portal with me at %s", roomID))
mx.log.Debugln("Leaving private chat room", roomID, "as", puppet.MXID, "after accepting invite from", inviter.MXID, "as we already have chat with the user")
_, _ = intent.LeaveRoom(roomID)
}
func (mx *MatrixHandler) createPrivatePortalFromInvite(roomID id.RoomID, inviter *User, puppet *Puppet, portal *Portal) {
portal.MXID = roomID
portal.Topic = "Skype private chat"
_, _ = portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
portal.Name = puppet.Displayname
portal.AvatarURL = puppet.AvatarURL
portal.Avatar = puppet.Avatar
_, _ = portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
_, _ = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
} else {
portal.Name = ""
}
mx.log.Infoln("Created private chat portal in %s after invite from", roomID, inviter.MXID)
intent := puppet.DefaultIntent()
if mx.bridge.Config.Bridge.Encryption.Default {
_, err := intent.InviteUser(roomID, &mautrix.ReqInviteUser{UserID: mx.bridge.Bot.UserID})
if err != nil {
mx.log.Warnln("Failed to invite bridge bot to enable e2be:", err)
}
err = mx.bridge.Bot.EnsureJoined(roomID)
if err != nil {
mx.log.Warnln("Failed to join as bridge bot to enable e2be:", err)
}
_, err = intent.SendStateEvent(roomID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
if err != nil {
mx.log.Warnln("Failed to enable e2be:", err)
}
mx.as.StateStore.SetMembership(roomID, inviter.MXID, event.MembershipJoin)
mx.as.StateStore.SetMembership(roomID, puppet.MXID, event.MembershipJoin)
mx.as.StateStore.SetMembership(roomID, mx.bridge.Bot.UserID, event.MembershipJoin)
portal.Encrypted = true
}
portal.Update()
portal.UpdateBridgeInfo()
_, _ = intent.SendNotice(roomID, "Private chat portal created")
err := portal.FillInitialHistory(inviter)
if err != nil {
mx.log.Errorln("Failed to fill history:", err)
}
inviter.addPortalToCommunity(portal)
inviter.addPuppetToCommunity(puppet)
}
func (mx *MatrixHandler) HandlePuppetInvite(evt *event.Event, inviter *User, puppet *Puppet) {
intent := puppet.DefaultIntent()
members := mx.joinAndCheckMembers(evt, intent)
if members == nil {
return
}
var hasBridgeBot, hasOtherUsers bool
for mxid, _ := range members.Joined {
mx.log.Debugfln("HandlePuppetInvite mxid", mxid)
mx.log.Debugfln("HandlePuppetInvite intent.UserID", intent.UserID)
mx.log.Debugfln("HandlePuppetInvite patch.Parse(intent.UserID)", id.UserID(patch.Parse(string(intent.UserID))))
mx.log.Debugfln("HandlePuppetInvite inviter.MXID", inviter.MXID)
if mxid == id.UserID(patch.Parse(string(intent.UserID))) || mxid == inviter.MXID {
continue
} else if mxid == mx.bridge.Bot.UserID {
hasBridgeBot = true
} else {
hasOtherUsers = true
}
}
if !hasBridgeBot && !hasOtherUsers {
key := database.NewPortalKey(puppet.JID, inviter.JID)
mx.handlePrivatePortal(evt.RoomID, inviter, puppet, key)
} else if !hasBridgeBot {
mx.log.Debugln("Leaving multi-user room", evt.RoomID, "as", puppet.MXID, "after accepting invite from", evt.Sender)
_, _ = intent.SendNotice(evt.RoomID, "Please invite the bridge bot first if you want to bridge to a skype group.")
_, _ = intent.LeaveRoom(evt.RoomID)
} else {
_, _ = intent.SendNotice(evt.RoomID, "This puppet will remain inactive until this room is bridged to a Skype group.")
}
}
func (mx *MatrixHandler) HandleMembership(evt *event.Event) {
mx.log.Debugfln("HandleMembership evt.Sender:", evt.Sender)
mx.log.Debugfln("HandleMembership evt.GetStateKey:", evt.GetStateKey())
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
return
}
if mx.bridge.Crypto != nil {
mx.bridge.Crypto.HandleMemberEvent(evt)
}
content := evt.Content.AsMember()
if content.Membership == event.MembershipInvite && id.UserID(evt.GetStateKey()) == mx.as.BotMXID() {
mx.HandleBotInvite(evt)
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil || user.Conn == nil || user.Conn.LoginInfo == nil || !user.Whitelisted || !user.IsConnected() {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if portal == nil {
puppet := mx.bridge.GetPuppetByMXID(id.UserID(evt.GetStateKey()))
if content.Membership == event.MembershipInvite && puppet != nil {
mx.HandlePuppetInvite(evt, user, puppet)
}
return
}
isSelf := id.UserID(evt.GetStateKey()) == evt.Sender
mx.log.Debugfln("HandleMembership isSelf:", isSelf)
mx.log.Debugfln("HandleMembership id.UserID(evt.GetStateKey()):", id.UserID(evt.GetStateKey()))
mx.log.Debugfln("HandleMembership evt.Sender:", evt.Sender)
if content.Membership == event.MembershipLeave {
if id.UserID(evt.GetStateKey()) == evt.Sender {
if evt.Unsigned.PrevContent != nil {
_ = evt.Unsigned.PrevContent.ParseRaw(evt.Type)
prevContent, ok := evt.Unsigned.PrevContent.Parsed.(*event.MemberEventContent)
if ok {
if portal.IsPrivateChat() || prevContent.Membership == "join" {
portal.HandleMatrixLeave(user)
}
}
}
} else {
mx.log.Debugfln("HandleMembership evt.RoomID", evt.RoomID)
mx.log.Debugfln("HandleMembership id.UserID(evt.GetStateKey())", id.UserID(evt.GetStateKey()))
mx.log.Debugfln("HandleMembership event.MembershipLeave", event.MembershipLeave)
mx.log.Debugfln("HandleMembership user.", event.MembershipLeave)
//mx.as.StateStore.SetMembership(evt.RoomID, id.UserID(evt.GetStateKey()), event.MembershipLeave)
portal.HandleMatrixKick(user, evt)
}
} else if content.Membership == event.MembershipInvite && !isSelf {
portal.HandleMatrixInvite(user, evt)
}
}
func (mx *MatrixHandler) HandleRoomMetadata(evt *event.Event) {
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil || !user.Whitelisted || !user.IsConnected() {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if user.Conn == nil || user.Conn.LoginInfo == nil || portal == nil || portal.IsPrivateChat() {
return
}
//var resp <-chan string
var resp string
var err error
switch content := evt.Content.Parsed.(type) {
case *event.RoomNameEventContent:
resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
"topic": content.Name,
})
case *event.TopicEventContent:
//resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
// "topic": content.Topic,
//})
return
case *event.RoomAvatarEventContent:
data, err := portal.MainIntent().DownloadBytes(content.URL)
if err != nil {
mx.log.Errorfln("Failed to download media in %v", err)
return
}
_, fileId, _, err := user.Conn.UploadFile(portal.Key.JID, &skype.SendMessage{
Jid: portal.Key.JID,
ClientMessageId: "",
Type: "avatar/group",
SendMediaMessage: &skype.SendMediaMessage{
FileName: "avatar",
RawData: data,
FileSize: strconv.Itoa(len(data)), // strconv.FormatUint(fileSize, 10),
Duration: 0,
},
})
if err != nil {
mx.log.Errorln(err)
return
}
resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
"picture": fmt.Sprintf("URL@https://api.asm.skype.com/v1/objects/%s", fileId),
})
}
if err != nil {
mx.log.Errorln(err)
} else {
//out := <-resp
mx.log.Infoln(resp)
}
}
func (mx *MatrixHandler) shouldIgnoreEvent(evt *event.Event) bool {
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
mx.log.Debugfln("shouldIgnoreEvent: isPuppet=%+v, evt.Sender=%+v", isPuppet, evt.Sender)
return true
}
isCustomPuppet, ok := evt.Content.Raw["net.maunium.skype.puppet"].(bool)
if ok && isCustomPuppet && mx.bridge.GetPuppetByCustomMXID(evt.Sender) != nil {
return true
}
user := mx.bridge.GetUserByMXID(evt.Sender)
mx.log.Debugfln("shouldIgnoreEvent: user%+v", *user)
if !user.RelaybotWhitelisted {
mx.log.Debugfln("user.RelaybotWhitelisted true", user.RelaybotWhitelisted)
return true
}
mx.log.Debugfln("shouldIgnoreEvent: false")
return false
}
func (mx *MatrixHandler) HandleEncrypted(evt *event.Event) {
if mx.shouldIgnoreEvent(evt) || mx.bridge.Crypto == nil {
mx.log.Debugfln("HandleEncrypted return 1")
return
}
decrypted, err := mx.bridge.Crypto.Decrypt(evt)
if err != nil {
mx.log.Warnfln("Failed to decrypt %s: %v", evt.ID, err)
return
}
mx.bridge.EventProcessor.Dispatch(decrypted)
}
func (mx *MatrixHandler) HandleMessage(evt *event.Event) {
if mx.shouldIgnoreEvent(evt) {
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
content := evt.Content.AsMessage()
if user.Whitelisted && content.MsgType == event.MsgText {
commandPrefix := mx.bridge.Config.Bridge.CommandPrefix
hasCommandPrefix := strings.HasPrefix(content.Body, commandPrefix)
if hasCommandPrefix {
content.Body = strings.TrimLeft(content.Body[len(commandPrefix):], " ")
}
if hasCommandPrefix || evt.RoomID == user.ManagementRoom {
mx.cmd.Handle(evt.RoomID, user, content.Body)
if strings.HasPrefix(content.Body, "login") == true {
go func() {
time.Sleep(time.Second * 10)
customPuppet := user.bridge.GetPuppetByJID(user.JID)
_, err := customPuppet.customIntent.RedactEvent(evt.RoomID, evt.ID)
if err != nil {
mx.log.Debugfln("HandleMessage RedactEvent: %+v", err)
}
}()
}
return
}
}
mx.log.Debugfln("HandleMessage evt.RoomID1: %+v", evt.RoomID)
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
mx.log.Debugfln("HandleMessage portal: %+v", portal)
if user.Conn != nil && portal != nil && (user.Whitelisted || portal.HasRelaybot()) {
portal.HandleMatrixMessage(user, evt)
}
}
func (mx *MatrixHandler) HandleRedaction(evt *event.Event) {
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
if !user.Whitelisted {
return
}
if !user.HasSession() {
return
} else if !user.IsConnected() {
msg := format.RenderMarkdown(fmt.Sprintf("[%[1]s](https://matrix.to/#/%[1]s): \u26a0 "+
"You are not connected to skype, so your redaction was not bridged. "+
"Use `%[2]s reconnect` to reconnect.", user.MXID, mx.bridge.Config.Bridge.CommandPrefix), true, false)
msg.MsgType = event.MsgNotice
_, _ = mx.bridge.Bot.SendMessageEvent(evt.RoomID, event.EventMessage, msg)
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if user.Conn != nil && user.Conn.LoginInfo != nil && portal != nil {
portal.HandleMatrixRedaction(user, evt)
}
}