/
main.go
216 lines (187 loc) · 5.19 KB
/
main.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
package main
import (
"embed"
"fmt"
"io"
"math"
"net/url"
"strconv"
"strings"
"text/template"
"github.com/pitr/geddit/db"
"github.com/pitr/gig"
)
//go:embed tmpl/*.gmi
var tmpls embed.FS
type Template struct {
t *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, _ gig.Context) error {
return t.t.ExecuteTemplate(w, fmt.Sprintf("%s.gmi", name), data)
}
func main() {
err := db.Initialize()
if err != nil {
panic(err)
}
g := gig.Default()
g.Use(func(next gig.HandlerFunc) gig.HandlerFunc {
return func(c gig.Context) (err error) {
err = next(c)
if c.Response().Status < 30 && c.Path() != "/stats" {
_ = db.CountPageview()
}
return
}
})
g.Renderer = &Template{t: template.Must(template.ParseFS(tmpls, "tmpl/*.gmi"))}
g.Handle("/", handleHome)
g.Handle("/post", handlePost)
g.Handle("/s/:id", handleShow)
g.Handle("/c/:id", handlePostComment)
g.Handle("/stats", handleStats, gig.CertAuth(gig.ValidateHasCertificate))
panic(g.Run("/meta/credentials/letsencrypt/current/fullchain.pem", "/meta/credentials/letsencrypt/current/privkey.pem"))
}
func handleHome(c gig.Context) error {
var (
page = 1
nextPage = 0
err error
pageparam = c.URL().Query().Get("page")
)
if pageparam != "" {
page, err = strconv.Atoi(pageparam)
if err != nil {
return c.NoContent(gig.StatusBadRequest, "Invalid path")
}
if page < 1 || page > 100 {
return c.NoContent(gig.StatusBadRequest, "Invalid path")
}
}
posts, err := db.Latest(page - 1)
if err != nil {
return c.NoContent(gig.StatusServerUnavailable, "Could not load main page")
}
if len(posts) == db.LatestMax {
nextPage = page + 1
}
return c.Render("index", struct {
Posts []db.Post
Page int
NextPage int
}{
Posts: posts,
Page: page,
NextPage: nextPage,
})
}
func handlePost(c gig.Context) error {
q := c.URL().RawQuery
if len(q) == 0 {
return c.NoContent(gig.StatusInput, "Enter url and title separated by space")
}
post, err := url.QueryUnescape(q)
if err != nil {
return c.NoContent(gig.StatusInput, "Could not parse your post, enter url and title separated by space")
}
post = strings.TrimSpace(post)
if len(post) < 5 {
return c.NoContent(gig.StatusInput, "Your post is too short, enter url and title separated by space")
}
postChunks := strings.SplitN(post, " ", 2)
var url, msg string
switch len(postChunks) {
case 0:
return c.NoContent(gig.StatusInput, "Cannot submit empty post, enter url and title separated by space")
case 1:
return c.NoContent(gig.StatusInput, "Cannot submit url without title, enter url and title separated by space")
case 2:
url = strings.TrimSpace(postChunks[0])
msg = strings.TrimSpace(postChunks[1])
default:
panic("Impossible error!")
}
if !strings.Contains(url, ".") {
return c.NoContent(gig.StatusInput, "First part does not seem to be a url, enter url and title separated by space")
}
if !strings.Contains(url, "://") {
url = "gemini://" + url
}
if !strings.HasPrefix(url, "gemini://") {
return c.NoContent(gig.StatusInput, "Only Gemini URLs are allowed, sorry")
}
postId, err := db.CreatePost(url, msg)
if err != nil {
return c.NoContent(gig.StatusServerUnavailable, "Could not save your post, please try again")
}
return c.NoContent(gig.StatusRedirectTemporary, fmt.Sprintf("/s/%d", postId))
}
func handleShow(c gig.Context) error {
postId, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.NoContent(gig.StatusBadRequest, "Invalid path")
}
post, err := db.GetPost(uint(postId))
if err != nil {
fmt.Printf("could not show a post: %s", err)
return c.NoContent(gig.StatusNotFound, fmt.Sprintf("Could not find post id '%d'", postId))
}
return c.Render("show", post)
}
func handlePostComment(c gig.Context) error {
if len(c.URL().RawQuery) == 0 {
return c.NoContent(gig.StatusInput, "Enter comment")
}
postId, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.NoContent(gig.StatusBadRequest, "Invalid path")
}
comment, err := url.QueryUnescape(c.URL().RawQuery)
if err != nil {
return c.NoContent(gig.StatusInput, "Could not parse comment, try again")
}
comment = strings.TrimSpace(comment)
if len(comment) < 3 {
return c.NoContent(gig.StatusInput, "Your comment is too short, please check it")
}
err = db.CreateComment(uint(postId), comment)
if err != nil {
return c.NoContent(gig.StatusServerUnavailable, "Could not save comment, please try again")
}
return c.NoContent(gig.StatusRedirectTemporary, fmt.Sprintf("/s/%d", postId))
}
var levels = []rune("▁▂▃▄▅▆▇█")
func handleStats(c gig.Context) error {
result, err := db.GetPageviewStats()
if err != nil {
return err
}
min := 0
max := 0
if len(result) > 0 {
min = result[0].Count
}
for _, r := range result {
if r.Count < min {
min = r.Count
}
if r.Count > max {
max = r.Count
}
}
if max == min {
max = min + 1
}
spark := make([]rune, len(result))
for i, r := range result {
j := int(math.Floor(float64(len(levels)-1.) * float64(r.Count-min) / float64(max-min)))
spark[len(result)-1-i] = levels[j]
}
return c.Render("stats", struct {
Result []db.Pageview
Sparkline string
}{
Result: result[:100],
Sparkline: string(spark),
})
}