-
Notifications
You must be signed in to change notification settings - Fork 2
/
post.go
2317 lines (2047 loc) · 92.6 KB
/
post.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
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
package routes
import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"sort"
"strings"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/deso-smart/deso-core/v2/lib"
"github.com/pkg/errors"
)
// GetPostsStatelessRequest ...
type GetPostsStatelessRequest struct {
// This is the PostHashHex of the post we want to start our paginated lookup at. We
// will fetch up to "NumToFetch" posts after it, ordered by time stamp. If no
// PostHashHex is provided we will return the most recent posts.
PostHashHex string `safeForLogging:"true"`
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
OrderBy string `safeForLogging:"true"`
StartTstampSecs uint64 `safeForLogging:"true"`
PostContent string `safeForLogging:"true"`
NumToFetch int `safeForLogging:"true"`
// Note: if the GetPostsForFollowFeed option is passed, FetchSubcomments is currently ignored
// (fetching comments / subcomments for the follow feed is currently unimplemented)
FetchSubcomments bool `safeForLogging:"true"`
// This gets posts by people that ReaderPublicKeyBase58Check follows.
GetPostsForFollowFeed bool `safeForLogging:"true"`
// This gets posts by people that ReaderPublicKeyBase58Check follows.
GetPostsForGlobalWhitelist bool `safeForLogging:"true"`
// This gets posts sorted by deso
GetPostsByDESO bool `safeForLogging:"true"`
GetPostsByClout bool // Deprecated
// This only gets posts that include media, like photos and videos
MediaRequired bool `safeForLogging:"true"`
PostsByDESOMinutesLookback uint64 `safeForLogging:"true"`
// If set to true, then the posts in the response will contain a boolean about whether they're in the global feed
AddGlobalFeedBool bool `safeForLogging:"true"`
}
type PostEntryResponse struct {
PostHashHex string
PosterPublicKeyBase58Check string
ParentStakeID string
Body string
ImageURLs []string
VideoURLs []string
RepostedPostEntryResponse *PostEntryResponse
CreatorBasisPoints uint64
StakeMultipleBasisPoints uint64
TimestampNanos uint64
IsHidden bool
ConfirmationBlockHeight uint32
InMempool bool
// The profile associated with this post.
ProfileEntryResponse *ProfileEntryResponse
// The comments associated with this post.
Comments []*PostEntryResponse
LikeCount uint64
DiamondCount uint64
// Information about the reader's state w/regard to this post (e.g. if they liked it).
PostEntryReaderState *lib.PostEntryReaderState
InGlobalFeed *bool `json:",omitempty"`
InHotFeed *bool `json:",omitempty"`
// True if this post hash hex is pinned to the global feed.
IsPinned *bool `json:",omitempty"`
// PostExtraData stores an arbitrary map of attributes of a PostEntry
PostExtraData map[string]string
CommentCount uint64
RepostCount uint64
QuoteRepostCount uint64
// A list of parent posts for this post (ordered: root -> closest parent post).
ParentPosts []*PostEntryResponse
// NFT info.
IsNFT bool
NumNFTCopies uint64
NumNFTCopiesForSale uint64
NumNFTCopiesBurned uint64
HasUnlockable bool
NFTRoyaltyToCreatorBasisPoints uint64
NFTRoyaltyToCoinBasisPoints uint64
// This map specifies royalties that should go to user's other than the creator
AdditionalDESORoyaltiesMap map[string]uint64
// This map specifies royalties that should be add to creator coins other than the creator's coin.
AdditionalCoinRoyaltiesMap map[string]uint64
// Number of diamonds the sender gave this post. Only set when getting diamond posts.
DiamondsFromSender uint64
// Score given to this post by the hot feed go routine. Not always populated.
HotnessScore uint64
PostMultiplier float64
RecloutCount uint64 // Deprecated
QuoteRecloutCount uint64 // Deprecated
RecloutedPostEntryResponse *PostEntryResponse // Deprecated
}
// GetPostsStatelessResponse ...
type GetPostsStatelessResponse struct {
PostsFound []*PostEntryResponse
}
// Given a post entry, check if it is reposting another post and if so, get that post entry as a response.
func (fes *APIServer) _getRepostPostEntryResponse(postEntry *lib.PostEntry, addGlobalFeedBool bool, params *lib.DeSoParams, utxoView *lib.UtxoView, readerPK []byte, maxDepth uint8) (_repostPostEntry *PostEntryResponse, err error) {
// if the maxDepth at this point is 0, we stop getting reposted post entries
if maxDepth == 0 {
return nil, nil
}
if postEntry == nil {
return nil, fmt.Errorf("_getRepostPostEntry: postEntry must be provided ")
}
// Only try to get the repostPostEntryResponse if there is a Repost PostHashHex
if postEntry.RepostedPostHash != nil {
// Fetch the postEntry requested.
repostedPostEntry := utxoView.GetPostEntryForPostHash(postEntry.RepostedPostHash)
if repostedPostEntry == nil {
return nil, fmt.Errorf("_getRepostPostEntry: Could not find postEntry for PostHashHex: #{postEntry.RepostedPostHash}")
} else {
var repostedPostEntryResponse *PostEntryResponse
repostedPostEntryResponse, err = fes._postEntryToResponse(repostedPostEntry, addGlobalFeedBool, params, utxoView, readerPK, maxDepth-1)
if err != nil {
return nil, fmt.Errorf("_getRepostPostEntry: error converting repost post entry to response")
}
profileEntry := utxoView.GetProfileEntryForPublicKey(repostedPostEntry.PosterPublicKey)
if profileEntry != nil {
// Convert it to a response since that sanitizes the inputs.
profileEntryResponse := fes._profileEntryToResponse(profileEntry, utxoView)
repostedPostEntryResponse.ProfileEntryResponse = profileEntryResponse
}
repostedPostEntryResponse.PostEntryReaderState = utxoView.GetPostEntryReaderState(readerPK, repostedPostEntry)
return repostedPostEntryResponse, nil
}
} else {
return nil, nil
}
}
func (fes *APIServer) _postEntryToResponse(postEntry *lib.PostEntry, addGlobalFeedBool bool, params *lib.DeSoParams, utxoView *lib.UtxoView, readerPK []byte, maxDepth uint8) (
*PostEntryResponse, error) {
// We only want to fetch reposted posts two levels down. We only want to display repost posts that are at most two levels deep.
// This only happens when someone reposts a post that is a quoted repost. For a quote repost for which the reposted
// post is itself a quote repost, we only display the new repost's quote and use quote from the post that was reposted
// as the quoted content.
if maxDepth > 2 {
maxDepth = 2
}
// Get the body
bodyJSONObj := &lib.DeSoBodySchema{}
err := json.Unmarshal(postEntry.Body, bodyJSONObj)
if err != nil {
// Just ignore posts whose JSON doesn't parse properly.
return nil, fmt.Errorf(
"_postEntryToResponse: Error unmarshling Body: %v", err)
}
stakeIDStr := ""
if len(postEntry.ParentStakeID) == lib.HashSizeBytes {
stakeIDStr = hex.EncodeToString(postEntry.ParentStakeID)
} else if len(postEntry.ParentStakeID) == btcec.PubKeyBytesLenCompressed {
stakeIDStr = lib.PkToString(postEntry.ParentStakeID, params)
}
var inMempool bool
// When a transaction is connected to the view, it is given a block height of
// "fes.blockchain.BlockTip().Height + 1". Therefore, if a postEntry has a confirmation
// blockheight greater than the current blockTip height, it hasn't mined yet.
if postEntry.ConfirmationBlockHeight > fes.blockchain.BlockTip().Height {
inMempool = true
}
var repostPostEntryResponse *PostEntryResponse
// Only get repostPostEntryResponse if this is the origination of the thread.
if stakeIDStr == "" {
// We don't care about an error here
repostPostEntryResponse, _ = fes._getRepostPostEntryResponse(postEntry, addGlobalFeedBool, params, utxoView, readerPK, maxDepth)
}
postEntryResponseExtraData := make(map[string]string)
if len(postEntry.PostExtraData) > 0 {
for k, v := range postEntry.PostExtraData {
if len(v) > 0 {
postEntryResponseExtraData[k] = string(v)
}
}
}
// convert additional DESO royalties map if applicable
additionalDESORoyaltyMap := make(map[string]uint64)
for pkidIter, basisPoints := range postEntry.AdditionalNFTRoyaltiesToCreatorsBasisPoints {
additionalDESORoyaltyPKID := pkidIter
pkBytes := utxoView.GetPublicKeyForPKID(&additionalDESORoyaltyPKID)
additionalDESORoyaltyMap[lib.PkToString(pkBytes, fes.Params)] = basisPoints
}
// convert additional coin royalties map if applicable
additionalCoinRoyaltyMap := make(map[string]uint64)
for pkidIter, basisPoints := range postEntry.AdditionalNFTRoyaltiesToCoinsBasisPoints {
additionalCoinRoyaltyPKID := pkidIter
pkBytes := utxoView.GetPublicKeyForPKID(&additionalCoinRoyaltyPKID)
additionalCoinRoyaltyMap[lib.PkToString(pkBytes, fes.Params)] = basisPoints
}
res := &PostEntryResponse{
PostHashHex: hex.EncodeToString(postEntry.PostHash[:]),
PosterPublicKeyBase58Check: lib.PkToString(postEntry.PosterPublicKey, params),
ParentStakeID: stakeIDStr,
Body: bodyJSONObj.Body,
ImageURLs: bodyJSONObj.ImageURLs,
VideoURLs: bodyJSONObj.VideoURLs,
RepostedPostEntryResponse: repostPostEntryResponse,
CreatorBasisPoints: postEntry.CreatorBasisPoints,
StakeMultipleBasisPoints: postEntry.StakeMultipleBasisPoints,
TimestampNanos: postEntry.TimestampNanos,
IsHidden: postEntry.IsHidden,
ConfirmationBlockHeight: postEntry.ConfirmationBlockHeight,
InMempool: inMempool,
LikeCount: postEntry.LikeCount,
DiamondCount: postEntry.DiamondCount,
CommentCount: postEntry.CommentCount,
RepostCount: postEntry.RepostCount,
QuoteRepostCount: postEntry.QuoteRepostCount,
IsPinned: &postEntry.IsPinned,
IsNFT: postEntry.IsNFT,
NumNFTCopies: postEntry.NumNFTCopies,
NumNFTCopiesForSale: postEntry.NumNFTCopiesForSale,
NumNFTCopiesBurned: postEntry.NumNFTCopiesBurned,
HasUnlockable: postEntry.HasUnlockable,
NFTRoyaltyToCreatorBasisPoints: postEntry.NFTRoyaltyToCreatorBasisPoints,
NFTRoyaltyToCoinBasisPoints: postEntry.NFTRoyaltyToCoinBasisPoints,
AdditionalDESORoyaltiesMap: additionalDESORoyaltyMap,
AdditionalCoinRoyaltiesMap: additionalCoinRoyaltyMap,
PostExtraData: postEntryResponseExtraData,
// Deprecated
RecloutedPostEntryResponse: repostPostEntryResponse,
RecloutCount: postEntry.RepostCount,
QuoteRecloutCount: postEntry.QuoteRepostCount,
}
if addGlobalFeedBool {
inGlobalFeed := false
dbKey := GlobalStateKeyForTstampPostHash(postEntry.TimestampNanos, postEntry.PostHash)
globalStateVal, err := fes.GlobalState.Get(dbKey)
if err != nil {
return nil, fmt.Errorf(
"_postEntryToResponse: Error fetching from global state: %v", err)
}
if globalStateVal == nil {
res.InGlobalFeed = &inGlobalFeed
} else {
inGlobalFeed = true
res.InGlobalFeed = &inGlobalFeed
}
_, inHotFeed := fes.HotFeedApprovedPostsToMultipliers[*postEntry.PostHash]
res.InHotFeed = &inHotFeed
}
return res, nil
}
func (fes *APIServer) GetAllPostEntries(readerPK []byte) (
_postEntries []*lib.PostEntry, _commentsByPostHash map[lib.BlockHash][]*lib.PostEntry,
_profilesByPublicKey map[lib.PkMapKey]*lib.ProfileEntry,
_postEntryReaderStates map[lib.BlockHash]*lib.PostEntryReaderState, err error) {
// Get a view with all the mempool transactions (used to get all posts / reader state).
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("GetPostsStateless: Error fetching mempool view: %v", err)
}
postEntries, commentsByPostHash, err := utxoView.GetAllPosts()
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("GetAllPostEntries: Error fetching posts from view: %v", err)
}
profileEntries := make(map[lib.PkMapKey]*lib.ProfileEntry)
for _, postEntry := range postEntries {
{
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
// Get the profileEntries for the comments as well
commentsFound := commentsByPostHash[*postEntry.PostHash]
for _, commentEntry := range commentsFound {
profileEntry := utxoView.GetProfileEntryForPublicKey(commentEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
}
postEntryReaderStates := make(map[lib.BlockHash]*lib.PostEntryReaderState)
// Create reader state map. Ie, whether the reader has liked the post, etc.
// If nil is passed in as the readerPK, this is skipped.
if readerPK != nil {
for _, postEntry := range postEntries {
postEntryReaderState := utxoView.GetPostEntryReaderState(readerPK, postEntry)
postEntryReaderStates[*postEntry.PostHash] = postEntryReaderState
}
}
return postEntries, commentsByPostHash, profileEntries, postEntryReaderStates, nil
}
func (fes *APIServer) GetPostEntriesForFollowFeed(
startAfterPostHash *lib.BlockHash, readerPK []byte, numToFetch int, utxoView *lib.UtxoView, mediaRequired bool) (
_postEntries []*lib.PostEntry,
_profilesByPublicKey map[lib.PkMapKey]*lib.ProfileEntry,
_postEntryReaderStates map[lib.BlockHash]*lib.PostEntryReaderState, err error) {
postEntries, err := fes.GetPostsForFollowFeedForPublicKey(utxoView, startAfterPostHash, readerPK, numToFetch, true /* skip hidden */, mediaRequired)
if err != nil {
return nil, nil, nil, fmt.Errorf("GetPostEntriesForFollowFeed: Error fetching posts from view: %v", err)
}
// Sort the postEntries by time.
sort.Slice(postEntries, func(ii, jj int) bool {
return postEntries[ii].TimestampNanos > postEntries[jj].TimestampNanos
})
profileEntries := make(map[lib.PkMapKey]*lib.ProfileEntry)
for _, postEntry := range postEntries {
{
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
}
postEntryReaderStates := make(map[lib.BlockHash]*lib.PostEntryReaderState)
// Create reader state map. Ie, whether the reader has liked the post, etc.
// If nil is passed in as the readerPK, this is skipped.
if readerPK != nil {
for _, postEntry := range postEntries {
postEntryReaderState := utxoView.GetPostEntryReaderState(readerPK, postEntry)
postEntryReaderStates[*postEntry.PostHash] = postEntryReaderState
}
}
return postEntries, profileEntries, postEntryReaderStates, nil
}
// Get the top numToFetch posts ordered by poster's coin price in the last number of minutes as defined by minutesLookback.
func (fes *APIServer) GetPostEntriesByDESOAfterTimePaginated(readerPK []byte,
minutesLookback uint64, numToFetch int, mediaRequired bool) (
_postEntries []*lib.PostEntry,
_profilesByPublicKey map[lib.PkMapKey]*lib.ProfileEntry, err error) {
// As a safeguard, we should only be able to look at least one hour in the past -- can be changed later.
if minutesLookback > 60 {
return nil, nil, fmt.Errorf("GetPostEntriesByDESO: Cannot fetch posts by deso more than an hour back")
}
currentTime := time.Now().UnixNano()
startTstampNanos := uint64(currentTime) - (uint64(time.Minute.Nanoseconds()) * minutesLookback)
// Get a view with all the mempool transactions (used to get all posts / reader state).
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
return nil, nil, fmt.Errorf("GetPostEntriesByDESO: Error fetching mempool view: %v", err)
}
// Start by fetching the posts we have in the db.
dbPostHashes, _, _, err := lib.DBGetPaginatedPostsOrderedByTime(
utxoView.Handle, startTstampNanos, nil, -1, false /*fetchEntries*/, false)
if err != nil {
return nil, nil, errors.Wrapf(err, "GetPostEntriesByDESO: Problem fetching ProfileEntrys from db: ")
}
// Iterate through the entries found in the db and force the view to load them.
// This fills in any gaps in the view so that, after this, the view should contain
// the union of what it had before plus what was in the db.
for _, dbPostHash := range dbPostHashes {
utxoView.GetPostEntryForPostHash(dbPostHash)
}
// Cycle through all the posts and store a map of the PubKeys so we can filter out those
// that are restricted later.
postEntryPubKeyMap := make(map[lib.PkMapKey][]byte)
for _, postEntry := range utxoView.PostHashToPostEntry {
// Ignore deleted / rolled-back / hidden posts.
if postEntry.IsDeleted() || postEntry.IsHidden {
continue
}
// If media is required and this post does not have media, skip it.
if mediaRequired && !postEntry.HasMedia() {
continue
}
// We make sure that the post isn't a comment.
if len(postEntry.ParentStakeID) == 0 {
postEntryPubKeyMap[lib.MakePkMapKey(postEntry.PosterPublicKey)] = postEntry.PosterPublicKey
}
}
// Filter restricted public keys out of the posts.
filteredPostEntryPubKeyMap, err := fes.FilterOutRestrictedPubKeysFromMap(postEntryPubKeyMap, readerPK, "leaderboard", utxoView)
if err != nil {
return nil, nil, errors.Wrapf(err, "GetPostsByDESO: Problem filtering restricted profiles from map: ")
}
// At this point, all the posts should be loaded into the view.
allCorePosts := []*lib.PostEntry{}
for _, postEntry := range utxoView.PostHashToPostEntry {
// Ignore deleted or rolled-back posts.
if postEntry.IsDeleted() || postEntry.IsHidden {
continue
}
if mediaRequired && !postEntry.HasMedia() {
continue
}
// Make sure this isn't a comment and then make sure the public key isn't restricted.
if len(postEntry.ParentStakeID) == 0 && postEntry.TimestampNanos > startTstampNanos {
if filteredPostEntryPubKeyMap[lib.MakePkMapKey(postEntry.PosterPublicKey)] == nil {
continue
}
allCorePosts = append(allCorePosts, postEntry)
}
}
profileEntries := make(map[lib.PkMapKey]*lib.ProfileEntry)
for _, postEntry := range allCorePosts {
{
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
}
// Order the posts by the poster's coin price.
sort.Slice(allCorePosts, func(ii, jj int) bool {
return profileEntries[lib.MakePkMapKey(allCorePosts[ii].PosterPublicKey)].CreatorCoinEntry.DeSoLockedNanos > profileEntries[lib.MakePkMapKey(allCorePosts[jj].PosterPublicKey)].CreatorCoinEntry.DeSoLockedNanos
})
// Select the top numToFetch posts.
if len(allCorePosts) > numToFetch {
allCorePosts = allCorePosts[:numToFetch]
}
return allCorePosts, profileEntries, nil
}
func (fes *APIServer) GetPostEntriesByTimePaginated(
startPostHash *lib.BlockHash, readerPK []byte, numToFetch int, utxoView *lib.UtxoView, mediaRequired bool) (
_postEntries []*lib.PostEntry, _commentsByPostHash map[lib.BlockHash][]*lib.PostEntry,
_profilesByPublicKey map[lib.PkMapKey]*lib.ProfileEntry,
_postEntryReaderStates map[lib.BlockHash]*lib.PostEntryReaderState, err error) {
postEntries,
commentsByPostHash,
err := fes.GetPostsByTime(utxoView, startPostHash, readerPK, numToFetch,
true /*skipHidden*/, true, mediaRequired)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("GetAllPostEntries: Error fetching posts from view: %v", err)
}
// Sort the postEntries by time.
sort.Slice(postEntries, func(ii, jj int) bool {
return postEntries[ii].TimestampNanos > postEntries[jj].TimestampNanos
})
// Take up to numToFetch. If this is a request for a single post, it was selected by the utxo view.
if len(postEntries) > numToFetch || startPostHash != nil {
startIndex := 0
if startPostHash != nil {
// If we have a startPostHash, find it's index in the postEntries slice as the starting point
for ii, postEntry := range postEntries {
if *(postEntry.PostHash) == *(startPostHash) {
// Start the new slice from the post that comes after the startPostHash
startIndex = ii + 1
break
}
}
}
postEntries = postEntries[startIndex:lib.MinInt(startIndex+numToFetch, len(postEntries))]
}
profileEntries := make(map[lib.PkMapKey]*lib.ProfileEntry)
for _, postEntry := range postEntries {
{
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
// Get the profileEntries for the comments (and subcomments) as well
commentsFound := commentsByPostHash[*postEntry.PostHash]
for _, commentEntry := range commentsFound {
profileEntry := utxoView.GetProfileEntryForPublicKey(commentEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
subCommentsFound := commentsByPostHash[*commentEntry.PostHash]
for _, subCommentEntry := range subCommentsFound {
subCommentProfileEntry := utxoView.GetProfileEntryForPublicKey(subCommentEntry.PosterPublicKey)
if subCommentProfileEntry != nil {
profileEntries[lib.MakePkMapKey(subCommentProfileEntry.PublicKey)] = subCommentProfileEntry
}
}
}
}
postEntryReaderStates := make(map[lib.BlockHash]*lib.PostEntryReaderState)
// Create reader state map. Ie, whether the reader has liked the post, etc.
// If nil is passed in as the readerPK, this is skipped.
if readerPK != nil {
for _, postEntry := range postEntries {
postEntryReaderState := utxoView.GetPostEntryReaderState(readerPK, postEntry)
postEntryReaderStates[*postEntry.PostHash] = postEntryReaderState
}
}
return postEntries, commentsByPostHash, profileEntries, postEntryReaderStates, nil
}
func (fes *APIServer) _getCommentResponse(
commentEntry *lib.PostEntry, profileEntryMap map[lib.PkMapKey]*lib.ProfileEntry, addGlobalFeedBool bool, utxoView *lib.UtxoView, readerPK []byte) (
*PostEntryResponse, error) {
commentResponse, err := fes._postEntryToResponse(commentEntry, addGlobalFeedBool, fes.Params, utxoView, readerPK, 2)
if err != nil {
return nil, err
}
profileEntryFound := profileEntryMap[lib.MakePkMapKey(commentEntry.PosterPublicKey)]
commentResponse.ProfileEntryResponse = fes._profileEntryToResponse(profileEntryFound, utxoView)
return commentResponse, nil
}
func (fes *APIServer) _shouldSkipCommentResponse(commentResponse *PostEntryResponse, err error) bool {
// If there's a problem with this comment then just skip it
return err != nil ||
// Don't add hidden comments
commentResponse.IsHidden
}
func (fes *APIServer) GetPostEntriesForGlobalWhitelist(
startPostHash *lib.BlockHash, readerPK []byte, numToFetch int, utxoView *lib.UtxoView, mediaRequired bool) (
_postEntries []*lib.PostEntry,
_profilesByPublicKey map[lib.PkMapKey]*lib.ProfileEntry,
_postEntryReaderStates map[lib.BlockHash]*lib.PostEntryReaderState, err error) {
var startPost *lib.PostEntry
if startPostHash != nil {
startPost = utxoView.GetPostEntryForPostHash(startPostHash)
}
var seekStartKey []byte
var seekStartPostHash *lib.BlockHash
skipFirstEntry := false
if startPost != nil {
seekStartKey = GlobalStateKeyForTstampPostHash(startPost.TimestampNanos, startPost.PostHash)
seekStartPostHash = startPost.PostHash
skipFirstEntry = true
} else {
// If we can't find a valid start post, we just use the prefix. Seek will
// pad the value as necessary.
seekStartKey = _GlobalStatePrefixTstampNanosPostHash
}
// Seek the global state for a list of [prefix][tstamp][posthash] keys.
validForPrefix := _GlobalStatePrefixTstampNanosPostHash
maxBigEndianUint64Bytes := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
maxKeyLen := 1 + len(maxBigEndianUint64Bytes) + lib.HashSizeBytes
var postEntries []*lib.PostEntry
nextStartKey := seekStartKey
nextStartPostHash := seekStartPostHash
index := 0
// Iterate over posts in global state until we have at least num to fetch
for len(postEntries) < numToFetch {
var postHashes []*lib.BlockHash
// If we're using an external global state, use the cached post hashes.
if fes.Config.GlobalStateAPIUrl != "" {
if nextStartPostHash != nil {
for ii := index; ii < len(fes.GlobalFeedPostHashes); ii++ {
if reflect.DeepEqual(*fes.GlobalFeedPostHashes[ii], *nextStartPostHash) {
index = ii
break
}
}
}
endIndex := lib.MinInt(index+numToFetch-len(postEntries), len(fes.GlobalFeedPostHashes))
postHashes = fes.GlobalFeedPostHashes[index:endIndex]
// At the next iteration, we can start looking endIndex for the post hash we need.
index = endIndex - 1
} else {
// Otherwise, we're using this node's global state.
var keys [][]byte
// Get numToFetch - len(postEntries) postHashes from global state.
keys, _, err = fes.GlobalState.Seek(nextStartKey /*startPrefix*/, validForPrefix, /*validForPrefix*/
maxKeyLen /*maxKeyLen -- ignored since reverse is false*/, numToFetch-len(postEntries), true, /*reverse*/
false /*fetchValues*/)
if err != nil {
return nil, nil, nil, fmt.Errorf("GetPostEntriesForGlobalWhitelist: Getting posts for reader: %v", err)
}
for _, dbKeyBytes := range keys {
postHash := &lib.BlockHash{}
copy(postHash[:], dbKeyBytes[1+len(maxBigEndianUint64Bytes):][:])
postHashes = append(postHashes, postHash)
}
}
// If there are no keys left, then there are no more postEntries to get so we exit the loop.
if len(postHashes) == 0 || (len(postHashes) == 1 && skipFirstEntry) {
break
}
var lastPost *lib.PostEntry
for ii, postHash := range postHashes {
// if we have a postHash at which we are starting, we should skip the first one so we don't have it
// duplicated in the response.
if skipFirstEntry && ii == 0 {
continue
}
// Get the postEntry from the utxoView.
postEntry := utxoView.GetPostEntryForPostHash(postHash)
if postEntry != nil {
lastPost = postEntry
}
if readerPK != nil && postEntry != nil && reflect.DeepEqual(postEntry.PosterPublicKey, readerPK) {
// We add the readers posts later so we can skip them here to avoid duplicates.
continue
}
// mediaRequired set to determine if we only want posts that include media and ignore posts without
if mediaRequired && postEntry != nil && !postEntry.HasMedia() {
continue
}
if postEntry != nil {
postEntries = append(postEntries, postEntry)
}
}
// If there are no post entries and no last post, we don't continue to fetch.
if len(postEntries) == 0 && lastPost == nil {
break
}
// Next time through the loop, start at the last key we retrieved
nextStartKey = GlobalStateKeyForTstampPostHash(lastPost.TimestampNanos, lastPost.PostHash)
nextStartPostHash = lastPost.PostHash
skipFirstEntry = true
}
// If we don't have any postEntries at this point, bail.
profileEntries := make(map[lib.PkMapKey]*lib.ProfileEntry)
postEntryReaderStates := make(map[lib.BlockHash]*lib.PostEntryReaderState)
// Now that we have the whitelist posts, we need to insert the user's posts.
if readerPK != nil {
maxTimestampNanos := uint64(time.Now().UTC().UnixNano()) // current tstamp
if startPost != nil {
maxTimestampNanos = startPost.TimestampNanos
}
var minTimestampNanos uint64
if len(postEntries) == 0 {
minTimestampNanos = 0
} else {
minTimestampNanos = postEntries[len(postEntries)-1].TimestampNanos
}
_, dbPostAndCommentHashes, _, err := lib.DBGetAllPostsAndCommentsForPublicKeyOrderedByTimestamp(
utxoView.Handle, readerPK, false /*fetchEntries*/, minTimestampNanos, maxTimestampNanos,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("GetPostEntriesForGlobalWhitelist: Getting posts for reader: %v", err)
}
// Load all the relevant post hashes into the view.
for _, dbPostOrCommentHash := range dbPostAndCommentHashes {
utxoView.GetPostEntryForPostHash(dbPostOrCommentHash)
}
// Loop through all the posts in the view and add those that are relevant.
for _, postEntry := range utxoView.PostHashToPostEntry {
// Skip deleted / hidden posts and any comments.
if postEntry.IsDeleted() || postEntry.IsHidden || len(postEntry.ParentStakeID) != 0 {
continue
}
// mediaRequired set to determine if we only want posts that include media and ignore posts without
if mediaRequired && !postEntry.HasMedia() {
continue
}
if postEntry.TimestampNanos <= maxTimestampNanos && postEntry.TimestampNanos > minTimestampNanos {
if reflect.DeepEqual(postEntry.PosterPublicKey, readerPK) {
postEntries = append(postEntries, postEntry)
}
}
}
}
// Sort the postEntries by time.
sort.Slice(postEntries, func(ii, jj int) bool {
return postEntries[ii].TimestampNanos > postEntries[jj].TimestampNanos
})
{
// Only add pinned posts if we are starting from the top of the feed.
if startPostHash == nil {
// Get all pinned posts and prepend them to the list of postEntries
pinnedStartKey := _GlobalStatePrefixTstampNanosPinnedPostHash
// todo: how many posts can we really pin?
keys, _, err := fes.GlobalState.Seek(pinnedStartKey, pinnedStartKey, maxKeyLen, 10, true, false)
if err != nil {
return nil, nil, nil, fmt.Errorf("GetPostEntriesForWhitelist: Getting pinned posts: %v", err)
}
var pinnedPostEntries []*lib.PostEntry
for _, dbKeyBytes := range keys {
postHash := &lib.BlockHash{}
copy(postHash[:], dbKeyBytes[1+len(maxBigEndianUint64Bytes):][:])
postEntry := utxoView.GetPostEntryForPostHash(postHash)
if postEntry != nil {
postEntry.IsPinned = true
pinnedPostEntries = append(pinnedPostEntries, postEntry)
}
}
postEntries = append(pinnedPostEntries, postEntries...)
}
}
if len(postEntries) == 0 {
return postEntries, profileEntries, postEntryReaderStates, nil
}
for _, postEntry := range postEntries {
{
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry != nil {
profileEntries[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry
}
}
}
// Create reader state map. Ie, whether the reader has liked the post, etc.
// If nil is passed in as the readerPK, this is skipped.
if readerPK != nil {
for _, postEntry := range postEntries {
postEntryReaderState := utxoView.GetPostEntryReaderState(readerPK, postEntry)
postEntryReaderStates[*postEntry.PostHash] = postEntryReaderState
}
}
return postEntries, profileEntries, postEntryReaderStates, nil
}
func (fes *APIServer) GetGlobalFeedPostHashesForLastWeek() (_postHashes []*lib.BlockHash, _err error) {
minTimestampNanos := uint64(time.Now().UTC().AddDate(0, 0, -7).UnixNano()) // 1 week ago
seekStartKey := GlobalStateSeekKeyForTstampPostHash(minTimestampNanos)
validForPrefix := _GlobalStatePrefixTstampNanosPostHash
maxBigEndianUint64Bytes := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
maxKeyLen := 1 + len(maxBigEndianUint64Bytes) + lib.HashSizeBytes
var postHashes []*lib.BlockHash
keys, _, err := fes.GlobalState.Seek(seekStartKey /*startPrefix*/, validForPrefix, /*validForPrefix*/
maxKeyLen /*maxKeyLen -- ignored since reverse is false*/, 0, false, /*reverse*/
false /*fetchValues*/)
if err != nil {
return nil, err
}
// We iterate backwards since we want the Posts to be ordered from most recent to least recent.
for ii := len(keys) - 1; ii >= 0; ii-- {
postHash := &lib.BlockHash{}
copy(postHash[:], keys[ii][1+len(maxBigEndianUint64Bytes):][:])
postHashes = append(postHashes, postHash)
}
return postHashes, nil
}
// GetPostsStateless ...
func (fes *APIServer) GetPostsStateless(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetPostsStatelessRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Problem parsing request body: %v", err))
return
}
// Decode the reader public key into bytes. Default to nil if no pub key is passed in.
var readerPublicKeyBytes []byte
var err error
if requestData.ReaderPublicKeyBase58Check != "" {
readerPublicKeyBytes, _, err = lib.Base58CheckDecode(requestData.ReaderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Problem decoding user public key: %v", err))
return
}
}
var startPostHash *lib.BlockHash
if requestData.PostHashHex != "" {
// Decode the postHash. This will give us the location where we start our paginated search.
startPostHash, err = GetPostHashFromPostHashHex(requestData.PostHashHex)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: %v", err))
return
}
}
// Default to 50 posts fetched.
numToFetch := 50
if requestData.NumToFetch != 0 {
numToFetch = requestData.NumToFetch
}
if startPostHash == nil && numToFetch == 1 {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Must provide PostHashHex when NumToFetch is 1"))
return
}
// Get a view with all the mempool transactions (used to get all posts / reader state).
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Error fetching mempool view"))
return
}
// Get all the PostEntries
var postEntries []*lib.PostEntry
var commentsByPostHash map[lib.BlockHash][]*lib.PostEntry
var profileEntryMap map[lib.PkMapKey]*lib.ProfileEntry
var readerStateMap map[lib.BlockHash]*lib.PostEntryReaderState
if requestData.GetPostsForFollowFeed {
postEntries,
profileEntryMap,
readerStateMap,
err = fes.GetPostEntriesForFollowFeed(startPostHash, readerPublicKeyBytes, numToFetch, utxoView,
requestData.MediaRequired)
// if we're getting posts for follow feed, no comments are returned (they aren't necessary)
commentsByPostHash = make(map[lib.BlockHash][]*lib.PostEntry)
} else if requestData.GetPostsForGlobalWhitelist {
postEntries,
profileEntryMap,
readerStateMap,
err = fes.GetPostEntriesForGlobalWhitelist(startPostHash, readerPublicKeyBytes, numToFetch, utxoView,
requestData.MediaRequired)
// if we're getting posts for the global whitelist, no comments are returned (they aren't necessary)
commentsByPostHash = make(map[lib.BlockHash][]*lib.PostEntry)
} else if requestData.GetPostsByDESO || requestData.GetPostsByClout {
postEntries,
profileEntryMap,
err = fes.GetPostEntriesByDESOAfterTimePaginated(readerPublicKeyBytes,
requestData.PostsByDESOMinutesLookback, numToFetch, requestData.MediaRequired)
} else {
postEntries,
commentsByPostHash,
profileEntryMap,
readerStateMap,
err = fes.GetPostEntriesByTimePaginated(startPostHash, readerPublicKeyBytes, numToFetch,
utxoView, requestData.MediaRequired)
}
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Error fetching posts: %v", err))
return
}
// Get a utxoView.
utxoView, err = fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Error constucting utxoView: %v", err))
return
}
blockedPubKeys, err := fes.GetBlockedPubKeysForUser(readerPublicKeyBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetPostsStateless: Error fetching blocked pub keys for user: %v", err))
return
}
postEntryResponses := []*PostEntryResponse{}
for _, postEntry := range postEntries {
// If the creator who posted postEntry is in the map of blocked pub keys, skip this postEntry
if _, ok := blockedPubKeys[lib.PkToString(postEntry.PosterPublicKey, fes.Params)]; !ok {
var postEntryResponse *PostEntryResponse
postEntryResponse, err = fes._postEntryToResponse(postEntry, requestData.AddGlobalFeedBool, fes.Params, utxoView, readerPublicKeyBytes, 2)
if err != nil {
// Just ignore posts that fail to convert for whatever reason.
continue
}
profileEntryFound := profileEntryMap[lib.MakePkMapKey(postEntry.PosterPublicKey)]
postEntryResponse.ProfileEntryResponse = fes._profileEntryToResponse(
profileEntryFound, utxoView)
commentsFound := commentsByPostHash[*postEntry.PostHash]
for _, commentEntry := range commentsFound {
if _, ok = blockedPubKeys[lib.PkToString(commentEntry.PosterPublicKey, fes.Params)]; !ok {
commentResponse, err := fes._getCommentResponse(commentEntry, profileEntryMap, requestData.AddGlobalFeedBool, utxoView, readerPublicKeyBytes)
if fes._shouldSkipCommentResponse(commentResponse, err) {
continue
}
// Fetch subcomments if needed
if requestData.FetchSubcomments {
subcommentsFound := commentsByPostHash[*commentEntry.PostHash]
for _, subCommentEntry := range subcommentsFound {
subcommentResponse, err := fes._getCommentResponse(subCommentEntry, profileEntryMap, requestData.AddGlobalFeedBool, utxoView, readerPublicKeyBytes)
if fes._shouldSkipCommentResponse(subcommentResponse, err) {
continue
}
commentResponse.Comments = append(commentResponse.Comments, subcommentResponse)
}
postEntryResponse.Comments = append(postEntryResponse.Comments, commentResponse)
}
}
}
postEntryResponse.PostEntryReaderState = readerStateMap[*postEntry.PostHash]
postEntryResponses = append(postEntryResponses, postEntryResponse)
}
}
if requestData.PostContent != "" {
lowercaseFilter := strings.ToLower(requestData.PostContent)
filteredResponses := []*PostEntryResponse{}
for _, postRes := range postEntryResponses {
if strings.Contains(strings.ToLower(postRes.Body), lowercaseFilter) {
filteredResponses = append(filteredResponses, postRes)
}
}
postEntryResponses = filteredResponses
}
if requestData.OrderBy == "newest" {
// Now sort the post list on the timestamp
sort.Slice(postEntryResponses, func(ii, jj int) bool {
return postEntryResponses[ii].TimestampNanos > postEntryResponses[jj].TimestampNanos
})
} else if requestData.OrderBy == "oldest" {
sort.Slice(postEntryResponses, func(ii, jj int) bool {
return postEntryResponses[ii].TimestampNanos < postEntryResponses[jj].TimestampNanos
})
} else if requestData.OrderBy == "last_comment" {
sort.Slice(postEntryResponses, func(ii, jj int) bool {
lastCommentTimeii := uint64(0)
if len(postEntryResponses[ii].Comments) > 0 {
lastCommentTimeii = postEntryResponses[ii].Comments[len(postEntryResponses[ii].Comments)-1].TimestampNanos
}
lastCommentTimejj := uint64(0)
if len(postEntryResponses[jj].Comments) > 0 {
lastCommentTimejj = postEntryResponses[jj].Comments[len(postEntryResponses[jj].Comments)-1].TimestampNanos
}
return lastCommentTimeii > lastCommentTimejj
})
}
// Return the posts found.
res := &GetPostsStatelessResponse{
PostsFound: postEntryResponses,
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetPostsStateless: Problem encoding response as JSON: %v", err))
return
}
}
type GetSinglePostRequest struct {
// PostHashHex to fetch.
PostHashHex string `safeForLogging:"true"`
FetchParents bool `safeForLogging:"true"`
CommentOffset uint32 `safeForLogging:"true"`
CommentLimit uint32 `safeForLogging:"true"`
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
// How many levels of replies will be retrieved. If unset, will only retrieve the top-level replies.
ThreadLevelLimit uint32 `safeForLogging:"true"`
// How many child replies of a parent comment will be considered when returning a comment thread. Setting this to -1 will include all child replies. This limit does not affect the top-level replies to a post.
ThreadLeafLimit int32 `safeForLogging:"true"`
// If the post contains a comment thread where all comments are created by the author, include that thread in the response.
LoadAuthorThread bool `safeForLogging:"true"`