summaryrefslogtreecommitdiff
path: root/internal/router/handlers/api-v1-blog-search.go
blob: c48b40a4e0a589e262b9926b4cc35e15a40b0eec (plain)
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
package handlers

import (
	"cmp"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/url"
	"regexp"
	"slices"
	"strings"
	"time"

	"github.com/SayaAndy/saya-today-web/internal/blog"
	"github.com/SayaAndy/saya-today-web/internal/router"
	"github.com/gofiber/fiber/v2"
)

type BlogSearchHandler struct {
	router.BasicHandler
	getTagsQuery *regexp.Regexp
}

func init() {
	router.Routes = append(router.Routes, &BlogSearchHandler{getTagsQuery: regexp.MustCompile(`tags\[\]=([\w]+)`)})
}

func (r *BlogSearchHandler) Filter() (method string, path string) {
	return "GET", "/api/v1/blog-search"
}

func (r *BlogSearchHandler) IsTemplated() bool {
	return false
}

func (r *BlogSearchHandler) TemplatesToInject() []string {
	return []string{"views/partials/catalogue-blog-cards.html", "views/partials/catalogue-blog-card-tags.html"}
}

func (r *BlogSearchHandler) ToCache() router.CacheSetting {
	return router.Disabled
}

func (r *BlogSearchHandler) ToValidateLang() router.LangSetting {
	return router.InForm
}

func (r *BlogSearchHandler) RateLimiter() *fiber.Handler {
	return &router.RateLimiterLoose
}

func (r *BlogSearchHandler) Render(c *fiber.Ctx, supplements *router.Supplements, lang string, templateMap fiber.Map) (statusCode int, err error) {
	sort := c.Query("sort")
	tz := c.Query("tz")
	medley := c.Query("medley")
	referer := c.Get("Referer")
	refererParts := strings.Split(referer, "/")
	refererPage := ""
	if len(refererParts) >= 1 {
		refererPage = refererParts[len(refererParts)-1]
	}
	hideTags := c.QueryBool("hideTags", false)
	hidePublishedTime := c.QueryBool("hidePublishedTime", false)

	loc, err := time.LoadLocation(tz)
	if err != nil {
		loc = time.UTC
		slog.Warn("unable to parse a client timezone, defaulting to UTC", slog.String("error", err.Error()), slog.String("tz", tz))
	}

	cacheKey := "blog-search." + lang + ".pages-list"

	var pages []*blog.Page
	if pagesBytes, ok := supplements.PageCache.Get(cacheKey); pagesBytes != nil || ok {
		json.Unmarshal(pagesBytes, &pages)
	} else {
		pages, err = supplements.BlogClient.Scan(lang + "/")
		if err != nil {
			return fiber.StatusInternalServerError, fmt.Errorf("failed to scan pages for '%s' lang: %w", lang, err)
		}
		pagesBytes, _ := json.Marshal(pages)
		supplements.PageCache.SetWithTTL(cacheKey, pagesBytes, int64(len(pagesBytes)), r.CacheDuration())
	}

	encodedQuery := c.Request().URI().QueryString()
	decodedQuery, _ := url.QueryUnescape(string(encodedQuery))
	matches := r.getTagsQuery.FindAllStringSubmatch(decodedQuery, -1)

	tags := make([]string, 0, len(matches))
	for _, match := range matches {
		tags = append(tags, string(match[1]))
	}

	pageMeta := make([]fiber.Map, 0, len(pages))
	for _, page := range pages {
		for _, tag := range page.Metadata.Tags {
			if len(tags) == 0 || slices.Contains(tags, tag) {
				if medley == "" || medley == page.Metadata.Medley {
					pageMeta = append(pageMeta, fiber.Map{
						"Link":             page.Link,
						"ArticleLink":      "/" + lang + "/blog/" + page.FileName,
						"Title":            page.Metadata.Title,
						"PublishedTime":    page.Metadata.PublishedTime.In(loc).Format("2006-01-02 15:04:05 -07:00"),
						"ActionDate":       page.Metadata.ActionDate,
						"ShortDescription": page.Metadata.ShortDescription,
						"Thumbnail":        page.Metadata.Thumbnail,
						"Tags":             page.Metadata.Tags,
						"LikeCount":        supplements.ClientCache.GetLikeCount(page.FileName),
						"Liked":            supplements.ClientCache.GetLikeStatus(c.IP(), page.FileName),
						"ViewCount":        supplements.ClientCache.GetViewCount(page.FileName),
						"Viewed":           supplements.ClientCache.GetViewStatus(c.IP(), page.FileName),
						"Medley":           page.Metadata.Medley,
						"MedleyPart":       page.Metadata.MedleyPart,
						"ToHighlight":      page.FileName == refererPage,
					})
					break
				}
			}
		}
	}

	slices.SortFunc(pageMeta, func(a, b fiber.Map) int {
		switch sort {
		case "titleAsc":
			return cmp.Compare(a["Title"].(string), b["Title"].(string))
		case "titleDesc":
			return cmp.Compare(b["Title"].(string), a["Title"].(string))
		case "actionDateAsc":
			return cmp.Compare(a["ActionDate"].(string), b["ActionDate"].(string))
		case "actionDateDesc":
			return cmp.Compare(b["ActionDate"].(string), a["ActionDate"].(string))
		case "publicationDateAsc":
			publishedTimeA, _ := time.Parse("2006-01-02 15:04:05 -07:00", a["PublishedTime"].(string))
			publishedTimeB, _ := time.Parse("2006-01-02 15:04:05 -07:00", b["PublishedTime"].(string))
			return publishedTimeA.Compare(publishedTimeB)
		case "publicationDateDesc":
			publishedTimeA, _ := time.Parse("2006-01-02 15:04:05 -07:00", a["PublishedTime"].(string))
			publishedTimeB, _ := time.Parse("2006-01-02 15:04:05 -07:00", b["PublishedTime"].(string))
			return publishedTimeB.Compare(publishedTimeA)
		case "medley":
			return cmp.Compare(a["MedleyPart"].(int), b["MedleyPart"].(int))
		}
		return 0
	})

	templateMap["BlogPages"] = pageMeta
	templateMap["HideTags"] = hideTags
	templateMap["HidePublishedTime"] = hidePublishedTime

	return fiber.StatusOK, nil
}