aboutsummaryrefslogtreecommitdiff
path: root/internal/feed/feed.go
blob: 5af41882e7664b6ca78688ce92b5bce4d8986c98 (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
package feed

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/mmcdole/gofeed"

	"github.com/Necoro/feed2imap-go/internal/config"
	"github.com/Necoro/feed2imap-go/internal/log"
)

type Feed struct {
	Name   string
	Target []string
	Url    string
	config.Options
	feed   *gofeed.Feed
	items  []feeditem
	cached CachedFeed
}

type feeditem struct {
	*gofeed.Feed
	*gofeed.Item
}

type Feeds struct {
	feeds map[string]*Feed
	cache Cache
}

func NewFeeds() *Feeds {
	return &Feeds{
		feeds: map[string]*Feed{},
	}
}

func (feeds *Feeds) String() string {
	var b strings.Builder
	app := func(a ...interface{}) {
		_, _ = fmt.Fprint(&b, a...)
	}
	app("Feeds [")

	first := true
	for k, v := range feeds.feeds {
		if !first {
			app(", ")
		}
		app(`"`, k, `"`, ": ")
		if v == nil {
			app("<nil>")
		} else {
			_, _ = fmt.Fprintf(&b, "%+v", *v)
		}
		first = false
	}
	app("]")

	return b.String()
}

func (feeds *Feeds) Len() int {
	return len(feeds.feeds)
}

func (feeds *Feeds) Contains(name string) bool {
	_, ok := feeds.feeds[name]
	return ok
}

func (feeds *Feeds) Set(name string, feed *Feed) {
	feeds.feeds[name] = feed
}

func (feeds *Feeds) Foreach(f func(*Feed)) {
	for _, feed := range feeds.feeds {
		f(feed)
	}
}

func (feeds *Feeds) ForeachGo(goFunc func(*Feed, *sync.WaitGroup)) {
	var wg sync.WaitGroup
	wg.Add(feeds.Len())

	for _, feed := range feeds.feeds {
		go goFunc(feed, &wg)
	}
	wg.Wait()
}

func (feed *Feed) NeedsUpdate(updateTime time.Time) bool {
	if !updateTime.IsZero() && int(time.Since(updateTime).Hours()) >= feed.MinFreq {
		log.Printf("Feed '%s' does not need updating, skipping.", feed.Name)
		return false
	}
	return true
}

func (feed *Feed) Success() bool {
	return feed.feed != nil
}