-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
contact.go
172 lines (154 loc) · 5.86 KB
/
contact.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
// mautrix-signal - A Matrix-signal puppeting bridge.
// Copyright (C) 2023 Scott Weber
//
// 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 signalmeow
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strings"
"github.com/google/uuid"
"github.com/rs/zerolog"
"google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-signal/pkg/libsignalgo"
signalpb "go.mau.fi/mautrix-signal/pkg/signalmeow/protobuf"
"go.mau.fi/mautrix-signal/pkg/signalmeow/types"
)
func (cli *Client) StoreContactDetailsAsContact(ctx context.Context, contactDetails *signalpb.ContactDetails, avatar *[]byte) (*types.Recipient, error) {
parsedUUID, err := uuid.Parse(contactDetails.GetAci())
if err != nil {
return nil, err
}
ctx = zerolog.Ctx(ctx).With().
Str("action", "store contact details as contact").
Stringer("uuid", parsedUUID).
Logger().WithContext(ctx)
return cli.Store.RecipientStore.LoadAndUpdateRecipient(ctx, parsedUUID, uuid.Nil, func(recipient *types.Recipient) (bool, error) {
if contactDetails.GetNumber() != "" {
recipient.E164 = contactDetails.GetNumber()
}
recipient.ContactName = contactDetails.GetName()
if profileKeyString := contactDetails.GetProfileKey(); profileKeyString != nil {
profileKey := libsignalgo.ProfileKey(profileKeyString)
recipient.Profile.Key = profileKey
}
if avatar != nil && *avatar != nil && len(*avatar) > 0 {
rawHash := sha256.Sum256(*avatar)
avatarHash := hex.EncodeToString(rawHash[:])
var contentType string
if avatarDetails := contactDetails.GetAvatar(); avatarDetails != nil && !strings.HasSuffix(avatarDetails.GetContentType(), "/*") {
contentType = *avatarDetails.ContentType
} else {
contentType = http.DetectContentType(*avatar)
}
recipient.ContactAvatar = types.ContactAvatar{
Image: *avatar,
ContentType: contentType,
Hash: avatarHash,
}
}
return true, nil
})
}
func (cli *Client) fetchContactThenTryAndUpdateWithProfile(ctx context.Context, aci uuid.UUID) (*types.Recipient, error) {
log := zerolog.Ctx(ctx).With().
Str("action", "fetch contact then try and update with profile").
Stringer("profile_aci", aci).
Logger()
ctx = log.WithContext(ctx)
profile, err := cli.RetrieveProfileByID(ctx, aci)
if err != nil {
logLevel := zerolog.ErrorLevel
if errors.Is(err, errProfileKeyNotFound) {
logLevel = zerolog.DebugLevel
}
log.WithLevel(logLevel).Err(err).Msg("Failed to fetch profile")
// Continue to return contact without profile
}
return cli.Store.RecipientStore.LoadAndUpdateRecipient(ctx, aci, uuid.Nil, func(recipient *types.Recipient) (changed bool, err error) {
if profile != nil {
// Don't bother saving every fetched timestamp to the database, but save if anything else changed
if !recipient.Profile.Equals(profile) || recipient.Profile.FetchedAt.IsZero() {
changed = true
}
recipient.Profile = *profile
}
return
})
}
func (cli *Client) ContactByACI(ctx context.Context, aci uuid.UUID) (*types.Recipient, error) {
return cli.fetchContactThenTryAndUpdateWithProfile(ctx, aci)
}
func (cli *Client) ContactByE164(ctx context.Context, e164 string) (*types.Recipient, error) {
contact, err := cli.Store.RecipientStore.LoadRecipientByE164(ctx, e164)
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("ContactByE164 error loading contact")
return nil, err
}
if contact == nil {
return nil, nil
}
if contact.ACI != uuid.Nil {
contact, err = cli.fetchContactThenTryAndUpdateWithProfile(ctx, contact.ACI)
}
return contact, err
}
// UnmarshalContactDetailsMessages unmarshals a slice of ContactDetails messages from a byte buffer.
func unmarshalContactDetailsMessages(byteStream []byte) ([]*signalpb.ContactDetails, [][]byte, error) {
var contactDetailsList []*signalpb.ContactDetails
var avatarList [][]byte
buf := bytes.NewBuffer(byteStream)
for {
// If no more bytes are left to read, break the loop
if buf.Len() == 0 {
break
}
// Read the length prefix (varint) of the next Protobuf message
msgLen, err := binary.ReadUvarint(buf)
if err != nil {
return nil, nil, fmt.Errorf("Failed to read message length: %v", err)
}
// If no more bytes are left to read, break the loop
if buf.Len() == 0 {
break
}
// Read the Protobuf message using the length obtained
msgBytes := buf.Next(int(msgLen))
// Unmarshal the Protobuf message into a ContactDetails object
contactDetails := &signalpb.ContactDetails{}
if err := proto.Unmarshal(msgBytes, contactDetails); err != nil {
return nil, nil, fmt.Errorf("Failed to unmarshal ContactDetails: %v", err)
}
// Append the ContactDetails object to the result slice
contactDetailsList = append(contactDetailsList, contactDetails)
// If the ContactDetails object has an avatar, read it into a byte slice
if contactDetails.Avatar != nil && contactDetails.Avatar.Length != nil && *contactDetails.Avatar.Length > 0 {
avatarBytes := buf.Next(int(*contactDetails.Avatar.Length))
// TODO why is this making a copy?
avatarBytesCopy := make([]byte, len(avatarBytes))
copy(avatarBytesCopy, avatarBytes)
avatarList = append(avatarList, avatarBytesCopy)
} else {
// If there isn't, append nil so the indicies line up
avatarList = append(avatarList, nil)
}
}
return contactDetailsList, avatarList, nil
}