forked from picosh/pico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
394 lines (334 loc) · 10 KB
/
api.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
package pastes
import (
"fmt"
"html/template"
"net/http"
"net/url"
"os"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/picosh/pico/db"
"github.com/picosh/pico/db/postgres"
"github.com/picosh/pico/shared"
"github.com/picosh/pico/shared/storage"
)
type PageData struct {
Site shared.SitePageData
}
type PostItemData struct {
URL template.URL
BlogURL template.URL
Username string
Title string
Description string
PublishAtISO string
PublishAt string
UpdatedAtISO string
UpdatedTimeAgo string
Padding string
}
type BlogPageData struct {
Site shared.SitePageData
PageTitle string
URL template.URL
RSSURL template.URL
Username string
Header *HeaderTxt
Posts []PostItemData
}
type PostPageData struct {
Site shared.SitePageData
PageTitle string
URL template.URL
RawURL template.URL
BlogURL template.URL
Title string
Description string
Username string
BlogName string
Contents template.HTML
PublishAtISO string
PublishAt string
ExpiresAt string
}
type TransparencyPageData struct {
Site shared.SitePageData
Analytics *db.Analytics
}
type Link struct {
URL string
Text string
}
type HeaderTxt struct {
Title string
Bio string
Nav []Link
HasLinks bool
}
func blogHandler(w http.ResponseWriter, r *http.Request) {
username := shared.GetUsernameFromRequest(r)
dbpool := shared.GetDB(r)
logger := shared.GetLogger(r)
cfg := shared.GetCfg(r)
user, err := dbpool.FindUserForName(username)
if err != nil {
logger.Infof("blog not found: %s", username)
http.Error(w, "blog not found", http.StatusNotFound)
return
}
pager, err := dbpool.FindPostsForUser(&db.Pager{Num: 1000, Page: 0}, user.ID, cfg.Space)
posts := pager.Data
if err != nil {
logger.Error(err)
http.Error(w, "could not fetch posts for blog", http.StatusInternalServerError)
return
}
ts, err := shared.RenderTemplate(cfg, []string{
cfg.StaticPath("html/blog.page.tmpl"),
})
if err != nil {
logger.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
headerTxt := &HeaderTxt{
Title: GetBlogName(username),
Bio: "",
}
curl := shared.CreateURLFromRequest(cfg, r)
postCollection := make([]PostItemData, 0, len(posts))
for _, post := range posts {
p := PostItemData{
URL: template.URL(cfg.FullPostURL(curl, post.Username, post.Slug)),
BlogURL: template.URL(cfg.FullBlogURL(curl, post.Username)),
Title: post.Filename,
PublishAt: post.PublishAt.Format("02 Jan, 2006"),
PublishAtISO: post.PublishAt.Format(time.RFC3339),
UpdatedTimeAgo: shared.TimeAgo(post.UpdatedAt),
UpdatedAtISO: post.UpdatedAt.Format(time.RFC3339),
}
postCollection = append(postCollection, p)
}
data := BlogPageData{
Site: *cfg.GetSiteData(),
PageTitle: headerTxt.Title,
URL: template.URL(cfg.FullBlogURL(curl, username)),
RSSURL: template.URL(cfg.RssBlogURL(curl, username, "")),
Header: headerTxt,
Username: username,
Posts: postCollection,
}
err = ts.Execute(w, data)
if err != nil {
logger.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func GetPostTitle(post *db.Post) string {
if post.Description == "" {
return post.Title
}
return fmt.Sprintf("%s: %s", post.Title, post.Description)
}
func GetBlogName(username string) string {
return fmt.Sprintf("%s's pastes", username)
}
func postHandler(w http.ResponseWriter, r *http.Request) {
username := shared.GetUsernameFromRequest(r)
subdomain := shared.GetSubdomain(r)
cfg := shared.GetCfg(r)
var slug string
if !cfg.IsSubdomains() || subdomain == "" {
slug, _ = url.PathUnescape(shared.GetField(r, 1))
} else {
slug, _ = url.PathUnescape(shared.GetField(r, 0))
}
dbpool := shared.GetDB(r)
logger := shared.GetLogger(r)
user, err := dbpool.FindUserForName(username)
if err != nil {
logger.Infof("blog not found: %s", username)
http.Error(w, "blog not found", http.StatusNotFound)
return
}
blogName := GetBlogName(username)
var data PostPageData
post, err := dbpool.FindPostWithSlug(slug, user.ID, cfg.Space)
if err == nil {
parsedText, err := ParseText(post.Filename, post.Text)
if err != nil {
logger.Error(err)
}
expiresAt := "never"
if post.ExpiresAt != nil {
expiresAt = post.ExpiresAt.Format("02 Jan, 2006")
}
data = PostPageData{
Site: *cfg.GetSiteData(),
PageTitle: post.Filename,
URL: template.URL(cfg.PostURL(post.Username, post.Slug)),
RawURL: template.URL(cfg.RawPostURL(post.Username, post.Slug)),
BlogURL: template.URL(cfg.BlogURL(username)),
Description: post.Description,
Title: post.Filename,
PublishAt: post.PublishAt.Format("02 Jan, 2006"),
PublishAtISO: post.PublishAt.Format(time.RFC3339),
Username: username,
BlogName: blogName,
Contents: template.HTML(parsedText),
ExpiresAt: expiresAt,
}
} else {
logger.Infof("post not found %s/%s", username, slug)
data = PostPageData{
Site: *cfg.GetSiteData(),
PageTitle: "Paste not found",
Description: "Paste not found",
Title: "Paste not found",
BlogURL: template.URL(cfg.BlogURL(username)),
PublishAt: time.Now().Format("02 Jan, 2006"),
PublishAtISO: time.Now().Format(time.RFC3339),
Username: username,
BlogName: blogName,
Contents: "oops! we can't seem to find this post.",
ExpiresAt: "",
}
}
ts, err := shared.RenderTemplate(cfg, []string{
cfg.StaticPath("html/post.page.tmpl"),
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
err = ts.Execute(w, data)
if err != nil {
logger.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func postHandlerRaw(w http.ResponseWriter, r *http.Request) {
username := shared.GetUsernameFromRequest(r)
subdomain := shared.GetSubdomain(r)
cfg := shared.GetCfg(r)
var slug string
if !cfg.IsSubdomains() || subdomain == "" {
slug, _ = url.PathUnescape(shared.GetField(r, 1))
} else {
slug, _ = url.PathUnescape(shared.GetField(r, 0))
}
dbpool := shared.GetDB(r)
logger := shared.GetLogger(r)
user, err := dbpool.FindUserForName(username)
if err != nil {
logger.Infof("blog not found: %s", username)
http.Error(w, "blog not found", http.StatusNotFound)
return
}
post, err := dbpool.FindPostWithSlug(slug, user.ID, cfg.Space)
if err != nil {
logger.Infof("post not found %s/%s", username, slug)
http.Error(w, "post not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/plain")
_, err = w.Write([]byte(post.Text))
if err != nil {
logger.Error(err)
}
}
func serveFile(file string, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logger := shared.GetLogger(r)
cfg := shared.GetCfg(r)
contents, err := os.ReadFile(cfg.StaticPath(fmt.Sprintf("public/%s", file)))
if err != nil {
logger.Error(err)
http.Error(w, "file not found", 404)
}
w.Header().Add("Content-Type", contentType)
_, err = w.Write(contents)
if err != nil {
logger.Error(err)
http.Error(w, "server error", 500)
}
}
}
func createStaticRoutes() []shared.Route {
return []shared.Route{
shared.NewRoute("GET", "/main.css", serveFile("main.css", "text/css")),
shared.NewRoute("GET", "/custom.css", serveFile("custom.css", "text/css")),
shared.NewRoute("GET", "/syntax.css", serveFile("syntax.css", "text/css")),
shared.NewRoute("GET", "/card.png", serveFile("card.png", "image/png")),
shared.NewRoute("GET", "/favicon-16x16.png", serveFile("favicon-16x16.png", "image/png")),
shared.NewRoute("GET", "/favicon-32x32.png", serveFile("favicon-32x32.png", "image/png")),
shared.NewRoute("GET", "/apple-touch-icon.png", serveFile("apple-touch-icon.png", "image/png")),
shared.NewRoute("GET", "/favicon.ico", serveFile("favicon.ico", "image/x-icon")),
shared.NewRoute("GET", "/robots.txt", serveFile("robots.txt", "text/plain")),
}
}
func createMainRoutes(staticRoutes []shared.Route) []shared.Route {
routes := []shared.Route{
shared.NewRoute("GET", "/", shared.CreatePageHandler("html/marketing.page.tmpl")),
shared.NewRoute("GET", "/check", shared.CheckHandler),
}
routes = append(
routes,
staticRoutes...,
)
routes = append(
routes,
shared.NewRoute("GET", "/([^/]+)", blogHandler),
shared.NewRoute("GET", "/([^/]+)/([^/]+)", postHandler),
shared.NewRoute("GET", "/([^/]+)/([^/]+)/raw", postHandlerRaw),
shared.NewRoute("GET", "/raw/([^/]+)/([^/]+)", postHandlerRaw),
)
return routes
}
func createSubdomainRoutes(staticRoutes []shared.Route) []shared.Route {
routes := []shared.Route{
shared.NewRoute("GET", "/", blogHandler),
}
routes = append(
routes,
staticRoutes...,
)
routes = append(
routes,
shared.NewRoute("GET", "/([^/]+)", postHandler),
shared.NewRoute("GET", "/([^/]+)/raw", postHandlerRaw),
shared.NewRoute("GET", "/raw/([^/]+)", postHandlerRaw),
)
return routes
}
func StartApiServer() {
cfg := NewConfigSite()
db := postgres.NewDB(cfg.DbURL, cfg.Logger)
defer db.Close()
logger := cfg.Logger
var st storage.ObjectStorage
var err error
if cfg.MinioURL == "" {
st, err = storage.NewStorageFS(cfg.StorageDir)
} else {
st, err = storage.NewStorageMinio(cfg.MinioURL, cfg.MinioUser, cfg.MinioPass)
}
cache := gocache.New(2*time.Minute, 5*time.Minute)
if err != nil {
logger.Fatal(err)
}
go CronDeleteExpiredPosts(cfg, db)
staticRoutes := createStaticRoutes()
if cfg.Debug {
staticRoutes = shared.CreatePProfRoutes(staticRoutes)
}
mainRoutes := createMainRoutes(staticRoutes)
subdomainRoutes := createSubdomainRoutes(staticRoutes)
handler := shared.CreateServe(mainRoutes, subdomainRoutes, cfg, db, st, logger, cache)
router := http.HandlerFunc(handler)
portStr := fmt.Sprintf(":%s", cfg.Port)
logger.Infof("Starting server on port %s", cfg.Port)
logger.Infof("Subdomains enabled: %t", cfg.SubdomainsEnabled)
logger.Infof("Domain: %s", cfg.Domain)
logger.Infof("Email: %s", cfg.Email)
logger.Fatal(http.ListenAndServe(portStr, router))
}