Search Apps Documentation Source Content File Folder Download Copy Actions Download

render.gno

2.62 Kb · 99 lines
 1package social
 2
 3import (
 4	"strconv"
 5	"strings"
 6
 7	"gno.land/r/sys/users"
 8)
 9
10// resolveAddr looks up an address by registered name first, then falls back
11// to treating the input as a raw address. This allows unregistered users to
12// be found by their address string.
13func resolveAddr(nameOrAddr string) address {
14	user, _ := users.ResolveName(nameOrAddr)
15	if user != nil {
16		return user.Addr()
17	}
18	return address(nameOrAddr)
19}
20
21func Render(path string) string {
22	if path == "" {
23		str := "Welcome to dSocial!\n\n"
24
25		// List the users who have posted. gUserAddressByName is already sorted by name.
26		gUserAddressByName.Iterate("", "", func(name string, value interface{}) bool {
27			str += " * [@" + name + "](" + gRealmPath + ":" + name + ")" + "\n"
28			return false
29		})
30
31		return str
32	}
33
34	parts := strings.Split(path, "/")
35	if len(parts) == 1 {
36		// /r/berty/social:USER_NAME_OR_ADDR
37		userAddr := resolveAddr(path)
38		userPosts := getUserPosts(userAddr)
39		if userPosts == nil {
40			return "No posts by: " + path
41		}
42
43		return userPosts.RenderUserPosts(false)
44	} else if len(parts) == 2 {
45		userAddr := resolveAddr(parts[0])
46		userPosts := getUserPosts(userAddr)
47		if userPosts == nil {
48			return "No posts by: " + parts[0]
49		}
50
51		if parts[1] == "home" {
52			// /r/berty/social:USER_NAME_OR_ADDR/home
53			return userPosts.RenderUserPosts(true)
54		} else if parts[1] == "followers" {
55			// /r/berty/social:USER_NAME_OR_ADDR/followers
56			return userPosts.RenderFollowers()
57		} else if parts[1] == "following" {
58			// /r/berty/social:USER_NAME_OR_ADDR/following
59			return userPosts.RenderFollowing()
60		} else {
61			// /r/berty/social:USER_NAME_OR_ADDR/THREAD_ID
62			pid, err := strconv.Atoi(parts[1])
63			if err != nil {
64				return "invalid thread id: " + parts[1]
65			}
66			thread := userPosts.GetThread(PostID(pid))
67			if thread == nil {
68				return "thread does not exist with id: " + parts[1]
69			}
70			return thread.RenderPost("", 5)
71		}
72	} else if len(parts) == 3 {
73		// /r/berty/social:USER_NAME_OR_ADDR/THREAD_ID/REPLY_ID
74		userAddr := resolveAddr(parts[0])
75		userPosts := getUserPosts(userAddr)
76		if userPosts == nil {
77			return "No posts by: " + parts[0]
78		}
79		pid, err := strconv.Atoi(parts[1])
80		if err != nil {
81			return "invalid thread id: " + parts[1]
82		}
83		thread := userPosts.GetThread(PostID(pid))
84		if thread == nil {
85			return "thread does not exist with id: " + parts[1]
86		}
87		rid, err := strconv.Atoi(parts[2])
88		if err != nil {
89			return "invalid reply id: " + parts[2]
90		}
91		reply := thread.GetReply(PostID(rid))
92		if reply == nil {
93			return "reply does not exist with id: " + parts[2]
94		}
95		return reply.RenderInner()
96	} else {
97		return "unrecognized path: " + path
98	}
99}