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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
package logic

import (
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/microcosm-cc/bluemonday"
	"github.com/mmcdole/gofeed"
	"github.com/spaolacci/murmur3"
	"html"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"rss_parrot/dal"
	"rss_parrot/shared"
	"rss_parrot/texts"
	"sort"
	"strings"
	"sync"
	"time"
)

const feedCheckLoopIdleWakeSec = 60
const postCountUpdateSecs = 60

type FeedStatus int32

const (
	FsNew             = 0
	FsAlreadyFollowed = 1
	FsError           = -1
	FsMastodon        = -2
	FsBanned          = -3
	FsOptOut          = -4
)

const (
	feedOrSiteTimeoutSec  = 10
	allowedFuturePostDays = 2
)

type IFeedFollower interface {
	GetAccountForFeed(urlStr string) (acct *dal.Account, status FeedStatus, err error)
	PurgeOldPosts(acct *dal.Account, minCount, minAgeDays int) error
}

type SiteInfo struct {
	Url          string
	ParrotHandle string
	FeedUrl      string
	LastUpdated  time.Time
	Title        string
	Description  string
}

type feedFollower struct {
	cfg                  *shared.Config
	logger               shared.ILogger
	userAgent            shared.IUserAgent
	repo                 dal.IRepo
	blockedFeeds         IBlockedFeeds
	messenger            IMessenger
	txt                  texts.ITexts
	keyStore             IKeyStore
	metrics              IMetrics
	lastCheckedPostCount time.Time
	muPurgingOldPosts    sync.Mutex
	isPurgingOldPosts    bool
	muPurgingUnfollowed  sync.Mutex
	isPurgingUnfollowed  bool
}

func NewFeedFollower(
	cfg *shared.Config,
	logger shared.ILogger,
	userAgent shared.IUserAgent,
	repo dal.IRepo,
	blockedFeeds IBlockedFeeds,
	messenger IMessenger,
	txt texts.ITexts,
	keyStore IKeyStore,
	metrics IMetrics,
) IFeedFollower {

	ff := feedFollower{
		cfg:                 cfg,
		logger:              logger,
		userAgent:           userAgent,
		repo:                repo,
		blockedFeeds:        blockedFeeds,
		messenger:           messenger,
		txt:                 txt,
		keyStore:            keyStore,
		metrics:             metrics,
		isPurgingUnfollowed: false,
	}

	ff.updateDBSizeMetric()
	ff.updateTotalPostsMetric()
	go ff.feedCheckLoop()

	return &ff
}

func (ff *feedFollower) getFeedUrl(siteUrl *url.URL, doc *goquery.Document) string {

	var feedUrlStr string
	isFeedRss := false
	doc.Find("link[rel='alternate']").Each(func(_ int, s *goquery.Selection) {
		var aType, aHref string
		var ok bool
		if aType, ok = s.Attr("type"); !ok {
			return
		}
		if aHref, ok = s.Attr("href"); !ok {
			return
		}
		if aType == "application/atom+xml" && !isFeedRss && feedUrlStr == "" {
			feedUrlStr = aHref
		}
		if aType == "application/rss+xml" && (feedUrlStr == "" || !isFeedRss) {
			feedUrlStr = aHref
			isFeedRss = true
		}
	})

	// Make it absolute
	feedUrl, err := url.Parse(feedUrlStr)
	if err != nil {
		return ""
	}
	if !feedUrl.IsAbs() {
		feedUrl = siteUrl.ResolveReference(feedUrl)
	}

	// Remove (most) query parameters
	ff.trimQueryParams(feedUrl)

	// It's a keeper
	res := feedUrl.String()
	res = strings.TrimRight(res, "/")
	return res
}

