-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeed.go
97 lines (79 loc) · 2.73 KB
/
feed.go
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
package main
import (
"fmt"
"log"
"os"
"reflect"
"slices"
"time"
rss "github.com/gorilla/feeds"
)
type NotificationSource struct {
Name string // Used in the log.
From string // Email the notifications come from.
Cfg string // Name of the config variable in Files section
Parser func([]*NotificationEmail) []*rss.Item // Parser function.
Title string // Feed title.
Link string // Feed link.
}
// All the notifiers we support go in here:
var SupportedNotifiers = []NotificationSource{
{
Name: "Archive of Our Own",
From: "[email protected]",
Cfg: "Aoo",
Parser: parseAoo,
Title: "Archive of Our Own Story Updates",
Link: "https://archiveofourown.org/",
},
}
// This function assembles the items a parser function produced into a feed.
func makeFeed(notifier NotificationSource, items []*rss.Item, format string) (string, error) {
now := time.Now()
slices.SortFunc(items, func(a *rss.Item, b *rss.Item) int {
return -a.Created.Compare(b.Created)
})
feed := &rss.Feed{
Title: notifier.Title,
Id: notifier.Link,
Link: &rss.Link{Href: notifier.Link, Rel: "self"},
Updated: now,
Created: now,
Items: items,
}
log.Printf("resulting feed of %s updates contains %d items", notifier.Name, len(items))
switch format {
case "atom":
return feed.ToAtom()
case "rss":
return feed.ToRss()
case "json":
return feed.ToJSON()
}
return "", fmt.Errorf("unsupported feed format '%s'", format)
}
// This goes through the list of notifiers we know, runs the parser functions for them,
// and feeds their output into the feed generator function above.
func generateFeeds(cfg NotifyRSSConfig, notifications []*NotificationEmail) {
for _, notifier := range SupportedNotifiers {
// The annoying part, we need to get the value of the config field using reflection,
// because I can't just add a pointer to a config field.
target := reflect.ValueOf(cfg.Files).FieldByName(notifier.Cfg).String()
// If the filename is configured, we run the appropriate parser.
if target != "" {
items := notifier.Parser(
slices.Collect(Filtered(notifications, func(n *NotificationEmail) bool {
return n.From == notifier.From
})))
feedText, err := makeFeed(notifier, items, cfg.Options.Format)
if err != nil {
log.Printf("failed to produce a feed, this might be a bug: %v", err)
}
log.Printf("saving feed in %s format to %s", cfg.Options.Format, target)
err = os.WriteFile(target, []byte(feedText), 0644)
if err != nil {
log.Fatalf("could not write target feed file %s: %v", target, err)
}
}
}
}