aboutsummaryrefslogtreecommitdiff
path: root/backend/data.go
blob: 76c2ccc161cbe74f42a7a1d16d30e951dcc95ffe (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
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
package backend

import (
	"context"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"html/template"
	"io"
	"io/fs"
	"log/slog"
	"math/rand"
	"net/http"
	"regexp"
	"strings"
	txt "text/template"
)

var (
	regexIsHttp = regexp.MustCompile(`^https?://`)
)

type dataUsable interface {
	SetData(*data)
}

type data struct {
	title           string
	Article         bool
	Domain          string
	URL             string
	Image           string
	PageDescription string
	Name            string
	Links           []Link
	Logo            *Logo
	Quote           string
	Language        string
	section         string
}

func (d *data) SetData(data *data) {
	*d = *data
}

func (d *data) merge(cfg *Config, r *http.Request) {
	if d.Domain == "" {
		d.Domain = cfg.Domain
	}
	if d.Name == "" {
		d.Name = cfg.Name
	}
	if d.PageDescription == "" {
		d.PageDescription = cfg.Description
	}
	if d.Links == nil {
		d.Links = cfg.Links
	}
	if d.Logo == nil {
		d.Logo = &cfg.Logo
	}
	if d.Quote == "" {
		if cfg.Quotes == nil {
			d.Quote = "Une citation"
		} else {
			d.Quote = cfg.Quotes[rand.Intn(len(cfg.Quotes))]
		}
	}
	if d.Image == "" {
		d.Image = cfg.DefaultImage
	}
	if d.URL == "" {
		if !strings.HasPrefix(r.URL.Path, "/") {
			r.URL.Path = "/" + r.URL.Path
		}
		d.URL = r.URL.Path
	}
	if d.Language == "" {
		d.Language = cfg.Language
	}
}

func (d *data) handleGeneric(w http.ResponseWriter, r *http.Request, name string, custom dataUsable) {
	cfg := r.Context().Value(configKey).(*Config)
	d.merge(cfg, r)
	t, err := template.New("").Funcs(template.FuncMap{
		"static": getStatic,
		"fullStatic": func(path string) string {
			if regexIsHttp.MatchString(path) {
				return path
			}
			return fmt.Sprintf("https://%s/static/%s", cfg.Domain, path)
		},
		"asset": func(path string) *assetData {
			return getAsset(r.Context(), path)
		},
		"next":   func(i int) int { return i + 1 },
		"before": func(i int) int { return i - 1 },
		"first":  templateFirst,
	}).ParseFS(templates, "templates/components.html", fmt.Sprintf("templates/%s.html", name), "templates/base.html")
	if err != nil {
		panic(err)
	}
	exec := "base.html"
	if custom == nil {
		err = t.ExecuteTemplate(w, exec, d)
	} else {
		custom.SetData(d)
		err = t.ExecuteTemplate(w, exec, custom)
	}
	if err != nil {
		panic(err)
	}
	if name == "404" {
		w.WriteHeader(http.StatusNotFound)
		return
	}
}

func (d *data) handleRSS(w http.ResponseWriter, r *http.Request, custom dataUsable) {
	cfg := r.Context().Value(configKey).(*Config)
	d.merge(cfg, r)
	t, err := txt.New("").Funcs(txt.FuncMap{
		"first": templateFirst,
		"uri": func(s string) string {
			if s == "" {
				return ""
			}
			return s + "/"
		},
	}).ParseFS(templates, "templates/rss.xml")
	if err != nil {
		panic(err)
	}
	r.Header.Set("Content-Type", "application/rss+xml")
	if custom == nil {
		err = t.ExecuteTemplate(w, "rss.xml", d)
	} else {
		custom.SetData(d)
		err = t.ExecuteTemplate(w, "rss.xml", custom)
	}
	if err != nil {
		panic(err)
	}
}

func (d *data) Title() string {
	title := d.Name
	if d.Article {
		title = fmt.Sprintf("%s - %s entry", title, d.section)
	}
	if len(d.title) != 0 {
		title += " - " + d.title
	}
	return title
}

func (d *data) PubDate() string {
	return ""
}

func getStatic(path string) string {
	if regexIsHttp.MatchString(path) {
		return path
	}
	return fmt.Sprintf("/static/%s", strings.TrimPrefix(path, "/"))
}

type assetData struct {
	Src      string
	Checksum string
}

var assets = map[string]*assetData{}

func getAsset(ctx context.Context, path string) *assetData {
	asset, ok := assets[path]
	if ok && !ctx.Value(debugKey).(bool) {
		return asset
	}
	asset = &assetData{}
	var b []byte
	if regexIsHttp.MatchString(path) {
		asset.Src = path
		resp, err := http.Get(path)
		if err != nil {
			slog.Warn("get remote asset", "error", err)
			return asset
		}
		defer resp.Body.Close()
		b, err = io.ReadAll(resp.Body)
		if err != nil {
			slog.Warn("read remote asset", "error", err)
			return asset
		}
	} else {
		asset.Src = fmt.Sprintf("/assets/%s", path)
		aFS := ctx.Value(assetsFSKey).(fs.FS)
		var err error
		b, err = fs.ReadFile(aFS, path)
		if err != nil {
			slog.Warn("read asset", "error", err)
			return asset
		}
	}
	sum := sha256.Sum256(b)
	checksum := base64.StdEncoding.EncodeToString(sum[:])
	asset.Checksum = fmt.Sprintf("sha256-%s", checksum)
	assets[path] = asset
	return asset
}

func templateFirst(a []*Section) *Section {
	if len(a) == 0 {
		return nil
	}
	return a[0]
}