| 1 | // # Copyright (C) 2025 Francois Marier |
| 2 | // |
| 3 | // Email-Reminder is free software; you can redistribute it and/or |
| 4 | // modify it under the terms of the GNU General Public License as |
| 5 | // published by the Free Software Foundation; either version 3 of the |
| 6 | // License, or (at your option) any later version. |
| 7 | // |
| 8 | // Email-Reminder is distributed in the hope that it will be useful, |
| 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 | // General Public License for more details. |
| 12 | // |
| 13 | // You should have received a copy of the GNU General Public License |
| 14 | // along with Email-Reminder; if not, write to the Free Software |
| 15 | // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
| 16 | // 02110-1301, USA. |
| 17 | package events |
| 18 | |
| 19 | import ( |
| 20 | "encoding/xml" |
| 21 | "fmt" |
| 22 | "log" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "time" |
| 26 | |
| 27 | "launchpad.net/email-reminder/internal/util" |
| 28 | ) |
| 29 | |
| 30 | const ( |
| 31 | hoursPerDay = 24 * time.Hour |
| 32 | maxNameLength = 1024 |
| 33 | maxEmailLength = 254 |
| 34 | ) |
| 35 | |
| 36 | type EventType string |
| 37 | |
| 38 | const ( |
| 39 | EventTypeAnniversary EventType = "anniversary" |
| 40 | EventTypeBirthday EventType = "birthday" |
| 41 | EventTypeYearly EventType = "yearly" |
| 42 | EventTypeMonthly EventType = "monthly" |
| 43 | EventTypeWeekly EventType = "weekly" |
| 44 | ) |
| 45 | |
| 46 | func (et *EventType) UnmarshalText(text []byte) error { |
| 47 | v := strings.TrimSpace(strings.ToLower(string(text))) |
| 48 | switch v { |
| 49 | case string(EventTypeAnniversary): |
| 50 | *et = EventTypeAnniversary |
| 51 | case string(EventTypeBirthday): |
| 52 | *et = EventTypeBirthday |
| 53 | case string(EventTypeYearly): |
| 54 | *et = EventTypeYearly |
| 55 | case string(EventTypeMonthly): |
| 56 | *et = EventTypeMonthly |
| 57 | case string(EventTypeWeekly): |
| 58 | *et = EventTypeWeekly |
| 59 | default: |
| 60 | *et = EventType(v) |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | // Valid values: 0-6 for weekly events, 1-31 otherwise |
| 66 | type EventDay int |
| 67 | |
| 68 | func (ed *EventDay) UnmarshalText(text []byte) error { |
| 69 | value := strings.TrimSpace(strings.ToLower(string(text))) |
| 70 | |
| 71 | // Numeric values |
| 72 | if day, err := strconv.Atoi(value); err == nil { |
| 73 | *ed = EventDay(day) |
| 74 | return nil |
| 75 | } |
| 76 | |
| 77 | // Handle textual day names (like Perl's Date::Manip ParseDate) |
| 78 | dayNames := map[string]int{ |
| 79 | "sunday": 0, |
| 80 | "monday": 1, |
| 81 | "tuesday": 2, |
| 82 | "wednesday": 3, |
| 83 | "thursday": 4, |
| 84 | "friday": 5, |
| 85 | "saturday": 6, |
| 86 | "sun": 0, |
| 87 | "mon": 1, |
| 88 | "tue": 2, |
| 89 | "wed": 3, |
| 90 | "thu": 4, |
| 91 | "fri": 5, |
| 92 | "sat": 6, |
| 93 | } |
| 94 | |
| 95 | if day, exists := dayNames[value]; exists { |
| 96 | *ed = EventDay(day) |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | *ed = EventDay(-1) |
| 101 | return fmt.Errorf("unrecognized day name: %s", value) |
| 102 | } |
| 103 | |
| 104 | type Event struct { |
| 105 | XMLName xml.Name `xml:"event"` |
| 106 | Type EventType `xml:"type,attr"` |
| 107 | Name string `xml:"name"` |
| 108 | Email string `xml:"email,omitempty"` |
| 109 | PartnerName string `xml:"partner_name,omitempty"` |
| 110 | PartnerEmail string `xml:"partner_email,omitempty"` |
| 111 | Reminders []Reminder `xml:"reminders>reminder,omitempty"` |
| 112 | Recipients []Recipient `xml:"recipients>recipient,omitempty"` |
| 113 | Day EventDay `xml:"day,omitempty"` |
| 114 | Month time.Month `xml:"month,omitempty"` |
| 115 | Year int `xml:"year,omitempty"` |
| 116 | } |
| 117 | |
| 118 | func (event Event) Validate() error { |
| 119 | if strings.TrimSpace(event.Name) == "" { |
| 120 | return fmt.Errorf("empty event name") |
| 121 | } |
| 122 | if len(event.Name) > maxNameLength { |
| 123 | return fmt.Errorf("event name exceeds maximum length of %d characters", maxNameLength) |
| 124 | } |
| 125 | |
| 126 | if len(event.Email) > maxEmailLength { |
| 127 | return fmt.Errorf("email exceeds maximum length of %d characters", maxEmailLength) |
| 128 | } |
| 129 | if len(event.PartnerEmail) > maxEmailLength { |
| 130 | return fmt.Errorf("partner email exceeds maximum length of %d characters", maxEmailLength) |
| 131 | } |
| 132 | |
| 133 | if event.Year < 0 { |
| 134 | return fmt.Errorf("%d is not a valid year", event.Year) |
| 135 | } |
| 136 | |
| 137 | switch event.Type { |
| 138 | case EventTypeAnniversary: |
| 139 | if strings.TrimSpace(event.PartnerName) == "" { |
| 140 | return fmt.Errorf("empty partner name") |
| 141 | } |
| 142 | if len(event.PartnerName) > maxNameLength { |
| 143 | return fmt.Errorf("partner name exceeds maximum length of %d characters", maxNameLength) |
| 144 | } |
| 145 | fallthrough |
| 146 | case EventTypeBirthday, EventTypeYearly: |
| 147 | if event.Month < 1 || event.Month > 12 { |
| 148 | return fmt.Errorf("%d is not a valid month", event.Month) |
| 149 | } |
| 150 | fallthrough |
| 151 | case EventTypeMonthly: |
| 152 | if event.Day < 1 || event.Day > 31 { |
| 153 | return fmt.Errorf("%d is not a valid day", event.Day) |
| 154 | } |
| 155 | case EventTypeWeekly: |
| 156 | if event.Day < 0 || event.Day > 7 { |
| 157 | return fmt.Errorf("%d is not a valid day of the week", event.Day) |
| 158 | } |
| 159 | default: |
| 160 | return fmt.Errorf("unknown event type: %s", event.Type) |
| 161 | } |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | func (event Event) IsOccurring(now time.Time, reminder Reminder) (bool, string, error) { |
| 166 | target := now |
| 167 | when := "" |
| 168 | switch reminder.Type { |
| 169 | case ReminderTypeSameDay: |
| 170 | when = "today" |
| 171 | case ReminderTypeDaysBefore: |
| 172 | if reminder.Days <= 0 { |
| 173 | return false, "", fmt.Errorf("invalid reminder days: %d", reminder.Days) |
| 174 | } |
| 175 | target = target.Add(hoursPerDay * time.Duration(reminder.Days)) |
| 176 | if reminder.Days == 1 { |
| 177 | when = fmt.Sprintf("tomorrow (%s)", target.Format("Mon Jan 2")) |
| 178 | } else { |
| 179 | when = fmt.Sprintf("in %d days (%s)", reminder.Days, target.Format("Mon Jan 2")) |
| 180 | } |
| 181 | default: |
| 182 | return false, "", fmt.Errorf("unknown reminder type: %s", reminder.Type) |
| 183 | } |
| 184 | |
| 185 | switch event.Type { |
| 186 | case EventTypeAnniversary, EventTypeBirthday, EventTypeYearly: |
| 187 | return event.IsSameDay(target), when, nil |
| 188 | case EventTypeMonthly: |
| 189 | if int(event.Day) == target.Day() { |
| 190 | return true, when, nil |
| 191 | } else if int(event.Day) > 28 && util.IsLastDayOfTheMonth(target) { |
| 192 | // If it's not possible for a monthly event to occur this month because there |
| 193 | // aren't enough days in the month, then we assume the user wants this event |
| 194 | // to occur on the last day of the month. |
| 195 | return true, when, nil |
| 196 | } |
| 197 | return false, when, nil |
| 198 | case EventTypeWeekly: |
| 199 | return target.Weekday() == event.Day.DayOfTheWeek(), when, nil |
| 200 | default: |
| 201 | return false, when, fmt.Errorf("unknown event type: %s", event.Type) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func (event Event) GetOccurrence(now time.Time) (int, bool) { |
| 206 | if event.Year == 0 { |
| 207 | return 0, false |
| 208 | } |
| 209 | |
| 210 | occurrence := now.Year() - event.Year |
| 211 | if now.Month() < event.Month { |
| 212 | // Haven't quite reached the anniversary month yet |
| 213 | occurrence -= 1 |
| 214 | } else if now.Month() == event.Month && now.Day() < int(event.Day) { |
| 215 | // Handle Feb 29th events correctly |
| 216 | if !event.IsSameDay(now) { |
| 217 | // Haven't quite reached the anniversary day yet |
| 218 | occurrence -= 1 |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | return occurrence, occurrence >= 0 |
| 223 | } |
| 224 | |
| 225 | func (event Event) GetRecipients(fallback util.EmailRecipient, maxRecipients int) []util.EmailRecipient { |
| 226 | to := []util.EmailRecipient{} |
| 227 | |
| 228 | // Look for event-specific recipients |
| 229 | for _, recipient := range event.Recipients { |
| 230 | emailRecipient := recipient.ToEmailRecipient() |
| 231 | if emailRecipient.Email == "" { |
| 232 | log.Printf("Ignoring recipient %s: missing email address", recipient) |
| 233 | continue |
| 234 | } |
| 235 | |
| 236 | if len(to) >= maxRecipients { |
| 237 | log.Printf("Warning: event '%s' has more than %d recipients, ignoring excess recipients", event.Name, maxRecipients) |
| 238 | break |
| 239 | } |
| 240 | |
| 241 | to = append(to, emailRecipient) |
| 242 | } |
| 243 | |
| 244 | if len(to) == 0 && fallback.Email != "" { |
| 245 | // Fall back to default destination email address if configured |
| 246 | to = []util.EmailRecipient{fallback} |
| 247 | } |
| 248 | return to |
| 249 | } |
| 250 | |
| 251 | func (event Event) AnniversaryContact() string { |
| 252 | email := strings.TrimSpace(event.Email) |
| 253 | partnerEmail := strings.TrimSpace(event.PartnerEmail) |
| 254 | if email != "" && partnerEmail != "" { |
| 255 | return fmt.Sprintf("You can reach them at %s and %s respectively.", email, partnerEmail) |
| 256 | } else if email != "" { |
| 257 | return fmt.Sprintf("You can reach %s at %s.", strings.TrimSpace(event.Name), email) |
| 258 | } else if partnerEmail != "" { |
| 259 | return fmt.Sprintf("You can reach %s at %s.", strings.TrimSpace(event.PartnerName), partnerEmail) |
| 260 | } |
| 261 | return "" // No contact details for either person |
| 262 | } |
| 263 | |
| 264 | func (event Event) ReminderMessage(now time.Time, occurringWhen string) (string, string, error) { |
| 265 | msg := "" |
| 266 | subject := strings.TrimSpace(event.Name) |
| 267 | name := strings.TrimSpace(event.Name) |
| 268 | switch event.Type { |
| 269 | case EventTypeAnniversary: |
| 270 | partnerName := strings.TrimSpace(event.PartnerName) |
| 271 | subject = fmt.Sprintf("Anniversary of %s and %s", name, partnerName) |
| 272 | anniversaryString := "anniversary" |
| 273 | specialName := "" |
| 274 | if occurrence, valid := event.GetOccurrence(now.UTC()); valid { |
| 275 | anniversaryString = fmt.Sprintf("%s anniversary", formatOrdinal(occurrence)) |
| 276 | if s := anniversaryName(occurrence); s != "" { |
| 277 | specialName = fmt.Sprintf(" (%s)", s) |
| 278 | } |
| 279 | subject = fmt.Sprintf("%s of %s and %s", anniversaryString, name, partnerName) |
| 280 | } |
| 281 | msg = fmt.Sprintf(`I just want to remind you that the %s%s of %s and %s is %s.`, anniversaryString, specialName, name, partnerName, occurringWhen) |
| 282 | if contactString := event.AnniversaryContact(); contactString != "" { |
| 283 | msg += fmt.Sprintf("\n\n%s", contactString) |
| 284 | } |
| 285 | case EventTypeBirthday: |
| 286 | subject = fmt.Sprintf("%s's birthday", name) |
| 287 | age := "getting one year older" |
| 288 | if occurrence, valid := event.GetOccurrence(now.UTC()); valid { |
| 289 | age = fmt.Sprintf("turning %d", occurrence) |
| 290 | if occurringWhen == "today" { |
| 291 | subject = fmt.Sprintf("%s is now %d", name, occurrence) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | email := strings.TrimSpace(event.Email) |
| 296 | fullName := name |
| 297 | if email != "" { |
| 298 | fullName = fmt.Sprintf("%s (%s)", name, email) |
| 299 | } |
| 300 | msg = fmt.Sprintf("I just want to remind you that %s is %s %s.", fullName, age, occurringWhen) |
| 301 | case EventTypeMonthly, EventTypeWeekly: |
| 302 | msg = fmt.Sprintf(`I just want to remind you of the following event %s: |
| 303 | |
| 304 | %s`, occurringWhen, name) |
| 305 | case EventTypeYearly: |
| 306 | // Use supplied 'now' for deterministic testing instead of current system time |
| 307 | if occurrence, valid := event.GetOccurrence(now.UTC()); valid { |
| 308 | name = fmt.Sprintf("%s %s", formatOrdinal(occurrence+1), name) |
| 309 | } |
| 310 | msg = fmt.Sprintf(`I just want to remind you of the following event %s: |
| 311 | |
| 312 | %s`, occurringWhen, name) |
| 313 | default: |
| 314 | return "", "", fmt.Errorf("unknown event type %s", event.Type) |
| 315 | } |
| 316 | return msg, subject, nil |
| 317 | } |
| 318 | |
| 319 | func (event Event) String() string { |
| 320 | name := strings.TrimSpace(event.Name) |
| 321 | switch event.Type { |
| 322 | case EventTypeBirthday: |
| 323 | if event.Year > 0 { |
| 324 | return fmt.Sprintf("%s's birthday (%d-%02d-%02d)", name, event.Year, event.Month, int(event.Day)) |
| 325 | } |
| 326 | return fmt.Sprintf("%s's birthday (%02d-%02d)", name, event.Month, int(event.Day)) |
| 327 | case EventTypeAnniversary: |
| 328 | return fmt.Sprintf("%s's anniversary (%d-%02d-%02d)", name, event.Year, event.Month, int(event.Day)) |
| 329 | case EventTypeMonthly: |
| 330 | return fmt.Sprintf("%s (monthly on day %d)", name, int(event.Day)) |
| 331 | case EventTypeWeekly: |
| 332 | return fmt.Sprintf("%s (weekly on %s)", name, event.Day.DayOfTheWeek()) |
| 333 | case EventTypeYearly: |
| 334 | return fmt.Sprintf("%s (yearly on %02d-%02d)", name, event.Month, int(event.Day)) |
| 335 | default: |
| 336 | return fmt.Sprintf("%s (%s)", name, event.Type) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | func (e Event) IsSameDay(now time.Time) bool { |
| 341 | if now.Month() == time.February && now.Day() == 28 && int(e.Day) == 29 { |
| 342 | // Feb 29th birthdays are typically celebrated on Feb 28th in non-leap years |
| 343 | return util.IsLastDayOfTheMonth(now) |
| 344 | } |
| 345 | return now.Month() == e.Month && now.Day() == int(e.Day) |
| 346 | } |
| 347 | |
| 348 | func (e EventDay) DayOfTheWeek() time.Weekday { |
| 349 | day := int(e) |
| 350 | if day < 1 || day > 6 { |
| 351 | // Default to Sunday for out of range dates (both 0 and 7 are Sunday in cron) |
| 352 | return time.Sunday |
| 353 | } |
| 354 | return time.Weekday(day) |
| 355 | } |
| 356 | |
| 357 | func anniversaryName(occurrence int) string { |
| 358 | // https://en.wikipedia.org/wiki/Wedding_anniversary#Traditional_anniversary_gifts |
| 359 | names := map[int]string{ |
| 360 | 1: "Paper", |
| 361 | 2: "Cotton", |
| 362 | 3: "Leather", |
| 363 | 4: "Linen", |
| 364 | 5: "Wood", |
| 365 | 6: "Iron", |
| 366 | 7: "Copper", |
| 367 | 8: "Bronze", |
| 368 | 9: "Pottery", |
| 369 | 10: "Tin", |
| 370 | 11: "Steel", |
| 371 | 12: "Silk", |
| 372 | 13: "Lace", |
| 373 | 14: "Ivory", |
| 374 | 15: "Crystal", |
| 375 | 20: "Porcelain", |
| 376 | 25: "Silver", |
| 377 | 30: "Pearl", |
| 378 | 35: "Coral", |
| 379 | 40: "Ruby", |
| 380 | 45: "Sapphire", |
| 381 | 50: "Gold", |
| 382 | 55: "Emerald", |
| 383 | 60: "Diamond", |
| 384 | 70: "Platinum", |
| 385 | } |
| 386 | |
| 387 | if name, exists := names[occurrence]; exists { |
| 388 | return name |
| 389 | } |
| 390 | return "" |
| 391 | } |
| 392 | |
| 393 | func formatOrdinal(n int) string { |
| 394 | lastTwoDigits := n % 100 |
| 395 | if lastTwoDigits >= 11 && lastTwoDigits <= 13 { |
| 396 | return fmt.Sprintf("%dth", n) |
| 397 | } |
| 398 | |
| 399 | switch n % 10 { |
| 400 | case 1: |
| 401 | return fmt.Sprintf("%dst", n) |
| 402 | case 2: |
| 403 | return fmt.Sprintf("%dnd", n) |
| 404 | case 3: |
| 405 | return fmt.Sprintf("%drd", n) |
| 406 | default: |
| 407 | return fmt.Sprintf("%dth", n) |
| 408 | } |
| 409 | } |