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
package server

import (
	"fmt"
	"html/template"
	"io/fs"
	"net/http"
	"rss-kakapo/dal"
	"rss-kakapo/shared"
	"rss-kakapo/texts"
	"rss-kakapo/www"
	"strconv"
	"strings"
	"time"
)

const feedsPerPage = 200
const postsPerPage = 100

var months = []string{
	"January", "February", "March", "April", "May", "June",
	"July", "August", "September", "October", "November", "December",
}

type webHandlerGroup struct {
	cfg           *shared.Config
	logger        shared.ILogger
	repo          dal.IRepo
	txt           texts.ITexts
	idb           shared.IdBuilder
	version       string
	timestamp     string
	pageTemplates map[string]*template.Template
}

func NewWebHandlerGroup(
	cfg *shared.Config,
	logger shared.ILogger,
	repo dal.IRepo,
	txt texts.ITexts,
) IHandlerGroup {
	res := webHandlerGroup{
		cfg:           cfg,
		logger:        logger,
		repo:          repo,
		txt:           txt,
		idb:           shared.IdBuilder{Host: cfg.Host},
		timestamp:     fmt.Sprintf("%d", time.Now().UnixMilli()),
		pageTemplates: make(map[string]*template.Template),
	}
	res.version = www.Version
	res.initTemplates()
	return &res
}

func (hg *webHandlerGroup) Prefix() string {
	return "/web"
}

func (hg *webHandlerGroup) GroupDefs() []handlerDef {
	return []handlerDef{
		{"GET", "/feeds/{feed}", func(w http.ResponseWriter, r *http.Request) { hg.getOneFeed(w, r) }},
		{"GET", "/feeds", func(w http.ResponseWriter, r *http.Request) { hg.getFeeds(w, r) }},
		{"GET", "/changes", func(w http.ResponseWriter, r *http.Request) { hg.getChanges(w, r) }},
		{"GET", "/about", func(w http.ResponseWriter, r *http.Request) { hg.getAbout(w, r) }},
		{"GET", rootPlacholder, func(w http.ResponseWriter, r *http.Request) { hg.getRoot(w, r) }},
		{"GET", notFoundPlacholder, func(w http.ResponseWriter, r *http.Request) { hg.send404(w, r) }},
	}
}

func (hg *webHandlerGroup) AuthMW() func(next http.Handler) http.Handler {
	return emptyMW
}

// initTemplates parses every page once, at startup: a main-<name>.tmpl
// together with all the templates that are not a main-*.tmpl. They are
// compiled into the binary (package www), so they cannot change while it runs.
func (hg *webHandlerGroup) initTemplates() {
	mainFiles, err := fs.Glob(www.FS, "main-*.tmpl")
	if err != nil {
		hg.logger.Errorf("Failed to list main-*.tmpl: %v", err)
		panic(err)
	}
	for _, fn := range mainFiles {
		mainName := strings.TrimPrefix(fn, "main-")
		mainName = strings.TrimSuffix(mainName, ".tmpl")
		var t *template.Template
		if t, err = hg.parsePageTemplate(mainName); err != nil {
			hg.logger.Errorf("Failed to parse page template: %s: %v", fn, err)
			panic(err)
		}
		hg.pageTemplates[mainName] = t
	}
}

func (hg *webHandlerGroup) parsePageTemplate(mainName string) (*template.Template, error) {

	t := template.New("master")

	hg.addTemplateFuncs(t)

	tmplFiles, err := fs.Glob(www.FS, "*.tmpl")
	if err != nil {
		return nil, err
	}
	var files []string
	foundMain := false
	for _, fn := range tmplFiles {
		if strings.HasPrefix(fn, "main-") {
			if fn != "main-"+mainName+".tmpl" {
				continue
			}
			foundMain = true
		}
		files = append(files, fn)
	}
	if !foundMain {
		return nil, fmt.Errorf("did not find 'main' template for %s", mainName)
	}
	return t.ParseFS(www.FS, files...)
}

