-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
173 lines (166 loc) · 4.69 KB
/
Copy pathmain.go
File metadata and controls
173 lines (166 loc) · 4.69 KB
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
// Copyright (c) 2023 Julian Müller (ChaoticByte)
package main
import (
"fmt"
"net/smtp"
"os"
"slices"
"time"
)
var executableName string
var logger Logger
func showVersion() {
fmt.Printf("wid-notifier %s\n", Version)
}
func showHelp() {
fmt.Printf("Usage: %v <configfile>\n\nIf the config file doesn't exist, an incomplete \n" +
"configuration with default values is created.\n\n",
executableName)
showVersion()
}
func main() {
// get cli arguments
args := os.Args
executableName = args[0]
if len(args) < 2 {
showHelp()
os.Exit(1)
}
for _, arg := range args {
switch arg {
case "-h", "--help":
showHelp()
os.Exit(0)
case "--version":
showVersion()
os.Exit(0)
}
}
configFilePath := args[1]
// create logger
logger = NewLogger(2)
// init
logger.info("Initializing ...")
defer logger.info("Exiting ...")
// open & check config
config := NewDataStore(
configFilePath,
NewConfig(),
true,
0600,
).data.(Config)
logger.LogLevel = config.LogLevel
logger.debug("Checking configuration file ...")
checkConfig(config)
// create mail template from mail template config
logger.debug("Parsing mail template ...")
if config.Template.SubjectTemplate == "" {
logger.debug("Using default template for mail subject")
config.Template.SubjectTemplate = DEFAULT_SUBJECT_TEMPLATE
}
if config.Template.BodyTemplate == "" {
logger.debug("Using default template for mail body")
config.Template.BodyTemplate = DEFAULT_BODY_TEMPLATE
}
mailTemplate := NewTemplateFromTemplateConfig(config.Template)
// mail authentication from config
mailAuth := smtp.PlainAuth(
"",
config.SmtpConfiguration.User,
config.SmtpConfiguration.Password,
config.SmtpConfiguration.ServerHost,
)
// filter out disabled api endpoints
enabledApiEndpoints := []ApiEndpoint{}
for _, a := range apiEndpoints {
for _, b := range config.EnabledApiEndpoints {
if a.Id == b {
logger.debug("Endpoint '" + b + "' is enabled")
enabledApiEndpoints = append(enabledApiEndpoints, a)
}
}
}
// open data file
persistent := NewDataStore(
config.PersistentDataFilePath,
NewPersistentData(config),
false,
0640)
// main loop
logger.debug("Entering main loop ...")
for {
t1 := time.Now().UnixMilli()
newNotices := []WidNotice{}
lastPublished := map[string]time.Time{} // endpoint id : last published timestamp
cache := map[string]*MailContent{} // cache generated emails for reuse
for _, a := range enabledApiEndpoints {
logger.info("Querying endpoint '" + a.Id + "' for new notices ...")
n, t, err := a.getNotices(persistent.data.(PersistentData).LastPublished[a.Id])
if err != nil {
// retry (once)
logger.warn("Couldn't query notices from API endpoint '" + a.Id + "'. Retrying ...")
logger.warn(err)
n, t, err = a.getNotices(persistent.data.(PersistentData).LastPublished[a.Id])
}
if err != nil {
// ok then...
logger.error("Couldn't query notices from API endpoint '" + a.Id + "'")
logger.error(err)
} else if len(n) > 0 {
newNotices = append(newNotices, n...)
lastPublished[a.Id] = t
}
}
logger.debug(fmt.Sprintf("Got %v new notices", len(newNotices)))
if len(newNotices) > 0 {
logger.info("Sending email notifications ...")
// mail recipient : pointer to slice of wid notices to be sent
noticesToBeSent := map[string][]*WidNotice{}
recipientsNotified := 0
var err error
for _, l := range *config.Lists {
// Filter notices for this list
for _, f := range l.Filter {
for _, n := range f.filter(newNotices) {
np := &n
for _, r := range l.Recipients {
if !noticeSliceContains(noticesToBeSent[r], np) {
noticesToBeSent[r] = append(noticesToBeSent[r], np)
}
}
}
}
}
for r, notices := range noticesToBeSent {
// sort by publish date
slices.SortFunc(notices, func(a *WidNotice, b *WidNotice) int {
if a.Published.Equal(b.Published) {
return 0
} else if a.Published.After(b.Published) {
return 1
} else {
return -1
}
})
// send
err = sendNotices(r, notices, mailTemplate, mailAuth, config.SmtpConfiguration, &cache)
if err != nil {
logger.error(err)
} else {
recipientsNotified++
}
}
if recipientsNotified < 1 && err != nil {
logger.error("Couldn't send any mail notification!")
} else {
for id, t := range lastPublished {
persistent.data.(PersistentData).LastPublished[id] = t
persistent.save()
}
logger.info(fmt.Sprintf("Email notifications sent to %v of %v recipients", recipientsNotified, len(noticesToBeSent)))
}
}
dt := int(time.Now().UnixMilli() - t1)
time.Sleep(time.Millisecond * time.Duration((config.ApiFetchInterval * 1000) - dt))
}
}