-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
puppet.go
383 lines (337 loc) · 10.1 KB
/
puppet.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
// mautrix-imessage - A Matrix-iMessage puppeting bridge.
// Copyright (C) 2021 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/gabriel-vasile/mimetype"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/bridge"
"maunium.net/go/mautrix/bridge/bridgeconfig"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-imessage/database"
"go.mau.fi/mautrix-imessage/imessage"
"go.mau.fi/mautrix-imessage/ipc"
)
var userIDRegex *regexp.Regexp
func (br *IMBridge) ParsePuppetMXID(mxid id.UserID) (string, bool) {
if userIDRegex == nil {
userIDRegex = br.Config.MakeUserIDRegex("(.+)")
}
match := userIDRegex.FindStringSubmatch(string(mxid))
if match == nil || len(match) != 2 {
return "", false
}
localID := match[1]
if number, err := strconv.Atoi(localID); err == nil {
return fmt.Sprintf("+%d", number), true
} else if localpart, err := id.DecodeUserLocalpart(localID); err == nil {
return localpart, true
} else {
br.Log.Debugfln("Failed to decode user localpart '%s': %v", localID, err)
return "", false
}
}
func (br *IMBridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
localID, ok := br.ParsePuppetMXID(mxid)
if !ok {
return nil
}
return br.GetPuppetByLocalID(localID)
}
func (br *IMBridge) GetPuppetByGUID(guid string) *Puppet {
return br.GetPuppetByLocalID(imessage.ParseIdentifier(guid).LocalID)
}
func (br *IMBridge) GetPuppetByLocalID(id string) *Puppet {
br.puppetsLock.Lock()
defer br.puppetsLock.Unlock()
puppet, ok := br.puppets[id]
if !ok {
dbPuppet := br.DB.Puppet.Get(id)
if dbPuppet == nil {
dbPuppet = br.DB.Puppet.New()
dbPuppet.ID = id
dbPuppet.Insert()
}
puppet = br.NewPuppet(dbPuppet)
br.puppets[puppet.ID] = puppet
}
return puppet
}
func (br *IMBridge) GetAllPuppets() []*Puppet {
return br.dbPuppetsToPuppets(br.DB.Puppet.GetAll())
}
func (br *IMBridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
br.puppetsLock.Lock()
defer br.puppetsLock.Unlock()
output := make([]*Puppet, len(dbPuppets))
for index, dbPuppet := range dbPuppets {
if dbPuppet == nil {
continue
}
puppet, ok := br.puppets[dbPuppet.ID]
if !ok {
puppet = br.NewPuppet(dbPuppet)
br.puppets[dbPuppet.ID] = puppet
}
output[index] = puppet
}
return output
}
func (br *IMBridge) FormatPuppetMXID(guid string) id.UserID {
return id.NewUserID(
br.Config.Bridge.FormatUsername(guid),
br.Config.Homeserver.Domain)
}
func (br *IMBridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
mxid := br.FormatPuppetMXID(dbPuppet.ID)
return &Puppet{
Puppet: dbPuppet,
bridge: br,
log: br.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.ID)),
MXID: mxid,
Intent: br.AS.Intent(mxid),
}
}
type Puppet struct {
*database.Puppet
bridge *IMBridge
log log.Logger
typingIn id.RoomID
typingAt int64
MXID id.UserID
Intent *appservice.IntentAPI
}
var _ bridge.Ghost = (*Puppet)(nil)
var _ bridge.GhostWithProfile = (*Puppet)(nil)
func (puppet *Puppet) GetDisplayname() string {
return puppet.Displayname
}
func (puppet *Puppet) GetAvatarURL() id.ContentURI {
return puppet.AvatarURL
}
func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
return nil
}
func (puppet *Puppet) SwitchCustomMXID(accessToken string, userID id.UserID) error {
panic("Puppet.SwitchCustomMXID is not implemented")
}
func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
return puppet.Intent
}
func (puppet *Puppet) GetMXID() id.UserID {
return puppet.MXID
}
func (puppet *Puppet) UpdateName(contact *imessage.Contact) bool {
if puppet.NameOverridden {
// Never replace custom names with contact list names
return false
} else if puppet.Displayname != "" && !contact.HasName() {
// Don't update displayname if there's no contact list name available
return false
}
return puppet.UpdateNameDirect(contact.Name())
}
func (puppet *Puppet) UpdateNameDirect(name string) bool {
if len(name) == 0 {
// TODO format if phone numbers
name = puppet.ID
}
newName := puppet.bridge.Config.Bridge.FormatDisplayname(name)
if puppet.Displayname != newName {
err := puppet.Intent.SetDisplayName(newName)
if err == nil {
puppet.Displayname = newName
go puppet.updatePortalName()
return true
} else {
puppet.log.Warnln("Failed to set display name:", err)
}
}
return false
}
func (puppet *Puppet) UpdateAvatar(contact *imessage.Contact) bool {
if contact == nil {
return false
}
return puppet.UpdateAvatarFromBytes(contact.Avatar)
}
func (puppet *Puppet) UpdateAvatarFromBytes(avatar []byte) bool {
if avatar == nil {
return false
}
avatarHash := sha256.Sum256(avatar)
if puppet.AvatarHash == nil || *puppet.AvatarHash != avatarHash {
puppet.AvatarHash = &avatarHash
mimeTypeData := mimetype.Detect(avatar)
resp, err := puppet.Intent.UploadBytesWithName(avatar, mimeTypeData.String(), "avatar"+mimeTypeData.Extension())
if err != nil {
puppet.AvatarHash = nil
puppet.log.Warnln("Failed to upload avatar:", err)
return false
}
return puppet.UpdateAvatarFromMXC(resp.ContentURI)
}
return false
}
func (puppet *Puppet) UpdateAvatarFromMXC(mxc id.ContentURI) bool {
puppet.AvatarURL = mxc
err := puppet.Intent.SetAvatarURL(puppet.AvatarURL)
if err != nil {
puppet.AvatarHash = nil
puppet.log.Warnln("Failed to set avatar:", err)
return false
}
go puppet.updatePortalAvatar()
return true
}
func applyMeta(portal *Portal, meta func(portal *Portal)) {
if portal == nil {
return
}
portal.roomCreateLock.Lock()
defer portal.roomCreateLock.Unlock()
meta(portal)
}
func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
imID := imessage.Identifier{Service: "iMessage", LocalID: puppet.ID}.String()
applyMeta(puppet.bridge.GetPortalByGUID(imID), meta)
smsID := imessage.Identifier{Service: "SMS", LocalID: puppet.ID}.String()
applyMeta(puppet.bridge.GetPortalByGUID(smsID), meta)
}
func (puppet *Puppet) updatePortalAvatar() {
puppet.updatePortalMeta(func(portal *Portal) {
if len(portal.MXID) > 0 && portal.shouldSetDMRoomMetadata() {
_, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
if err != nil {
portal.log.Warnln("Failed to set avatar:", err)
}
}
portal.AvatarURL = puppet.AvatarURL
portal.AvatarHash = puppet.AvatarHash
portal.Update(nil)
portal.UpdateBridgeInfo()
})
}
func (puppet *Puppet) updatePortalName() {
puppet.updatePortalMeta(func(portal *Portal) {
if len(portal.MXID) > 0 && portal.shouldSetDMRoomMetadata() {
_, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
if err != nil {
portal.log.Warnln("Failed to set name:", err)
}
}
portal.Name = puppet.Displayname
portal.Update(nil)
portal.UpdateBridgeInfo()
})
}
func (puppet *Puppet) Sync() {
err := puppet.Intent.EnsureRegistered()
if err != nil {
puppet.log.Errorln("Failed to ensure registered:", err)
}
contact, err := puppet.bridge.IM.GetContactInfo(puppet.ID)
if err != nil && !errors.Is(err, ipc.ErrUnknownCommand) {
puppet.log.Errorln("Failed to get contact info:", err)
}
puppet.SyncWithContact(contact)
}
var avatarDownloadClient = http.Client{
Timeout: 30 * time.Second,
}
func (puppet *Puppet) backgroundAvatarUpdate(url string) {
puppet.log.Debugfln("Updating avatar from remote URL in background")
var resp *http.Response
var body []byte
var err error
defer func() {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}()
if resp, err = avatarDownloadClient.Get(url); err != nil {
puppet.log.Warnfln("Failed to request override avatar from %s: %v", url, err)
} else if body, err = io.ReadAll(resp.Body); err != nil {
puppet.log.Warnfln("Failed to read override avatar from %s: %v", url, err)
} else {
puppet.UpdateAvatarFromBytes(body)
}
}
func (puppet *Puppet) syncAvatarWithRawURL(rawURL string) {
mxc, err := id.ParseContentURI(rawURL)
if err != nil {
go puppet.backgroundAvatarUpdate(rawURL)
return
}
puppet.UpdateAvatarFromMXC(mxc)
}
func (puppet *Puppet) SyncWithProfileOverride(override ProfileOverride) {
if len(override.Displayname) > 0 {
puppet.UpdateNameDirect(override.Displayname)
}
if len(override.PhotoURL) > 0 {
puppet.syncAvatarWithRawURL(override.PhotoURL)
}
}
func (puppet *Puppet) UpdateContactInfo() bool {
if puppet.bridge.Config.Homeserver.Software != bridgeconfig.SoftwareHungry {
return false
}
if !puppet.ContactInfoSet {
contactInfo := map[string]any{
"com.beeper.bridge.remote_id": puppet.ID,
}
if strings.ContainsRune(puppet.ID, '@') {
contactInfo["com.beeper.bridge.identifiers"] = []string{fmt.Sprintf("mailto:%s", puppet.ID)}
} else {
contactInfo["com.beeper.bridge.identifiers"] = []string{fmt.Sprintf("tel:%s", puppet.ID)}
}
if puppet.bridge.Config.IMessage.Platform == "android" {
contactInfo["com.beeper.bridge.service"] = "androidsms"
contactInfo["com.beeper.bridge.network"] = "androidsms"
} else {
contactInfo["com.beeper.bridge.service"] = "imessagecloud"
contactInfo["com.beeper.bridge.network"] = "imessage"
}
err := puppet.DefaultIntent().BeeperUpdateProfile(contactInfo)
if err != nil {
puppet.log.Warnln("Failed to store custom contact info in profile:", err)
return false
} else {
puppet.ContactInfoSet = true
return true
}
}
return false
}
func (puppet *Puppet) SyncWithContact(contact *imessage.Contact) {
update := false
update = puppet.UpdateName(contact) || update
update = puppet.UpdateAvatar(contact) || update
update = puppet.UpdateContactInfo() || update
if update {
puppet.Update()
}
}