func (ff *feedFollower) trimQueryParams(feedUrl *url.URL) {
	// The few exceptions where we keep the query param
	// #33: Youtube feeds look like this: https://www.youtube.com/feeds/videos.xml?channel_id=UCfZz8F37oSJ2rtcEJHM2kCg
	// #69: Youtube playlists feeds: https://www.youtube.com/feeds/videos.xml?playlist_id=PL8_lN8JGpWGzorDyFQ5sW-FutcpCTIKHs
	if strings.Contains(feedUrl.Host, "youtube.com") {
		if strings.Contains(feedUrl.RawQuery, "channel_id") || strings.Contains(feedUrl.RawQuery, "playlist_id") {
			return
		}
	}
	// #37: Archive.org: https://archive.org/services/collection-rss.php?collection=misczinespunk
	if strings.Contains(feedUrl.Host, "archive.org") {
		return
	}
	// #63: Language Log
	if strings.Contains(feedUrl.Host, "languagelog.ldc.upenn.edu") {
		return
	}

	// Squarespace RSS feeds have `?format=rss` (https://support.squarespace.com/hc/en-us/articles/215761717-Using-RSS-feeds)
	if strings.Contains(feedUrl.RawQuery, "format=rss") {
		feedUrl.RawQuery = "format=rss"
		return
	}

	// All otheres: remove query
	feedUrl.RawQuery = ""
}

func (ff *feedFollower) trimQueryParamsStr(urlStr string) (string, error) {
	if parsedUrl, err := url.Parse(urlStr); err != nil {
		return "", err
	} else {
		ff.trimQueryParams(parsedUrl)
		return parsedUrl.String(), nil
	}

}

func (ff *feedFollower) getMetas(doc *goquery.Document, si *SiteInfo) {
	s := doc.Find("title").First()
	if s.Length() != 0 {
		si.Title = s.Text()
	}
	s = doc.Find("meta[name='description']").First()
	if s.Length() != 0 {
		si.Description = s.AttrOr("content", "")
	}
}

func getLastUpdated(feed *gofeed.Feed) time.Time {
	var t time.Time
	if feed.PublishedParsed != nil {
		t = *feed.PublishedParsed
	}
	if feed.UpdatedParsed != nil && feed.UpdatedParsed.After(t) {
		t = *feed.UpdatedParsed
	}
	for _, itm := range feed.Items {
		if itm.PublishedParsed != nil && itm.PublishedParsed.After(t) {
			t = *itm.PublishedParsed
		}
		if itm.UpdatedParsed != nil && itm.UpdatedParsed.After(t) {
			t = *itm.UpdatedParsed
		}
	}
	return t
}

func (ff *feedFollower) validateSiteInfo(si *SiteInfo) error {
	if _, err := url.Parse(si.FeedUrl); err != nil {
		return err
	}
	if err := shared.ValidateHandle(si.ParrotHandle); err != nil {
		return err
	}
	return nil
}

func (ff *feedFollower) getSiteInfo(urlStr string) (*SiteInfo, *gofeed.Feed, error) {

	urlStr = strings.TrimRight(urlStr, "/")
	var res SiteInfo
	var err error

	// First, let's see if this is the feed itself
	var feed *gofeed.Feed
	var noQueryUrlStr string
	if noQueryUrlStr, err = ff.trimQueryParamsStr(urlStr); err != nil {
		return nil, nil, err
	}
	feed, err = ff.fetchParseFeed(noQueryUrlStr)
	if err == nil {
		res.FeedUrl = noQueryUrlStr
		res.LastUpdated = getLastUpdated(feed)
		res.Title = feed.Title
		res.Description = feed.Description
		res.Url = feed.Link
		res.ParrotHandle = shared.GetHandleFromUrl(res.Url)
		return &res, feed, nil
	}

	// Normalize URL
	siteUrl, err := url.Parse(urlStr)
	if err != nil {
		return nil, nil, err
	}
	res.Url = urlStr
	res.ParrotHandle = shared.GetHandleFromUrl(res.Url)

	// Get the page
	client := http.Client{}
	client.Timeout = feedOrSiteTimeoutSec * time.Second
	resp, err := client.Get(urlStr)
	if err != nil {
		ff.logger.Warnf("Failed to get %s: %v", siteUrl, err)
		return nil, nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		err = fmt.Errorf("request for %s failed with status %d", siteUrl, resp.StatusCode)
		ff.logger.Warnf("Failed to get site: %v", err)
		return nil, nil, err
	}

	// Load the HTML document
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		ff.logger.Warnf("Failed to parse HTML from %s: %v", siteUrl, err)
		return nil, nil, err
	}

	// Pick out the data we're interested in
	res.FeedUrl = ff.getFeedUrl(siteUrl, doc)
	if res.FeedUrl == "" {
		ff.logger.Warnf("No feed URL found: %s", siteUrl)
		return nil, nil, fmt.Errorf("no feed URL found at %s", siteUrl)
	}
	ff.getMetas(doc, &res)

	// Get the feed to make sure it's there, and know when it's last changed
	feed, err = ff.fetchParseFeed(res.FeedUrl)
	if err != nil {
		ff.logger.Warnf("Failed to retrieve and parse feed: %s, %v", res.FeedUrl, err)
		return nil, nil, err
	}
	res.LastUpdated = getLastUpdated(feed)

	return &res, feed, nil
}

