LCOV - code coverage report
Current view: top level - matchscore/telegram - match_notifications.clj Coverage Total Hit
Test: lcov.info Lines: 98.0 % 205 201
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.telegram.match-notifications
       2              :   (:require
       3              :    [cheshire.core :as json]
       4              :    [clojure.string :as str]
       5              :    [matchscore.telegram.localization :as l10n])
       6              :   (:import
       7              :    (java.nio.charset StandardCharsets)
       8              :    (java.security    MessageDigest)
       9              :    (java.time        Instant OffsetDateTime ZoneId ZonedDateTime)
      10              :    (java.time.format DateTimeFormatter)
      11              :    (java.util        Base64 Date)))
      12              : 
      13              : 
      14            8 : (def setting-key :telegram-match-notifications-enabled)
      15              : 
      16              : 
      17            4 : (def ^:private setting-keys
      18           28 :   [setting-key
      19              :    :telegramMatchNotificationsEnabled
      20              :    :telegram_match_notifications_enabled
      21              :    "telegram-match-notifications-enabled"
      22              :    "telegramMatchNotificationsEnabled"
      23              :    "telegram_match_notifications_enabled"])
      24              : 
      25              : 
      26            4 : (defn setting-value
      27              :  "Returns the explicit boolean notification setting, or nil when the resource
      28              :    inherits/defaults."
      29              :  [settings]
      30            4 :  (loop [[k & more] setting-keys]
      31            6 :    (when k
      32           19 :      (if (contains? (or settings {}) k)
      33           20 :        (let [v (get settings k)] (when (boolean? v) v))
      34            2 :        (recur more)))))
      35              : 
      36              : 
      37            4 : (defn effective-event-enabled?
      38              :  "Event values override template values. Missing values are deliberately off."
      39              :  [event-settings template-settings]
      40            4 :  (let [event-value    (setting-value event-settings)
      41            3 :        template-value (setting-value template-settings)]
      42            8 :    (cond (boolean? event-value)    event-value
      43            4 :          (boolean? template-value) template-value
      44              :          :else                     false)))
      45              : 
      46              : 
      47            4 : (defn user-enabled?
      48              :  "Match notifications are opt-out for linked players."
      49              :  [settings]
      50           12 :  (not= false (setting-value settings)))
      51              : 
      52              : 
      53            4 : (defn- sha256
      54              :   [value]
      55            2 :   (let [digest (.digest
      56            3 :                 (MessageDigest/getInstance "SHA-256")
      57            5 :                 (.getBytes (pr-str value) StandardCharsets/UTF_8))]
      58           14 :     (apply str (map #(format "%02x" (bit-and (int %) 0xff)) digest))))
      59              : 
      60              : 
      61            4 : (defn pairing-revision
      62              :  [{:keys [home-participant-id away-participant-id]}]
      63            9 :  (sha256 [(str home-participant-id) (str away-participant-id)]))
      64              : 
      65              : 
      66            4 : (defn result-revision
      67              :  [{:keys [state home-participant-id away-participant-id result segments]}]
      68            2 :  (sha256
      69            2 :   [state
      70            3 :    (str home-participant-id)
      71            3 :    (str away-participant-id)
      72           12 :    (when result (mapv result [:winner-id :loser-id :home-score :away-score :outcome]))
      73            3 :    (mapv
      74            9 :     #(mapv % [:home-score :away-score :winner-id :state :order])
      75            9 :     (sort-by :order (or segments [])))]))
      76              : 
      77              : 
      78            4 : (defn card-revision
      79              :  [{:keys [state
      80              :           court
      81              :           datetime-start
      82              :           datetime-end
      83              :           round-label
      84              :           event-name
      85              :           event-public-id
      86              :           language
      87              :           timezone
      88              :           home-user-id
      89              :           away-user-id
      90              :           home-name
      91              :           away-name]
      92              :    :as   match}]
      93            2 :  (sha256
      94            2 :   [state
      95            1 :    court
      96            3 :    (str datetime-start)
      97            3 :    (str datetime-end)
      98            1 :    round-label
      99            1 :    event-name
     100            1 :    event-public-id
     101            1 :    language
     102            1 :    timezone
     103            1 :    home-user-id
     104            1 :    away-user-id
     105            1 :    home-name
     106            1 :    away-name
     107            3 :    (result-revision match)]))
     108              : 
     109              : 
     110            4 : (defn- escape-html
     111              :   [value]
     112            3 :   (->
     113            7 :     (str (or value ""))
     114            4 :     (str/replace "&" "&")
     115            4 :     (str/replace "<" "&lt;")
     116            4 :     (str/replace ">" "&gt;")
     117            4 :     (str/replace "\"" "&quot;")
     118            1 :     (str/replace "'" "&#39;")))
     119              : 
     120              : 
     121           16 : (def ^:private datetime-formatter (DateTimeFormatter/ofPattern "dd.MM.yyyy HH:mm"))
     122              : 
     123              : 
     124            4 : (defn- ->instant
     125              :   [value]
     126           10 :   (cond (instance? Instant value)        value
     127            5 :         (instance? OffsetDateTime value) (.toInstant ^OffsetDateTime value)
     128            4 :         (instance? ZonedDateTime value)  (.toInstant ^ZonedDateTime value)
     129            4 :         (instance? Date value)           (.toInstant ^Date value)
     130              :         :else                            nil))
     131              : 
     132              : 
     133            4 : (defn format-datetime
     134              :  [value timezone]
     135            9 :  (when-let [instant (->instant value)]
     136            2 :    (let [zone (try
     137            7 :                 (ZoneId/of (or timezone "UTC"))
     138            0 :                 (catch Exception _ (ZoneId/of "UTC")))]
     139            3 :      (.format datetime-formatter (.atZone ^Instant instant zone)))))
     140              : 
     141              : 
     142            4 : (defn localized-stage-label
     143              :  [locale value]
     144           34 :  (let [label (some->
     145            2 :                value
     146            2 :                str
     147            2 :                str/trim)]
     148           11 :    (when-not (str/blank? label)
     149           13 :      (cond (re-matches #"(?i)^Places\s+(\d+)\s*[-–—]\s*(\d+)$" label)
     150           10 :            (let [[_ from to] (re-matches #"(?i)^Places\s+(\d+)\s*[-–—]\s*(\d+)$" label)]
     151           12 :              (l10n/t locale :telegram.match/places from to))
     152              : 
     153            8 :            (re-matches #"(?i)^Round\s+(\d+)$" label)
     154           10 :            (let [[_ number] (re-matches #"(?i)^Round\s+(\d+)$" label)]
     155           10 :              (l10n/t locale :telegram.match/round-number number))
     156              : 
     157            1 :            :else label))))
     158              : 
     159              : 
     160            4 : (defn- score-values
     161              :   [{:keys [result segments recipient-participant-id away-participant-id]}]
     162            3 :   (when result
     163            6 :     (let [swap?        (and
     164            1 :                         recipient-participant-id
     165            6 :                         (= (str recipient-participant-id) (str away-participant-id)))
     166            1 :           format-score (fn [home away]
     167           12 :                         (when (and (some? home) (some? away))
     168           12 :                           (if swap? (str away "–" home) (str home "–" away))))
     169            8 :           total        (format-score (:home-score result) (:away-score result))
     170            2 :           sets         (->>
     171            1 :                          segments
     172            3 :                          (sort-by :order)
     173           11 :                          (keep #(format-score (:home-score %) (:away-score %)))
     174            1 :                          (str/join ", "))]
     175            4 :       {:total total
     176            6 :        :sets  (when (seq sets) sets)})))
     177              : 
     178              : 
     179            4 : (defn- recipient-outcome
     180              :   [{:keys [result recipient-participant-id]}]
     181           10 :   (let [recipient-id (some->
     182            1 :                        recipient-participant-id
     183            1 :                        str)
     184            9 :         winner-id    (some->
     185            3 :                        (:winner-id result)
     186            1 :                        str)
     187            9 :         loser-id     (some->
     188            3 :                        (:loser-id result)
     189            1 :                        str)]
     190           18 :     (cond (and recipient-id winner-id (= recipient-id winner-id)) :won
     191           12 :           (and recipient-id loser-id (= recipient-id loser-id))   :lost
     192              :           :else                                                   nil)))
     193              : 
     194              : 
     195            4 : (defn- outcome-line
     196              :   [locale match]
     197            6 :   (case (recipient-outcome match)
     198            4 :     :won  (l10n/t locale :telegram.match/won)
     199            4 :     :lost (l10n/t locale :telegram.match/lost)
     200              :     nil))
     201              : 
     202              : 
     203            4 : (defn startapp-link
     204              :  [bot-username path]
     205           46 :  (when (and (not (str/blank? bot-username)) (not (str/blank? path)))
     206            6 :    (let [payload (.encodeToString
     207            9 :                   (.withoutPadding (Base64/getUrlEncoder))
     208            6 :                   (.getBytes path StandardCharsets/UTF_8))]
     209           30 :      (str "https://t.me/" (str/replace bot-username #"^@" "") "?startapp=" payload))))
     210              : 
     211              : 
     212            4 : (defn deep-link
     213              :  [bot-username event-public-id match-uuid]
     214            7 :  (when (and event-public-id match-uuid)
     215            9 :    (startapp-link bot-username (str "/events/" event-public-id "?tab=draws&match=" match-uuid))))
     216              : 
     217              : 
     218            4 : (defn event-link
     219              :  [bot-username event-public-id]
     220           10 :  (when event-public-id (startapp-link bot-username (str "/events/" event-public-id))))
     221              : 
     222              : 
     223            4 : (defn user-profile-link
     224              :  [bot-username user-id]
     225           10 :  (when user-id (startapp-link bot-username (str "/users/" user-id))))
     226              : 
     227              : 
     228            4 : (defn- action-keyboard
     229              :   [locale bot-username match completed?]
     230           10 :   (let [result-url   (deep-link bot-username (:event-public-id match) (:uuid match))
     231            6 :         event-url    (event-link bot-username (:event-public-id match))
     232            6 :         opponent-url (user-profile-link bot-username (:opponent-user-id match))
     233            2 :         result-label (l10n/t
     234            1 :                       locale
     235            4 :                       (if completed? :telegram.match/view-edit-result :telegram.match/enter-result))
     236            7 :         secondary    (cond-> []
     237            4 :                        event-url    (conj
     238            7 :                                      {:text (l10n/t locale :telegram.match/open-event)
     239            1 :                                       :url  event-url})
     240              : 
     241            2 :                        opponent-url (conj
     242            7 :                                      {:text (l10n/t locale :telegram.match/opponent-profile)
     243            1 :                                       :url  opponent-url}))]
     244            8 :     {:inline_keyboard (cond-> []
     245            4 :                         result-url      (conj
     246            7 :                                          [{:text  result-label
     247              :                                            :style "primary"
     248            1 :                                            :url   result-url}])
     249            5 :                         (seq secondary) (conj secondary))}))
     250              : 
     251              : 
     252            4 : (defn- detail-lines
     253              :   [locale match]
     254            9 :   (let [when-text (format-datetime (:datetime-start match) (:timezone match))
     255            6 :         stage     (localized-stage-label locale (:round-label match))]
     256            2 :     (keep
     257            1 :      identity
     258           10 :      [(l10n/t locale :telegram.match/opponent (escape-html (:opponent-name match)))
     259            9 :       (l10n/t locale :telegram.match/event (escape-html (:event-name match)))
     260           10 :       (when stage (l10n/t locale :telegram.match/round (escape-html stage)))
     261           10 :       (when when-text (l10n/t locale :telegram.match/time (escape-html when-text)))
     262           16 :       (when-let [court (some->
     263            3 :                          (:court match)
     264            0 :                          str
     265            0 :                          not-empty)]
     266            0 :         (l10n/t locale :telegram.match/court (escape-html court)))])))
     267              : 
     268              : 
     269            4 : (defn card
     270              :  "Builds the current canonical card and its Mini App button."
     271              :  [locale bot-username match]
     272            6 :  (let [completed? (some? (:result match))
     273            2 :        header     (if completed?
     274           12 :                     (or (outcome-line locale match) (l10n/t locale :telegram.match/result-header))
     275            4 :                     (l10n/t locale :telegram.match/ready-header))
     276            6 :        score      (when completed? (score-values match))
     277            9 :        score-line (when-let [value (:total score)]
     278            7 :                     (l10n/t locale :telegram.match/score (escape-html value)))
     279            9 :        sets-line  (when-let [value (:sets score)]
     280            7 :                     (l10n/t locale :telegram.match/sets (escape-html value)))
     281            3 :        text       (str/join
     282              :                    "\n"
     283            2 :                    (concat
     284            3 :                     [header ""]
     285            4 :                     (detail-lines locale match)
     286            6 :                     (keep identity [score-line sets-line])))]
     287            4 :    {:text         text
     288            6 :     :reply-markup (action-keyboard locale bot-username match completed?)}))
     289              : 
     290              : 
     291            4 : (defn stale-card
     292              :  [locale match]
     293            6 :  {:text         (str/join
     294              :                  "\n"
     295            6 :                  [(l10n/t locale :telegram.match/changed-header)
     296              :                   ""
     297            9 :                   (l10n/t locale :telegram.match/event (escape-html (:event-name match)))
     298            4 :                   (l10n/t locale :telegram.match/changed-body)])
     299            3 :   :reply-markup {:inline_keyboard []}})
     300              : 
     301              : 
     302            4 : (defn result-alert
     303              :  [locale bot-username match deleted?]
     304            7 :  (let [score   (when-not deleted? (score-values match))
     305            7 :        outcome (when-not deleted? (outcome-line locale match))]
     306            6 :    {:text         (str/join
     307              :                    "\n"
     308            2 :                    (keep
     309            1 :                     identity
     310            4 :                     [(l10n/t
     311            1 :                       locale
     312            3 :                       (if deleted?
     313              :                         :telegram.match/result-removed-alert
     314              :                         :telegram.match/result-updated-alert))
     315              :                      ""
     316            1 :                      outcome
     317            9 :                      (l10n/t locale :telegram.match/opponent (escape-html (:opponent-name match)))
     318            9 :                      (l10n/t locale :telegram.match/event (escape-html (:event-name match)))
     319            9 :                      (when-let [value (:total score)]
     320            7 :                        (l10n/t locale :telegram.match/score (escape-html value)))
     321            9 :                      (when-let [value (:sets score)]
     322            7 :                        (l10n/t locale :telegram.match/sets (escape-html value)))]))
     323            8 :     :reply-markup (action-keyboard locale bot-username match (not deleted?))}))
     324              : 
     325              : 
     326            4 : (defn telegram-params
     327              :  [{:keys [telegram-id]} {:keys [text reply-markup]}]
     328            8 :  {:chat_id      telegram-id
     329            1 :   :text         text
     330              :   :parse_mode   "HTML"
     331            3 :   :link_preview_options {:is_disabled true}
     332            3 :   :reply_markup (json/generate-string reply-markup)})
        

Generated by: LCOV version 2.0-1