GoBlog/posts.go

297 lines
7.8 KiB
Go
Raw Normal View History

2020-07-28 19:17:07 +00:00
package main
import (
"errors"
2020-08-05 17:54:04 +00:00
"fmt"
2020-10-18 09:54:29 +00:00
"html/template"
2020-07-28 19:17:07 +00:00
"net/http"
"reflect"
2020-08-05 17:54:04 +00:00
"strconv"
2020-09-24 15:13:03 +00:00
"strings"
2020-10-06 17:07:48 +00:00
2021-03-03 17:19:55 +00:00
"github.com/go-chi/chi/v5"
2021-03-08 17:14:52 +00:00
"github.com/microcosm-cc/bluemonday"
2021-03-10 17:47:56 +00:00
servertiming "github.com/mitchellh/go-server-timing"
2020-10-06 17:07:48 +00:00
"github.com/vcraescu/go-paginator"
2020-07-28 19:17:07 +00:00
)
2020-07-30 19:18:13 +00:00
var errPostNotFound = errors.New("post not found")
2020-07-28 19:17:07 +00:00
2020-10-15 15:32:46 +00:00
type post struct {
2020-08-31 19:12:43 +00:00
Path string `json:"path"`
Content string `json:"content"`
Published string `json:"published"`
Updated string `json:"updated"`
Parameters map[string][]string `json:"parameters"`
2020-10-06 17:07:48 +00:00
Blog string `json:"blog"`
Section string `json:"section"`
2021-01-15 20:56:46 +00:00
Status postStatus `json:"status"`
2020-10-06 17:07:48 +00:00
// Not persisted
Slug string `json:"slug"`
rendered template.HTML
absoluteRendered template.HTML
2020-07-28 19:17:07 +00:00
}
2021-01-15 20:56:46 +00:00
type postStatus string
const (
statusNil postStatus = ""
statusPublished postStatus = "published"
statusDraft postStatus = "draft"
)
2020-07-29 14:41:36 +00:00
func servePost(w http.ResponseWriter, r *http.Request) {
2021-03-10 17:47:56 +00:00
t := servertiming.FromContext(r.Context()).NewMetric("gp").Start()
p, err := getPost(r.URL.Path)
2021-03-10 17:47:56 +00:00
t.Stop()
2020-07-30 19:18:13 +00:00
if err == errPostNotFound {
serve404(w, r)
2020-07-29 14:41:36 +00:00
return
2020-07-28 19:17:07 +00:00
} else if err != nil {
2020-12-24 09:09:34 +00:00
serveError(w, r, err.Error(), http.StatusInternalServerError)
2020-07-29 14:41:36 +00:00
return
2020-07-28 19:17:07 +00:00
}
2021-02-24 12:16:33 +00:00
if asRequest, ok := r.Context().Value(asRequestKey).(bool); ok && asRequest {
p.serveActivityStreams(w)
return
}
2020-11-01 17:37:21 +00:00
canonical := p.firstParameter("original")
if canonical == "" {
canonical = p.fullURL()
2020-11-01 17:37:21 +00:00
}
2020-12-23 15:53:10 +00:00
template := templatePost
if p.Path == appConfig.Blogs[p.Blog].Path {
template = templateStaticHome
}
2020-12-22 21:15:29 +00:00
w.Header().Add("Link", fmt.Sprintf("<%s>; rel=shortlink", p.shortURL()))
2021-02-20 22:35:16 +00:00
render(w, r, template, &renderData{
2021-01-17 11:53:07 +00:00
BlogString: p.Blog,
2020-11-01 17:37:21 +00:00
Canonical: canonical,
2020-10-15 15:32:46 +00:00
Data: p,
2020-10-12 16:47:23 +00:00
})
2020-07-28 19:17:07 +00:00
}
func redirectToRandomPost(blog string) func(http.ResponseWriter, *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
randomPath, err := getRandomPostPath(blog)
if err != nil {
serveError(rw, r, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(rw, r, randomPath, http.StatusFound)
}
}
type postPaginationAdapter struct {
2020-10-19 18:25:30 +00:00
config *postsRequestConfig
2020-11-17 16:38:17 +00:00
nums int64
}
2020-11-17 16:38:17 +00:00
func (p *postPaginationAdapter) Nums() (int64, error) {
if p.nums == 0 {
2020-11-17 16:38:17 +00:00
nums, _ := countPosts(p.config)
p.nums = int64(nums)
}
2020-11-17 16:38:17 +00:00
return p.nums, nil
}
func (p *postPaginationAdapter) Slice(offset, length int, data interface{}) error {
2020-08-31 19:12:43 +00:00
modifiedConfig := *p.config
modifiedConfig.offset = offset
modifiedConfig.limit = length
2020-10-19 18:25:30 +00:00
posts, err := getPosts(&modifiedConfig)
reflect.ValueOf(data).Elem().Set(reflect.ValueOf(&posts).Elem())
return err
}
2020-10-15 17:50:34 +00:00
func serveHome(blog string, path string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
2021-02-24 12:16:33 +00:00
if asRequest, ok := r.Context().Value(asRequestKey).(bool); ok && asRequest {
2020-12-24 09:09:34 +00:00
appConfig.Blogs[blog].serveActivityStreams(blog, w, r)
return
}
serveIndex(&indexConfig{
blog: blog,
path: path,
})(w, r)
}
2020-08-25 18:55:32 +00:00
}
2020-10-15 17:50:34 +00:00
func serveSection(blog string, path string, section *section) func(w http.ResponseWriter, r *http.Request) {
2020-09-21 16:03:05 +00:00
return serveIndex(&indexConfig{
2020-10-06 17:07:48 +00:00
blog: blog,
2020-09-21 16:03:05 +00:00
path: path,
section: section,
})
2020-08-31 19:12:43 +00:00
}
2020-10-15 17:50:34 +00:00
func serveTaxonomyValue(blog string, path string, tax *taxonomy, value string) func(w http.ResponseWriter, r *http.Request) {
2020-09-21 16:03:05 +00:00
return serveIndex(&indexConfig{
2020-10-06 17:07:48 +00:00
blog: blog,
2020-09-21 16:03:05 +00:00
path: path,
tax: tax,
taxValue: value,
})
2020-08-31 19:12:43 +00:00
}
2020-11-10 15:48:59 +00:00
func servePhotos(blog string, path string) func(w http.ResponseWriter, r *http.Request) {
2020-09-21 16:03:05 +00:00
return serveIndex(&indexConfig{
blog: blog,
path: path,
parameter: appConfig.Blogs[blog].Photos.Parameter,
title: appConfig.Blogs[blog].Photos.Title,
description: appConfig.Blogs[blog].Photos.Description,
summaryTemplate: templatePhotosSummary,
2020-09-21 16:03:05 +00:00
})
}
2020-11-15 10:34:48 +00:00
func serveSearchResults(blog string, path string) func(w http.ResponseWriter, r *http.Request) {
return serveIndex(&indexConfig{
blog: blog,
path: path,
2020-11-15 10:34:48 +00:00
})
}
func serveDate(blog string, path string, year, month, day int) func(w http.ResponseWriter, r *http.Request) {
var title strings.Builder
if year != 0 {
title.WriteString(fmt.Sprintf("%0004d", year))
} else {
title.WriteString("XXXX")
}
if month != 0 {
title.WriteString(fmt.Sprintf("-%02d", month))
} else if day != 0 {
title.WriteString("-XX")
}
if day != 0 {
title.WriteString(fmt.Sprintf("-%02d", day))
2020-12-13 14:16:47 +00:00
}
return serveIndex(&indexConfig{
blog: blog,
path: path,
year: year,
month: month,
day: day,
title: title.String(),
2020-12-13 14:16:47 +00:00
})
}
2020-09-21 16:03:05 +00:00
type indexConfig struct {
blog string
path string
section *section
tax *taxonomy
taxValue string
parameter string
year, month, day int
title string
description string
summaryTemplate string
2020-09-21 16:03:05 +00:00
}
func serveIndex(ic *indexConfig) func(w http.ResponseWriter, r *http.Request) {
2020-08-05 17:54:04 +00:00
return func(w http.ResponseWriter, r *http.Request) {
2020-11-15 10:34:48 +00:00
search := chi.URLParam(r, "search")
if search != "" {
search = searchDecode(search)
}
2020-08-05 17:54:04 +00:00
pageNoString := chi.URLParam(r, "page")
pageNo, _ := strconv.Atoi(pageNoString)
2020-10-06 17:07:48 +00:00
var sections []string
2020-09-21 16:03:05 +00:00
if ic.section != nil {
2020-10-06 17:07:48 +00:00
sections = []string{ic.section.Name}
} else {
for sectionKey := range appConfig.Blogs[ic.blog].Sections {
sections = append(sections, sectionKey)
}
2020-08-25 18:55:32 +00:00
}
2020-10-19 18:25:30 +00:00
p := paginator.New(&postPaginationAdapter{config: &postsRequestConfig{
2020-12-13 14:16:47 +00:00
blog: ic.blog,
sections: sections,
taxonomy: ic.tax,
taxonomyValue: ic.taxValue,
parameter: ic.parameter,
search: search,
publishedYear: ic.year,
publishedMonth: ic.month,
publishedDay: ic.day,
2021-01-15 20:56:46 +00:00
status: statusPublished,
2020-10-06 17:07:48 +00:00
}}, appConfig.Blogs[ic.blog].Pagination)
p.SetPage(pageNo)
2020-10-15 15:32:46 +00:00
var posts []*post
2021-03-10 17:47:56 +00:00
t := servertiming.FromContext(r.Context()).NewMetric("gp").Start()
err := p.Results(&posts)
2021-03-10 17:47:56 +00:00
t.Stop()
2020-08-05 17:54:04 +00:00
if err != nil {
2020-12-24 09:09:34 +00:00
serveError(w, r, err.Error(), http.StatusInternalServerError)
2020-08-05 17:54:04 +00:00
return
}
// Meta
title := ic.title
description := ic.description
2020-09-21 16:03:05 +00:00
if ic.tax != nil {
title = fmt.Sprintf("%s: %s", ic.tax.Title, ic.taxValue)
} else if ic.section != nil {
title = ic.section.Title
description = ic.section.Description
2020-11-15 10:34:48 +00:00
} else if search != "" {
title = fmt.Sprintf("%s: %s", appConfig.Blogs[ic.blog].Search.Title, search)
}
2021-03-08 17:14:52 +00:00
// Clean title
title = bluemonday.StrictPolicy().Sanitize(title)
// Check if feed
2020-10-15 17:50:34 +00:00
if ft := feedType(chi.URLParam(r, "feed")); ft != noFeed {
generateFeed(ic.blog, ft, w, r, posts, title, description)
2020-09-02 15:48:37 +00:00
return
}
2020-11-15 11:46:24 +00:00
// Path
path := ic.path
if strings.Contains(path, searchPlaceholder) {
path = strings.ReplaceAll(path, searchPlaceholder, searchEncode(search))
}
// Navigation
2020-11-17 16:38:17 +00:00
var hasPrev, hasNext bool
var prevPage, nextPage int
var prevPath, nextPath string
hasPrev, _ = p.HasPrev()
if hasPrev {
prevPage, _ = p.PrevPage()
} else {
prevPage, _ = p.Page()
}
2020-11-15 11:46:24 +00:00
if prevPage < 2 {
prevPath = path
2020-11-17 16:38:17 +00:00
} else {
prevPath = fmt.Sprintf("%s/page/%d", path, prevPage)
2020-11-15 11:46:24 +00:00
}
2020-11-17 16:38:17 +00:00
hasNext, _ = p.HasNext()
if hasNext {
nextPage, _ = p.NextPage()
} else {
nextPage, _ = p.Page()
}
2020-11-17 16:38:17 +00:00
nextPath = fmt.Sprintf("%s/page/%d", path, nextPage)
summaryTemplate := ic.summaryTemplate
if summaryTemplate == "" {
summaryTemplate = templateSummary
2020-09-21 16:03:05 +00:00
}
2021-02-20 22:35:16 +00:00
render(w, r, templateIndex, &renderData{
2021-01-17 11:53:07 +00:00
BlogString: ic.blog,
2020-11-17 13:52:17 +00:00
Canonical: appConfig.Server.PublicAddress + path,
Data: map[string]interface{}{
"Title": title,
"Description": description,
"Posts": posts,
2020-11-17 16:38:17 +00:00
"HasPrev": hasPrev,
"HasNext": hasNext,
2020-11-17 16:43:30 +00:00
"First": slashIfEmpty(path),
"Prev": slashIfEmpty(prevPath),
"Next": slashIfEmpty(nextPath),
"SummaryTemplate": summaryTemplate,
2020-10-12 16:47:23 +00:00
},
2020-08-05 17:54:04 +00:00
})
2020-08-05 17:14:10 +00:00
}
}