func getItemHash(itm *gofeed.Item) uint {
	str := itm.GUID + "\t" + itm.Link
	hasher := murmur3.New32()
	_, _ = hasher.Write([]byte(str))
	return uint(hasher.Sum32())
}

func (ff *feedFollower) updateAccountPosts(
	accountId int,
	accountHandle string,
	feed *gofeed.Feed,
	tootNew bool,
) (err error) {
	err = nil
	var lastKnownFeedUpdated time.Time

	if lastKnownFeedUpdated, err = ff.repo.GetFeedLastUpdated(accountId); err != nil {
		return
	}

	// Deal with feed items newer than our last seen
	// This goes from older to newer
	keepers, newLastUpdated := getSortedPosts(feed.Items, lastKnownFeedUpdated)
	for _, k := range keepers {
		fixPodcastLink(k.itm)
		if err = ff.storePostIfNew(accountId, accountHandle, k.postTime, k.itm, tootNew); err != nil {
			return
		}
	}

	nextCheckDue := ff.getNextCheckTime(newLastUpdated)
	if err = ff.repo.UpdateAccountFeedTimes(accountId, newLastUpdated, nextCheckDue); err != nil {
		return
	}
	return
}

func fixPodcastLink(itm *gofeed.Item) {
	if itm.Link != "" {
		return
	}
	for _, enc := range itm.Enclosures {
		if !strings.HasPrefix(enc.Type, "audio/") || enc.URL == "" {
			continue
		}
		parsedUrl, err := url.Parse(enc.URL)
		if err != nil {
			continue
		}
		parsedUrl.RawQuery = ""
		itm.Link = parsedUrl.String()
		return
	}
}

type sortedPost struct {
	itm      *gofeed.Item
	postTime time.Time
}

func getSortedPosts(items []*gofeed.Item, lastKnownFeedUpdated time.Time) ([]sortedPost, time.Time) {
	var keepers []sortedPost
	newLastUpdated := lastKnownFeedUpdated
	futureLimit := time.Now().Add(allowedFuturePostDays * time.Hour * 24)

	for _, itm := range items {
		keeper, postTime := checkItemTime(itm, lastKnownFeedUpdated, futureLimit)
		if !keeper {
			continue
		}
		if postTime.After(newLastUpdated) {
			newLastUpdated = postTime
		}
		keepers = append(keepers, sortedPost{itm, postTime})
	}

	sort.Slice(keepers, func(i, j int) bool {
		return keepers[i].postTime.Before(keepers[j].postTime)
	})

	return keepers, newLastUpdated
}

func checkItemTime(itm *gofeed.Item, latestKown, futureLimit time.Time) (keeper bool, postTime time.Time) {
	keeper = false
	postTime = time.Time{}
	if itm.PublishedParsed != nil && itm.PublishedParsed.After(latestKown) {
		keeper = true
		postTime = *itm.PublishedParsed
	}
	if itm.UpdatedParsed != nil && itm.UpdatedParsed.After(latestKown) {
		keeper = true
		if itm.UpdatedParsed.After(postTime) {
			postTime = *itm.UpdatedParsed
		}
	}
	// Accept posts a little bit into the future, but not far ahead
	// Future posts would prevent us from routinely purging old posts
	if futureLimit.Sub(postTime) < 0 {
		keeper = false
	}
	return
}

func (ff *feedFollower) getNextCheckTime(lastChanged time.Time) time.Time {
	return time.Now().Add(ff.getCheckInterval(lastChanged))
}

