LCOV - code coverage report
Current view: top level - matchscore/telegram - admin_posts.clj Coverage Total Hit
Test: lcov.info Lines: 96.4 % 166 160
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.telegram.admin-posts
       2              :   "Validation and idempotent delivery for root-controlled rich channel posts."
       3              :   (:require
       4              :    [clojure.string :as str]
       5              :    [matchscore.db.postgres.telegram-publications :as publications]
       6              :    [matchscore.telegram.messages :as messages]
       7              :    [telegrambot-lib.core :as tbot]))
       8              : 
       9              : 
      10            8 : (def ^:private max-message-length 32768)
      11              : 
      12              : 
      13            8 : (def ^:private chat-id-pattern #"^(?:@[A-Za-z][A-Za-z0-9_]{4,}|-?[0-9]+)$")
      14              : 
      15              : 
      16            8 : (def ^:private image-url-pattern #"^https://[^\s]+$")
      17              : 
      18              : 
      19            8 : (def ^:private inline-pattern #"\*\*(.+?)\*\*|`([^`\n]+)`|\[([^\]]+)\]\((https?://[^)\s]+)\)")
      20              : 
      21              : 
      22            8 : (def ^:private media-block-pattern #"^!\[([^\]]*)\]\((https://[^)\s]+)(?:\s+\"([^\"]*)\")?\)$")
      23              : 
      24              : 
      25            8 : (def ^:private media-block-search-pattern
      26              :   #"(?m)^!\[[^\]]*\]\((https://[^)\s]+)(?:\s+\"[^\"]*\")?\)$")
      27              : 
      28              : 
      29            8 : (def ^:private insecure-media-block-pattern
      30              :   #"(?m)^!\[[^\]]*\]\(http://[^)\s]+(?:\s+\"[^\"]*\")?\)$")
      31              : 
      32              : 
      33            4 : (defn- malformed-media-block?
      34              :   [text]
      35            4 :   (some
      36            2 :    (fn [line]
      37           32 :     (and (str/starts-with? (str/trim line) "![") (not (re-matches media-block-pattern line))))
      38            6 :    (str/split-lines text)))
      39              : 
      40              : 
      41            4 : (defn- escape-html
      42              :   [text]
      43            6 :   (->
      44           10 :     (or text "")
      45            8 :     (str/replace "&" "&")
      46            8 :     (str/replace "<" "&lt;")
      47            8 :     (str/replace ">" "&gt;")
      48            8 :     (str/replace "\"" "&quot;")
      49            2 :     (str/replace "'" "&#39;")))
      50              : 
      51              : 
      52            4 : (defn- inline->html
      53              :   [text]
      54           10 :   (let [matcher (re-matcher inline-pattern text)]
      55            4 :     (loop [offset 0
      56            2 :            parts  []]
      57            4 :       (if (.find matcher)
      58            4 :         (let [start (.start matcher)
      59            2 :               end   (.end matcher)
      60            4 :               bold  (.group matcher 1)
      61            4 :               code  (.group matcher 2)
      62            4 :               label (.group matcher 3)
      63            4 :               url   (.group matcher 4)]
      64            2 :           (recur
      65              :            end
      66              :            (cond-> parts
      67              :              (< offset start) (conj (escape-html (subs text offset start)))
      68              :              bold  (conj (str "<b>" (escape-html bold) "</b>"))
      69              :              code  (conj (str "<code>" (escape-html code) "</code>"))
      70              :              label (conj (str "<a href=\"" (escape-html url) "\">" (escape-html label) "</a>")))))
      71            4 :         (apply
      72            2 :          str
      73           34 :          (cond-> parts (< offset (count text)) (conj (escape-html (subs text offset)))))))))
      74              : 
      75              : 
      76            4 : (defn- line->html
      77              :   [line]
      78           18 :   (if-let [[_ alt url caption] (re-matches media-block-pattern line)]
      79           12 :     (str
      80              :      "<figure><img src=\""
      81            6 :      (escape-html url)
      82              :      "\" alt=\""
      83            6 :      (escape-html alt)
      84              :      "\">"
      85           24 :      (when (seq caption) (str "<figcaption>" (escape-html caption) "</figcaption>"))
      86              :      "</figure>")
      87           14 :     (cond (re-matches #"^#{1,6}\s+.+" line)
      88           10 :           (let [[_ title] (re-matches #"^#{1,6}\s+(.+)" line)]
      89           14 :             (str "<b>" (inline->html title) "</b>"))
      90              : 
      91            8 :           (re-matches #"^\s*-\s+.+" line)
      92           22 :           (let [[_ item] (re-matches #"^\s*-\s+(.+)" line)] (str "• " (inline->html item)))
      93              : 
      94            6 :           :else (inline->html line))))
      95              : 
      96              : 
      97            4 : (defn markdown->telegram-html
      98              :  "Creates a safe lightweight browser preview. Telegram receives the original
      99              :    Rich Markdown, not this HTML representation."
     100              :  [markdown]
     101            2 :  (->>
     102           26 :    (str/split (str/replace (or markdown "") "\r\n" "\n") #"\n" -1)
     103            6 :    (map line->html)
     104            6 :    (str/join "\n")
     105            2 :    str/trim))
     106              : 
     107              : 
     108            4 : (defn- validation-error
     109              :   [message]
     110            1 :   (throw
     111            2 :    (ex-info
     112            1 :     message
     113            4 :     {:type    :admin-telegram-validation
     114            1 :      :message message})))
     115              : 
     116              : 
     117            4 : (defn- normalize-chat-id
     118              :   [chat-id]
     119           32 :   (let [chat-id (some->
     120            2 :                   chat-id
     121            2 :                   str
     122            2 :                   str/trim)]
     123           25 :     (when-not (and (seq chat-id) (re-matches chat-id-pattern chat-id))
     124            3 :       (validation-error "Channel must be an @username or numeric Telegram chat ID."))
     125            2 :     chat-id))
     126              : 
     127              : 
     128            4 : (defn- prepare-post
     129              :   [{:keys [text image-url]}]
     130           18 :   (let [text              (str/trim (or text ""))
     131           30 :         image-url         (some->
     132            2 :                             image-url
     133            1 :                             str/trim
     134            1 :                             not-empty)
     135            4 :         text-length       (count text)
     136              :         media-id          "media-1"
     137           12 :         markdown          (cond-> text
     138            4 :                             image-url (str "\n\n![Attached image](tg://photo?id=" media-id ")"))
     139           14 :         inline-image-urls (mapv second (re-seq media-block-search-pattern text))
     140           13 :         media-count       (+ (count inline-image-urls) (if image-url 1 0))
     141            4 :         rich-length       (count markdown)
     142           15 :         rich-message      (cond-> {:markdown markdown}
     143            3 :                             image-url (assoc :media
     144            5 :                                        [{:id    media-id
     145            4 :                                          :media {:type  "photo"
     146            1 :                                                  :media image-url}}]))]
     147            8 :     (when (str/blank? text) (validation-error "Every post must contain text."))
     148            8 :     (when (> rich-length max-message-length)
     149            0 :       (validation-error
     150            0 :        (str "A post is " rich-length " characters; Telegram allows " max-message-length ".")))
     151            8 :     (when (> media-count 50)
     152            0 :       (validation-error "A Rich Message can contain at most 50 media blocks."))
     153           18 :     (when (and image-url (not (re-matches image-url-pattern image-url)))
     154            0 :       (validation-error "Image URLs must use HTTPS and cannot contain spaces."))
     155           11 :     (when (re-find insecure-media-block-pattern text)
     156            3 :       (validation-error "Inline image URLs must use HTTPS."))
     157            9 :     (when (malformed-media-block? text)
     158            2 :       (validation-error
     159            4 :        (str
     160              :         "Inline images must use a complete standalone block such as "
     161              :         "![](https://example.com/image.jpg \"Caption\").")))
     162           20 :     {:html              (markdown->telegram-html text)
     163            2 :      :markdown          text
     164            2 :      :length            text-length
     165            2 :      :image-url         image-url
     166            2 :      :inline-image-urls inline-image-urls
     167            2 :      :rich-message      rich-message}))
     168              : 
     169              : 
     170            4 : (defn prepare
     171              :  "Validates and normalizes an admin publication for a saved preview."
     172              :  [{:keys [chat-id posts disable-notification]}]
     173           16 :  (when-not (<= 1 (count posts) 20)
     174            0 :    (validation-error "A publication must contain between 1 and 20 posts."))
     175           14 :  {:chat-id (normalize-chat-id chat-id)
     176            6 :   :disable-notification (true? disable-notification)
     177            8 :   :posts   (mapv prepare-post posts)})
     178              : 
     179              : 
     180            4 : (defn- telegram-send-rich-message [bot params] (tbot/call bot "sendRichMessage" params))
     181              : 
     182              : 
     183            4 : (defn- saved-result
     184              :   [delivery items]
     185           12 :   {:ok? (= "published" (:status delivery))
     186              :    :already-existed? true
     187            3 :    :delivery-id (:uuid delivery)
     188            3 :    :delivery-status (:status delivery)
     189            1 :    :sent-message-ids (->>
     190            1 :                        items
     191            3 :                        (keep :telegram-message-id)
     192            1 :                        vec)})
     193              : 
     194              : 
     195            4 : (defn publish!
     196              :  "Publishes an immutable saved revision with a database idempotency claim.
     197              :    A transport ambiguity is recorded and never retried automatically."
     198              :  [ds bot requester-id revision idempotency-key]
     199            4 :  (let [content        (:content revision)
     200              :        {:keys [created? delivery]}
     201            9 :        (publications/begin-delivery! ds requester-id (:uuid revision) idempotency-key content)
     202            3 :        delivery-id    (:uuid delivery)
     203            3 :        publication-id (:publication-id revision)]
     204            4 :    (if-not created?
     205            7 :      (saved-result delivery (publications/delivery-items ds delivery-id))
     206            5 :      (loop [remaining        (publications/delivery-items ds delivery-id)
     207            1 :             sent-message-ids []]
     208            8 :        (if-let [item (first remaining)]
     209            1 :          (do
     210            6 :            (publications/mark-item-sending! ds (:uuid item))
     211            1 :            (let [attempt
     212            1 :                  (try
     213            1 :                    {:response (messages/request! telegram-send-rich-message bot (:payload item))}
     214              :                    (catch clojure.lang.ExceptionInfo e
     215           11 :                      {:error (select-keys (ex-data e) [:error_code :description :parameters])})
     216              :                    (catch Exception _
     217            0 :                      {:error {:description "Telegram delivery status is unknown."}}))]
     218            8 :              (if-let [error (:error attempt)]
     219            6 :                (let [known-failure?  (some? (:error_code error))
     220            4 :                      item-status     (if known-failure? "failed" "delivery_unknown")
     221            7 :                      delivery-status (cond (not known-failure?)   "delivery_unknown"
     222            3 :                                            (seq sent-message-ids) "partially_published"
     223              :                                            :else                  "failed")]
     224            8 :                  (publications/mark-item-error! ds (:uuid item) item-status error)
     225            2 :                  (publications/finish-delivery!
     226            1 :                   ds
     227            1 :                   delivery-id
     228            1 :                   publication-id
     229            1 :                   requester-id
     230            1 :                   delivery-status
     231            1 :                   error)
     232            9 :                  {:ok? false
     233              :                   :already-existed? false
     234            1 :                   :delivery-id delivery-id
     235            1 :                   :delivery-status delivery-status
     236            1 :                   :sent-message-ids sent-message-ids
     237            1 :                   :error error})
     238            8 :                (let [message-id (get-in attempt [:response :result :message_id])]
     239            7 :                  (publications/mark-item-sent! ds (:uuid item) message-id)
     240            1 :                  (recur (rest remaining) (cond-> sent-message-ids message-id (conj message-id)))))))
     241            1 :          (do
     242            4 :            (publications/finish-delivery!
     243            1 :             ds
     244            1 :             delivery-id
     245            1 :             publication-id
     246            1 :             requester-id
     247              :             "published"
     248              :             nil)
     249            9 :            {:ok? true
     250              :             :already-existed? false
     251            1 :             :delivery-id delivery-id
     252              :             :delivery-status "published"
     253            1 :             :sent-message-ids sent-message-ids}))))))
        

Generated by: LCOV version 2.0-1