-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpublic.gno
402 lines (349 loc) · 12.6 KB
/
public.gno
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
package social
import (
"std"
"strconv"
"gno.land/p/demo/avl"
"gno.land/p/demo/ufmt"
"gno.land/r/demo/users"
)
type UserAndPostID struct {
UserPostAddr std.Address
PostID PostID
}
// Post a message to the caller's main user posts.
// The caller must already be registered with /r/demo/users Register.
// Return the "thread ID" of the new post.
// (This is similar to boards.CreateThread, but no message title)
func PostMessage(body string) PostID {
caller := std.GetOrigCaller()
name := usernameOf(caller)
if name == "" {
panic("please register")
}
userPosts := getOrCreateUserPosts(caller, name)
thread := userPosts.AddThread(body)
return thread.id
}
// Post a reply to the user posts of userPostsAddr where threadid is the ID returned by
// the original call to PostMessage. If postid == threadid then create another top-level
// post for the threadid, otherwise post a reply to the postid "sub reply".
// The caller must already be registered with /r/demo/users Register.
// Return the new post ID.
// (This is similar to boards.CreateReply.)
func PostReply(userPostsAddr std.Address, threadid, postid PostID, body string) PostID {
caller := std.GetOrigCaller()
if usernameOf(caller) == "" {
panic("please register")
}
userPosts := getUserPosts(userPostsAddr)
if userPosts == nil {
panic("posts for userPostsAddr do not exist")
}
thread := userPosts.GetThread(threadid)
if thread == nil {
panic("threadid in user posts does not exist")
}
if postid == threadid {
reply := thread.AddReply(caller, body)
return reply.id
} else {
post := thread.GetReply(postid)
if post == nil {
panic("postid does not exist")
}
reply := post.AddReply(caller, body)
return reply.id
}
}
// Repost the message from the user posts of userPostsAddr where threadid is the ID returned by
// the original call to PostMessage. This must be a top-level thread (not a reply).
// Return the new post ID.
// (This is similar to boards.CreateRepost.)
func RepostThread(userPostsAddr std.Address, threadid PostID, comment string) PostID {
caller := std.GetOrigCaller()
if userPostsAddr == caller {
panic("Cannot repost a user's own message")
}
name := usernameOf(caller)
if name == "" {
panic("please register")
}
dstUserPosts := getOrCreateUserPosts(caller, name)
userPosts := getUserPosts(userPostsAddr)
if userPosts == nil {
panic("posts for userPostsAddr do not exist")
}
thread := userPosts.GetThread(threadid)
if thread == nil {
panic("threadid in user posts does not exist")
}
repost := thread.AddRepostTo(caller, comment, dstUserPosts)
return repost.id
}
// For each address/PostID in addrAndIDs, get the thread post. The Post ID must be
// for a a top-level thread (not a reply; to get reply posts, use GetThreadPosts).
// If the Post ID is not found, set the result for that Post ID to {}.
// The response is a JSON string.
func GetJsonTopPostsByID(addrAndIDs []UserAndPostID) string {
json := "[ "
for _, addrAndID := range addrAndIDs {
if len(json) > 2 {
json += ",\n "
}
userPosts := getUserPosts(addrAndID.UserPostAddr)
if userPosts == nil {
json += "{}"
continue
}
post := userPosts.GetThread(PostID(addrAndID.PostID))
if post == nil {
json += "{}"
continue
}
postJson, err := post.MarshalJSON()
if err != nil {
panic("can't get post JSON")
}
json += string(postJson)
}
json += "]"
return json
}
// Get posts in a thread for a user. A thread is the sequence of posts without replies.
// While each post has an an arbitrary id, it also has an index within the thread starting from 0.
// Limit the response to posts from startIndex up to (not including) endIndex within the thread.
// If you just want the total count, set startIndex and endIndex to 0 and see the response "n_threads".
// If threadID is 0 then return the user's top-level posts. (Like render args "user".)
// If threadID is X and replyID is 0, then return the posts (without replies) in that thread. (Like render args "user/2".)
// If threadID is X and replyID is Y, then return the posts in the thread starting with replyID. (Like render args "user/2/5".)
// The response includes reposts by this user (only if threadID is 0), but not messages of other
// users that are being followed. (See GetHomePosts.) The response is a JSON string.
func GetThreadPosts(userPostsAddr std.Address, threadID int, replyID int, startIndex int, endIndex int) string {
userPosts := getUserPosts(userPostsAddr)
if userPosts == nil {
panic("posts for userPostsAddr do not exist")
}
if threadID == 0 {
return getPosts(userPosts.threads, startIndex, endIndex)
}
thread := userPosts.GetThread(PostID(threadID))
if thread == nil {
panic(ufmt.Sprintf("thread does not exist with id %d", threadID))
}
if replyID == 0 {
return getPosts(thread.replies, startIndex, endIndex)
} else {
reply := thread.GetReply(PostID(replyID))
if reply == nil {
panic(ufmt.Sprintf("reply does not exist with id %d in thread with id %d", replyID, threadID))
}
return getPosts(reply.replies, startIndex, endIndex)
}
}
// Update the home posts by scanning all posts from all followed users and adding the
// followed posts since the last call to RefreshHomePosts (or since started following the user).
// Return the new count of home posts. The result is something like "(12 int)".
func RefreshHomePosts(userPostsAddr std.Address) int {
userPosts := getUserPosts(userPostsAddr)
if userPosts == nil {
panic("posts for userPostsAddr do not exist")
}
userPosts.refreshHomePosts()
return userPosts.homePosts.Size()
}
// Get the number of posts which GetHomePosts or GetJsonHomePosts will return.
// The result is something like "(12 int)".
// This returns the current count of the home posts (without need to pay gas). To include the
// latest followed posts, call RefreshHomePosts.
func GetHomePostsCount(userPostsAddr std.Address) int {
return GetHomePosts(userPostsAddr).Size()
}
// Get home posts for a user, which are the user's top-level posts plus all posts of all
// users being followed.
// The response is a map of postID -> *Post. The avl.Tree sorts by the post ID which is
// unique for every post and increases in time.
// If you just want the total count, use GetHomePostsCount.
// This returns the current state of the home posts (without need to pay gas). To include the
// latest followed posts, call RefreshHomePosts.
func GetHomePosts(userPostsAddr std.Address) *avl.Tree {
userPosts := getUserPosts(userPostsAddr)
if userPosts == nil {
panic("posts for userPostsAddr do not exist")
}
return &userPosts.homePosts
}
// Get home posts for a user (using GetHomePosts), which are the user's top-level posts plus all
// posts of all users being followed.
// Limit the response to posts from startIndex up to (not including) endIndex within the home posts.
// If you just want the total count, use GetHomePostsCount.
// The response is a JSON string.
// This returns the current state of the home posts (without need to pay gas). To include the
// latest posts, call RefreshHomePosts.
func GetJsonHomePosts(userPostsAddr std.Address, startIndex int, endIndex int) string {
allPosts := GetHomePosts(userPostsAddr)
postsJson := ""
for i := startIndex; i < endIndex && i < allPosts.Size(); i++ {
_, postI := allPosts.GetByIndex(i)
if postsJson != "" {
postsJson += ",\n "
}
postJson, err := postI.(*Post).MarshalJSON()
if err != nil {
panic("can't get post JSON")
}
postsJson += ufmt.Sprintf("{\"index\": %d, \"post\": %s}", int(i), string(postJson))
}
return ufmt.Sprintf("{\"n_posts\": %d, \"posts\": [\n %s]}", allPosts.Size(), postsJson)
}
// Update the caller to follow the user with followedAddr. See UserPosts.Follow.
func Follow(followedAddr std.Address) PostID {
caller := std.GetOrigCaller()
name := usernameOf(caller)
if name == "" {
panic("please register")
}
if followedAddr == caller {
panic("you can't follow yourself")
}
// A user can follow someone before doing any posts, so create the UserPosts if needed.
userPosts := getOrCreateUserPosts(caller, name)
return userPosts.Follow(followedAddr)
}
// Update the caller to unfollow the user with followedAddr. See UserPosts.Unfollow.
func Unfollow(followedAddr std.Address) {
caller := std.GetOrigCaller()
name := usernameOf(caller)
if name == "" {
panic("please register")
}
userPosts := getUserPosts(caller)
if userPosts == nil {
// We don't expect this, but just do nothing.
return
}
userPosts.Unfollow(followedAddr)
}
// Call users.GetUserByAddress and return the result as JSON, or "" if not found.
// (This is a temporary utility until gno.land supports returning structured data directly.)
func GetJsonUserByAddress(addr std.Address) string {
user := users.GetUserByAddress(addr)
if user == nil {
return ""
}
return marshalJsonUser(user)
}
// Call users.GetUserByName and return the result as JSON, or "" if not found.
// (This is a temporary utility until gno.land supports returning structured data directly.)
func GetJsonUserByName(name string) string {
user := users.GetUserByName(name)
if user == nil {
return ""
}
return marshalJsonUser(user)
}
// Get the UserPosts info for the user with the given address, including
// url, n_threads, n_followers and n_following. If the user address is not
// found, return "". The name of this function has "Info" because it just returns
// the number of items, not the items themselves. To get the items, see
// GetJsonFollowers, etc.
// The response is a JSON string.
func GetJsonUserPostsInfo(address std.Address) string {
userPosts := getUserPosts(address)
if userPosts == nil {
return ""
}
json, err := userPosts.MarshalJSON()
if err != nil {
panic("can't get UserPosts JSON")
}
return string(json)
}
// Get the UserPosts for the user with the given address, and return
// the list of followers. If the user address is not found, return "".
// Limit the response to entries from startIndex up to (not including) endIndex.
// The response is a JSON string.
func GetJsonFollowers(address std.Address, startIndex int, endIndex int) string {
userPosts := getUserPosts(address)
if userPosts == nil {
return ""
}
json := ufmt.Sprintf("{\"n_followers\": %d, \"followers\": [\n ", userPosts.followers.Size())
for i := startIndex; i < endIndex && i < userPosts.followers.Size(); i++ {
addr, _ := userPosts.followers.GetByIndex(i)
if i > startIndex {
json += ",\n "
}
json += ufmt.Sprintf(`{"address": "%s"}`, addr)
}
json += "]}"
return json
}
// Get the UserPosts for the user with the given address, and return
// the list of other users that this user is following.
// If the user address is not found, return "".
// Limit the response to entries from startIndex up to (not including) endIndex.
// The response is a JSON string.
func GetJsonFollowing(address std.Address, startIndex int, endIndex int) string {
userPosts := getUserPosts(address)
if userPosts == nil {
return ""
}
json := ufmt.Sprintf("{\"n_following\": %d, \"following\": [\n ", userPosts.following.Size())
for i := startIndex; i < endIndex && i < userPosts.following.Size(); i++ {
addr, infoI := userPosts.following.GetByIndex(i)
if i > startIndex {
json += ",\n "
}
startedAt, err := infoI.(*FollowingInfo).startedFollowingAt.MarshalJSON()
if err != nil {
panic("can't get startedFollowingAt JSON")
}
json += ufmt.Sprintf(`{"address": "%s", "started_following_at": %s}`,
addr, string(startedAt))
}
json += "]}"
return json
}
// TODO: This is a temporary copy. Remove this when they merge https://github.com/gnolang/gno/pull/1708.
func listKeysByPrefix(tree avl.Tree, prefix string, maxResults int) []string {
end := ""
n := len(prefix)
// To make the end of the search, increment the final character ASCII by one.
for n > 0 {
if ascii := int(prefix[n-1]); ascii < 0xff {
end = prefix[0:n-1] + string(ascii+1)
break
}
// The last character is 0xff. Try the previous character.
n--
}
result := []string{}
tree.Iterate(prefix, end, func(key string, value interface{}) bool {
result = append(result, key)
if len(result) >= maxResults {
return true
}
return false
})
return result
}
// Get a list of user names starting from the given prefix. Limit the
// number of results to maxResults.
func ListUsersByPrefix(prefix string, maxResults int) []string {
return listKeysByPrefix(gUserAddressByName, prefix, maxResults)
}
// Get a list of user names starting from the given prefix. Limit the
// number of results to maxResults.
// The response is a JSON string.
func ListJsonUsersByPrefix(prefix string, maxResults int) string {
names := ListUsersByPrefix(prefix, maxResults)
json := "["
for i, name := range names {
if i > 0 {
json += ", "
}
json += strconv.Quote(name)
}
json += "]"
return json
}