// getCheckInterval is how long to wait between two checks of a feed that last
// changed at lastChanged, from the update_schedule config (in hours).
func (ff *feedFollower) getCheckInterval(lastChanged time.Time) time.Duration {

	// Pick by how long the feed has been idle:
	// changed in the last day: update_schedule.day
	// in the last week: .week; in the last 4 weeks: .weeks4; else: .older
	var hours = float64(ff.cfg.UpdateSchedule.Day)
	idleFor := time.Now().Sub(lastChanged)
	if idleFor.Hours() > 24 {
		hours = float64(ff.cfg.UpdateSchedule.Week)
	}
	if idleFor.Hours() > 168 {
		hours = float64(ff.cfg.UpdateSchedule.Weeks4)
	}
	if idleFor.Hours() > 168*4 {
		hours = float64(ff.cfg.UpdateSchedule.Older)
	}

	hours = hours * (0.8 + 0.4*rand.Float64()) // 0.8 - 1.2 random band around targeted value
	return time.Duration(float64(time.Hour) * hours)
}

func stripHtml(htm string) string {
	p := bluemonday.StrictPolicy()
	plain := p.Sanitize(htm)
	plain = html.UnescapeString(plain)
	plain = strings.TrimSpace(plain)
	return plain
}

func (ff *feedFollower) storePostIfNew(
	accountId int,
	accountHandle string,
	postTime time.Time,
	itm *gofeed.Item,
	tootNew bool,
) (err error) {
	var isNew bool
	plainTitle := stripHtml(itm.Title)
	plainDescription := stripHtml(itm.Description)
	isNew, err = ff.repo.AddFeedPostIfNew(accountId, &dal.FeedPost{
		PostGuidHash: int64(getItemHash(itm)),
		PostTime:     postTime,
		Link:         itm.Link,
		Title:        plainTitle,
		Description:  plainDescription,
	})
	if err != nil {
		return
	}
	if isNew {
		ff.metrics.NewPostSaved()
		if err = ff.createToot(accountId, accountHandle, itm, tootNew); err != nil {
			return
		}
	}
	return
}

func (ff *feedFollower) createToot(accountId int, accountHandle string, itm *gofeed.Item, sendToot bool) error {
	prettyUrl := itm.Link
	prettyUrl = strings.TrimPrefix(prettyUrl, "http://")
	prettyUrl = strings.TrimPrefix(prettyUrl, "https://")
	prettyUrl = strings.TrimRight(prettyUrl, "/")
	plainTitle := stripHtml(itm.Title)
	plainDescription := stripHtml(itm.Description)
	plainDescription = shared.TruncateWithEllipsis(plainDescription, shared.MaxDescriptionLen)
	content := ff.txt.WithVals("toot_new_post.html", map[string]string{
		"title":       plainTitle,
		"url":         itm.Link,
		"prettyUrl":   prettyUrl,
		"description": plainDescription,
	})
	idb := shared.IdBuilder{Host: ff.cfg.Host}
	id := ff.repo.GetNextId()
	statusId := idb.UserStatus(accountHandle, id)
	tootedAt := time.Now()
	err := ff.repo.AddToot(accountId, &dal.Toot{
		PostGuidHash: int64(getItemHash(itm)),
		TootedAt:     tootedAt,
		StatusId:     statusId,
		Content:      content,
	})
	if err != nil {
		return err
	}
	if sendToot {
		if err = ff.messenger.EnqueueBroadcast(accountHandle, statusId, tootedAt, content); err != nil {
			return err
		}
	}
	return nil
}

func (ff *feedFollower) filterFeed(feedUrl string, feed *gofeed.Feed) (FeedStatus, error) {

	// We don't parrot Mastond RSS feeds
	generator := strings.ToLower(feed.Generator)
	if strings.Contains(generator, "mastodon") {
		return FsMastodon, nil
	}

	// We don't parrot blocked feeds
	var err error
	var blocked bool
	blocked, err = ff.blockedFeeds.IsBlocked(feedUrl)
	if err != nil {
		return FsError, err
	}
	if blocked {
		return FsOptOut, nil
	}

	// FsError is the OK response
	return FsError, nil
}

