Line data Source code
1 4 : (ns matchscore.telegram.updates
2 : "Pure rendering of a user's pending update rows into one Telegram HTML digest."
3 : (:require
4 : [clojure.string :as str]
5 : [matchscore.i18n :as i18n]
6 : [matchscore.telegram.formatting :as formatting]
7 : [matchscore.telegram.match-notifications :as match-notifications]
8 : [matchscore.utils.countries :as countries])
9 : (:import
10 : (java.time Instant LocalDate ZoneId ZonedDateTime)
11 : (java.time.format DateTimeFormatter)))
12 :
13 :
14 8 : (def ^:private max-lines
15 : "Items per digest (match blocks, draw lines, new-tournament lines); the rest becomes \"…and N more\"."
16 : 30)
17 :
18 :
19 8 : (def ^:private visible-items "Items shown before the rest folds into one expandable blockquote." 6)
20 :
21 :
22 8 : (def ^:private max-chars
23 : "Telegram's 4096 limit counts the text after entity parsing (no tags, no hrefs)."
24 : 3800)
25 :
26 :
27 8 : (def ^:private more-reserve 40)
28 :
29 :
30 4 : (defn- escape-html
31 : [value]
32 6 : (->
33 16 : (str (or value ""))
34 8 : (str/replace "&" "&")
35 8 : (str/replace "<" "<")
36 8 : (str/replace ">" ">")
37 8 : (str/replace "\"" """)
38 2 : (str/replace "'" "'")))
39 :
40 :
41 4 : (defn visible-length
42 : "Length Telegram counts for an HTML message: tags (and their hrefs) removed,
43 : entities counted as one character (UTF-16 units, like Telegram)."
44 : [html]
45 2 : (->
46 14 : (str (or html ""))
47 8 : (str/replace #"<[^>]*>" "")
48 8 : (str/replace #"&(amp|lt|gt|quot|#39);" "_")
49 : count))
50 :
51 :
52 16 : (defn- tr [locale k & args] (apply i18n/translate locale k args))
53 :
54 :
55 4 : (def ^:private months
56 64 : {:en ["Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"]
57 : :uk
58 52 : ["січ." "лют." "бер." "квіт." "трав." "черв." "лип." "серп." "вер." "жовт." "лист." "груд."]})
59 :
60 :
61 4 : (def ^:private weekdays
62 44 : {:en ["Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"]
63 32 : :uk ["Пн" "Вт" "Ср" "Чт" "Пт" "Сб" "Нд"]})
64 :
65 :
66 4 : (defn- ->zone
67 : [tz]
68 12 : (when-not (str/blank? tz)
69 3 : (try
70 6 : (ZoneId/of tz)
71 : (catch Exception _ nil))))
72 :
73 :
74 4 : (defn- ->instant
75 : [value]
76 20 : (cond (instance? Instant value) value
77 6 : (string? value)
78 1 : (try
79 3 : (Instant/parse value)
80 : (catch Exception _ nil))
81 :
82 8 : (instance? java.util.Date value) (.toInstant ^java.util.Date value)
83 8 : (instance? java.time.OffsetDateTime value) (.toInstant ^java.time.OffsetDateTime value)
84 : :else nil))
85 :
86 :
87 4 : (defn- city
88 : [^ZoneId zone]
89 3 : (->
90 1 : (.getId zone)
91 3 : (str/split #"/")
92 1 : last
93 2 : (str/replace "_" " ")))
94 :
95 :
96 16 : (def ^:private hm-formatter (DateTimeFormatter/ofPattern "HH:mm"))
97 :
98 :
99 4 : (defn- day-label
100 : [locale ^ZonedDateTime zdt]
101 3 : (format
102 : "%s %d %s"
103 8 : (get-in weekdays [locale (dec (.getValue (.getDayOfWeek zdt)))])
104 1 : (.getDayOfMonth zdt)
105 7 : (get-in months [locale (dec (.getMonthValue zdt))])))
106 :
107 :
108 4 : (defn format-dual-datetime
109 : "Venue local time with the venue city and, when it differs, the user's time."
110 : [locale instant venue-tz user-tz]
111 8 : (let [locale (formatting/normalize-locale locale)
112 6 : inst (->instant instant)
113 6 : vzone (->zone venue-tz)
114 6 : uzone (->zone user-tz)]
115 14 : (when (and inst vzone)
116 3 : (let [vz (.atZone ^Instant inst vzone)
117 : venue-part
118 14 : (str (day-label locale vz) ", " (.format hm-formatter vz) " (" (city vzone) ")")]
119 12 : (if (and uzone (not= (.getOffset vz) (.getOffset (.atZone ^Instant inst uzone))))
120 3 : (let [uz (.atZone ^Instant inst uzone)
121 3 : same-day (= (.toLocalDate vz) (.toLocalDate uz))
122 2 : utime (if same-day
123 2 : (.format hm-formatter uz)
124 9 : (str (day-label locale uz) ", " (.format hm-formatter uz)))]
125 12 : (str venue-part " · " (tr locale :telegram.updates/your-time utime (city uzone))))
126 1 : venue-part)))))
127 :
128 :
129 4 : (defn- format-dates
130 : [locale start end]
131 2 : (let [parse (fn [v]
132 2 : (try
133 5 : (LocalDate/parse (str v))
134 : (catch Exception _ nil)))
135 3 : s (parse start)
136 8 : e (or (parse end) s)
137 1 : mon (fn [^LocalDate d]
138 7 : (get-in months [locale (dec (.getMonthValue d))]))]
139 3 : (when s
140 14 : (cond (= s e) (str (.getDayOfMonth s) " " (mon s) " " (.getYear s))
141 :
142 9 : (and (= (.getMonth s) (.getMonth e)) (= (.getYear s) (.getYear e)))
143 11 : (str (.getDayOfMonth s) "–" (.getDayOfMonth e) " " (mon s) " " (.getYear s))
144 :
145 : :else
146 0 : (str
147 0 : (.getDayOfMonth s)
148 0 : " " (mon s)
149 0 : " – " (.getDayOfMonth e)
150 0 : " " (mon e)
151 0 : " " (.getYear e))))))
152 :
153 :
154 8 : (def ^:private sponsor-tail #"(?i)\s+(powered|presented|sponsored)\s+by\s+.*$")
155 :
156 :
157 4 : (defn strip-sponsor
158 : "Drops a trailing \"powered/presented/sponsored by ...\" tail from a tournament or event name."
159 : [value]
160 6 : (when value
161 2 : (->
162 6 : (str value)
163 8 : (str/replace sponsor-tail "")
164 2 : str/trim)))
165 :
166 :
167 4 : (defn localize-location
168 : "\"Marsa, MLT\" -> \"Marsa 🇲🇹\" (escaped); a trailing code without a known flag stays."
169 : [location]
170 6 : (when-not (str/blank? location)
171 11 : (if-let [[_ place code] (re-matches #"(.*?)\s*,\s*([A-Za-z]{2,3})\s*" (str location))]
172 8 : (if-let [flag (countries/flag-emoji code)]
173 7 : (str (escape-html place) " " flag)
174 3 : (escape-html location))
175 3 : (escape-html location))))
176 :
177 :
178 4 : (defn localize-round
179 : "Round label in the locale; unknown labels pass through unchanged."
180 : [locale label]
181 11 : (when-not (str/blank? label)
182 6 : (let [label (str/trim (str label))
183 3 : l (str/lower-case label)]
184 4 : (if (= locale :uk)
185 10 : (cond (= l "final") "Фінал"
186 4 : (re-matches #"semi[\s-]?finals?" l) "1/2 фіналу"
187 4 : (re-matches #"quarter[\s-]?finals?" l) "1/4 фіналу"
188 : :else
189 9 : (if-let [[_ n] (re-matches #"round of (\d+)" l)]
190 9 : (str "1/" (quot (parse-long n) 2) " фіналу")
191 5 : (if-let [[_ _ rn fin]
192 4 : (re-matches #"qualif(?:ying|ication)(\s+(?:round\s+(\d+)|(final)))?" l)]
193 3 : (str
194 : "Кваліфікація"
195 10 : (cond rn (str " · раунд " rn)
196 1 : fin " · фінал"
197 : :else ""))
198 4 : (match-notifications/localized-stage-label locale label))))
199 4 : (match-notifications/localized-stage-label locale label)))))
200 :
201 :
202 4 : (defn localize-draw
203 : "Draw name in the locale; unknown names pass through unchanged."
204 : [locale name]
205 11 : (when-not (str/blank? name)
206 6 : (let [name (str/trim (str name))
207 3 : l (str/lower-case name)]
208 4 : (if (= locale :uk)
209 13 : (cond (re-matches #"men(?:['’]s)?" l) "Чоловіки"
210 4 : (re-matches #"women(?:['’]s)?" l) "Жінки"
211 4 : (re-matches #"men(?:['’]s)?\s+qualif(?:ying|ication)" l) "Чоловіки · кваліфікація"
212 4 : (re-matches #"women(?:['’]s)?\s+qualif(?:ying|ication)" l) "Жінки · кваліфікація"
213 : :else
214 9 : (if-let [[_ kind rest] (re-matches #"(?i)(boys|girls)\s+(.+)" name)]
215 11 : (str (if (= "boys" (str/lower-case kind)) "Хлопці " "Дівчата ") rest)
216 1 : name))
217 1 : name))))
218 :
219 :
220 4 : (defn- player-text
221 : "Optional ⭐, flag (text code when no flag), name; the name is bold when `bold?`."
222 : [{:keys [name country followed]} {:keys [star? bold?]}]
223 8 : (let [flag (countries/flag-emoji country)
224 6 : nm (escape-html name)]
225 4 : (str
226 18 : (when (and followed star?) "⭐ ")
227 14 : (when flag (str flag " "))
228 16 : (if bold? (str "<b>" nm "</b>") nm)
229 28 : (when (and (not (str/blank? country)) (nil? flag)) (str " (" (escape-html country) ")")))))
230 :
231 :
232 24 : (def ^:private walkover-outcomes #{"walkover" "no_show" "forfeit" "disqualified"})
233 :
234 :
235 7 : (defn- flip-pair [[a b]] [b a])
236 :
237 :
238 4 : (defn- match-model
239 : "Players in display order (decided before the result: exactly one followed side first,
240 : else home first) and the result expressed in that order."
241 : [{:keys [home away winner total games outcome]}]
242 10 : (let [hf? (boolean (:followed home))
243 8 : af? (boolean (:followed away))
244 8 : one? (not= hf? af?)
245 12 : flipped? (and one? af?)
246 18 : winner (some->
247 2 : winner
248 2 : name)
249 16 : winner (when (#{"home" "away"} winner) winner)
250 2 : ->order (fn [pair]
251 9 : (if flipped? (flip-pair pair) pair))
252 22 : win-side (when winner (if (= winner (if flipped? "away" "home")) :first :second))]
253 25 : {:first (if flipped? away home)
254 7 : :second (if flipped? home away)
255 8 : :followed (when one? :first)
256 2 : :winner-side win-side
257 30 : :has-result? (boolean (or winner (seq total) (seq games)))
258 22 : :total (when (= 2 (count total)) (->order (vec total)))
259 18 : :games (mapv #(->order (vec %)) games)
260 4 : :walkover? (contains?
261 2 : walkover-outcomes
262 16 : (some->
263 2 : outcome
264 1 : name))}))
265 :
266 :
267 4 : (defn- total-text
268 : [{:keys [total]}]
269 40 : (when (and (first total) (second total)) (str (first total) "–" (second total))))
270 :
271 :
272 4 : (defn- games-text
273 : [{:keys [games]}]
274 10 : (when (seq games)
275 6 : (str/join
276 : ", "
277 4 : (map
278 2 : (fn [[a b]]
279 10 : (str a "–" b))
280 2 : games))))
281 :
282 :
283 4 : (defn- result-detail
284 : "The games, or the walkover word, for a result."
285 : [locale m]
286 18 : (if (:walkover? m) (tr locale :telegram.updates/walkover) (games-text m)))
287 :
288 :
289 4 : (defn- players-line
290 : "Line 1. `reveal?` is true only in show mode with a result."
291 : [_locale mode m corrected?]
292 22 : (let [show? (and (= mode "show") (:has-result? m))
293 29 : marked? (and show? (:followed m) (:winner-side m))
294 20 : won? (and marked? (= :first (:winner-side m)))
295 12 : w (when show? (:winner-side m))
296 4 : p1 (player-text
297 6 : (:first m)
298 12 : {:star? (not marked?)
299 6 : :bold? (= :first w)})
300 4 : p2 (player-text
301 6 : (:second m)
302 8 : {:star? true
303 6 : :bold? (= :second w)})
304 28 : mid (if show? (str "<b>" (or (total-text m) "—") "</b>") "—")]
305 33 : (str (when corrected? "✏️ ") (when marked? (if won? "✅ " "❌ ")) p1 " " mid " " p2)))
306 :
307 :
308 4 : (defn- video-links
309 : [locale videos]
310 4 : (->>
311 2 : videos
312 4 : (keep
313 2 : (fn [{:keys [kind url]}]
314 10 : (when-not (str/blank? url)
315 32 : (let [kind (some->
316 2 : kind
317 2 : name
318 2 : str/lower-case)
319 14 : k (cond (= kind "highlights") :telegram.updates/video-highlights
320 8 : (and kind (str/includes? kind "full")) :telegram.updates/video-full
321 : :else :telegram.updates/video-other)]
322 24 : (str "<a href=\"" (escape-html url) "\">" (tr locale k) "</a>")))))
323 2 : (str/join " · ")))
324 :
325 :
326 4 : (defn- match-path
327 : [payload]
328 40 : (when (and (not (str/blank? (:event-public-id payload))) (not (str/blank? (:match-id payload))))
329 20 : (str "/events/" (:event-public-id payload) "?tab=draws&locate=" (:match-id payload))))
330 :
331 :
332 4 : (defn- match-url
333 : [bot-username payload]
334 18 : (some->>
335 6 : (match-path payload)
336 4 : (match-notifications/startapp-link bot-username)))
337 :
338 :
339 4 : (defn- linked
340 : "`label` (already escaped) wrapped in a link to `url` when both are present."
341 : [label url]
342 29 : (if (and (not (str/blank? label)) (not (str/blank? url)))
343 18 : (str "<a href=\"" (escape-html url) "\">" label "</a>")
344 2 : label))
345 :
346 :
347 4 : (defn- match-block
348 : "Two lines (three with videos): players, italic details, video links. The draw
349 : is the section heading above the block, so the details start with the round
350 : (the match link); without a round the draw takes its place."
351 : [{:keys [locale user-tz results-mode bot-username]} {:keys [kind payload corrected?]}]
352 8 : (let [m (match-model payload)
353 8 : url (match-url bot-username payload)
354 2 : mode results-mode
355 12 : round (localize-round locale (:round-label payload))
356 21 : label (if (str/blank? round) (localize-draw locale (:draw-name payload)) round)
357 10 : time (when (= kind "pairing")
358 20 : (format-dual-datetime locale (:starts-at payload) (:venue-tz payload) user-tz))
359 6 : res? (:has-result? m)
360 28 : detail (when (and res? (= mode "show")) (result-detail locale m))
361 20 : spoiler (when (and res? (= mode "spoiler"))
362 4 : (->>
363 8 : [(total-text m)
364 8 : (if (:walkover? m)
365 4 : (result-detail locale m)
366 16 : (some->>
367 6 : (games-text m)
368 12 : (#(str "(" % ")"))))]
369 6 : (remove str/blank?)
370 2 : (str/join " ")))
371 2 : parts (->>
372 14 : [(linked (escape-html label) url)
373 6 : (escape-html detail)
374 6 : (escape-html time)
375 9 : (when corrected? (tr locale :telegram.updates/corrected))
376 12 : (when-not (str/blank? spoiler)
377 14 : (str "<tg-spoiler>" (escape-html spoiler) "</tg-spoiler>"))]
378 4 : (remove str/blank?))
379 12 : links (video-links locale (:videos payload))]
380 4 : (->>
381 14 : [(players-line locale mode m corrected?)
382 26 : (when (seq parts) (str "<i>" (str/join " · " parts) "</i>"))
383 20 : (when-not (str/blank? links) (str "▶️ " links))]
384 6 : (remove nil?)
385 2 : (str/join "\n"))))
386 :
387 :
388 4 : (defn- tier-label
389 : [locale payload]
390 6 : (let [code (str (:tier-code payload))]
391 3 : (when-not
392 9 : (or
393 3 : (str/blank? code)
394 4 : (str/ends-with? code ":other")
395 6 : (contains? #{"esf:junior" "esf:masters" "psa:non-tour"} code))
396 8 : (get payload (if (= locale :uk) :tier-label-uk :tier-label-en)))))
397 :
398 :
399 4 : (defn- tournament-new-block
400 : [{:keys [locale]} {:keys [payload]}]
401 2 : (let [parts (->>
402 10 : [(format-dates locale (:date-start payload) (:date-end payload))
403 5 : (localize-location (:location payload))
404 6 : (escape-html (tier-label locale payload))]
405 2 : (remove str/blank?))]
406 12 : (if (seq parts) (str "<i>" (str/join " · " parts) "</i>") "")))
407 :
408 :
409 4 : (defn- row-text
410 : [ctx
411 : {:keys [kind]
412 : :as row}]
413 6 : (case kind
414 4 : "tournament_new" (tournament-new-block ctx row)
415 6 : "draw_published" (tr (:locale ctx) :telegram.updates/draw-published)
416 8 : (match-block ctx row)))
417 :
418 :
419 4 : (def ^:private kind-order
420 44 : {"tournament_new" 0
421 : "draw_published" 0
422 : "result" 1
423 : "pairing" 2
424 : "video" 3})
425 :
426 :
427 13 : (defn- log2 [n] (Math/round (/ (Math/log n) (Math/log 2))))
428 :
429 :
430 4 : (defn round-rank
431 : "Importance of a round label, lower = closer to the title (shown first): final,
432 : semis, quarters, round of N / 1/N, numbered rounds (later first), placement
433 : matches (better places first), qualifying, then anything unknown (groups).
434 : Same order as the My updates feed (frontend `my/updates/views.cljs`)."
435 : [label]
436 16 : (let [l (str/lower-case (str/trim (str label)))
437 2 : num (fn [re]
438 17 : (some->
439 4 : (re-matches re l)
440 1 : second
441 1 : parse-long))
442 8 : qual? (re-find #"^(qualif|квал)" l)]
443 23 : (cond (str/blank? l) 10000
444 11 : (and (not qual?) (re-matches #"(grand\s+)?finals?|фінал" l)) 0
445 4 : (re-matches #"semi[\s-]?finals?|півфінал(и)?" l) 1
446 4 : (re-matches #"quarter[\s-]?finals?|чвертьфінал(и)?" l) 2
447 9 : (some->
448 3 : (num #"round of (\d+)")
449 : pos?)
450 8 : (max 3 (dec (log2 (num #"round of (\d+)"))))
451 :
452 9 : (some->
453 3 : (num #"1/(\d+)(\s+фіналу)?")
454 : pos?)
455 5 : (log2 (num #"1/(\d+)(\s+фіналу)?"))
456 :
457 8 : (num #"(?:round|раунд|r)\s*(\d+)") (- 1000 (num #"(?:round|раунд|r)\s*(\d+)"))
458 8 : (num #"(?:places|місця)\s+(\d+).*") (+ 2000 (num #"(?:places|місця)\s+(\d+).*"))
459 16 : qual? (if (re-find #"final|фінал" l) 3000 (- 4000 (or (num #".*?(\d+)\D*") 0)))
460 : :else 5000)))
461 :
462 :
463 18 : (defn- match-row? [{:keys [kind]}] (contains? #{"result" "pairing" "video"} kind))
464 :
465 :
466 4 : (defn- category
467 : "Section a match row is listed under: its draw (\"Boys U15\"), unless the draw is
468 : blank or just repeats the round."
469 : [{:keys [payload]}]
470 16 : (let [draw (str/trim (str (:draw-name payload)))
471 14 : round (str/trim (str (:round-label payload)))]
472 26 : (when-not (or (str/blank? draw) (= (str/lower-case draw) (str/lower-case round))) draw)))
473 :
474 :
475 4 : (defn- order-rows
476 : "One tournament's rows: tournament-level rows first, then the matches by category.
477 : Categories go from the one with the most important round down (ties keep feed
478 : order) and rows without a category come last; inside a category, rows go by
479 : round importance, then result, pairing, video, then feed order."
480 : [rows]
481 10 : (let [indexed (map-indexed vector rows)
482 2 : rank (fn [[_ r]]
483 16 : (round-rank (get-in r [:payload :round-label])))
484 2 : cats (->>
485 2 : indexed
486 12 : (filter (comp match-row? second))
487 10 : (group-by (comp category second)))
488 4 : cat-key (into
489 2 : {}
490 4 : (map
491 2 : (fn [[c rs]]
492 34 : [c (if (nil? c) [1 0 0] [0 (apply min (map rank rs)) (ffirst rs)])]))
493 2 : cats)
494 2 : row-key (fn [[i r :as ir]]
495 8 : (if (match-row? r)
496 32 : [1 (cat-key (category r)) (rank ir) (kind-order (:kind r)) i]
497 13 : [0 [0 0 0] 0 (kind-order (:kind r)) i]))]
498 2 : (->>
499 2 : indexed
500 6 : (sort-by row-key)
501 4 : (mapv second))))
502 :
503 :
504 4 : (defn- group-rows
505 : [results-mode rows]
506 21 : (let [rows (if (= results-mode "off") (remove #(= "result" (:kind %)) rows) rows)
507 4 : result-matches (set
508 11 : (when-not (= results-mode "off")
509 6 : (keep
510 26 : #(when (= "result" (:kind %)) (get-in % [:payload :match-id]))
511 2 : rows)))
512 6 : rows (remove
513 10 : #(and
514 10 : (= "pairing" (:kind %))
515 16 : (contains? result-matches (get-in % [:payload :match-id])))
516 2 : rows)
517 24 : rows (vec (filter #(contains? kind-order (:kind %)) rows))]
518 2 : (->>
519 2 : rows
520 6 : (group-by
521 32 : #(let [p (:payload %)] [(= "tournament_new" (:kind %)) (:source p) (:tournament-key p)]))
522 4 : (sort-by
523 2 : (fn [[_ rs]]
524 4 : (.indexOf ^java.util.List rows (first rs))))
525 2 : (map
526 2 : (fn [[[new?] rs]]
527 8 : {:new? new?
528 6 : :rows (order-rows rs)})))))
529 :
530 :
531 4 : (defn- tournament-path
532 : "Where the tournament name leads: the imported event's draws when there is one,
533 : otherwise the PSA/ESF tournament page (same as the My updates feed header)."
534 : [{:keys [source key event]}]
535 20 : (cond event (str "/events/" event "?tab=draws")
536 27 : (and (#{"psa" "esf"} source) (not (str/blank? key)))
537 6 : (str "/explore/" source "/tournaments/" key)
538 :
539 : :else nil))
540 :
541 :
542 4 : (defn- groups
543 : "[{:header html :items [{:text :category}] ...}], one item per draw line or match
544 : block; `:category` is the localized draw a match is listed under (nil for
545 : tournament-level rows and matches without one)."
546 : [{:keys [locale bot-username]
547 : :as ctx}
548 : grouped]
549 60 : (for [{:keys [new? rows]} grouped
550 10 : :let [p (:payload (first rows))
551 10 : name (strip-sponsor (:tournament-name p))
552 24 : event (some #(not-empty (get-in % [:payload :event-public-id])) rows)
553 11 : url (when-not (str/blank? bot-username)
554 18 : (some->>
555 4 : (tournament-path
556 14 : {:source (:source p)
557 6 : :key (:tournament-key p)
558 2 : :event event})
559 4 : (match-notifications/startapp-link bot-username)))
560 2 : items (->>
561 2 : rows
562 4 : (map
563 2 : (fn [r]
564 14 : {:text (row-text ctx r)
565 22 : :category (when (match-row? r) (localize-draw locale (category r)))}))
566 12 : (remove (comp str/blank? :text))
567 2 : vec)]]
568 16 : {:header (when-not (str/blank? name)
569 27 : (str (if new? "🆕" "🏆") " <b>" (linked (escape-html name) url) "</b>"))
570 2 : :items items}))
571 :
572 :
573 11 : (defn- category-heading [category] (str "▸ <b>" (escape-html category) "</b>"))
574 :
575 :
576 4 : (defn- item-lines
577 : "Item texts with a category heading in front of each item that starts a new category."
578 : [items]
579 2 : (->>
580 22 : (map vector items (cons nil (map :category items)))
581 2 : (mapcat
582 2 : (fn [[{:keys [text category]} prev]]
583 25 : (if (and category (not= category prev)) [(category-heading category) text] [text])))))
584 :
585 :
586 4 : (defn- fit
587 : "Keep whole items within the item and visible-character budgets. Returns kept groups and dropped count."
588 : [groups]
589 8 : (let [budget (- max-chars more-reserve)
590 : res
591 4 : (reduce
592 2 : (fn
593 : [{:keys [kept n chars dropped full]
594 : :as st}
595 : {:keys [header items]
596 : :as group}]
597 2 : (let [take-items
598 4 : (loop [its items
599 2 : acc []
600 2 : n n
601 18 : chars (+ chars (if header (+ 2 (visible-length header)) 0))]
602 16 : (if-let [it (first its)]
603 5 : (let [heading (when
604 9 : (and
605 6 : (:category it)
606 9 : (not= (:category it) (:category (peek acc))))
607 5 : (category-heading (:category it)))
608 6 : c (+
609 : 1
610 10 : (visible-length (:text it))
611 11 : (if heading (+ 1 (visible-length heading)) 0))]
612 25 : (if (and (< n max-lines) (<= (+ chars c) budget))
613 2 : (recur (rest its) (conj acc it) (inc n) (+ chars c))
614 6 : {:acc acc
615 1 : :n n
616 1 : :chars chars
617 2 : :left (count its)}))
618 14 : {:acc acc
619 2 : :n n
620 2 : :chars chars
621 : :left 0}))]
622 24 : (if (and (not full) (seq (:acc take-items)))
623 32 : {:kept (conj kept (assoc group :items (:acc take-items)))
624 6 : :n (:n take-items)
625 6 : :chars (:chars take-items)
626 10 : :dropped (+ dropped (:left take-items))
627 8 : :full (pos? (:left take-items))}
628 6 : (assoc st
629 4 : :dropped (+ dropped (count items))
630 : :full true))))
631 22 : {:kept []
632 : :n 0
633 : :chars 0
634 : :dropped 0
635 : :full false}
636 2 : groups)]
637 12 : {:groups (:kept res)
638 6 : :dropped (:dropped res)}))
639 :
640 :
641 4 : (defn- groups-html
642 : [gs]
643 6 : (str/join
644 : "\n\n"
645 40 : (map #(str/join "\n" (remove nil? (cons (:header %) (item-lines (:items %))))) gs)))
646 :
647 :
648 4 : (defn- split-visible
649 : "[visible-groups quoted-groups]: the first `visible-items` items stay visible; a group
650 : cut in the middle continues in the quote under its own header again."
651 : [kept]
652 6 : (loop [[g & more] kept
653 : n 0
654 2 : shown []
655 2 : quoted []]
656 20 : (cond (nil? g) [shown quoted]
657 7 : (>= n visible-items) (recur more n shown (conj quoted g))
658 : :else
659 18 : (let [[a b] (split-at (- visible-items n) (:items g))]
660 2 : (recur
661 : more
662 : (+ n (count a))
663 : (conj shown (assoc g :items (vec a)))
664 : (cond-> quoted (seq b) (conj (assoc g :items (vec b)))))))))
665 :
666 :
667 4 : (defn render-digest
668 : "Render rows into {:text html}. Links (tournament names, rounds, the closing
669 : updates link) need `bot-username`; there are no inline buttons."
670 : [{:keys [locale user-tz results-mode bot-username]} rows]
671 8 : (let [locale (formatting/normalize-locale locale)
672 16 : mode (if (#{"show" "spoiler" "off"} results-mode) results-mode "show")
673 12 : ctx {:locale locale
674 2 : :user-tz user-tz
675 2 : :results-mode mode
676 2 : :bot-username bot-username}
677 : {kept :groups
678 : dropped :dropped}
679 18 : (fit (groups ctx (group-rows mode rows)))
680 6 : [shown quoted] (split-visible kept)
681 11 : updates-link (when-not (str/blank? bot-username)
682 4 : (linked
683 12 : (escape-html (tr locale :telegram.updates/open-updates))
684 8 : (match-notifications/startapp-link bot-username "/my/updates")))
685 4 : footer (->>
686 16 : [(when (pos? dropped) (tr locale :telegram.updates/more dropped)) updates-link]
687 6 : (remove str/blank?)
688 2 : (str/join " · "))
689 21 : blocks (cond-> [(groups-html shown)]
690 9 : (seq quoted) (conj
691 7 : (str "<blockquote expandable>" (groups-html quoted) "</blockquote>"))
692 10 : (seq footer) (conj footer))]
693 12 : {:text (str/join "\n\n" blocks)}))
|