1// Microblog is a website with shortform posts from users.
2// The API is simple - "AddPost" takes markdown and
3// adds it to the users site.
4// The microblog location is determined by the user address
5// /r/demo/microblog:<YOUR-ADDRESS>
6package microblog
7
8import (
9 "std"
10 "strings"
11
12 "gno.land/p/demo/microblog"
13 "gno.land/p/demo/ufmt"
14 "gno.land/r/demo/users"
15)
16
17var (
18 title = "gno-based microblog"
19 prefix = "/r/demo/microblog:"
20 m *microblog.Microblog
21)
22
23func init() {
24 m = microblog.NewMicroblog(title, prefix)
25}
26
27func renderHome() string {
28 output := ufmt.Sprintf("# %s\n\n", m.Title)
29 output += "# pages\n\n"
30
31 for _, page := range m.GetPages() {
32 if u := users.GetUserByAddress(page.Author); u != nil {
33 output += ufmt.Sprintf("- [%s (%s)](%s%s)\n", u.Name, page.Author.String(), m.Prefix, page.Author.String())
34 } else {
35 output += ufmt.Sprintf("- [%s](%s%s)\n", page.Author.String(), m.Prefix, page.Author.String())
36 }
37 }
38
39 return output
40}
41
42func renderUser(user string) string {
43 silo, found := m.Pages.Get(user)
44 if !found {
45 return "404" // StatusNotFound
46 }
47
48 return PageToString((silo.(*microblog.Page)))
49}
50
51func Render(path string) string {
52 parts := strings.Split(path, "/")
53
54 isHome := path == ""
55 isUser := len(parts) == 1
56
57 switch {
58 case isHome:
59 return renderHome()
60
61 case isUser:
62 return renderUser(parts[0])
63 }
64
65 return "404" // StatusNotFound
66}
67
68func PageToString(p *microblog.Page) string {
69 o := ""
70 if u := users.GetUserByAddress(p.Author); u != nil {
71 o += ufmt.Sprintf("# [%s](/r/demo/users:%s)\n\n", u, u)
72 o += ufmt.Sprintf("%s\n\n", u.Profile)
73 }
74 o += ufmt.Sprintf("## [%s](/r/demo/microblog:%s)\n\n", p.Author, p.Author)
75
76 o += ufmt.Sprintf("joined %s, last updated %s\n\n", p.CreatedAt.Format("2006-02-01"), p.LastPosted.Format("2006-02-01"))
77 o += "## feed\n\n"
78 for _, u := range p.GetPosts() {
79 o += u.String() + "\n\n"
80 }
81 return o
82}
83
84// NewPost takes a single argument (post markdown) and
85// adds a post to the address of the caller.
86func NewPost(text string) string {
87 if err := m.NewPost(text); err != nil {
88 return "unable to add new post"
89 }
90 return "added new post"
91}
92
93func Register(name, profile string) string {
94 caller := std.GetOrigCaller() // main
95 users.Register(caller, name, profile)
96 return "OK"
97}
microblog.gno
2.22 Kb ยท 97 lines