LCOV - code coverage report
Current view: top level - matchscore/jobs - telegram_photo_reminder.clj Coverage Total Hit
Test: lcov.info Lines: 91.3 % 127 116
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.jobs.telegram-photo-reminder
       2              :   "A while after an event is completed, privately asks its host to add photos
       3              :    to the event gallery. The message carries a button that opens the mini app
       4              :    straight on the gallery section of the event edit form."
       5              :   (:require
       6              :    [cheshire.core :as json]
       7              :    [clojure.string :as str]
       8              :    [matchscore.domain.event.repository.postgres :as event-postgres-repo]
       9              :    [matchscore.domain.telegram-chat-message.repository.postgres
      10              :     :as
      11              :     telegram-chat-message-postgres-repo]
      12              :    [matchscore.telegram.event-lock :as event-lock]
      13              :    [matchscore.telegram.formatting :as formatting]
      14              :    [matchscore.telegram.localization :as l10n]
      15              :    [matchscore.telegram.match-notifications :as match-notifications]
      16              :    [next.jdbc :as jdbc]
      17              :    [next.jdbc.result-set :as rs]
      18              :    [taoensso.telemere :as t]
      19              :    [telegrambot-lib.core :as tbot])
      20              :   (:import
      21              :    (java.time Duration Instant OffsetDateTime ZonedDateTime)
      22              :    (java.util Date)))
      23              : 
      24              : 
      25            8 : (def message-kind "photo_reminder")
      26              : 
      27              : 
      28            4 : (def ^:private max-age
      29              :   "Reopening and completing an old event to fix a result should not bring up a
      30              :    reminder about photos from weeks ago."
      31           12 :   (Duration/ofDays 3))
      32              : 
      33              : 
      34            4 : (defn- ->instant
      35              :   [value]
      36            6 :   (cond (instance? Instant value)        value
      37            5 :         (instance? Date value)           (.toInstant ^Date value)
      38            0 :         (instance? OffsetDateTime value) (.toInstant ^OffsetDateTime value)
      39            0 :         (instance? ZonedDateTime value)  (.toInstant ^ZonedDateTime value)
      40              :         :else                            nil))
      41              : 
      42              : 
      43            4 : (defn- escape-html
      44              :   [s]
      45            3 :   (->
      46            1 :     s
      47            4 :     (str/replace "&" "&")
      48            4 :     (str/replace "<" "&lt;")
      49            1 :     (str/replace ">" "&gt;")))
      50              : 
      51              : 
      52            4 : (defn- stale?
      53              :   [event now]
      54           15 :   (when-let [end (->instant (or (:datetime-end event) (:datetime-start event)))]
      55            3 :     (.isBefore end (.minus ^Instant now max-age))))
      56              : 
      57              : 
      58            4 : (defn- has-own-images?
      59              :   "True once the event has a photo uploaded for it. A new event starts with a
      60              :    snapshot of its template's gallery; those assets were uploaded for the
      61              :    template, so they don't count."
      62              :   [pg event-uuid]
      63            2 :   (some?
      64            2 :    (jdbc/execute-one!
      65            1 :     pg
      66            2 :     ["SELECT 1 FROM event_images i
      67              :       JOIN media_assets a ON a.uuid = i.asset_id
      68              :       WHERE i.event_id = ?::uuid AND a.state = 'ready' AND a.resource_type = 'event'
      69              :       LIMIT 1"
      70            3 :      (str event-uuid)])))
      71              : 
      72              : 
      73            4 : (defn reminder-recipient
      74              :  "The one person asked for photos, as a vector of zero or one row: the event's
      75              :    host, else the creator of its template (the event's own creator when it has no
      76              :    template). Only someone who has started the bot can be messaged; when neither
      77              :    can, nobody is asked."
      78              :  [pg event-uuid]
      79            2 :  (jdbc/execute!
      80            1 :   pg
      81            2 :   ["SELECT u.uuid AS user_id, u.telegram_id, u.settings AS user_settings
      82              :     FROM events e
      83              :     LEFT JOIN templates tpl ON tpl.uuid = e.template_id
      84              :     JOIN LATERAL (VALUES (1, e.host_user_id),
      85              :                          (2, CASE WHEN e.template_id IS NULL THEN e.created_by
      86              :                                   ELSE tpl.created_by END))
      87              :          AS candidate(rank, user_id) ON candidate.user_id IS NOT NULL
      88              :     JOIN users u ON u.uuid = candidate.user_id
      89              :     WHERE e.uuid = ?::uuid
      90              :       AND u.telegram_id IS NOT NULL
      91              :       AND u.telegram_bot_access_status = 'confirmed'
      92              :     ORDER BY candidate.rank
      93              :     LIMIT 1"
      94            3 :    (str event-uuid)]
      95            3 :   {:builder-fn rs/as-unqualified-kebab-maps}))
      96              : 
      97              : 
      98            4 : (defn- already-reminded?
      99              :   "Any reminder for this event, deleted or not, so a reopened and re-completed
     100              :    event (or one whose host changed since) never asks twice."
     101              :   [pg event-uuid]
     102            2 :   (some?
     103            2 :    (jdbc/execute-one!
     104            1 :     pg
     105            2 :     ["SELECT 1 FROM telegram_chat_messages WHERE event_id = ?::uuid AND kind = ? LIMIT 1"
     106            3 :      (str event-uuid)
     107            1 :      message-kind])))
     108              : 
     109              : 
     110            4 : (defn- recipient-locale
     111              :   [event recipient]
     112            2 :   (formatting/normalize-locale
     113            4 :    (or
     114            6 :     (get-in recipient [:user-settings :language])
     115            0 :     (get-in recipient [:user-settings "language"])
     116            0 :     (l10n/resource-locale event))))
     117              : 
     118              : 
     119            4 : (defn gallery-path
     120              :  [event]
     121            7 :  (str "/events/" (:public-id event) "/edit?section=images"))
     122              : 
     123              : 
     124            4 : (defn build-message
     125              :  [locale event bot-username]
     126           23 :  (let [name   (some->
     127            3 :                 (:name event)
     128            1 :                 str
     129            1 :                 str/trim
     130            1 :                 not-empty)
     131            2 :        title  (if name
     132            7 :                 (l10n/t locale :telegram.photo-reminder/title (escape-html name))
     133            0 :                 (l10n/t locale :telegram.photo-reminder/title-no-name))
     134            3 :        detail (formatting/event-datetime-detail event)
     135            6 :        url    (match-notifications/startapp-link bot-username (gallery-path event))]
     136            5 :    (cond->
     137            5 :      {:text (str/join
     138              :              "\n\n"
     139            2 :              (remove
     140            1 :               str/blank?
     141           12 :               [(cond-> title detail (str "\n" (escape-html detail)))
     142            4 :                (l10n/t locale :telegram.photo-reminder/body)]))}
     143            2 :      url (assoc :reply-markup
     144           11 :           {:inline_keyboard [[{:text (l10n/t locale :telegram.photo-reminder/button)
     145            1 :                                :url  url}]]}))))
     146              : 
     147              : 
     148            4 : (defn- send!
     149              :   "Returns the Telegram message id, or nil when the message could not be sent
     150              :    (blocked bot, deleted account); a failed reminder is not worth retrying."
     151              :   [bot chat-id {:keys [text reply-markup]}]
     152            1 :   (try
     153            1 :     (->
     154            2 :       (tbot/send-message
     155            1 :        bot
     156            5 :        (cond->
     157            6 :          {:chat_id    chat-id
     158            1 :           :text       text
     159              :           :parse_mode "HTML"}
     160            5 :          reply-markup (assoc :reply_markup (json/generate-string reply-markup))))
     161            4 :       (get-in [:result :message_id]))
     162              :     (catch Exception e
     163            0 :       (t/log!
     164              :        :warn
     165            0 :        {:message   "Failed to send photo reminder (ignored)"
     166            0 :         :chat-id   chat-id
     167            0 :         :exception e})
     168              :       nil)))
     169              : 
     170              : 
     171            4 : (defn- remind-under-lock!
     172              :   [{:keys [pg repos telegram-bot config]} event-uuid now]
     173            8 :   (let [event (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-uuid nil)
     174            1 :         skip  (fn [reason]
     175          100 :                (t/log! :info (str "TG photo-reminder: " (name reason) ", skipping " event-uuid))
     176            6 :                {:status :skipped
     177            1 :                 :reason reason
     178              :                 :count  0})]
     179           10 :     (cond (not event) (skip :event-not-found)
     180            9 :           (not= "completed" (:state event)) (skip :not-completed)
     181            7 :           (stale? event now) (skip :too-old)
     182            7 :           (has-own-images? pg event-uuid) (skip :has-images)
     183            5 :           (str/blank? (:public-id event)) (skip :no-public-id)
     184            7 :           (already-reminded? pg event-uuid) (skip :already-reminded)
     185              :           :else
     186            7 :           (let [bot-username (get-in config [:telegram :bot-username])
     187            4 :                 recipients   (reminder-recipient pg event-uuid)
     188            3 :                 msg-repo     (:telegram-chat-message-postgres-repo repos)
     189            3 :                 sent         (reduce
     190            1 :                               (fn
     191              :                                [sent
     192              :                                 {:keys [telegram-id user-id]
     193              :                                  :as   recipient}]
     194            3 :                                (let [message (build-message
     195            4 :                                               (recipient-locale event recipient)
     196            1 :                                               event
     197            1 :                                               bot-username)]
     198           10 :                                  (if-let [message-id (send! telegram-bot telegram-id message)]
     199            1 :                                    (do
     200            2 :                                      (telegram-chat-message-postgres-repo/record!
     201            1 :                                       msg-repo
     202           10 :                                       {:chat-id     telegram-id
     203            1 :                                        :message-id  message-id
     204              :                                        :sender-kind "bot"
     205            1 :                                        :kind        message-kind
     206            1 :                                        :user-id     user-id
     207            3 :                                        :text        (:text message)
     208            1 :                                        :event-id    event-uuid})
     209            2 :                                      (inc sent))
     210            0 :                                    sent)))
     211              :                               0
     212            1 :                               recipients)]
     213           92 :             (t/log!
     214              :              :info
     215            5 :              (str
     216            1 :               "TG photo-reminder: sent to " sent
     217            2 :               "/" (count recipients)
     218            1 :               " recipient(s) for event " event-uuid))
     219            4 :             {:status :ok
     220            1 :              :count  sent}))))
     221              : 
     222              : 
     223            4 : (defn photo-reminder-job
     224              :  "Goose job: asks the host (or template creator) of a completed event without its
     225              :    own photos to add some. Sent at most once per event."
     226            0 :  ([system-components event-uuid] (photo-reminder-job system-components event-uuid (Instant/now)))
     227              :  ([{:keys [pg repos]
     228              :     :as   system-components}
     229              :    event-uuid
     230              :    now]
     231            6 :   (let [pg (or pg (:ds (:telegram-chat-message-postgres-repo repos)))]
     232            3 :     (event-lock/with-lock
     233            1 :      pg
     234            1 :      event-uuid
     235            9 :      #(remind-under-lock! (assoc system-components :pg pg) event-uuid now)))))
        

Generated by: LCOV version 2.0-1