summaryrefslogtreecommitdiff
path: root/internal/feed/parse.go
blob: 1ba90fdb82d033e00cfa1ce20456e14d332ff4bc (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
package feed

import (
	ctxt "context"
	"crypto/tls"
	"fmt"
	"net/http"
	"time"

	"github.com/google/uuid"
	"github.com/mmcdole/gofeed"

	"github.com/Necoro/feed2imap-go/pkg/log"
)

// share HTTP clients
var (
	stdHTTPClient    *http.Client
	unsafeHTTPClient *http.Client
)

func init() {
	// std
	stdHTTPClient = &http.Client{Transport: http.DefaultTransport}

	// unsafe
	tlsConfig := &tls.Config{InsecureSkipVerify: true}
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.TLSClientConfig = tlsConfig
	unsafeHTTPClient = &http.Client{Transport: transport}
}

func context(timeout int) (ctxt.Context, ctxt.CancelFunc) {
	return ctxt.WithTimeout(ctxt.Background(), time.Duration(timeout)*time.Second)
}

func httpClient(disableTLS bool) *http.Client {
	if disableTLS {
		return unsafeHTTPClient
	}
	return stdHTTPClient
}

func (feed *Feed) parse() error {
	ctx, cancel := context(feed.Global.Timeout)
	defer cancel()

	fp := gofeed.NewParser()
	fp.Client = httpClient(feed.NoTLS)

	parsedFeed, err := fp.ParseURLWithContext(feed.Url, ctx)
	if err != nil {
		return fmt.Errorf("while fetching %s from %s: %w", feed.Name, feed.Url, err)
	}

	feed.feed = parsedFeed
	feed.items = make([]item, len(parsedFeed.Items))
	for idx, feedItem := range parsedFeed.Items {
		feed.items[idx] = item{Feed: parsedFeed, Item: feedItem, itemId: uuid.New(), feed: feed}
	}
	return nil
}

func handleFeed(feed *Feed) {
	log.Printf("Fetching %s from %s", feed.Name, feed.Url)

	err := feed.parse()
	if err != nil {
		if feed.cached.Failures() >= feed.Global.MaxFailures {
			log.Error(err)
		} else {
			log.Print(err)
		}
	}
}