summaryrefslogtreecommitdiff
path: root/src/render/methods.go
blob: ee22dfdebc2bb61964a00664c7616605f8962a57 (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
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
package render

import (
	"bytes"
	"context"
	"fmt"
	"html/template"
	"net/url"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"dev.mediocregopher.com/mediocre-blog.git/src/gmi/gemtext"
	"dev.mediocregopher.com/mediocre-blog.git/src/post"
	"dev.mediocregopher.com/mediocre-blog.git/src/post/asset"
	"github.com/gomarkdown/markdown"
	"github.com/gomarkdown/markdown/html"
	"github.com/gomarkdown/markdown/parser"
	gmnhg "github.com/tdemin/gmnhg"
)

type ctxKey string

const (
	ctxKeyPost ctxKey = "post"
)

// WithPost sets the post on a Context, such that it can be retrieved using
// the GetThisPost method.
func WithPost(ctx context.Context, p post.StoredPost) context.Context {
	return context.WithValue(ctx, ctxKeyPost, p)
}

// GetPostsRes are the fields returned from the GetPosts method.
type GetPostsRes struct {
	Posts   []post.StoredPost
	HasMore bool
}

// GetDraftPostsRes are the fields returned from the GetDraftPosts method.
type GetDraftPostsRes struct {
	Posts   []post.Post
	HasMore bool
}

// GetPostSeriesNextPreviousRes are the fields returned from the
// GetPostSeriesNextPreviousRes method.
type GetPostSeriesNextPreviousRes struct {
	Next     *post.StoredPost
	Previous *post.StoredPost
}

// Methods carries methods which are designed to be accessible from a template.
type Methods struct {
	ctx              context.Context
	url              *url.URL
	publicURL        *url.URL
	httpURL          *url.URL
	geminiURL        *url.URL
	geminiGatewayURL *url.URL
	postStore        post.Store
	postAssetStore   asset.Store
	postDraftStore   post.DraftStore
	preprocessFuncs  post.PreprocessFunctions

	thisPost      *post.StoredPost // cache
	thisDraftPost *post.Post       // cache
}

// NewMethods initializes a Methods using its required dependencies.
func NewMethods(
	ctx context.Context,
	url *url.URL,
	publicURL *url.URL,
	httpURL *url.URL,
	geminiURL *url.URL,
	geminiGatewayURL *url.URL,
	postStore post.Store,
	postAssetStore asset.Store,
	postDraftStore post.DraftStore,
	preprocessFuncs post.PreprocessFunctions,
) *Methods {
	return &Methods{
		ctx,
		url,
		publicURL,
		httpURL,
		geminiURL,
		geminiGatewayURL,
		postStore,
		postAssetStore,
		postDraftStore,
		preprocessFuncs,
		nil, // thisPost
		nil, // thisDraftPost
	}
}

func (m *Methods) RootURL() URLBuilder {
	return NewURLBuilder(m.publicURL, m.httpURL, m.geminiURL)
}

func (m *Methods) GetTags() ([]string, error) {
	return m.postStore.GetTags()
}

func (m *Methods) GetPostAssetIDs() ([]string, error) {
	return m.postAssetStore.List()
}

func (m *Methods) GetPosts(page, count int) (GetPostsRes, error) {
	posts, hasMore, err := m.postStore.Get(page, count)
	return GetPostsRes{posts, hasMore}, err
}

func (m *Methods) GetDraftPosts(page, count int) (GetDraftPostsRes, error) {
	posts, hasMore, err := m.postDraftStore.Get(page, count)
	return GetDraftPostsRes{posts, hasMore}, err
}

func (m *Methods) GetThisPost() (p post.StoredPost, err error) {
	if m.thisPost != nil {
		return *m.thisPost, nil
	}

	defer func() {
		m.thisPost = &p
	}()

	if p, ok := m.ctx.Value(ctxKeyPost).(post.StoredPost); ok {
		return p, nil
	}

	id := path.Base(m.url.Path)
	id = strings.TrimSuffix(id, path.Ext(id))

	return m.postStore.GetByID(id)
}

func (m *Methods) GetThisDraftPost() (p post.Post, err error) {
	if m.thisPost != nil {
		return *m.thisDraftPost, nil
	}

	defer func() {
		m.thisDraftPost = &p
	}()

	id := path.Base(m.url.Path)
	if id == "/" {
		// An empty draft is fine, in the context of editing
		return
	}

	id = strings.TrimSuffix(id, path.Ext(id))
	return m.postDraftStore.GetByID(id)
}

func (m *Methods) GetPostSeriesNextPrevious(
	p post.StoredPost,
) (
	GetPostSeriesNextPreviousRes, error,
) {

	seriesPosts, err := m.postStore.GetBySeries(p.Series)
	if err != nil {
		return GetPostSeriesNextPreviousRes{}, fmt.Errorf(
			"fetching posts for series %q: %w", p.Series, err,
		)
	}

	var (
		res       GetPostSeriesNextPreviousRes
		foundThis bool
	)

	for i := range seriesPosts {

		seriesPost := seriesPosts[i]

		if seriesPost.ID == p.ID {
			foundThis = true
			continue
		}

		if !foundThis {
			res.Next = &seriesPost
			continue
		}

		res.Previous = &seriesPost
		break
	}

	return res, nil
}

func (m *Methods) PostGemtextBody(p post.StoredPost) (string, error) {

	buf := new(bytes.Buffer)

	if err := p.PreprocessBody(buf, m.preprocessFuncs); err != nil {
		return "", fmt.Errorf("preprocessing post body: %w", err)
	}

	bodyBytes := buf.Bytes()

	if p.Format == post.FormatMarkdown {

		gemtextBodyBytes, err := gmnhg.RenderMarkdown(bodyBytes, 0)
		if err != nil {
			return "", fmt.Errorf("converting from markdown: %w", err)
		}

		bodyBytes = gemtextBodyBytes
	}

	return string(bodyBytes), nil
}

func (m *Methods) PostHTMLBody(p post.StoredPost) (template.HTML, error) {
	bodyBuf := new(bytes.Buffer)

	if err := p.PreprocessBody(bodyBuf, m.preprocessFuncs); err != nil {
		return "", fmt.Errorf("preprocessing post body: %w", err)
	}

	if p.Format == post.FormatGemtext {

		prevBodyBuf := bodyBuf
		bodyBuf = new(bytes.Buffer)

		err := gemtext.ToMarkdown(
			bodyBuf, prevBodyBuf, m.geminiGatewayURL,
		)

		if err != nil {
			return "", fmt.Errorf("converting gemtext to markdown: %w", err)
		}
	}

	// this helps the markdown renderer properly parse pages which end in a
	// `</script>` tag... I don't know why.
	_, _ = bodyBuf.WriteString("\n")

	parserExt := parser.CommonExtensions | parser.AutoHeadingIDs
	parser := parser.NewWithExtensions(parserExt)

	htmlFlags := html.HrefTargetBlank
	htmlRenderer := html.NewRenderer(html.RendererOptions{Flags: htmlFlags})

	renderedBody := markdown.ToHTML(bodyBuf.Bytes(), parser, htmlRenderer)
	return template.HTML(renderedBody), nil
}

func (m *Methods) GetQueryValue(key, def string) string {
	v := m.url.Query().Get(key)
	if v == "" {
		v = def
	}
	return v
}

func (m *Methods) GetQueryIntValue(key string, def int) (int, error) {
	vStr := m.GetQueryValue(key, strconv.Itoa(def))
	return strconv.Atoi(vStr)
}

func (m *Methods) GetPath() (string, error) {
	basePath := filepath.Join("/", m.publicURL.Path) // in case it's empty
	return filepath.Rel(basePath, m.url.Path)
}

func (m *Methods) Add(a, b int) int { return a + b }