-
Notifications
You must be signed in to change notification settings - Fork 248
/
api.go
471 lines (401 loc) · 15.9 KB
/
api.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package chat
import (
"context"
"errors"
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/images"
"github.com/status-im/status-go/protocol"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/communities"
"github.com/status-im/status-go/protocol/protobuf"
"github.com/status-im/status-go/protocol/requests"
v1protocol "github.com/status-im/status-go/protocol/v1"
)
var (
ErrChatNotFound = errors.New("can't find chat")
ErrCommunityNotFound = errors.New("can't find community")
ErrCommunitiesNotSupported = errors.New("communities are not supported")
ErrChatTypeNotSupported = errors.New("chat type not supported")
)
type ChannelGroupType string
const Personal ChannelGroupType = "personal"
const Community ChannelGroupType = "community"
type PinnedMessages struct {
Cursor string
PinnedMessages []*common.PinnedMessage
}
type Member struct {
// Community Roles
Roles []protobuf.CommunityMember_Roles `json:"roles,omitempty"`
// Admin indicates if the member is an admin of the group chat
Admin bool `json:"admin"`
// Joined indicates if the member has joined the group chat
Joined bool `json:"joined"`
}
type Chat struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Color string `json:"color"`
Emoji string `json:"emoji"`
Active bool `json:"active"`
ChatType protocol.ChatType `json:"chatType"`
Timestamp int64 `json:"timestamp"`
LastClockValue uint64 `json:"lastClockValue"`
DeletedAtClockValue uint64 `json:"deletedAtClockValue"`
ReadMessagesAtClockValue uint64 `json:"readMessagesAtClockValue"`
UnviewedMessagesCount uint `json:"unviewedMessagesCount"`
UnviewedMentionsCount uint `json:"unviewedMentionsCount"`
LastMessage *common.Message `json:"lastMessage"`
Members map[string]Member `json:"members,omitempty"`
MembershipUpdates []v1protocol.MembershipUpdateEvent `json:"membershipUpdateEvents"`
Alias string `json:"alias,omitempty"`
Identicon string `json:"identicon"`
Muted bool `json:"muted"`
InvitationAdmin string `json:"invitationAdmin,omitempty"`
ReceivedInvitationAdmin string `json:"receivedInvitationAdmin,omitempty"`
Profile string `json:"profile,omitempty"`
CommunityID string `json:"communityId"`
CategoryID string `json:"categoryId"`
Position int32 `json:"position,omitempty"`
Permissions *protobuf.CommunityPermissions `json:"permissions,omitempty"`
Joined int64 `json:"joined,omitempty"`
SyncedTo uint32 `json:"syncedTo,omitempty"`
SyncedFrom uint32 `json:"syncedFrom,omitempty"`
FirstMessageTimestamp uint32 `json:"firstMessageTimestamp,omitempty"`
Highlight bool `json:"highlight,omitempty"`
PinnedMessages *PinnedMessages `json:"pinnedMessages,omitempty"`
CanPost bool `json:"canPost"`
Base64Image string `json:"image,omitempty"`
}
type ChannelGroup struct {
Type ChannelGroupType `json:"channelGroupType"`
Name string `json:"name"`
Images map[string]images.IdentityImage `json:"images"`
Color string `json:"color"`
Chats map[string]*Chat `json:"chats"`
Categories map[string]communities.CommunityCategory `json:"categories"`
EnsName string `json:"ensName"`
Admin bool `json:"admin"`
Verified bool `json:"verified"`
Description string `json:"description"`
IntroMessage string `json:"introMessage"`
OutroMessage string `json:"outroMessage"`
Tags []communities.CommunityTag `json:"tags"`
Permissions *protobuf.CommunityPermissions `json:"permissions"`
Members map[string]*protobuf.CommunityMember `json:"members"`
CanManageUsers bool `json:"canManageUsers"`
Muted bool `json:"muted"`
BanList []string `json:"banList"`
Encrypted bool `json:"encrypted"`
}
func NewAPI(service *Service) *API {
return &API{
s: service,
}
}
type API struct {
s *Service
}
func unique(communities []*communities.Community) (result []*communities.Community) {
inResult := make(map[string]bool)
for _, community := range communities {
if _, ok := inResult[community.IDString()]; !ok {
inResult[community.IDString()] = true
result = append(result, community)
}
}
return result
}
func (api *API) GetChats(ctx context.Context) (map[string]ChannelGroup, error) {
joinedCommunities, err := api.s.messenger.JoinedCommunities()
if err != nil {
return nil, err
}
spectatedCommunities, err := api.s.messenger.SpectatedCommunities()
if err != nil {
return nil, err
}
channels := api.s.messenger.Chats()
pubKey := types.EncodeHex(crypto.FromECDSAPub(api.s.messenger.IdentityPublicKey()))
result := make(map[string]ChannelGroup)
result[pubKey] = ChannelGroup{
Type: Personal,
Name: "",
Images: make(map[string]images.IdentityImage),
Color: "",
Chats: make(map[string]*Chat),
Categories: make(map[string]communities.CommunityCategory),
EnsName: "", // Not implemented yet in communities
Admin: true,
Verified: true,
Description: "",
IntroMessage: "",
OutroMessage: "",
Tags: []communities.CommunityTag{},
Permissions: &protobuf.CommunityPermissions{},
Muted: false,
}
for _, chat := range channels {
if !chat.Active || (!chat.OneToOne() && !chat.PrivateGroupChat() && !chat.Public()) || chat.CommunityID != "" {
continue
}
c, err := api.toAPIChat(chat, nil, pubKey)
if err != nil {
return nil, err
}
result[pubKey].Chats[chat.ID] = c
}
for _, community := range unique(append(joinedCommunities, spectatedCommunities...)) {
chGrp := ChannelGroup{
Type: Community,
Name: community.Name(),
Color: community.Color(),
Images: make(map[string]images.IdentityImage),
Chats: make(map[string]*Chat),
Categories: make(map[string]communities.CommunityCategory),
Admin: community.IsAdmin(),
Verified: community.Verified(),
Description: community.DescriptionText(),
IntroMessage: community.IntroMessage(),
OutroMessage: community.OutroMessage(),
Tags: community.Tags(),
Permissions: community.Description().Permissions,
Members: community.Description().Members,
CanManageUsers: community.CanManageUsers(community.MemberIdentity()),
Muted: community.Muted(),
BanList: community.Description().BanList,
Encrypted: community.Encrypted(),
}
for t, i := range community.Images() {
chGrp.Images[t] = images.IdentityImage{Name: t, Payload: i.Payload}
}
for _, cat := range community.Categories() {
chGrp.Categories[cat.CategoryId] = communities.CommunityCategory{
ID: cat.CategoryId,
Name: cat.Name,
Position: int(cat.Position),
}
}
for _, chat := range channels {
if chat.CommunityID == community.IDString() && chat.Active {
c, err := api.toAPIChat(chat, community, pubKey)
if err != nil {
return nil, err
}
chGrp.Chats[c.ID] = c
}
}
result[community.IDString()] = chGrp
}
return result, nil
}
func (api *API) GetChat(ctx context.Context, communityID types.HexBytes, chatID string) (*Chat, error) {
pubKey := types.EncodeHex(crypto.FromECDSAPub(api.s.messenger.IdentityPublicKey()))
messengerChat, community, err := api.getChatAndCommunity(pubKey, communityID, chatID)
if err != nil {
return nil, err
}
if messengerChat == nil {
return nil, ErrChatNotFound
}
result, err := api.toAPIChat(messengerChat, community, pubKey)
if err != nil {
return nil, err
}
return result, nil
}
func (api *API) GetMembers(ctx context.Context, communityID types.HexBytes, chatID string) (map[string]Member, error) {
pubKey := types.EncodeHex(crypto.FromECDSAPub(api.s.messenger.IdentityPublicKey()))
messengerChat, community, err := api.getChatAndCommunity(pubKey, communityID, chatID)
if err != nil {
return nil, err
}
return getChatMembers(messengerChat, community, pubKey)
}
func (api *API) JoinChat(ctx context.Context, communityID types.HexBytes, chatID string) (*Chat, error) {
if len(communityID) != 0 {
return nil, ErrCommunitiesNotSupported
}
response, err := api.s.messenger.CreatePublicChat(&requests.CreatePublicChat{ID: chatID})
if err != nil {
return nil, err
}
pubKey := types.EncodeHex(crypto.FromECDSAPub(api.s.messenger.IdentityPublicKey()))
return api.toAPIChat(response.Chats()[0], nil, pubKey)
}
func (api *API) toAPIChat(protocolChat *protocol.Chat, community *communities.Community, pubKey string) (*Chat, error) {
pinnedMessages, cursor, err := api.s.messenger.PinnedMessageByChatID(protocolChat.ID, "", -1)
if err != nil {
return nil, err
}
chat := &Chat{
ID: strings.TrimPrefix(protocolChat.ID, protocolChat.CommunityID),
Name: protocolChat.Name,
Description: protocolChat.Description,
Color: protocolChat.Color,
Emoji: protocolChat.Emoji,
Active: protocolChat.Active,
ChatType: protocolChat.ChatType,
Timestamp: protocolChat.Timestamp,
LastClockValue: protocolChat.LastClockValue,
DeletedAtClockValue: protocolChat.DeletedAtClockValue,
ReadMessagesAtClockValue: protocolChat.ReadMessagesAtClockValue,
UnviewedMessagesCount: protocolChat.UnviewedMessagesCount,
UnviewedMentionsCount: protocolChat.UnviewedMentionsCount,
LastMessage: protocolChat.LastMessage,
MembershipUpdates: protocolChat.MembershipUpdates,
Alias: protocolChat.Alias,
Identicon: protocolChat.Identicon,
Muted: protocolChat.Muted,
InvitationAdmin: protocolChat.InvitationAdmin,
ReceivedInvitationAdmin: protocolChat.ReceivedInvitationAdmin,
Profile: protocolChat.Profile,
CommunityID: protocolChat.CommunityID,
CategoryID: protocolChat.CategoryID,
Joined: protocolChat.Joined,
SyncedTo: protocolChat.SyncedTo,
SyncedFrom: protocolChat.SyncedFrom,
FirstMessageTimestamp: protocolChat.FirstMessageTimestamp,
Highlight: protocolChat.Highlight,
Base64Image: protocolChat.Base64Image,
}
if protocolChat.OneToOne() {
chat.Name = "" // Emptying since it contains non useful data
}
if len(pinnedMessages) != 0 {
chat.PinnedMessages = &PinnedMessages{
Cursor: cursor,
PinnedMessages: pinnedMessages,
}
}
err = chat.populateCommunityFields(community)
if err != nil {
return nil, err
}
chatMembers, err := getChatMembers(protocolChat, community, pubKey)
if err != nil {
return nil, err
}
chat.Members = chatMembers
return chat, nil
}
func getChatMembers(sourceChat *protocol.Chat, community *communities.Community, userPubKey string) (map[string]Member, error) {
result := make(map[string]Member)
if sourceChat != nil {
if sourceChat.ChatType == protocol.ChatTypePrivateGroupChat && len(sourceChat.Members) > 0 {
for _, m := range sourceChat.Members {
result[m.ID] = Member{
Admin: m.Admin,
Joined: true,
}
}
return result, nil
}
if sourceChat.ChatType == protocol.ChatTypeOneToOne {
result[sourceChat.ID] = Member{
Joined: true,
}
result[userPubKey] = Member{
Joined: true,
}
return result, nil
}
}
if community != nil {
for member, m := range community.Description().Members {
pubKey, err := common.HexToPubkey(member)
if err != nil {
return nil, err
}
result[member] = Member{
Roles: m.Roles,
Joined: community.Joined(),
Admin: community.IsMemberAdmin(pubKey),
}
}
return result, nil
}
return nil, nil
}
func (api *API) getCommunityByID(id string) (*communities.Community, error) {
communityID, err := hexutil.Decode(id)
if err != nil {
return nil, err
}
community, err := api.s.messenger.GetCommunityByID(communityID)
if community == nil && err == nil {
return nil, ErrCommunityNotFound
}
return community, err
}
func (chat *Chat) populateCommunityFields(community *communities.Community) error {
if community == nil {
return nil
}
commChat, exists := community.Chats()[chat.ID]
if !exists {
// Skip unknown community chats. They might be channels that were deleted
return nil
}
canPost, err := community.CanMemberIdentityPost(chat.ID)
if err != nil {
return err
}
chat.CategoryID = commChat.CategoryId
chat.Position = commChat.Position
chat.Permissions = commChat.Permissions
chat.Emoji = commChat.Identity.Emoji
chat.Name = commChat.Identity.DisplayName
chat.Description = commChat.Identity.Description
chat.CanPost = canPost
return nil
}
func (api *API) getChatAndCommunity(pubKey string, communityID types.HexBytes, chatID string) (*protocol.Chat, *communities.Community, error) {
fullChatID := chatID
if string(communityID.Bytes()) == pubKey { // Obtaining chats from personal
communityID = []byte{}
}
if len(communityID) != 0 {
id := string(communityID.Bytes())
if chatID == "" {
community, err := api.getCommunityByID(id)
return nil, community, err
}
fullChatID = id + chatID
}
messengerChat := api.s.messenger.Chat(fullChatID)
if messengerChat == nil {
return nil, nil, ErrChatNotFound
}
var community *communities.Community
if messengerChat.CommunityID != "" {
var err error
community, err = api.getCommunityByID(messengerChat.CommunityID)
if err != nil {
return nil, nil, err
}
}
return messengerChat, community, nil
}
func (api *API) EditChat(ctx context.Context, communityID types.HexBytes, chatID string, name string, color string, image images.CroppedImage) (*Chat, error) {
if len(communityID) != 0 {
return nil, ErrCommunitiesNotSupported
}
chatToEdit := api.s.messenger.Chat(chatID)
if chatToEdit == nil {
return nil, ErrChatNotFound
}
if chatToEdit.ChatType != protocol.ChatTypePrivateGroupChat {
return nil, ErrChatTypeNotSupported
}
response, err := api.s.messenger.EditGroupChat(ctx, chatID, name, color, image)
if err != nil {
return nil, err
}
pubKey := types.EncodeHex(crypto.FromECDSAPub(api.s.messenger.IdentityPublicKey()))
return api.toAPIChat(response.Chats()[0], nil, pubKey)
}