func (ff *feedFollower) GetAccountForFeed(urlStr string) (acct *dal.Account, status FeedStatus, err error) {

	ff.logger.Infof("Retrieving site information: %s", urlStr)

	feedLabel := "failed"
	defer func() {
		ff.metrics.FeedRequested(feedLabel)
	}()

	acct = nil
	status = FsError
	err = nil

	si, feed, siErr := ff.getSiteInfo(urlStr)
	if siErr == nil {
		siErr = ff.validateSiteInfo(si)
	}
	if siErr != nil {
		err = siErr
		return
	}

	status, err = ff.filterFeed(si.FeedUrl, feed)
	if err != nil {
		status = FsError
		return
	}
	if status != FsError {
		return
	}

	idb := shared.IdBuilder{Host: ff.cfg.Host}

	var pubKey string
	var privKey string
	pubKey, privKey, err = ff.keyStore.MakeKeyPair()
	if err != nil {
		ff.logger.Errorf("Failed to create key pair: %v", err)
		return
	}

	var isNew bool
	isNew, err = ff.repo.AddAccountIfNotExist(&dal.Account{
		CreatedAt:   time.Now(),
		Handle:      si.ParrotHandle,
		UserUrl:     idb.UserUrl(si.ParrotHandle),
		FeedName:    si.Title,
		FeedSummary: si.Description,
		SiteUrl:     si.Url,
		FeedUrl:     si.FeedUrl,
		PubKey:      pubKey,
	}, privKey)

	if err != nil {
		ff.logger.Errorf("Failed to create/get account for %s: %v", si.ParrotHandle, isNew)
		return
	}

	ff.logger.Infof("Account is %s; newly created: %v", si.ParrotHandle, isNew)

	acct, err = ff.repo.GetAccount(si.ParrotHandle)
	if err != nil {
		ff.logger.Errorf("Failed to load account for %s; was newly created: %v", si.ParrotHandle, isNew)
		acct = nil
		return
	}

	err = ff.updateAccountPosts(acct.Id, si.ParrotHandle, feed, !isNew)
	if err != nil {
		ff.logger.Errorf("Failed to update account's posts: %s: %v", acct.Handle, err)
		acct = nil
		return
	}

	if isNew {
		status = FsNew
		feedLabel = "new"
	} else {
		status = FsAlreadyFollowed
		feedLabel = "existing"
	}
	return
}

func (ff *feedFollower) fetchParseFeed(feedUrl string) (feed *gofeed.Feed, err error) {
	res, err := ff.fetchFeed(feedUrl, "", "")
	if err != nil {
		return nil, err
	}
	if res.notModified {
		// We sent no validators, so the server has nothing to compare against.
		return nil, fmt.Errorf("unexpected 304 Not Modified for unconditional request")
	}
	return res.feed, nil
}

// feedFetchResult is the outcome of a successful fetchFeed: either the
// feed is unchanged (notModified, feed is nil), or it is the parsed feed
// together with the validators to send next time.
type feedFetchResult struct {
	feed         *gofeed.Feed
	notModified  bool
	etag         string
	lastModified string
}

// fetchFeed GETs a feed. If etag or lastModified are set (from the last 200
// response), the request is conditional and a 304 is reported as notModified.
// A non-2xx status is returned as a *feedFetchError, carrying Retry-After.
func (ff *feedFollower) fetchFeed(feedUrl, etag, lastModified string) (*feedFetchResult, error) {

	req, err := http.NewRequest("GET", feedUrl, nil)
	if err != nil {
		return nil, err
	}
	ff.userAgent.AddUserAgent(req)
	if etag != "" {
		req.Header.Set("If-None-Match", etag)
	}
	if lastModified != "" {
		req.Header.Set("If-Modified-Since", lastModified)
	}

	client := http.Client{}
	client.Timeout = time.Second * feedOrSiteTimeoutSec
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
	case http.StatusNotModified:
		return &feedFetchResult{notModified: true, etag: etag, lastModified: lastModified}, nil
	default:
		return nil, &feedFetchError{
			StatusCode: resp.StatusCode,
			RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After"), time.Now()),
		}
	}

	fp := gofeed.NewParser()
	feed, err := fp.Parse(resp.Body)
	if err != nil {
		return nil, err
	}
	return &feedFetchResult{
		feed:         feed,
		etag:         resp.Header.Get("ETag"),
		lastModified: resp.Header.Get("Last-Modified"),
	}, nil
}

