Repository Public
1package maintenance23import (4 "bytes"5 "fmt"6 "io"7 "sort"8 "strings"9 "time"10 "unicode/utf8"1112 "github.com/google/uuid"13)1415const (16 icsUTC = "20060102T150405Z"17 icsLocal = "20060102T150405"18 // maxObservances caps the STANDARD/DAYLIGHT sub-components of one19 // VTIMEZONE (the most recent ones are kept).20 maxObservances = 20021 icsProdID = "-//MacLustr Command Center//Maintenance//EN"22 icsCalName = "MacLustr Maintenance"23)2425// WriteICS writes an RFC 5545 VCALENDAR with one VEVENT per window. Windows26// with no occurrence intersecting [from, to) are skipped, as are windows that27// cannot be expanded (unknown zone or recurrence, end <= start) and repeated28// window IDs. now is DTSTAMP; uidDomain is the right-hand side of the UIDs29// (e.g. "clustr.spboucher.ai").30//31// Non-recurring windows use UTC DTSTART/DTEND. Recurring windows use32// DTSTART/DTEND with TZID plus an RRULE equivalent to Expand's rules, and33// every TZID gets a VTIMEZONE generated from Go's tz database.34//35// Lines end with CRLF and are folded at 75 octets without splitting a UTF-836// sequence.37func WriteICS(out io.Writer, windows []Window, from, to, now time.Time, uidDomain string) error {38 type event struct {39 w Window40 loc *time.Location41 }42 var events []event43 seen := map[uuid.UUID]bool{}44 zoneLoc := map[string]*time.Location{}45 zoneFirst := map[string]time.Time{}46 for _, w := range windows {47 if seen[w.ID] {48 continue49 }50 occ, _, err := Expand(w, from, to, 1)51 if err != nil || len(occ) == 0 {52 continue53 }54 loc, err := loadLocation(w.Timezone)55 if err != nil {56 continue57 }58 seen[w.ID] = true59 events = append(events, event{w, loc})60 if recurring(w) {61 first, ok := zoneFirst[w.Timezone]62 if !ok || w.StartsAt.Before(first) {63 zoneFirst[w.Timezone] = w.StartsAt64 }65 zoneLoc[w.Timezone] = loc66 }67 }6869 var b bytes.Buffer70 line := func(s string) { writeFolded(&b, s) }71 line("BEGIN:VCALENDAR")72 line("VERSION:2.0")73 line("PRODID:" + icsProdID)74 line("CALSCALE:GREGORIAN")75 line("METHOD:PUBLISH")76 line("X-WR-CALNAME:" + escapeText(icsCalName))7778 zones := make([]string, 0, len(zoneLoc))79 for z := range zoneLoc {80 zones = append(zones, z)81 }82 sort.Strings(zones)83 for _, z := range zones {84 writeVTimezone(line, z, zoneLoc[z], zoneFirst[z], to)85 }8687 domain := cleanToken(uidDomain)88 for _, e := range events {89 w := e.w90 line("BEGIN:VEVENT")91 line("UID:" + w.ID.String() + "@" + domain)92 line("DTSTAMP:" + now.UTC().Format(icsUTC))93 if !w.UpdatedAt.IsZero() {94 line("LAST-MODIFIED:" + w.UpdatedAt.UTC().Format(icsUTC))95 }96 if recurring(w) {97 tz := ";TZID=" + w.Timezone + ":"98 line("DTSTART" + tz + w.StartsAt.In(e.loc).Format(icsLocal))99 line("DTEND" + tz + w.EndsAt.In(e.loc).Format(icsLocal))100 line("RRULE:" + rrule(w, e.loc))101 } else {102 line("DTSTART:" + w.StartsAt.UTC().Format(icsUTC))103 line("DTEND:" + w.EndsAt.UTC().Format(icsUTC))104 }105 line("SUMMARY:" + escapeText(w.Title))106 if w.Description != "" {107 line("DESCRIPTION:" + escapeText(w.Description))108 }109 if w.Category != "" {110 line("CATEGORIES:" + escapeText(strings.ToUpper(w.Category)))111 }112 if w.Status == StatusCancelled {113 line("STATUS:CANCELLED")114 } else {115 line("STATUS:CONFIRMED")116 }117 line("TRANSP:TRANSPARENT")118 line("END:VEVENT")119 }120 line("END:VCALENDAR")121 _, err := out.Write(b.Bytes())122 return err123}124125func recurring(w Window) bool {126 switch w.Recurrence {127 case RecurrenceDaily, RecurrenceWeekly, RecurrenceMonthly:128 return true129 }130 return false131}132133// rrule builds the RRULE value matching the recurrence rules of Expand. For134// monthly windows on day 29/30/31, "last day of shorter months" is expressed135// with BYMONTHDAY/BYSETPOS.136func rrule(w Window, loc *time.Location) string {137 var sb strings.Builder138 switch w.Recurrence {139 case RecurrenceDaily:140 sb.WriteString("FREQ=DAILY")141 case RecurrenceWeekly:142 sb.WriteString("FREQ=WEEKLY")143 default:144 sb.WriteString("FREQ=MONTHLY")145 }146 if w.RecurrenceUntil != nil {147 sb.WriteString(";UNTIL=" + w.RecurrenceUntil.UTC().Format(icsUTC))148 }149 if w.Recurrence == RecurrenceMonthly {150 switch d := w.StartsAt.In(loc).Day(); d {151 case 31:152 sb.WriteString(";BYMONTHDAY=-1")153 case 30:154 sb.WriteString(";BYMONTHDAY=28,29,30;BYSETPOS=-1")155 case 29:156 sb.WriteString(";BYMONTHDAY=28,29;BYSETPOS=-1")157 default:158 fmt.Fprintf(&sb, ";BYMONTHDAY=%d", d)159 }160 }161 return sb.String()162}163164type observance struct {165 dst bool166 start string // local time of the transition, in the offset before it167 from, to int168 name string169}170171// writeVTimezone emits the VTIMEZONE of one zone: one STANDARD/DAYLIGHT172// observance per real transition of Go's tz database between (first − 1 year)173// and (to + 1 year), or a single STANDARD observance when there is none.174func writeVTimezone(line func(string), name string, loc *time.Location, first, to time.Time) {175 spanStart := first.AddDate(-1, 0, 0)176 spanEnd := to.AddDate(1, 0, 0)177 if !spanEnd.After(first) {178 spanEnd = first.AddDate(1, 0, 0)179 }180 var obs []observance181 t := spanStart.In(loc)182 for i := 0; i < 5000; i++ {183 _, end := t.ZoneBounds()184 if end.IsZero() || !end.Before(spanEnd) || !end.After(t) {185 break186 }187 prevName, prevOff := end.Add(-time.Second).In(loc).Zone()188 after := end.In(loc)189 newName, newOff := after.Zone()190 if prevOff != newOff || prevName != newName {191 obs = append(obs, observance{192 dst: after.IsDST(),193 start: end.UTC().Add(time.Duration(prevOff) * time.Second).Format(icsLocal),194 from: prevOff,195 to: newOff,196 name: newName,197 })198 }199 t = after200 }201 if len(obs) > maxObservances {202 obs = obs[len(obs)-maxObservances:]203 }204 if len(obs) == 0 {205 zn, off := first.In(loc).Zone()206 obs = []observance{{start: "19700101T000000", from: off, to: off, name: zn}}207 }208 line("BEGIN:VTIMEZONE")209 line("TZID:" + name)210 for _, o := range obs {211 kind := "STANDARD"212 if o.dst {213 kind = "DAYLIGHT"214 }215 line("BEGIN:" + kind)216 line("DTSTART:" + o.start)217 line("TZOFFSETFROM:" + formatOffset(o.from))218 line("TZOFFSETTO:" + formatOffset(o.to))219 line("TZNAME:" + escapeText(o.name))220 line("END:" + kind)221 }222 line("END:VTIMEZONE")223}224225// formatOffset formats a UTC offset in seconds as ±HHMM (or ±HHMMSS).226func formatOffset(sec int) string {227 sign := "+"228 if sec < 0 {229 sign, sec = "-", -sec230 }231 h, m, s := sec/3600, sec%3600/60, sec%60232 if s != 0 {233 return fmt.Sprintf("%s%02d%02d%02d", sign, h, m, s)234 }235 return fmt.Sprintf("%s%02d%02d", sign, h, m)236}237238// escapeText escapes an RFC 5545 TEXT value: backslash, semicolon, comma and239// newline (CRLF, CR and LF all become "\n"). Other control characters are240// dropped and invalid UTF-8 is replaced.241func escapeText(s string) string {242 s = strings.ToValidUTF8(s, "�")243 s = strings.ReplaceAll(s, "\r\n", "\n")244 s = strings.ReplaceAll(s, "\r", "\n")245 var sb strings.Builder246 sb.Grow(len(s) + 8)247 for _, r := range s {248 switch {249 case r == '\\':250 sb.WriteString(`\\`)251 case r == ';':252 sb.WriteString(`\;`)253 case r == ',':254 sb.WriteString(`\,`)255 case r == '\n':256 sb.WriteString(`\n`)257 case r == '\t':258 sb.WriteRune(r)259 case r < 0x20 || r == 0x7f:260 default:261 sb.WriteRune(r)262 }263 }264 return sb.String()265}266267// cleanToken removes control characters and spaces (for the UID domain).268func cleanToken(s string) string {269 s = strings.ToValidUTF8(s, "")270 return strings.Map(func(r rune) rune {271 if r <= 0x20 || r == 0x7f {272 return -1273 }274 return r275 }, s)276}277278// writeFolded writes one content line, folded at 75 octets (continuation279// lines start with one space, which counts), never inside a UTF-8 sequence,280// terminated by CRLF.281func writeFolded(b *bytes.Buffer, s string) {282 limit := 75283 for len(s) > limit {284 cut := limit285 for cut > 0 && !utf8.RuneStart(s[cut]) {286 cut--287 }288 if cut == 0 {289 cut = limit290 }291 b.WriteString(s[:cut])292 b.WriteString("\r\n ")293 s = s[cut:]294 limit = 74295 }296 b.WriteString(s)297 b.WriteString("\r\n")298}299