func (hg *webHandlerGroup) mustGetPageTemplate(mainName string) (*template.Template, *baseModel) {
	t, found := hg.pageTemplates[mainName]
	if !found {
		err := fmt.Errorf("Page template not found: %s", mainName)
		hg.logger.Errorf("%v", err)
		panic(err)
	}
	return t, &baseModel{
		// The assets cannot change while the binary runs, so its start time
		// is a cache buster that changes exactly when they may have.
		Timestamp: hg.timestamp,
		Version:   hg.version,
		Host:      hg.cfg.Host,
		Birb:      shared.MakeFullMoniker(hg.cfg.Host, hg.cfg.Birb.User),
		// Restricted tells visitors that they cannot request feeds themselves.
		Restricted: hg.cfg.RestrictRequests,
	}
}

func (hg *webHandlerGroup) addTemplateFuncs(t *template.Template) {

	profileUrl := func(handle string) string {
		return hg.idb.UserProfile(handle)
	}
	prettyDate := func(t time.Time) string {
		return fmt.Sprintf("%s %d, %d", months[t.Month()-1], t.Day(), t.Year())
	}
	prettyDateTime := func(t time.Time) string {
		dateStr := prettyDate(t)
		return fmt.Sprintf("%s %02d:%02d", dateStr, t.Hour(), t.Minute())
	}

	t.Funcs(template.FuncMap{
		"isNonEmptyString": func(s string) bool { return s != "" },
		"prettyDate":       prettyDate,
		"prettyDateTime":   prettyDateTime,
		"profileUrl":       profileUrl,
	})
}

type baseModel struct {
	Timestamp       string
	Version         string
	Host            string // public domain of this instance
	Birb            string // full moniker of the birb, @user@host
	Restricted      bool   // only allowlisted requesters may add feeds
	LnkFeedsClass   string
	LnkChangesClass string
	LnkAboutClass   string
	Data            any
}

func (hg *webHandlerGroup) getRoot(w http.ResponseWriter, r *http.Request) {

	t, model := hg.mustGetPageTemplate("root")
	t.ExecuteTemplate(w, "index.tmpl", model)
}

func (hg *webHandlerGroup) send404(w http.ResponseWriter, r *http.Request) {

	if acceptsJson(r) {
		writeErrorResponse(w, notFoundStr, http.StatusNotFound)
		return
	}

	t, model := hg.mustGetPageTemplate("404")
	w.WriteHeader(http.StatusNotFound)
	w.Header().Set("X-Robots-Tag", "noindex")
	t.ExecuteTemplate(w, "index.tmpl", model)
}

func (hg *webHandlerGroup) send500(w http.ResponseWriter, r *http.Request) {

	t, model := hg.mustGetPageTemplate("500")
	w.WriteHeader(http.StatusNotFound)
	w.Header().Set("X-Robots-Tag", "noindex")
	t.ExecuteTemplate(w, "index.tmpl", model)
}

func (hg *webHandlerGroup) getAbout(w http.ResponseWriter, r *http.Request) {

	t, model := hg.mustGetPageTemplate("about")
	model.LnkAboutClass = "selected"
	t.ExecuteTemplate(w, "index.tmpl", model)
}

func (hg *webHandlerGroup) getChanges(w http.ResponseWriter, r *http.Request) {

	t, model := hg.mustGetPageTemplate("changes")
	model.LnkChangesClass = "selected"
	t.ExecuteTemplate(w, "index.tmpl", model)
}

type feedsModel struct {
	Feeds []*dal.Account
	Pages []pageLink
}

type pageLink struct {
	Query   string
	Display int
	Class   string
}

func (hg *webHandlerGroup) getFeeds(w http.ResponseWriter, r *http.Request) {

	var err error
	pageIx := 0
	pageParam := r.URL.Query().Get("page")
	if pageIx, err = strconv.Atoi(pageParam); err != nil || pageIx < 0 {
		pageIx = 0
	}

	var accounts []*dal.Account
	var total int
	accounts, total, err = hg.repo.GetAccountsPage(pageIx*feedsPerPage, feedsPerPage)

	if err != nil {
		hg.logger.Errorf("Error retrieving feeds %v", err)
		hg.send500(w, r)
		return
	}

	// Remove birb's built-in account
	total -= 1
	nonBuiltInAccounts := make([]*dal.Account, 0, len(accounts))
	for _, acct := range accounts {
		if acct.Handle == hg.cfg.Birb.User {
			continue
		}
		nonBuiltInAccounts = append(nonBuiltInAccounts, acct)
	}

	data := feedsModel{
		Feeds: nonBuiltInAccounts,
	}
	for i := 0; i < total/feedsPerPage+1; i++ {
		pl := pageLink{
			Display: i + 1,
		}
		if i == pageIx {
			pl.Class = "selected"
		}
		if i != 0 {
			pl.Query = fmt.Sprintf("?page=%d", i)
		}
		data.Pages = append(data.Pages, pl)
	}

	t, model := hg.mustGetPageTemplate("feeds")
	model.LnkFeedsClass = "selected"
	model.Data = &data

	w.Header().Set("X-Robots-Tag", "noindex")
	t.ExecuteTemplate(w, "index.tmpl", model)
}