func (ff *feedFollower) updateFeed(acct *dal.Account) error {

	var err error
	ff.logger.Infof("Updating account %s: %s", acct.Handle, acct.FeedUrl)
	ff.metrics.FeedUpdated()

	var res *feedFetchResult
	if res, err = ff.fetchFeed(acct.FeedUrl, acct.FeedEtag, acct.FeedLastModified); err != nil {
		return err
	}

	if res.notModified {
		// Nothing new: schedule the next check as if no new post appeared,
		// which is exactly what happened.
		ff.logger.Debugf("Feed not modified: %s", acct.Handle)
		nextCheckDue := ff.getNextCheckTime(acct.FeedLastUpdated)
		if err = ff.repo.UpdateAccountFeedTimes(acct.Id, acct.FeedLastUpdated, nextCheckDue); err != nil {
			return err
		}
		return ff.repo.SetFeedFetchState(acct.Id, res.etag, res.lastModified, 0)
	}

	if err = ff.updateAccountPosts(acct.Id, acct.Handle, res.feed, true); err != nil {
		return err
	}
	if err = ff.repo.SetFeedFetchState(acct.Id, res.etag, res.lastModified, 0); err != nil {
		return err
	}

	go func() {
		if err = ff.PurgeOldPosts(acct, ff.cfg.PostsMinCountKept, ff.cfg.PostsMinDaysKept); err != nil {
			// If purging errors out: swallow it (updateFeed still succeeds); just log
			ff.logger.Errorf("Error purging old posts for account %s: %v", acct.Handle, err)
		}
	}()

	return nil
}

func (ff *feedFollower) PurgeOldPosts(acct *dal.Account, minCount, minAgeDays int) error {

	if minCount <= 0 || minAgeDays <= 0 {
		return nil
	}

	// We're fired off as a goroutine each time a feed has been refreshed
	// Only run one purge at a time
	canProceed := false
	ff.muPurgingOldPosts.Lock()
	if !ff.isPurgingOldPosts {
		canProceed = true
		ff.isPurgingOldPosts = true
	}
	ff.muPurgingOldPosts.Unlock()
	if !canProceed {
		return nil
	}
	signalDone := func() {
		ff.muPurgingOldPosts.Lock()
		ff.isPurgingOldPosts = false
		ff.muPurgingOldPosts.Unlock()
	}
	defer signalDone()
	if ff.cfg.PurgeWaitSec > 0 {
		time.Sleep(time.Duration(ff.cfg.PurgeWaitSec) * time.Second)
	}

	var err error
	var toots []*dal.Toot
	if toots, err = ff.repo.GetTootExtracts(acct.Id); err != nil {
		return err
	}
	// Fewer than minimum count - nothing to do
	if len(toots) <= minCount {
		return nil
	}
	// Sort from newest to oldest
	sort.Slice(toots, func(i, j int) bool {
		return toots[i].TootedAt.After(toots[j].TootedAt)
	})
	// Check each item from start; if we're past minimum count, find time of latest toot to delete
	var fromBefore *time.Time = nil
	nToDel := 0
	now := time.Now().UTC()
	for i, toot := range toots {
		if i < minCount {
			continue
		}
		tootAgeDays := now.Sub(toot.TootedAt).Hours() / 24.0
		if tootAgeDays < float64(minAgeDays) {
			continue
		}
		fromBefore = &time.Time{}
		*fromBefore = toot.TootedAt
		nToDel = len(toots) - i
		break
	}
	if fromBefore == nil {
		return nil
	}

	// Purge 'em
	ff.logger.Infof("Purging %d old toots+posts from account %s", nToDel, acct.Handle)
	if err = ff.repo.PurgePostsAndToots(acct.Id, *fromBefore); err != nil {
		return err
	}
	ff.metrics.PostsDeleted(nToDel)
	return nil
}

func (ff *feedFollower) purgeUnfollowedAccount(acct *dal.Account) {

	// We're fired off as a goroutine each time there's a deletable account
	// Only run one account deleting at a time
	canProceed := false
	ff.muPurgingUnfollowed.Lock()
	if !ff.isPurgingUnfollowed {
		canProceed = true
		ff.isPurgingUnfollowed = true
	}
	ff.muPurgingUnfollowed.Unlock()
	if !canProceed {
		return
	}
	signalDone := func() {
		ff.muPurgingUnfollowed.Lock()
		ff.isPurgingUnfollowed = false
		ff.muPurgingUnfollowed.Unlock()
	}
	defer signalDone()

	followerCount, err := ff.repo.GetFollowerCount(acct.Handle, false)
	if err != nil {
		ff.logger.Errorf("Error getting follower count of feed: %s: %v", acct.Handle, err)
		return
	}
	if followerCount != 0 {
		return
	}
	ff.logger.Infof("Deleting account with 0 followers: %s", acct.Handle)
	if err = ff.repo.BruteDeleteAccount(acct.Id); err != nil {
		ff.logger.Errorf("Failed to brute-delete account: %s: %v", acct.Handle, err)
		return
	}
	if ff.cfg.PurgeWaitSec > 0 {
		time.Sleep(time.Duration(ff.cfg.PurgeWaitSec) * time.Second)
	}
}

