-
Notifications
You must be signed in to change notification settings - Fork 1
/
communities.go
558 lines (539 loc) · 20 KB
/
communities.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/vocdoni/vote-frame/communityhub"
"github.com/vocdoni/vote-frame/farcasterapi"
"github.com/vocdoni/vote-frame/mongo"
"go.vocdoni.io/dvote/httprouter"
"go.vocdoni.io/dvote/httprouter/apirest"
"go.vocdoni.io/dvote/log"
)
// syncedCommunities is a map to store the communities that are already synced for a quick check
var syncedCommunities sync.Map
func (v *vocdoniHandler) parseCommunityIDFromURL(ctx *httprouter.HTTPContext) (string, string, uint64, error) {
// get community id from the URL
strID := ctx.URLParam("communityID")
if strID == "" {
return "", "", 0, fmt.Errorf("no community ID provided")
}
// check if the community ID is prefixed and decode it
if _, prefixedID, ok := communityhub.DecodePrefix(strID); ok {
strID = prefixedID
}
id, err := strconv.ParseUint(strID, 10, 64)
if err != nil {
return "", "", 0, fmt.Errorf("invalid community ID: %w", err)
}
// get community chain from the URL
chainAlias := ctx.URLParam("chainAlias")
if chainAlias == "" {
return "", "", 0, fmt.Errorf("no community chain short name provided")
}
communityID, ok := v.comhub.CommunityIDByChainAlias(id, chainAlias)
if !ok {
return "", "", 0, fmt.Errorf("invalid community ID")
}
return communityID, chainAlias, id, nil
}
// CommunityStatus method checks the status of a community based on the census
// type. If the census type is not based on ERC20 or NFT, it returns true and
// 100% progress, because different types of census do not require syncing, they
// depend on external sources. If the census type is based on ERC20 or NFT, it
// iterates over the addresses of the community getting the status of the token
// in census3. It returns false if any token is not synced, and the average
// progress of all tokens.
func (v *vocdoniHandler) CommunityStatus(community *mongo.Community) (bool, int, error) {
// return error if the community is nil
if community == nil {
return false, 0, fmt.Errorf("community not found")
}
// quick check if the community is already synced
if _, ok := syncedCommunities.Load(community.ID); ok {
return true, 100, nil
}
// return true if the community is not based on ERC20 or NFT
if community.Census.Type != mongo.TypeCommunityCensusERC20 &&
community.Census.Type != mongo.TypeCommunityCensusNFT {
return true, 100, nil
}
synced := true
progress := 0
nTokens := len(community.Census.Addresses)
// iterate over the addresses of the community getting status of token in census3
for _, contract := range community.Census.Addresses {
if contract.Blockchain == "ethereum" {
contract.Blockchain = "eth"
}
chainID, ok := v.comhub.Census3ChainID(contract.Blockchain)
if !ok {
log.Warnf("invalid blockchain alias %s for community %s", contract.Blockchain, community.ID)
continue
}
tokenInfo, err := v.census3.Token(contract.Address, chainID, "")
if err != nil {
return false, 0, fmt.Errorf("error getting token info for %s: %w", contract.Address, err)
}
if tokenInfo == nil {
return false, 0, fmt.Errorf("token not found")
}
synced = synced && tokenInfo.Status.Synced
progress += tokenInfo.Status.Progress / nTokens
}
if synced {
syncedCommunities.Store(community.ID, true)
}
return synced, progress, nil
}
// censusChannelOrAddresses gets the census channel or addresses based on the
// type of the census provided from the database. If the census provided is
// based on a channel, it gets the channel information from the farcaster API,
// and returns a nil for the addresses and the channel information. If the
// census provided is based on addresses, it converts the address from the
// database to the API format and returns them, with a nil for the channel
// information.
func (v *vocdoniHandler) censusChannelOrAddresses(ctx context.Context,
dbCensus mongo.CommunityCensus,
) ([]*CensusAddress, *Channel, *User, error) {
var censusChannel *Channel
var censusAddresses []*CensusAddress
var user *User
switch dbCensus.Type {
case mongo.TypeCommunityCensusFollowers:
fid, err := communityhub.DecodeUserChannelFID(dbCensus.Channel)
if err != nil {
return nil, nil, nil, fmt.Errorf("invalid user reference: %w", err)
}
dbUser, err := v.db.User(fid)
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting user: %w", err)
}
if dbUser == nil {
return nil, nil, nil, fmt.Errorf("user not found")
}
user = &User{
FID: dbUser.UserID,
Username: dbUser.Username,
DisplayName: dbUser.Displayname,
Avatar: dbUser.Avatar,
}
case mongo.TypeCommunityCensusChannel:
channel, err := v.fcapi.Channel(ctx, dbCensus.Channel)
if err != nil {
return nil, nil, nil, err
}
if channel == nil {
return nil, nil, nil, farcasterapi.ErrChannelNotFound
}
censusChannel = &Channel{
ID: channel.ID,
Name: channel.Name,
Description: channel.Description,
Followers: channel.Followers,
ImageURL: channel.Image,
URL: channel.URL,
}
case mongo.TypeCommunityCensusERC20, mongo.TypeCommunityCensusNFT:
censusAddresses = []*CensusAddress{}
if len(dbCensus.Addresses) > 0 {
for _, addr := range dbCensus.Addresses {
censusAddresses = append(censusAddresses, &CensusAddress{
Address: addr.Address,
Blockchain: addr.Blockchain,
})
}
}
default:
return nil, nil, nil, fmt.Errorf("invalid census type")
}
return censusAddresses, censusChannel, user, nil
}
func (v *vocdoniHandler) redirectCommunitiesHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
chainAlias := ctx.URLParam("chainAlias")
communityID := ctx.URLParam("communityID")
ctx.SetHeader("Location", "/app/#/communities/"+chainAlias+"/"+communityID)
return ctx.Send([]byte("redirecting to proper /app/#/communities path"), http.StatusMovedPermanently)
}
func (v *vocdoniHandler) listCommunitiesHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
var err error
var dbCommunities []mongo.Community
// check if the query has the byAdminFID or byAdminUsername parameters and
// list communities by admin FID or username respectively, otherwise list
// all communities
byAdminFID := ctx.Request.URL.Query().Get("byAdminFID")
byAdminUsername := ctx.Request.URL.Query().Get("byAdminUsername")
featured := ctx.Request.URL.Query().Get("featured")
// get optional parameters to paginate the results
limit := maxPaginatedItems
strLimit := ctx.Request.URL.Query().Get("limit")
if strLimit != "" {
// if the query has the limit parameter, list the first n communities
n, err := strconv.Atoi(strLimit)
if err != nil {
return ctx.Send([]byte("invalid limit"), http.StatusBadRequest)
}
limit = int64(n)
if limit > maxPaginatedItems {
limit = maxPaginatedItems
} else if limit < minPaginatedItems {
limit = minPaginatedItems
}
}
offset := int64(0)
strOffset := ctx.Request.URL.Query().Get("offset")
if strOffset != "" {
// if the query has the offset parameter, list communities starting from
// the n th community
n, err := strconv.Atoi(strOffset)
if err != nil {
return ctx.Send([]byte("invalid offset"), http.StatusBadRequest)
}
offset = int64(n)
}
var totalCommunities int64
switch {
case byAdminFID != "":
// if the query has the byAdminFID parameter, list communities by admin FID
var adminFID int
adminFID, err = strconv.Atoi(byAdminFID)
if err != nil {
return ctx.Send([]byte("invalid admin FID"), http.StatusBadRequest)
}
if dbCommunities, totalCommunities, err = v.db.ListCommunitiesByAdminFID(uint64(adminFID), limit, offset); err != nil {
return ctx.Send([]byte("error listing communities"), http.StatusInternalServerError)
}
case byAdminUsername != "":
// if the query has the byAdminUsername parameter, list communities by admin username
if dbCommunities, totalCommunities, err = v.db.ListCommunitiesByAdminUsername(byAdminUsername, limit, offset); err != nil {
return ctx.Send([]byte("error listing communities"), http.StatusInternalServerError)
}
case featured == "true":
// if the query has the featured parameter, list featured communities
if dbCommunities, totalCommunities, err = v.db.ListFeaturedCommunities(limit, offset); err != nil {
return ctx.Send([]byte("error listing communities"), http.StatusInternalServerError)
}
default:
// otherwise, list all communities
if dbCommunities, totalCommunities, err = v.db.ListCommunities(limit, offset); err != nil {
return ctx.Send([]byte("error listing communities"), http.StatusInternalServerError)
}
}
if len(dbCommunities) == 0 {
return ctx.Send([]byte("no communities found"), http.StatusNotFound)
}
communities := CommunityList{
Communities: []*Community{},
Pagination: &Pagination{
Limit: limit,
Offset: offset,
Total: totalCommunities,
},
}
for _, c := range dbCommunities {
// get admin profiles from the database
admins := []*User{}
for _, admin := range c.Admins {
user, err := v.db.User(admin)
if err != nil {
if err == farcasterapi.ErrNoDataFound ||
strings.Contains(err.Error(), "user unknown") {
log.Warnw("community admin not found in the database",
"err", err,
"user", admin,
"community", c.ID)
admins = append(admins, &User{FID: admin})
continue
}
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
admins = append(admins, &User{
FID: user.UserID,
Username: user.Username,
DisplayName: user.Displayname,
Avatar: user.Avatar,
})
}
// get census channel, addresses or user reference based on the type
cAddresses, cChannel, userRef, err := v.censusChannelOrAddresses(ctx.Request.Context(), c.Census)
if err != nil && err != farcasterapi.ErrChannelNotFound {
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
// check if the community is ready (soft check, if it fails, continue)
ready, _, err := v.CommunityStatus(&c)
if err != nil {
log.Warnw("error getting community status", "err", err, "community", c.ID)
}
// add community to the list
communities.Communities = append(communities.Communities, &Community{
ID: c.ID,
Name: c.Name,
LogoURL: c.ImageURL,
GroupChatURL: c.GroupChatURL,
Admins: admins,
Notifications: c.Notifications,
CensusType: c.Census.Type,
CensusAddresses: cAddresses,
CensusChannel: cChannel,
UserRef: userRef,
Channels: c.Channels,
Disabled: c.Disabled,
Ready: ready,
CanSendAnnouncements: c.LastAnnouncement.Add(DefaultAnnouncementTimeSpan).Before(time.Now()),
})
}
res, err := json.Marshal(communities)
if err != nil {
return ctx.Send([]byte("error encoding communities"), http.StatusInternalServerError)
}
return ctx.Send(res, http.StatusOK)
}
func (v *vocdoniHandler) communityHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// get community id from the URL
communityID, _, _, err := v.parseCommunityIDFromURL(ctx)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusBadRequest)
}
// get the community from the database by its id
dbCommunity, err := v.db.Community(communityID)
if err != nil {
return ctx.Send([]byte("error getting community"), http.StatusInternalServerError)
}
if dbCommunity == nil {
return ctx.Send([]byte("community not found"), http.StatusNotFound)
}
// get admin profiles for the community
admins := []*User{}
for _, admin := range dbCommunity.Admins {
user, err := v.db.User(admin)
if err != nil {
if err == farcasterapi.ErrNoDataFound {
log.Warnw("community admin not found in the database",
"err", err,
"user", admin,
"community", dbCommunity.ID)
continue
}
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
admins = append(admins, &User{
FID: user.UserID,
Username: user.Username,
DisplayName: user.Displayname,
Avatar: user.Avatar,
})
}
// get census channel or addresses based on the type
cAddresses, cChannel, userRef, err := v.censusChannelOrAddresses(ctx.Request.Context(), dbCommunity.Census)
if err != nil && err != farcasterapi.ErrChannelNotFound {
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
// check if the community is ready (hard check, if it fails return an error)
ready, _, err := v.CommunityStatus(dbCommunity)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
// encode the community
res, err := json.Marshal(Community{
ID: dbCommunity.ID,
Name: dbCommunity.Name,
LogoURL: dbCommunity.ImageURL,
GroupChatURL: dbCommunity.GroupChatURL,
Admins: admins,
Notifications: dbCommunity.Notifications,
CensusType: dbCommunity.Census.Type,
CensusAddresses: cAddresses,
CensusChannel: cChannel,
UserRef: userRef,
Channels: dbCommunity.Channels,
Disabled: dbCommunity.Disabled,
Ready: ready,
CanSendAnnouncements: dbCommunity.LastAnnouncement.Add(DefaultAnnouncementTimeSpan).Before(time.Now()),
})
if err != nil {
return ctx.Send([]byte("error encoding community"), http.StatusInternalServerError)
}
return ctx.Send(res, http.StatusOK)
}
func (v *vocdoniHandler) communityStatusHandler(_ *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// get community id from the URL
communityID, _, _, err := v.parseCommunityIDFromURL(ctx)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusBadRequest)
}
// get the community from the database by its id
dbCommunity, err := v.db.Community(communityID)
if err != nil {
return ctx.Send([]byte("error getting community"), http.StatusInternalServerError)
}
if dbCommunity == nil {
return ctx.Send([]byte("community not found"), http.StatusNotFound)
}
// get the status of the community
ready, progress, err := v.CommunityStatus(dbCommunity)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusInternalServerError)
}
// encode the status
res, err := json.Marshal(Community{
Ready: ready,
Progress: progress,
})
if err != nil {
return ctx.Send([]byte("error encoding community status"), http.StatusInternalServerError)
}
return ctx.Send(res, http.StatusOK)
}
// communitySettingsHandler allows to an admin of a community to update the
// community information.
func (v *vocdoniHandler) communitySettingsHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// extract userFID from auth token
userFID, err := v.db.UserFromAuthToken(msg.AuthToken)
if err != nil {
return fmt.Errorf("cannot get user from auth token: %w", err)
}
// get community id from the URL
communityID, chainAlias, contractID, err := v.parseCommunityIDFromURL(ctx)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusBadRequest)
}
chainID, ok := v.comhub.ChainIDFromAlias(chainAlias)
if !ok {
return ctx.Send([]byte("invalid community chain alias provided"), http.StatusBadRequest)
}
// get the community from the database by its id
dbCommunity, err := v.db.Community(communityID)
if err != nil {
return ctx.Send([]byte("error getting community"), http.StatusInternalServerError)
}
if dbCommunity == nil {
return ctx.Send([]byte("community not found"), http.StatusNotFound)
}
// check if the current user is an admin of the community
var authorized bool
for _, admin := range dbCommunity.Admins {
if admin == userFID {
authorized = true
break
}
}
if !authorized {
return ctx.Send([]byte("you are not an admin of this community"), http.StatusUnauthorized)
}
var typedCommunity Community
if err := json.Unmarshal(msg.Data, &typedCommunity); err != nil {
return ctx.Send([]byte("error decoding community data"), http.StatusBadRequest)
}
// check optional booleans fields from a map to avoid setting them to false
// if they are not provided
var mapCommunity map[string]interface{}
if err := json.Unmarshal(msg.Data, &mapCommunity); err != nil {
return ctx.Send([]byte("error decoding community data"), http.StatusBadRequest)
}
notification := &dbCommunity.Notifications
if _, ok := mapCommunity["notifications"]; ok {
*notification = typedCommunity.Notifications
}
disabled := &dbCommunity.Disabled
if _, ok := mapCommunity["disabled"]; ok {
*disabled = typedCommunity.Disabled
}
// parse the admins and census addresses
admins := []uint64{}
for _, user := range typedCommunity.Admins {
admins = append(admins, user.FID)
}
// parse the census channel or addresses based on the census type
var censusChannel string
censusAddresses := []*communityhub.ContractAddress{}
switch communityhub.CensusType(typedCommunity.CensusType) {
case communityhub.CensusTypeERC20, communityhub.CensusTypeNFT:
for _, addr := range typedCommunity.CensusAddresses {
censusAddresses = append(censusAddresses, &communityhub.ContractAddress{
Blockchain: addr.Blockchain,
Address: common.HexToAddress(addr.Address),
})
}
case communityhub.CensusTypeFollowers:
censusChannel = communityhub.EncodeUserChannelFID(userFID)
case communityhub.CensusTypeChannel:
if typedCommunity.CensusChannel != nil {
censusChannel = typedCommunity.CensusChannel.ID
}
default:
return ctx.Send([]byte("invalid census type"), http.StatusBadRequest)
}
// update the community image
if typedCommunity.LogoURL != "" && typedCommunity.LogoURL != dbCommunity.ImageURL {
// check if the current avatar is an internal image
avatarID, isInternalAvatar := avatarIDfromURL(dbCommunity.ImageURL)
// if is internal delete the current avatar from the database after
// uploading the new one
if isInternalAvatar {
if err := v.db.RemoveAvatar(avatarID); err != nil {
log.Warnw("error deleting avatar", "err", err, "avatarID", avatarID)
}
}
// upload the new avatar if it is base64 encoded
if isBase64Image(typedCommunity.LogoURL) {
// empty the avatarID to generate a new one based on the data
avatarURL, err := v.uploadAvatar("", userFID, communityID, typedCommunity.LogoURL)
if err != nil {
return fmt.Errorf("cannot upload avatar: %w", err)
}
// set the new avatar URL
typedCommunity.LogoURL = avatarURL
}
}
log.Infow("updating community", "community", communityID)
// update the community in the community hub
if err := v.comhub.UpdateCommunity(&communityhub.HubCommunity{
CommunityID: communityID,
ContractID: contractID,
ChainID: chainID,
Name: typedCommunity.Name,
ImageURL: typedCommunity.LogoURL,
GroupChatURL: typedCommunity.GroupChatURL,
CensusType: communityhub.CensusType(typedCommunity.CensusType),
CensusAddesses: censusAddresses,
CensusChannel: censusChannel,
Channels: typedCommunity.Channels,
Admins: admins,
Notifications: notification,
Disabled: disabled,
}); err != nil {
return fmt.Errorf("error updating community: %w", err)
}
// remove the community from the synced communities map, so it will be checked again
syncedCommunities.Delete(communityID)
// set the strategy to zero to force the community strategy to be updated
if err := v.db.SetCommunityCensusStrategy(communityID, 0); err != nil {
return fmt.Errorf("error setting community census strategy to 0: %w", err)
}
return ctx.Send([]byte("ok"), http.StatusOK)
}
func (v *vocdoniHandler) communityDelegationsHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
// get community id from the URL
communityID, _, _, err := v.parseCommunityIDFromURL(ctx)
if err != nil {
return ctx.Send([]byte(err.Error()), http.StatusBadRequest)
}
delegations, err := v.db.DelegationsByCommunity(communityID, false, true)
if err != nil {
return ctx.Send([]byte("error getting delegations"), http.StatusInternalServerError)
}
if len(delegations) == 0 {
return ctx.Send(nil, http.StatusNoContent)
}
res, err := json.Marshal(delegations)
if err != nil {
return ctx.Send([]byte("error encoding delegations"), http.StatusInternalServerError)
}
return ctx.Send(res, http.StatusOK)
}