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

import (
	"bufio"
	"fmt"
	"os"
	"rss_parrot/shared"
	"strings"
)

type IBlockedFeeds interface {
	IsBlocked(feedUrl string) (bool, error)
}

// blockedFeeds is the list of feeds whose sites have opted out, read from
// blocked_feeds_file on every request, so that it can be edited while the
// service runs.
//
// Without blocked_feeds_file nothing is blocked. With it, it has to be there:
// a missing file is an error at startup, not a quietly empty list, since that
// would let through sites that opted out; and a request that cannot read it
// fails, for the same reason.
type blockedFeeds struct {
	file string
}

func NewBlockedFeeds(cfg *shared.Config) (IBlockedFeeds, error) {
	return newBlockedFeeds(cfg.BlockedFeedsFile)
}

func newBlockedFeeds(file string) (*blockedFeeds, error) {
	if file != "" {
		f, err := os.Open(file)
		if err != nil {
			return nil, fmt.Errorf("blocked_feeds_file: %w", err)
		}
		_ = f.Close()
	}
	return &blockedFeeds{file}, nil
}

func (bf *blockedFeeds) IsBlocked(feedUrl string) (bool, error) {

	if bf.file == "" {
		return false, nil
	}
	feedUrl = strings.ToLower(feedUrl)
	feedUrl = strings.TrimPrefix(feedUrl, "https://")
	feedUrl = strings.TrimPrefix(feedUrl, "http://")
	readFile, err := os.Open(bf.file)
	if err != nil {
		return false, err
	}
	defer readFile.Close()
	fileScanner := bufio.NewScanner(readFile)
	fileScanner.Split(bufio.ScanLines)

	for fileScanner.Scan() {
		line := fileScanner.Text()
		if feedUrl == line {
			return true, nil
		}
	}
	return false, nil
}