type oneFeedModel struct {
	Handle          string
	Name            string
	Bio             template.HTML
	SiteUrl         string
	SiteUrlNoSchema string
	FeedUrl         string
	FeedUrlNoSchema string
	FollowerCount   uint
	PostCount       uint
	Posts           []*dal.FeedPost
	NotShownPosts   uint
}

func (hg *webHandlerGroup) loadFeedData(acct *dal.Account) *oneFeedModel {

	var err error

	bio := hg.txt.WithVals("acct_bio.html", map[string]string{
		"siteUrl":     hg.idb.SiteUrl(),
		"description": acct.FeedSummary,
	})
	var followerCount, postCount uint
	if followerCount, err = hg.repo.GetFollowerCount(acct.Handle, true); err != nil {
		hg.logger.Errorf("Error retrieving follower count for %s: %v", acct.Handle, err)
		return nil
	}
	if postCount, err = hg.repo.GetPostCount(acct.Handle); err != nil {
		hg.logger.Errorf("Error retrieving post count for %s: %v", acct.Handle, err)
		return nil
	}

	data := oneFeedModel{
		Handle:        shared.MakeFullMoniker(hg.cfg.Host, acct.Handle),
		Name:          shared.GetNameWithParrot(acct.FeedName),
		Bio:           template.HTML(bio),
		SiteUrl:       acct.SiteUrl,
		FeedUrl:       acct.FeedUrl,
		FollowerCount: followerCount,
		PostCount:     postCount,
	}
	data.FeedUrlNoSchema = strings.TrimPrefix(data.FeedUrl, "https://")
	data.FeedUrlNoSchema = strings.TrimPrefix(data.FeedUrlNoSchema, "http://")
	data.SiteUrlNoSchema = strings.TrimPrefix(data.SiteUrl, "https://")
	data.SiteUrlNoSchema = strings.TrimPrefix(data.SiteUrlNoSchema, "http://")

	data.Posts, err = hg.repo.GetPostsPage(acct.Id, 0, postsPerPage)
	if err != nil {
		hg.logger.Errorf("Error retrieving posts for %s: %v", acct.Handle, err)
		return nil
	}

	for _, p := range data.Posts {
		p.Description = shared.TruncateWithEllipsis(p.Description, shared.MaxDescriptionLen)
	}

	if data.PostCount > uint(len(data.Posts)) {
		data.NotShownPosts = data.PostCount - uint(len(data.Posts))
	}

	return &data
}

func (hg *webHandlerGroup) getOneFeed(w http.ResponseWriter, r *http.Request) {

	hg.logger.Infof("Handling user GET: %s", r.URL.Path)
	feedName := r.PathValue("feed")
	feedName = strings.ToLower(feedName)

	if feedName == hg.cfg.Birb.User {
		hg.logger.Infof("Requesting profile of '%s'; redirecting to root", hg.cfg.Birb.User)
		http.Redirect(w, r, "/", http.StatusSeeOther)
		return
	}

	acct, err := hg.repo.GetAccount(feedName)
	if acct == nil {
		if err == nil {
			hg.logger.Infof("Feed '%s' doesn't exist; returning a 404", feedName)
			hg.send404(w, r)
			return
		} else {
			hg.logger.Errorf("Error retrieving feed %s: %v", feedName, err)
			hg.send500(w, r)
			return
		}
	}

	data := hg.loadFeedData(acct)
	if data == nil {
		hg.send500(w, r)
		return
	}

	t, model := hg.mustGetPageTemplate("one-feed")
	model.LnkFeedsClass = "selected"
	model.Data = data

	w.Header().Set("X-Robots-Tag", "noindex")
	t.ExecuteTemplate(w, "index.tmpl", model)
}