Debian Codegraph @

cmd/send-reminders/main.go

raw symbols SCIP
1 // Send email reminders set by users for special occasions.
2 //
3 // Email-reminder allows users to define events that they want to be
4 // reminded of by email.
5 //
6 // This script is meant to be invoked every day by a cron job. It mails
7 // the actual reminders out.
8 //
9 // When run by the root user, it processes all of the spooled reminders.
10 // When run by a specific user, it only processes the reminders set by that
11 // user.
12 //
13 // # Copyright (C) 2024-2025 Francois Marier
14 //
15 // Email-Reminder is free software; you can redistribute it and/or
16 // modify it under the terms of the GNU General Public License as
17 // published by the Free Software Foundation; either version 3 of the
18 // License, or (at your option) any later version.
19 //
20 // Email-Reminder is distributed in the hope that it will be useful,
21 // but WITHOUT ANY WARRANTY; without even the implied warranty of
22 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 // General Public License for more details.
24 //
25 // You should have received a copy of the GNU General Public License
26 // along with Email-Reminder; if not, write to the Free Software
27 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
28 // 02110-1301, USA.
29 package main
30
31 import (
32 "flag"
33 "fmt"
34 "io"
35 "io/fs"
36 "log"
37 "os"
38 "os/user"
39 "path/filepath"
40 "strings"
41 "sync"
42 "time"
43
44 "launchpad.net/email-reminder/internal/config"
45 "launchpad.net/email-reminder/internal/events"
46 "launchpad.net/email-reminder/internal/util"
47 )
48
49 func processEvent(now time.Time, event events.Event, defaultRecipient util.EmailRecipient, conf config.Config, notifier Notifier) {
50 if conf.Verbose {
51 log.Printf("Processing %s", event)
52 }
53 if err := event.Validate(); err != nil {
54 log.Printf("Skipping invalid event '%s': %s", event, err)
55 return
56 }
57
58 recipients := event.GetRecipients(defaultRecipient, conf.MaxRecipientsPerEvent)
59 if len(recipients) == 0 {
60 log.Printf("Skipping '%s': no recipient email addresses configured", event)
61 return
62 }
63
64 for _, reminder := range event.Reminders {
65 isOccurring, when, err := event.IsOccurring(now, reminder)
66 if err != nil {
67 log.Printf("Cannot tell whether '%s' is occurring: %s", event, err)
68 continue
69 }
70 if !isOccurring {
71 continue
72 }
73
74 body, subject, err := event.ReminderMessage(now, when)
75 if err != nil {
76 log.Printf("Skipping '%s': %s", event, err)
77 break
78 }
79
80 if errs := notifier.Send(body, subject, recipients); len(errs) > 0 {
81 log.Printf("Failed to send reminder(s) for '%s': %v", event, errs)
82 notifier.SendDebug(now, event, when, errs, defaultRecipient)
83 }
84
85 break
86 }
87 }
88
89 func processFile(now time.Time, filename string, contents []byte, conf config.Config) {
90 if len(contents) > conf.MaxXMLSizeBytes {
91 log.Printf("Skipping %s: XML file too large (max %d bytes)\n", filename, conf.MaxXMLSizeBytes)
92 return
93 }
94
95 if conf.Verbose {
96 log.Printf("Extracting events from %s\n", filename)
97 }
98
99 user, err := events.LoadUserEvents(filename, contents, conf)
100 if err != nil {
101 log.Printf("Skipping %s: %s", filename, err)
102 return
103 }
104 if conf.Verbose {
105 log.Printf("%d events found in %s\n", len(user.Events), filename)
106 }
107
108 defaultRecipient := user.ToEmailRecipient()
109 notifier := &SmtpNotifier{Conf: conf}
110
111 var wg sync.WaitGroup
112 for _, event := range user.Events {
113 wg.Go(func() {
114 processEvent(now, event, defaultRecipient, conf, notifier)
115 })
116 }
117 wg.Wait()
118 }
119
120 func processUserConfigFile(now time.Time, conf config.Config) {
121 if conf.Verbose {
122 log.Println("Processing only the current user's reminders")
123 }
124
125 homeDir, err := os.UserHomeDir()
126 if err != nil {
127 log.Fatalln("No HOME environment variable set")
128 }
129 configFilename, errors := config.GetUserConfigFilename(homeDir)
130 if configFilename == "" {
131 log.Fatalln("No user config file found.")
132 for _, e := range errors {
133 log.Println(e)
134 }
135 }
136 configFilePath := filepath.Join(homeDir, configFilename)
137
138 file, err := os.OpenInRoot(homeDir, configFilename)
139 if err != nil {
140 log.Fatalf("Aborting due to unreadable %s: %s\n", configFilePath, err)
141 }
142 defer file.Close()
143
144 limitedReader := io.LimitReader(file, int64(conf.MaxXMLSizeBytes)+1) // one extra byte to detect truncated files
145 contents, err := io.ReadAll(limitedReader)
146 if err != nil {
147 log.Fatalf("Aborting due to unreadable %s: %s\n", configFilePath, err)
148 }
149
150 processFile(now, configFilePath, contents, conf)
151 }
152
153 func shouldProcessPath(path string, d fs.DirEntry, spoolDir string, walkErr error, conf config.Config) (process bool, err error) {
154 if walkErr != nil {
155 if path == spoolDir {
156 // If the spoolDir can't be opened, we can't process anything.
157 if conf.Verbose {
158 log.Println(walkErr)
159 }
160 return false, walkErr
161 }
162
163 // Skip files that cannot be opened
164 if conf.Verbose {
165 log.Printf("Skipping unreadable file %s: %s\n", path, walkErr)
166 }
167 return false, nil
168 }
169
170 if strings.HasPrefix(filepath.Base(path), ".") {
171 if d.IsDir() {
172 // Skip hidden dirs and return to the parent dir
173 return false, fs.SkipDir
174 }
175 return false, nil // Skip hidden files but continue with siblings
176 }
177
178 if d.IsDir() {
179 // Don't try to read directories, but keep recursing in them
180 return false, nil
181 }
182
183 return true, nil
184 }
185
186 func processSpooledFile(fullpath string, spoolDir string, now time.Time, conf config.Config) error {
187 relPath, err := filepath.Rel(spoolDir, fullpath)
188 if err != nil {
189 if conf.Verbose {
190 log.Printf("Skipping file %s: cannot determine relative path: %s\n", fullpath, err)
191 }
192 return nil
193 }
194
195 file, err := os.OpenInRoot(spoolDir, relPath)
196 if err != nil {
197 if conf.Verbose {
198 log.Printf("Skipping unreadable file %s: %s\n", fullpath, err)
199 }
200 return nil
201 }
202 defer file.Close()
203
204 limitedReader := io.LimitReader(file, int64(conf.MaxXMLSizeBytes)+1) // one extra byte to detect truncation
205 contents, err := io.ReadAll(limitedReader)
206 if err != nil {
207 if conf.Verbose {
208 log.Printf("Skipping unreadable file %s: %s\n", file.Name(), err)
209 }
210 return nil
211 }
212
213 // Start by deleting the file so that we don't end up in a loop if the file somehow crashes send-reminders:
214 // 1. opening the file
215 // 2. attempting to process it
216 // 3. crashing
217 // 4. opening the file again
218 // etc.
219 if conf.Verbose {
220 log.Printf("Deleting %s\n", file.Name())
221 }
222 if conf.Simulate {
223 log.Println("Simulating, not actually deleting the file")
224 } else {
225 if err := os.Remove(file.Name()); err != nil {
226 if conf.Verbose {
227 log.Printf("Unable to delete %s\n", file.Name())
228 }
229 // Without write access to the spoolDir, fall back to just the current user's reminders
230 // TODO: return nil instead and then only fall back if we've been unable to delete anything from the spoolDir
231 return err
232 }
233 }
234
235 processFile(now, file.Name(), contents, conf)
236 return nil
237 }
238
239 func processFiles(spoolDir string, conf config.Config) {
240 // Set a consistent time for all reminders
241 now := time.Now()
242
243 err := filepath.WalkDir(spoolDir, func(path string, d fs.DirEntry, err error) error {
244 process, walkErr := shouldProcessPath(path, d, spoolDir, err, conf)
245 if walkErr != nil {
246 return walkErr // can be fs.SkipDir or another error
247 }
248 if !process {
249 return nil
250 }
251
252 return processSpooledFile(path, spoolDir, now, conf)
253 })
254 if err != nil {
255 processUserConfigFile(now, conf)
256 }
257 }
258
259 func main() {
260 log.SetFlags(0)
261
262 simulate := flag.Bool("simulate", false, "does not actually send any emails out")
263 verbose := flag.Bool("verbose", false, "print out information about what the program is doing, including the full emails being sent out")
264 version := flag.Bool("version", false, "display the version number")
265 // TODO: add short names too, either hacking it like in https://www.antoniojgutierrez.com/posts/2021-05-14-short-and-long-options-in-go-flags-pkg/
266 // or using another package like golang-github-pborman-getopt-dev in Debian
267 flag.Parse()
268 if *version {
269 fmt.Println("send-reminders " + config.VersionNumber)
270 os.Exit(0)
271 }
272
273 conf := config.ReadSystemWideConfig(*simulate, *verbose)
274
275 // Check for root
276 currentUser, err := user.Current()
277 if err != nil {
278 log.Fatalln(err)
279 }
280 if currentUser.Uid == "0" {
281 log.Println("Warning: for security reasons, this script should not be run as root.")
282 } else if conf.Verbose {
283 log.Printf("Current user is %s (%s)\n", currentUser.Username, currentUser.Uid)
284 }
285
286 if !conf.SendReminders {
287 if conf.Verbose {
288 log.Printf("Nothing to do: reminders are disabled in system-wide configuration file")
289 }
290 os.Exit(0)
291 }
292
293 processFiles(config.SpoolDir, conf)
294 }