func (ff *feedFollower) updateDBSizeMetric() {

	// In case feed follower is running on a mock config in a unit test: don't bother
	if ff.cfg.DbFile == "" {
		return
	}

	var err error
	var fi os.FileInfo
	fi, err = os.Stat(ff.cfg.DbFile)
	if err != nil {
		ff.logger.Errorf("Error getting DB file size: %v", err)
		return
	}
	ff.metrics.DbFileSize(fi.Size())
}

func (ff *feedFollower) updateTotalPostsMetric() {
	now := time.Now()
	if now.Sub(ff.lastCheckedPostCount).Seconds() < postCountUpdateSecs {
		return
	}
	ff.lastCheckedPostCount = now
	ff.logger.Info("Updating total post count metric")
	if count, err := ff.repo.GetTotalPostCount(); err != nil {
		ff.logger.Errorf("Error getting total post count: %v", err)
		return
	} else {
		ff.metrics.TotalPosts(int(count))
	}
}

func (ff *feedFollower) feedCheckLoop() {
	for {
		// This is why we're here
		ff.feedCheckLoopInner()

		// This is real doggone ugly here, but -
		// Other option is to create a logic class just for this
		// Rather a little ugliness here, then all that boilerplate
		// And we're already also setting the "feed-followers" metrics in this module
		ff.updateDBSizeMetric()
		ff.updateTotalPostsMetric()
	}
}

func (ff *feedFollower) feedCheckLoopInner() {

	defer func() {
		if r := recover(); r != nil {
			const panicSleepSec = 10
			ff.logger.Errorf("Feed check cycle panicked: %v", r)
			ff.logger.Infof("Sleeping %d seconds after panic", panicSleepSec)
			time.Sleep(time.Second * panicSleepSec)
		}
	}()

	var err error
	var acct *dal.Account
	var total int
	if acct, total, err = ff.repo.GetAccountToCheck(time.Now()); err != nil {
		ff.logger.Errorf("Failed to get next feed due for checking: %v", err)
		time.Sleep(feedCheckLoopIdleWakeSec * time.Second)
		return
	}
	ff.metrics.CheckableFeedCount(total)
	if acct == nil {
		ff.logger.Debugf("No feeds to check; sleeping %d seconds", feedCheckLoopIdleWakeSec)
		time.Sleep(feedCheckLoopIdleWakeSec * time.Second)
		return
	}
	lastUpdated := acct.FeedLastUpdated
	err = ff.updateFeed(acct)
	if err != nil {
		// Back off: every consecutive failure doubles the wait, and a server
		// that says when to come back (Retry-After) is listened to.
		failures := acct.FetchFailures + 1
		var retryAfter time.Duration
		var fetchErr *feedFetchError
		if errors.As(err, &fetchErr) {
			retryAfter = fetchErr.RetryAfter
		}
		delay := backoffDelay(ff.getCheckInterval(lastUpdated), failures, retryAfter,
			maxRetryDelay(ff.cfg.MaxRetryDelayHours))
		ff.logger.Errorf("Error updating feed: %s: %v (failure %d, next check in %s)",
			acct.Handle, err, failures, delay.Round(time.Minute))
		if err = ff.repo.UpdateAccountFeedTimes(acct.Id, lastUpdated, time.Now().Add(delay)); err != nil {
			ff.logger.Errorf("Failed to reschedule for checking after error: %s: %v", acct.Handle, err)
		}
		if err = ff.repo.SetFeedFetchState(acct.Id, acct.FeedEtag, acct.FeedLastModified, failures); err != nil {
			ff.logger.Errorf("Failed to record fetch failure: %s: %v", acct.Handle, err)
		}
	}
	// If no error, updateFeed has set next due date for checking
	// Delete account if no followers; purge old posts
	go ff.purgeUnfollowedAccount(acct)
}