-
Notifications
You must be signed in to change notification settings - Fork 106
/
Users.ts
1337 lines (1219 loc) · 42.9 KB
/
Users.ts
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { pick, isEqual } from 'lodash'
import { Base, BaseConstructorArgs, Services } from './base'
import { Nullable, UserMetadata, Utils } from '../utils'
import {
CreatorNode,
getSpIDForEndpoint,
setSpIDForEndpoint
} from '../services/creatorNode'
import type { ServiceProvider } from './ServiceProvider'
import { EntityManagerClient } from '../services/dataContracts/EntityManagerClient'
// User metadata fields that are required on the metadata object and can have
// null or non-null values
const USER_PROPS = [
'is_verified',
'is_deactivated',
'name',
'handle',
'profile_picture',
'profile_picture_sizes',
'cover_photo',
'cover_photo_sizes',
'bio',
'location',
'creator_node_endpoint',
'associated_wallets',
'associated_sol_wallets',
'collectibles',
'playlist_library',
'events'
] as Array<keyof UserMetadata>
// User metadata fields that are required on the metadata object and only can have
// non-null values
const USER_REQUIRED_PROPS = ['name', 'handle']
// Constants for user metadata fields
export class Users extends Base {
ServiceProvider: ServiceProvider
preferHigherPatchForPrimary: boolean
preferHigherPatchForSecondaries: boolean
constructor(
serviceProvider: ServiceProvider,
preferHigherPatchForPrimary: boolean,
preferHigherPatchForSecondaries: boolean,
...args: BaseConstructorArgs
) {
super(...args)
this.ServiceProvider = serviceProvider
this.preferHigherPatchForPrimary = preferHigherPatchForPrimary
this.preferHigherPatchForSecondaries = preferHigherPatchForSecondaries
this.getUsers = this.getUsers.bind(this)
this.getMutualFollowers = this.getMutualFollowers.bind(this)
this.getFollowersForUser = this.getFollowersForUser.bind(this)
this.getFolloweesForUser = this.getFolloweesForUser.bind(this)
this.getUserRepostFeed = this.getUserRepostFeed.bind(this)
this.getSocialFeed = this.getSocialFeed.bind(this)
this.getTopCreatorsByGenres = this.getTopCreatorsByGenres.bind(this)
this.uploadProfileImages = this.uploadProfileImages.bind(this)
this.createEntityManagerUser = this.createEntityManagerUser.bind(this)
this.addUser = this.addUser.bind(this)
this.updateUser = this.updateUser.bind(this)
this.updateCreator = this.updateCreator.bind(this)
this.updateIsVerified = this.updateIsVerified.bind(this)
this.addUserFollow = this.addUserFollow.bind(this)
this.deleteUserFollow = this.deleteUserFollow.bind(this)
// For adding replica set to users on sign up
this.assignReplicaSet = this.assignReplicaSet.bind(this)
this.getClockValuesFromReplicaSet =
this.getClockValuesFromReplicaSet.bind(this)
this._waitForCreatorNodeEndpointIndexing =
this._waitForCreatorNodeEndpointIndexing.bind(this)
this._addUserOperations = this._addUserOperations.bind(this)
this._updateUserOperations = this._updateUserOperations.bind(this)
this._validateUserMetadata = this._validateUserMetadata.bind(this)
this.cleanUserMetadata = this.cleanUserMetadata.bind(this)
// For adding a creator_node_endpoint for a user if null
this.assignReplicaSetIfNecessary =
this.assignReplicaSetIfNecessary.bind(this)
}
/* ----------- GETTERS ---------- */
/**
* get users with all relevant user data
* can be filtered by providing an integer array of ids
* @returns Array of User metadata Objects
* additional metadata fields on user objects:
* {Integer} track_count - track count for given user
* {Integer} playlist_count - playlist count for given user
* {Integer} album_count - album count for given user
* {Integer} follower_count - follower count for given user
* {Integer} followee_count - followee count for given user
* {Integer} repost_count - repost count for given user
* {Integer} track_blocknumber - blocknumber of latest track for user
* {Boolean} does_current_user_follow - does current user follow given user
* {Array} followee_follows - followees of current user that follow given user
* @example
* await getUsers()
* await getUsers(100, 0, [3,2,6]) - Invalid user ids will not be accepted
*/
async getUsers(
limit = 100,
offset = 0,
idsArray: Nullable<number[]> = null,
walletAddress: Nullable<string> = null,
handle: Nullable<string> = null,
minBlockNumber: Nullable<number> = null
) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
return await this.discoveryProvider.getUsers(
limit,
offset,
idsArray,
walletAddress,
handle,
minBlockNumber
)
}
/**
* get intersection of users that follow followeeUserId and users that are followed by followerUserId
* @param followeeUserId user that is followed
* @example
* getMutualFollowers(100, 0, 1, 1) - IDs must be valid
*/
async getMutualFollowers(limit = 100, offset = 0, followeeUserId: number) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
const followerUserId = this.userStateManager.getCurrentUserId()
if (followerUserId) {
return await this.discoveryProvider.getFollowIntersectionUsers(
limit,
offset,
followeeUserId,
followerUserId
)
}
return []
}
/**
* get users that follow followeeUserId, sorted by follower count descending
*/
async getFollowersForUser(limit = 100, offset = 0, followeeUserId: string) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
return await this.discoveryProvider.getFollowersForUser(
limit,
offset,
followeeUserId
)
}
/**
* get users that are followed by followerUserId, sorted by follower count descending
*/
async getFolloweesForUser(limit = 100, offset = 0, followerUserId: string) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
return await this.discoveryProvider.getFolloweesForUser(
limit,
offset,
followerUserId
)
}
/**
* Return repost feed for requested user
* @param userId - requested user id
* @param limit - max # of items to return (for pagination)
* @param offset - offset into list to return from (for pagination)
* @returns Array of track and playlist metadata objects
* additional metadata fields on track and playlist objects:
* {String} activity_timestamp - timestamp of requested user's repost for given track or playlist,
* used for sorting feed
* {Integer} repost_count - repost count of given track/playlist
* {Integer} save_count - save count of given track/playlist
* {Boolean} has_current_user_reposted - has current user reposted given track/playlist
* {Array} followee_reposts - followees of current user that have reposted given track/playlist
*/
async getUserRepostFeed(
userId: number,
limit = 100,
offset = 0,
withUsers = false
) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
return await this.discoveryProvider.getUserRepostFeed(
userId,
limit,
offset,
withUsers
)
}
/**
* Return social feed for current user
* @param limit - max # of items to return
* @param filter - filter by "all", "original", or "repost"
* @param offset - offset into list to return from (for pagination)
* @returns Array of track and playlist metadata objects
* additional metadata fields on track and playlist objects:
* {String} activity_timestamp - timestamp of requested user's repost for given track or playlist,
* used for sorting feed
* {Integer} repost_count - repost count of given track/playlist
* {Integer} save_count - save count of given track/playlist
* {Boolean} has_current_user_reposted - has current user reposted given track/playlist
* {Array} followee_reposts - followees of current user that have reposted given track/playlist
*/
async getSocialFeed(
filter: string,
limit = 100,
offset = 0,
withUsers = false,
tracksOnly = false
) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
const owner = this.userStateManager.getCurrentUser()
if (owner) {
return await this.discoveryProvider.getSocialFeed(
filter,
limit,
offset,
withUsers,
tracksOnly
)
}
return []
}
/**
* Returns the top users for the specified genres
* @param genres - filter by genres ie. "Rock", "Alternative"
* @param limit - max # of items to return
* @param offset - offset into list to return from (for pagination)
* @param withUsers - If the userIds should be returned or the full user metadata
* @returns Array of user objects if with_users set, else array of userId
*/
async getTopCreatorsByGenres(
genres: string[],
limit = 30,
offset = 0,
withUsers = false
) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
return await this.discoveryProvider.getTopCreatorsByGenres(
genres,
limit,
offset,
withUsers
)
}
/* ------- SETTERS ------- */
/**
* Assigns a replica set to the user's metadata and adds new metadata to chain.
* This creates a record for that user on the connected creator node.
*/
async assignReplicaSet({ userId }: { userId: number }) {
this.REQUIRES(Services.CREATOR_NODE)
const phases = {
CLEAN_AND_VALIDATE_METADATA: 'CLEAN_AND_VALIDATE_METADATA',
AUTOSELECT_CONTENT_NODES: 'AUTOSELECT_CONTENT_NODES',
SYNC_ACROSS_CONTENT_NODES: 'SYNC_ACROSS_CONTENT_NODES',
SET_PRIMARY: 'SET_PRIMARY',
UPLOAD_METADATA_AND_UPDATE_ON_CHAIN: 'UPLOAD_METADATA_AND_UPDATE_ON_CHAIN'
}
let phase = ''
const logPrefix = `[User:assignReplicaSet()] [userId: ${userId}]`
const fnStartMs = Date.now()
let startMs = fnStartMs
const user = this.userStateManager.getCurrentUser()
// Failed the addUser() step
if (!user) {
throw new Error('No current user')
}
// No-op if the user already has a replica set assigned under creator_node_endpoint
if (user.creator_node_endpoint && user.creator_node_endpoint.length > 0)
return
// The new metadata object that will contain the replica set
const newMetadata = { ...user }
try {
// Create starter metadata and validate
phase = phases.CLEAN_AND_VALIDATE_METADATA
// Autoselect a new replica set and update the metadata object with new content node endpoints
phase = phases.AUTOSELECT_CONTENT_NODES
const response = await this.ServiceProvider.autoSelectCreatorNodes({
performSyncCheck: false,
preferHigherPatchForPrimary: this.preferHigherPatchForPrimary,
preferHigherPatchForSecondaries: this.preferHigherPatchForSecondaries
})
console.log(
`${logPrefix} [phase: ${phase}] ServiceProvider.autoSelectCreatorNodes() completed in ${
Date.now() - startMs
}ms`
)
startMs = Date.now()
// Ideally, 1 primary and n-1 secondaries are chosen. The best-worst case scenario is that at least 1 primary
// is chosen. If a primary was not selected (which also implies that secondaries were not chosen), throw
// an error.
const { primary, secondaries } = response
if (!primary) {
throw new Error('Could not select a primary.')
}
const newContentNodeEndpoints = CreatorNode.buildEndpoint(
primary,
secondaries
)
newMetadata.creator_node_endpoint = newContentNodeEndpoints
// Update the new primary to the auto-selected primary
phase = phases.SET_PRIMARY
await this.creatorNode.setEndpoint(primary)
// Update metadata in CN and on chain of newly assigned replica set
phase = phases.UPLOAD_METADATA_AND_UPDATE_ON_CHAIN
await this.updateAndUploadMetadata({
newMetadata,
userId
})
console.log(
`${logPrefix} [phase: ${phase}] updateAndUploadMetadata() completed in ${
Date.now() - startMs
}ms`
)
console.log(`${logPrefix} completed in ${Date.now() - fnStartMs}ms`)
} catch (e) {
const errorMsg = `assignReplicaSet() Error -- Phase ${phase} in ${
Date.now() - fnStartMs
}ms: ${e}`
throw new Error(errorMsg)
}
return newMetadata
}
/**
* Util to upload profile picture and cover photo images and update
* a metadata object. This method inherently calls triggerSecondarySyncs().
* @param profilePictureFile an optional file to upload as the profile picture
* @param coverPhotoFile an optional file to upload as the cover photo
* @param metadata to update
* @returns the passed in metadata object with profile_picture_sizes and cover_photo_sizes fields added
*/
async uploadProfileImages(
profilePictureFile: File,
coverPhotoFile: File,
metadata: UserMetadata,
useEntityManager: boolean
) {
let didMetadataUpdate = false
if (profilePictureFile) {
const resp = await this.creatorNode.uploadImage(profilePictureFile, true)
metadata.profile_picture_sizes = resp.dirCID
didMetadataUpdate = true
}
if (coverPhotoFile) {
const resp = await this.creatorNode.uploadImage(coverPhotoFile, false)
metadata.cover_photo_sizes = resp.dirCID
didMetadataUpdate = true
}
if (didMetadataUpdate) {
await this.updateAndUploadMetadata({
newMetadata: metadata,
userId: metadata.user_id,
useEntityManager
})
}
return metadata
}
async createEntityManagerUser({ metadata }: { metadata: UserMetadata }) {
this.REQUIRES(Services.CREATOR_NODE)
const phases = {
CLEAN_AND_VALIDATE_METADATA: 'CLEAN_AND_VALIDATE_METADATA',
AUTOSELECT_CONTENT_NODES: 'AUTOSELECT_CONTENT_NODES',
SYNC_ACROSS_CONTENT_NODES: 'SYNC_ACROSS_CONTENT_NODES',
SET_PRIMARY: 'SET_PRIMARY',
UPLOAD_METADATA_AND_UPDATE_ON_CHAIN: 'UPLOAD_METADATA_AND_UPDATE_ON_CHAIN'
}
let phase = ''
const logPrefix = `[User:assignReplicaSet()]`
const fnStartMs = Date.now()
let startMs = fnStartMs
// The new metadata object that will contain the replica set
try {
// Create starter metadata and validate
phase = phases.CLEAN_AND_VALIDATE_METADATA
// Autoselect a new replica set and update the metadata object with new content node endpoints
phase = phases.AUTOSELECT_CONTENT_NODES
const response = await this.ServiceProvider.autoSelectCreatorNodes({
performSyncCheck: false,
preferHigherPatchForPrimary: this.preferHigherPatchForPrimary,
preferHigherPatchForSecondaries: this.preferHigherPatchForSecondaries
})
console.log(
`${logPrefix} [phase: ${phase}] ServiceProvider.autoSelectCreatorNodes() completed in ${
Date.now() - startMs
}ms`
)
startMs = Date.now()
// Ideally, 1 primary and n-1 secondaries are chosen. The best-worst case scenario is that at least 1 primary
// is chosen. If a primary was not selected (which also implies that secondaries were not chosen), throw
// an error.
const { primary, secondaries } = response
if (!primary) {
throw new Error('Could not select a primary.')
}
const spIds = await Promise.all(
[primary, ...secondaries].map(
async (endpoint) => await this._retrieveSpIDFromEndpoint(endpoint)
)
)
// Create the user with entityMananer
const userId = Users.generateUserId()
const manageEntityResponse =
await this.contracts.EntityManagerClient!.manageEntity(
userId,
EntityManagerClient.EntityType.USER,
userId,
EntityManagerClient.Action.CREATE,
spIds.join(',')
)
await this.waitForReplicaSetDiscoveryIndexing(
userId,
spIds,
manageEntityResponse.txReceipt.blockNumber
)
// Upload metadata and call update user with the metadata
const newMetadata = this.cleanUserMetadata({ ...metadata })
this._validateUserMetadata(newMetadata)
const newContentNodeEndpoints = CreatorNode.buildEndpoint(
primary,
secondaries
)
newMetadata.wallet = this.web3Manager.getWalletAddress()
newMetadata.user_id = userId
newMetadata.creator_node_endpoint = newContentNodeEndpoints
this.userStateManager.setCurrentUser({
...newMetadata,
// Initialize counts to be 0. We don't want to write this data to backends ever really
// (hence the cleanUserMetadata above), but we do want to make sure clients
// can properly "do math" on these numbers.
followee_count: 0,
follower_count: 0,
repost_count: 0
})
// Update the new primary to the auto-selected primary
phase = phases.SET_PRIMARY
await this.creatorNode.setEndpoint(primary)
// Update metadata in CN and on chain of newly assigned replica set
phase = phases.UPLOAD_METADATA_AND_UPDATE_ON_CHAIN
await this.updateAndUploadMetadata({
newMetadata,
userId,
useEntityManager: true
})
console.log(
`${logPrefix} [phase: ${phase}] updateAndUploadMetadata() completed in ${
Date.now() - startMs
}ms`
)
console.log(`${logPrefix} completed in ${Date.now() - fnStartMs}ms`)
return newMetadata
} catch (e) {
const errorMsg = `assignReplicaSet() Error -- Phase ${phase} in ${
Date.now() - fnStartMs
}ms: ${e}`
throw new Error(errorMsg)
}
}
/**
* Create an on-chain non-creator user. Some fields are restricted (ex.
* creator_node_endpoint); this should error if the metadata given attempts to set them.
* @param {Object} metadata metadata to associate with the user
*/
async addUser(metadata: UserMetadata) {
this.IS_OBJECT(metadata)
const newMetadata = this.cleanUserMetadata(metadata)
this._validateUserMetadata(newMetadata)
let userId
const currentUser = this.userStateManager.getCurrentUser()
if (currentUser?.handle) {
userId = currentUser.user_id
} else {
userId = (
await this.contracts.UserFactoryClient.addUser(newMetadata.handle)
).userId
}
const result = await this._addUserOperations(userId, newMetadata)
const blockHash: string | undefined = result.latestBlockHash
const blockNumber: number = result.latestBlockNumber
newMetadata.wallet = this.web3Manager.getWalletAddress()
newMetadata.user_id = userId
this.userStateManager.setCurrentUser({
...newMetadata,
// Initialize counts to be 0. We don't want to write this data to backends ever really
// (hence the cleanUserMetadata above), but we do want to make sure clients
// can properly "do math" on these numbers.
followee_count: 0,
follower_count: 0,
repost_count: 0
})
return { blockHash, blockNumber, userId }
}
async updateEntityManagerReplicaSet({
userId,
primary,
secondaries,
oldPrimary,
oldSecondaries
}: {
userId: number
primary: number
secondaries: number[]
oldPrimary: number
oldSecondaries: number[]
}) {
const updateReplica = `${[oldPrimary, ...oldSecondaries].join(',')}:${[
primary,
...secondaries
].join(',')}`
const response = await this.contracts.EntityManagerClient!.manageEntity(
userId,
EntityManagerClient.EntityType.USER_REPLICA_SET,
userId,
EntityManagerClient.Action.UPDATE,
updateReplica
)
return {
blockHash: response.txReceipt.blockHash,
blockNumber: response.txReceipt.blockNumber
}
}
/**
* Updates a user
*/
async updateUser(userId: number, metadata: UserMetadata) {
this.REQUIRES(Services.DISCOVERY_PROVIDER)
this.IS_OBJECT(metadata)
const newMetadata = this.cleanUserMetadata(metadata)
this._validateUserMetadata(newMetadata)
// Retrieve the current user metadata
const users = await this.discoveryProvider.getUsers(
1,
0,
[userId],
null,
null,
null
)
if (!users || !users[0])
throw new Error(
`Cannot update user because no current record exists for user id ${userId}`
)
const oldMetadata = users[0]
const { latestBlockHash: blockHash, latestBlockNumber: blockNumber } =
await this._updateUserOperations(newMetadata, oldMetadata, userId)
this.userStateManager.setCurrentUser({ ...oldMetadata, ...newMetadata })
return { blockHash, blockNumber }
}
/**
* Updates a creator (updates their data on the creator node)
*/
async updateCreator(
userId: number,
metadata: UserMetadata,
useEntityManager: boolean
) {
this.REQUIRES(Services.CREATOR_NODE, Services.DISCOVERY_PROVIDER)
this.IS_OBJECT(metadata)
const newMetadata = this.cleanUserMetadata(metadata)
this._validateUserMetadata(newMetadata)
const logPrefix = `[User:updateCreator()] [userId: ${userId}] [useEntityManager: ${useEntityManager}]`
const fnStartMs = Date.now()
let startMs = fnStartMs
// Error if libs instance does not already have existing user state
const user = this.userStateManager.getCurrentUser()
if (!user) {
throw new Error('No current user')
}
// Ensure libs is connected to correct CN
if (
this.creatorNode.getEndpoint() !==
CreatorNode.getPrimary(newMetadata.creator_node_endpoint)
) {
throw new Error(
`Not connected to correct content node. Expected ${CreatorNode.getPrimary(
newMetadata.creator_node_endpoint
)}, got ${this.creatorNode.getEndpoint()}`
)
}
// Preserve old metadata object
const oldMetadata = { ...user }
// Update user creator_node_endpoint on chain if applicable
const updateEndpointTxBlockNumber = null
if (
newMetadata.creator_node_endpoint !== oldMetadata.creator_node_endpoint
) {
// Perform update to new contract
startMs = Date.now()
await this._updateReplicaSetOnChain(
userId,
newMetadata.creator_node_endpoint
)
console.log(
`${logPrefix} _waitForURSMCreatorNodeEndpointIndexing() completed in ${
Date.now() - startMs
}ms`
)
}
// Upload new metadata object to CN
const { metadataMultihash, metadataFileUUID } =
await this.creatorNode.uploadCreatorContent(
// @ts-expect-error pretty tough one to type
newMetadata,
updateEndpointTxBlockNumber
)
let txReceipt
let latestBlockHash
let latestBlockNumber
if (!useEntityManager) {
// Write metadata multihash to chain
const updatedMultihashDecoded = Utils.decodeMultihash(metadataMultihash)
const updateMultiHashResp =
await this.contracts.UserFactoryClient.updateMultihash(
userId,
updatedMultihashDecoded.digest
)
txReceipt = updateMultiHashResp.txReceipt
// Write remaining metadata fields to chain
const updateUserResp = await this._updateUserOperations(
newMetadata,
oldMetadata,
userId
)
latestBlockHash = updateUserResp.latestBlockHash
latestBlockNumber = Math.max(
txReceipt.blockNumber,
updateUserResp.latestBlockNumber
)
} else {
const response = await this.contracts.EntityManagerClient!.manageEntity(
userId,
EntityManagerClient.EntityType.USER,
userId,
EntityManagerClient.Action.UPDATE,
metadataMultihash
)
txReceipt = response.txReceipt
latestBlockNumber = txReceipt.blockNumber
}
// Write to CN to associate blockchain user id with updated metadata and block number
await this.creatorNode.associateCreator(
userId,
metadataFileUUID,
latestBlockNumber
)
// Update libs instance with new user metadata object
this.userStateManager.setCurrentUser({ ...oldMetadata, ...newMetadata })
if (!latestBlockHash || !latestBlockNumber) {
latestBlockHash = txReceipt.blockHash
latestBlockNumber = txReceipt.blockNumber
}
return {
blockHash: latestBlockHash,
blockNumber: latestBlockNumber,
userId
}
}
/**
* Updates a user on whether they are verified on Audius
*/
async updateIsVerified(
userId: number,
isVerified: boolean,
privateKey: string
) {
return await this.contracts.UserFactoryClient.updateIsVerified(
userId,
isVerified,
privateKey
)
}
/**
* Adds a user follow for a given follower and followee
*/
async addUserFollow(followeeUserId: number) {
const followerUserId = this.userStateManager.getCurrentUserId()
return await this.contracts.SocialFeatureFactoryClient.addUserFollow(
followerUserId!,
followeeUserId
)
}
/**
* Deletes a user follow for a given follower and followee
*/
async deleteUserFollow(followeeUserId: number) {
const followerUserId = this.userStateManager.getCurrentUserId()
return await this.contracts.SocialFeatureFactoryClient.deleteUserFollow(
followerUserId!,
followeeUserId
)
}
/**
* Gets the clock status for user in userStateManager across replica set.
*/
async getClockValuesFromReplicaSet() {
return await this.creatorNode.getClockValuesFromReplicaSet()
}
/* ------- PRIVATE ------- */
/**
* 1. Uploads metadata to primary Content Node (which inherently calls a sync accross secondaries)
* 2. Updates metadata on chain
*/
async updateAndUploadMetadata({
newMetadata,
userId,
useEntityManager
}: {
newMetadata: UserMetadata
userId: number
useEntityManager: boolean
}) {
this.REQUIRES(Services.CREATOR_NODE, Services.DISCOVERY_PROVIDER)
this.IS_OBJECT(newMetadata)
const phases = {
UPDATE_CONTENT_NODE_ENDPOINT_ON_CHAIN:
'UPDATE_CONTENT_NODE_ENDPOINT_ON_CHAIN',
UPLOAD_METADATA: 'UPLOAD_METADATA',
UPDATE_METADATA_ON_CHAIN: 'UPDATE_METADATA_ON_CHAIN',
UPDATE_USER_ON_CHAIN_OPS: 'UPDATE_USER_ON_CHAIN_OPS',
ASSOCIATE_USER: 'ASSOCIATE_USER'
}
let phase = ''
const oldMetadata = this.userStateManager.getCurrentUser()
if (!oldMetadata) {
throw new Error('No current user.')
}
newMetadata = this.cleanUserMetadata(newMetadata)
this._validateUserMetadata(newMetadata)
const logPrefix = `[User:updateAndUploadMetadata()] [userId: ${userId}]`
const fnStartMs = Date.now()
let startMs = fnStartMs
try {
// Update user creator_node_endpoint on chain if applicable
if (
newMetadata.creator_node_endpoint !== oldMetadata.creator_node_endpoint
) {
phase = phases.UPDATE_CONTENT_NODE_ENDPOINT_ON_CHAIN
const { txReceipt, replicaSetSPIDs } =
await this._updateReplicaSetOnChain(
userId,
newMetadata.creator_node_endpoint
)
console.log(
`${logPrefix} [phase: ${phase}] _updateReplicaSetOnChain() completed in ${
Date.now() - startMs
}ms`
)
if (useEntityManager) {
startMs = Date.now()
await this.waitForReplicaSetDiscoveryIndexing(
userId,
replicaSetSPIDs,
txReceipt.blockNumber
)
// @ts-expect-error
newMetadata.primary_id = replicaSetSPIDs[0]
newMetadata.secondary_ids = replicaSetSPIDs.slice(1)
console.log(
`${logPrefix} [phase: ${phase}] waitForReplicaSetDiscoveryIndexing() completed in ${
Date.now() - startMs
}ms`
)
} else {
startMs = Date.now()
await this._waitForURSMCreatorNodeEndpointIndexing(
userId,
replicaSetSPIDs
)
console.log(
`${logPrefix} [phase: ${phase}] _waitForURSMCreatorNodeEndpointIndexing() completed in ${
Date.now() - startMs
}ms`
)
}
}
// Upload new metadata object to CN
phase = phases.UPLOAD_METADATA
const { metadataMultihash, metadataFileUUID } =
// @ts-expect-error tough converting UserMetadata to Metadata
await this.creatorNode.uploadCreatorContent(newMetadata)
console.log(
`${logPrefix} [phase: ${phase}] creatorNode.uploadCreatorContent() completed in ${
Date.now() - startMs
}ms`
)
startMs = Date.now()
// Write metadata multihash to chain
phase = phases.UPDATE_METADATA_ON_CHAIN
let txReceipt
let blockNumber
if (useEntityManager) {
const response = await this.contracts.EntityManagerClient!.manageEntity(
userId,
EntityManagerClient.EntityType.USER,
userId,
EntityManagerClient.Action.UPDATE,
metadataMultihash
)
txReceipt = response.txReceipt
blockNumber = txReceipt.blockNumber
} else {
const updatedMultihashDecoded = Utils.decodeMultihash(metadataMultihash)
const res = await this.contracts.UserFactoryClient.updateMultihash(
userId,
updatedMultihashDecoded.digest
)
txReceipt = res.txReceipt
console.log(
`${logPrefix} [phase: ${phase}] UserFactoryClient.updateMultihash() completed in ${
Date.now() - startMs
}ms`
)
startMs = Date.now()
// Write remaining metadata fields to chain
phase = phases.UPDATE_USER_ON_CHAIN_OPS
const { latestBlockNumber } = await this._updateUserOperations(
newMetadata,
oldMetadata,
userId,
['creator_node_endpoint']
)
console.log(
`${logPrefix} [phase: ${phase}] _updateUserOperations() completed in ${
Date.now() - startMs
}ms`
)
blockNumber = Math.max(txReceipt.blockNumber, latestBlockNumber)
}
startMs = Date.now()
// Write to CN to associate blockchain user id with updated metadata and block number
phase = phases.ASSOCIATE_USER
await this.creatorNode.associateCreator(
userId,
metadataFileUUID,
blockNumber
)
console.log(
`${logPrefix} [phase: ${phase}] creatorNode.associateCreator() completed in ${
Date.now() - startMs
}ms`
)
startMs = Date.now()
// Update libs instance with new user metadata object
this.userStateManager.setCurrentUser({ ...oldMetadata, ...newMetadata })
console.log(`${logPrefix} completed in ${Date.now() - fnStartMs}ms`)
} catch (e) {
// TODO: think about handling the update metadata on chain and associating..
const errorMsg = `updateAndUploadMetadata() Error -- Phase ${phase} in ${
Date.now() - fnStartMs
}ms: ${e}`
throw new Error(errorMsg)
}
}
/**
* If a user's creator_node_endpoint is null, assign a replica set.
* Used during the sanity check and in uploadImage() in files.js
*/
async assignReplicaSetIfNecessary() {
const user = this.userStateManager.getCurrentUser()
// If no user is logged in, or a creator node endpoint is already assigned,
// skip this call
if (!user || user.creator_node_endpoint) return
// Generate a replica set and assign to user
try {
await this.assignReplicaSet({ userId: user.user_id })
} catch (e) {
throw new Error(
`assignReplicaSetIfNecessary error - ${(e as any).toString()}`
)
}
}
/** Waits for a discovery provider to confirm that a creator node endpoint is updated. */
async _waitForCreatorNodeEndpointIndexing(
userId: number,
creatorNodeEndpoint: string
) {
while (true) {
const userList = await this.discoveryProvider.getUsers(1, 0, [userId])
if (userList) {
const user = userList[0]
if (user && user.creator_node_endpoint === creatorNodeEndpoint) {
break
}
}
await Utils.wait(500)
}
}
/**
* Waits for the input replica set to be indexed by the discovery node
* If then replica set matches at the requested block number -> return null
* If the replica set response is null at the block number -> throw error
* If the replica set is mismatched at the block number -> throw error
* If the timeout is exceeded before replica set indexed -> throw error
*/
async waitForReplicaSetDiscoveryIndexing(
userId: number,
replicaSetSPIDs: number[],
blockNumber: number,
timeoutMs = 60000
): Promise<void> {
const asyncFn = async () => {
while (true) {
const encodedUserId = Utils.encodeHashId(userId)
let replicaSet
try {
// If the discovery node has not yet indexed the blocknumber,
// this method will throw an error
// If the user replica set does not exist, it will return an empty object
// which should lead to the method throwing an error
replicaSet = await this.discoveryProvider.getUserReplicaSet({
encodedUserId: encodedUserId!,
blockNumber
})
} catch (err) {