Line data Source code
1 4 : (ns matchscore.utils.rrule
2 : (:require
3 : [clojure.string :as str])
4 : (:import
5 : (java.time Instant LocalDateTime OffsetDateTime ZoneId ZonedDateTime)
6 : (java.time.format DateTimeFormatter)
7 : (java.util ArrayList)
8 : (net.fortuna.ical4j.model Parameter Period PropertyList Recur)
9 : (net.fortuna.ical4j.model.component VEvent)
10 : (net.fortuna.ical4j.model.property DtStart RRule)))
11 :
12 :
13 4 : (defn- number-list->vec
14 : [number-list]
15 9 : (when (and number-list (seq number-list))
16 2 : (vec
17 2 : (map
18 1 : (fn [n]
19 6 : (cond (number? n) (long n)
20 0 : (string? n) (Long/parseLong n)
21 : :else
22 0 : (try
23 0 : (Long/parseLong (str n))
24 0 : (catch Exception _ (str n)))))
25 1 : number-list))))
26 :
27 :
28 4 : (defn- weekday-list->vec
29 : [weekday-list]
30 60 : (when (and weekday-list (seq weekday-list)) (vec (map str weekday-list))))
31 :
32 :
33 4 : (defn- recur->map
34 : [^Recur recur]
35 12 : (when recur
36 8 : (let [freq (.getFrequency recur)
37 4 : until (.getUntil recur)
38 4 : wkst (.getWeekStartDay recur)
39 4 : count (.getCount recur)
40 4 : interval (.getInterval recur)
41 4 : byday (.getDayList recur)
42 4 : bymonth (.getMonthList recur)
43 4 : bymonthday (.getMonthDayList recur)
44 4 : byyearday (.getYearDayList recur)
45 4 : byweekno (.getWeekNoList recur)
46 4 : byhour (.getHourList recur)
47 4 : byminute (.getMinuteList recur)
48 4 : bysecond (.getSecondList recur)
49 4 : bysetpos (.getSetPosList recur)]
50 130 : (cond-> {}
51 44 : freq (assoc :freq (keyword (str/lower-case (str freq))))
52 16 : (pos? interval) (assoc :interval interval)
53 16 : (pos? count) (assoc :count count)
54 4 : until (assoc :until (str until))
55 4 : wkst (assoc :wkst (str wkst))
56 36 : (seq byday) (assoc :byday (weekday-list->vec byday))
57 12 : (seq bymonth) (assoc :bymonth (number-list->vec bymonth))
58 18 : (seq bymonthday) (assoc :bymonthday (number-list->vec bymonthday))
59 12 : (seq byyearday) (assoc :byyearday (number-list->vec byyearday))
60 12 : (seq byweekno) (assoc :byweekno (number-list->vec byweekno))
61 18 : (seq byhour) (assoc :byhour (number-list->vec byhour))
62 18 : (seq byminute) (assoc :byminute (number-list->vec byminute))
63 12 : (seq bysecond) (assoc :bysecond (number-list->vec bysecond))
64 12 : (seq bysetpos) (assoc :bysetpos (number-list->vec bysetpos))))))
65 :
66 :
67 4 : (defn rrule->map
68 : "Parses an iCal4j RRULE into a Clojure map. Accepts a string, RRule, or Recur."
69 : [rrule]
70 30 : (cond (nil? rrule) nil
71 19 : (instance? Recur rrule) (recur->map rrule)
72 28 : (instance? RRule rrule) (recur->map (.getRecur ^RRule rrule))
73 7 : (string? rrule) (recur->map (Recur. rrule))
74 0 : :else (throw (ex-info "Unsupported RRULE input type" {:type (type rrule)}))))
75 :
76 :
77 4 : (defn- dtstart->map
78 : [^DtStart dtstart]
79 12 : (when dtstart
80 12 : (let [tzid-opt (.getParameter dtstart Parameter/TZID)
81 28 : timezone (when (.isPresent tzid-opt) (str (.getValue (.get tzid-opt))))
82 4 : value (.getDate dtstart)
83 24 : dtstart (cond (instance? Instant value) (str value)
84 28 : (instance? ZonedDateTime value) (str (.toInstant ^ZonedDateTime value))
85 0 : (instance? OffsetDateTime value) (str (.toInstant ^OffsetDateTime value))
86 0 : :else (str value))]
87 44 : (cond-> {:dtstart dtstart} timezone (assoc :timezone timezone)))))
88 :
89 :
90 4 : (defn vevent->rrule-map
91 : "Extracts DTSTART and RRULE data from a VEvent and parses them into a Clojure map."
92 : [^VEvent vevent]
93 12 : (when vevent
94 12 : (let [dtstart-opt (.getProperty vevent "DTSTART")
95 8 : rrule-opt (.getProperty vevent "RRULE")
96 24 : dtstart-map (when (.isPresent dtstart-opt) (dtstart->map (.get ^DtStart dtstart-opt)))
97 24 : rrule-map (when (.isPresent rrule-opt) (rrule->map (.get ^RRule rrule-opt)))]
98 44 : (when (or dtstart-map rrule-map) (merge dtstart-map rrule-map)))))
99 :
100 :
101 4 : (defn iso8601->dtstart
102 : "Creates an iCal4j DtStart from an ISO 8601 datetime string."
103 4 : ([datetime-str] (iso8601->dtstart datetime-str nil))
104 : ([datetime-str timezone]
105 4 : (let [instant (Instant/parse datetime-str)]
106 2 : (if timezone
107 : ;; With timezone: convert to ZonedDateTime in that timezone
108 4 : (let [zone-id (ZoneId/of timezone)
109 4 : zdt (ZonedDateTime/ofInstant instant zone-id)]
110 2 : (DtStart. zdt))
111 : ;; UTC: use Instant directly
112 2 : (DtStart. instant)))))
113 :
114 :
115 4 : (def -ical-basic-formatter
116 : "Formatter for basic iCal datetime format: yyyyMMdd'T'HHmmss"
117 12 : (DateTimeFormatter/ofPattern "yyyyMMdd'T'HHmmss"))
118 :
119 :
120 4 : (defn- parse-dtstart-line
121 : "Parses a DTSTART line and returns [DtStart timezone-id]."
122 : [line]
123 16 : (let [line (str/trim line)]
124 8 : (cond
125 : ;; With TZID parameter
126 16 : (str/starts-with? line "DTSTART;TZID=")
127 27 : (let [[params value] (str/split (subs line 8) #":" 2)
128 21 : tzid (second (str/split params #"=" 2))
129 9 : zone-id (ZoneId/of tzid)
130 12 : ldt (LocalDateTime/parse value -ical-basic-formatter)
131 6 : zdt (.atZone ldt zone-id)]
132 12 : [(DtStart. zdt) tzid])
133 :
134 : ;; UTC (ends with Z) or floating time
135 16 : (str/starts-with? line "DTSTART:")
136 20 : (let [value (subs line 8)]
137 20 : (if (str/ends-with? value "Z")
138 : ;; UTC time - use ZonedDateTime for recurrence compatibility
139 44 : (let [ldt (LocalDateTime/parse (subs value 0 (dec (count value))) -ical-basic-formatter)
140 16 : zdt (.atZone ldt (ZoneId/of "UTC"))]
141 16 : [(DtStart. zdt) "UTC"])
142 : ;; Floating time (no timezone) - treat as UTC
143 5 : (let [ldt (LocalDateTime/parse value -ical-basic-formatter)
144 4 : zdt (.atZone ldt (ZoneId/of "UTC"))]
145 4 : [(DtStart. zdt) "UTC"])))
146 :
147 0 : :else (throw (ex-info "Invalid DTSTART format" {:line line})))))
148 :
149 :
150 4 : (defn- parse-rrule-line
151 : "Parses an RRULE line and returns an RRule object."
152 : [line]
153 16 : (let [line (str/trim line)]
154 20 : (if (str/starts-with? line "RRULE:")
155 36 : (let [value (subs line 6) recur (Recur. value)] (RRule. recur))
156 0 : (throw (ex-info "Invalid RRULE format" {:line line})))))
157 :
158 :
159 4 : (defn parse-rrule-string
160 : "Parses an iCal RRULE string with DTSTART into a VEvent object."
161 : [rrule-str]
162 8 : (let [lines (->>
163 12 : (str/split-lines rrule-str)
164 12 : (map str/trim)
165 8 : (remove str/blank?))
166 40 : dtstart-line (first (filter #(str/starts-with? % "DTSTART") lines))
167 40 : rrule-line (first (filter #(str/starts-with? % "RRULE:") lines))]
168 :
169 20 : (when-not dtstart-line (throw (ex-info "DTSTART line is required" {:input rrule-str})))
170 :
171 16 : (let [[dtstart _tzid] (parse-dtstart-line dtstart-line)
172 4 : props (ArrayList.)]
173 : ;; Add DTSTART
174 8 : (.add props dtstart)
175 :
176 : ;; Add RRULE if present
177 28 : (when rrule-line (.add props (parse-rrule-line rrule-line)))
178 :
179 12 : (VEvent. (PropertyList. props)))))
180 :
181 :
182 4 : (defn get-occurrences
183 : "Returns recurrence occurrences for a VEvent within a date range.
184 :
185 : Arguments:
186 : - vevent: A VEvent object with DTSTART and optionally RRULE
187 : - range-start: ISO 8601 string for range start (e.g., \"2026-01-01T00:00:00Z\")
188 : - range-end: ISO 8601 string for range end (e.g., \"2026-12-31T23:59:59Z\")
189 :
190 : Returns:
191 : - A vector of maps with :start and :end instants for each occurrence
192 :
193 : Example:
194 : (get-occurrences vevent \"2026-01-01T00:00:00Z\" \"2026-03-01T00:00:00Z\")
195 : ;; => [{:start #inst \"2026-01-05T09:00:00Z\" :end #inst \"2026-01-05T10:00:00Z\"}
196 : ;; {:start #inst \"2026-01-07T09:00:00Z\" :end #inst \"2026-01-07T10:00:00Z\"}
197 : ;; ...]"
198 : [^VEvent vevent ^String range-start ^String range-end]
199 9 : (let [start-zdt (ZonedDateTime/ofInstant (Instant/parse range-start) (ZoneId/of "UTC"))
200 8 : end-zdt (ZonedDateTime/ofInstant (Instant/parse range-end) (ZoneId/of "UTC"))
201 3 : period (Period. start-zdt end-zdt)
202 2 : recurrence-set (.calculateRecurrenceSet vevent period)]
203 1 : (->>
204 1 : recurrence-set
205 2 : (map
206 1 : (fn [^Period p]
207 4 : {:start (.getStart p)
208 1 : :end (.getEnd p)}))
209 1 : vec)))
210 :
211 :
212 4 : (defn next-occurrence
213 : "The first scheduled start strictly after an instant. Preserve DTSTART's timezone
214 : so recurring wall-clock times stay correct across DST changes."
215 : [rrule-str ^Instant after]
216 12 : (let [vevent (parse-rrule-string rrule-str)
217 12 : seed (.getDate (.get (.getProperty vevent "DTSTART")))
218 6 : rule (.getProperty vevent "RRULE")
219 12 : cursor (ZonedDateTime/ofInstant after (.getZone ^ZonedDateTime seed))]
220 6 : (if (.isPresent rule)
221 23 : (some->
222 15 : (.getNextDate (.getRecur ^RRule (.get rule)) seed cursor)
223 : .toInstant)
224 6 : (when (.isAfter (.toInstant ^ZonedDateTime seed) after) (.toInstant ^ZonedDateTime seed)))))
225 :
226 :
227 4 : (defn min-occurrence-gap-ms
228 : "The shortest distance between consecutive scheduled starts over the year after
229 : an instant, or nil when fewer than two starts remain. Sparser schedules are
230 : measured by their next two starts."
231 : [rrule-str ^Instant after]
232 30 : (let [horizon (.plusSeconds after (* 366 24 60 60))
233 3 : starts (->>
234 9 : (iterate
235 27 : #(some->>
236 : %
237 6 : (next-occurrence rrule-str))
238 3 : after)
239 3 : rest
240 9 : (take-while some?))
241 45 : starts (concat (take 2 starts) (take-while #(.isBefore ^Instant % horizon) (drop 2 starts)))
242 3 : millis #(.toEpochMilli ^Instant %)]
243 66 : (when (next starts) (apply min (map #(- (millis %2) (millis %1)) starts (rest starts))))))
|