Line data Source code
1 4 : (ns matchscore.jobs.telegram-commands
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [clojure.string :as str]
6 : #_[honey.sql :as sql]
7 : #_[matchscore.application.event.add-participant :as add-participant]
8 : #_[matchscore.application.event.remove-participant :as remove-participant]
9 : #_[matchscore.domain.class-participant.command :as class-participant-command]
10 : #_[matchscore.domain.class-participant.repository.postgres :as class-participant-postgres-repo]
11 : #_[matchscore.domain.class.repository.postgres :as class-postgres-repo]
12 : #_[matchscore.domain.event-participant.repository.postgres :as event-participant-postgres-repo]
13 : [matchscore.domain.event-telegram-link.repository.postgres :as event-telegram-link-postgres-repo]
14 : [matchscore.domain.event.repository.postgres :as event-postgres-repo]
15 : [matchscore.domain.participant.repository.postgres :as participant-postgres-repo]
16 : [matchscore.domain.telegram-chat-message.repository.postgres
17 : :as
18 : telegram-chat-message-postgres-repo]
19 : [matchscore.domain.template-telegram-link.repository.postgres
20 : :as
21 : template-telegram-link-postgres-repo]
22 : [matchscore.domain.template.repository.postgres :as template-postgres-repo]
23 : [matchscore.domain.user.query :as user-query]
24 : [matchscore.jobs.scheduler :as scheduler]
25 : [matchscore.jobs.telegram-name-reminder :as name-jobs]
26 : [matchscore.telegram.commands :as commands]
27 : [matchscore.telegram.link-wizard :as link-wizard]
28 : [matchscore.telegram.localization :as l10n]
29 : [matchscore.telegram.notifications-trigger :as notifications-trigger]
30 : [matchscore.telegram.template-summary :as template-summary]
31 : #_[matchscore.utils.db :as utils.db]
32 : #_[next.jdbc :as jdbc]
33 : [taoensso.carmine :as car]
34 : [taoensso.telemere :as t]
35 : [telegrambot-lib.core :as tbot])
36 : #_(:import
37 : (java.time Instant)))
38 :
39 :
40 : ;; ---- audit helpers
41 : ;; ---------------------------------------------------------------------------
42 :
43 :
44 4 : (defn- record-user-cmd!
45 : "Records the user's own command message in the audit table."
46 : [ctx {:keys [chat-id thread-id sender-tg-id sender-uuid message-id]} command target]
47 4 : (commands/record-msg!
48 2 : ctx
49 26 : (cond->
50 20 : {:chat-id chat-id
51 2 : :thread-id thread-id
52 2 : :message-id message-id
53 : :sender-kind "user"
54 : :kind "command"
55 2 : :command command}
56 10 : sender-tg-id (assoc :sender-tg-id sender-tg-id)
57 10 : sender-uuid (assoc :user-id sender-uuid)
58 18 : (:event-id target) (assoc :event-id (:event-id target))
59 14 : (:template-id target) (assoc :template-id (:template-id target)))))
60 :
61 :
62 4 : (defn- reply-and-record!
63 : "Sends a bot reply and records it in the audit table. Returns the bot message id or nil."
64 : [{:keys [telegram-bot]
65 : :as ctx}
66 : {:keys [chat-id thread-id]
67 : :as actor}
68 : text
69 : target]
70 10 : (let [reply (commands/mention-prefixed-text text actor)
71 22 : msg-id (commands/reply! telegram-bot chat-id thread-id (:text reply) (:parse-mode reply))]
72 6 : (when msg-id
73 4 : (commands/record-msg!
74 2 : ctx
75 18 : (cond->
76 20 : {:chat-id chat-id
77 2 : :thread-id thread-id
78 2 : :message-id msg-id
79 : :sender-kind "bot"
80 : :kind "reply"
81 6 : :text (:text reply)}
82 18 : (:event-id target) (assoc :event-id (:event-id target))
83 14 : (:template-id target) (assoc :template-id (:template-id target)))))
84 2 : msg-id))
85 :
86 :
87 4 : (defn- resource-name
88 : [resource]
89 12 : (or
90 44 : (some->
91 6 : (:name resource)
92 2 : str
93 2 : str/trim
94 2 : not-empty)
95 22 : (some->
96 3 : (:public-id resource)
97 1 : str
98 1 : str/trim
99 1 : not-empty)
100 : "resource"))
101 :
102 :
103 4 : (defn- resource-label
104 : [resource]
105 34 : (let [name (some->
106 6 : (:name resource)
107 2 : str
108 2 : str/trim)
109 32 : public-id (some->
110 6 : (:public-id resource)
111 2 : str
112 2 : str/trim)]
113 33 : (cond (and (not (str/blank? name)) (not (str/blank? public-id)))
114 12 : (str name " (id: " public-id ")")
115 :
116 6 : (not (str/blank? name)) name
117 9 : (not (str/blank? public-id)) (str "id: " public-id)
118 : :else "resource")))
119 :
120 :
121 4 : (defn- linked-message
122 : [locale resource-kind resource]
123 12 : (let [message-key (case resource-kind
124 : :template :telegram.reply/linked-template
125 : :event :telegram.reply/linked-event
126 : :telegram.reply/linked)]
127 14 : (l10n/t locale message-key (resource-label resource))))
128 :
129 :
130 4 : (defn- linked-templates-message
131 : [repos chat-id thread-id locale]
132 6 : (let [links (template-telegram-link-postgres-repo/find-all-by-chat-and-thread
133 6 : (:template-telegram-link-postgres-repo repos)
134 2 : chat-id
135 2 : thread-id)
136 6 : templates (keep
137 4 : #(some->
138 4 : (template-postgres-repo/find-by-id
139 6 : (:template-postgres-repo repos)
140 6 : (:template-id %)
141 2 : {}))
142 2 : links)]
143 18 : (when (seq templates) (template-summary/format-linked-templates locale templates))))
144 :
145 :
146 4 : (defn- unlinked-message
147 : [locale resource]
148 14 : (l10n/t locale :telegram.reply/unlinked (resource-name resource)))
149 :
150 :
151 4 : (defn- link-error-message
152 : [locale result resource]
153 1 : (if
154 2 : (contains?
155 3 : #{:error.event-telegram-link/already-linked :error.template-telegram-link/already-linked}
156 5 : (:code (c/extract result)))
157 7 : (l10n/t locale :telegram.reply/already-linked (resource-name resource))
158 7 : (l10n/t locale :telegram.reply/link-failed (resource-name resource))))
159 :
160 :
161 : ;; ---- /link_event
162 : ;; -----------------------------------------------------------------------------
163 :
164 :
165 4 : (defn- handle-link-event!
166 : [{:keys [repos telegram-bot]
167 : :as ctx}
168 : {:keys [chat-id thread-id sender-tg-id sender-uuid]
169 : :as actor}
170 : public-id]
171 10 : (let [event (commands/resolve-event-by-public-id ctx public-id)]
172 20 : (record-user-cmd! ctx actor "link_event" {:event-id (:uuid event)})
173 16 : (cond (nil? event)
174 0 : (do
175 0 : (reply-and-record! ctx actor (str "Event not found: " public-id) nil)
176 0 : (throw (ex-info "event not found" {:type ::abort})))
177 :
178 12 : (not= (:created-by event) sender-uuid)
179 0 : (do
180 0 : (reply-and-record!
181 0 : ctx
182 0 : actor
183 0 : (l10n/t (l10n/resource-locale event) :telegram.reply/not-event-creator)
184 0 : {:event-id (:uuid event)})
185 0 : (throw (ex-info "not creator" {:type ::abort})))
186 :
187 14 : (not (commands/check-chat-admin? telegram-bot chat-id sender-tg-id))
188 0 : (do
189 0 : (reply-and-record!
190 0 : ctx
191 0 : actor
192 0 : (l10n/t (l10n/resource-locale event) :telegram.reply/admin-required-link)
193 0 : {:event-id (:uuid event)})
194 0 : (throw (ex-info "not admin" {:type ::abort})))
195 :
196 : :else
197 4 : (let [chat-title (try
198 4 : (get-in
199 12 : (tbot/get-chat telegram-bot {:chat_id chat-id})
200 6 : [:result :title])
201 : (catch Exception _ nil))
202 4 : upsert-result (event-telegram-link-postgres-repo/upsert!
203 6 : (:event-telegram-link-postgres-repo repos)
204 18 : {:event-id (:uuid event)
205 2 : :chat-id chat-id
206 2 : :thread-id thread-id
207 2 : :linked-by-user-id sender-uuid
208 2 : :chat-title chat-title})]
209 8 : (when (either/left? upsert-result)
210 0 : (reply-and-record!
211 0 : ctx
212 0 : actor
213 0 : (link-error-message (l10n/resource-locale event) upsert-result event)
214 0 : {:event-id (:uuid event)})
215 0 : (throw (ex-info "upsert failed" {:type ::abort})))
216 4 : (reply-and-record!
217 2 : ctx
218 2 : actor
219 14 : (linked-message (l10n/resource-locale event) :event event)
220 10 : {:event-id (:uuid event)})
221 12 : (notifications-trigger/trigger-debounced! ctx (:uuid event))))))
222 :
223 :
224 : ;; ---- /unlink_event
225 : ;; ---------------------------------------------------------------------------
226 :
227 :
228 4 : (defn- handle-unlink-event!
229 : [{:keys [repos telegram-bot goose]
230 : :as ctx}
231 : {:keys [chat-id thread-id sender-tg-id]
232 : :as actor}
233 : public-id]
234 5 : (let [event (commands/resolve-event-by-public-id ctx public-id)]
235 10 : (record-user-cmd! ctx actor "unlink_event" {:event-id (:uuid event)})
236 7 : (cond (nil? event)
237 0 : (do
238 0 : (reply-and-record! ctx actor (str "Event not found: " public-id) nil)
239 0 : (throw (ex-info "event not found" {:type ::abort})))
240 :
241 7 : (not (commands/check-chat-admin? telegram-bot chat-id sender-tg-id))
242 1 : (do
243 2 : (reply-and-record!
244 1 : ctx
245 1 : actor
246 6 : (l10n/t (l10n/resource-locale event) :telegram.reply/admin-required-unlink)
247 5 : {:event-id (:uuid event)})
248 7 : (throw (ex-info "not admin" {:type ::abort})))
249 :
250 : :else
251 1 : (do
252 2 : (event-telegram-link-postgres-repo/delete!
253 3 : (:event-telegram-link-postgres-repo repos)
254 3 : (:uuid event)
255 1 : chat-id
256 1 : thread-id)
257 : ;; Take the list out of the chat it no longer belongs to.
258 3 : (scheduler/schedule-job
259 1 : goose
260 : `matchscore.jobs.telegram-notifications/remove-unlinked-posts-job
261 6 : {:args [(:uuid event)]})
262 2 : (reply-and-record!
263 1 : ctx
264 1 : actor
265 6 : (unlinked-message (l10n/resource-locale event) event)
266 5 : {:event-id (:uuid event)})))))
267 :
268 :
269 : ;; ---- /link_template
270 : ;; --------------------------------------------------------------------------
271 :
272 :
273 4 : (defn- handle-link-template!
274 : [{:keys [repos telegram-bot]
275 : :as ctx}
276 : {:keys [chat-id thread-id sender-tg-id sender-uuid]
277 : :as actor}
278 : public-id]
279 10 : (let [template (commands/resolve-template-by-public-id ctx public-id)]
280 20 : (record-user-cmd! ctx actor "link_template" {:template-id (:uuid template)})
281 8 : (cond
282 8 : (nil? template)
283 0 : (do
284 0 : (reply-and-record! ctx actor (l10n/t :en :telegram.reply/template-not-found public-id) nil)
285 0 : (throw (ex-info "template not found" {:type ::abort})))
286 :
287 12 : (not= (:created-by template) sender-uuid)
288 1 : (do
289 2 : (reply-and-record!
290 1 : ctx
291 1 : actor
292 6 : (l10n/t (l10n/resource-locale template) :telegram.reply/not-template-creator)
293 5 : {:template-id (:uuid template)})
294 7 : (throw (ex-info "not creator" {:type ::abort})))
295 :
296 14 : (not (commands/check-chat-admin? telegram-bot chat-id sender-tg-id))
297 1 : (do
298 2 : (reply-and-record!
299 1 : ctx
300 1 : actor
301 6 : (l10n/t (l10n/resource-locale template) :telegram.reply/admin-required-link)
302 5 : {:template-id (:uuid template)})
303 7 : (throw (ex-info "not admin" {:type ::abort})))
304 :
305 : :else
306 4 : (let [chat-title (try
307 4 : (get-in
308 12 : (tbot/get-chat telegram-bot {:chat_id chat-id})
309 6 : [:result :title])
310 : (catch Exception _ nil))
311 4 : upsert-result (template-telegram-link-postgres-repo/upsert!
312 6 : (:template-telegram-link-postgres-repo repos)
313 18 : {:template-id (:uuid template)
314 2 : :chat-id chat-id
315 2 : :thread-id thread-id
316 2 : :linked-by-user-id sender-uuid
317 2 : :chat-title chat-title})]
318 9 : (when (either/left? upsert-result)
319 2 : (reply-and-record!
320 1 : ctx
321 1 : actor
322 7 : (link-error-message (l10n/resource-locale template) upsert-result template)
323 5 : {:template-id (:uuid template)})
324 7 : (throw (ex-info "upsert failed" {:type ::abort})))
325 8 : (let [locale (l10n/resource-locale template)
326 12 : summary (linked-templates-message repos chat-id thread-id locale)]
327 4 : (reply-and-record!
328 2 : ctx
329 2 : actor
330 26 : (cond-> (linked-message locale :template template) summary (str "\n\n" summary))
331 10 : {:template-id (:uuid template)}))
332 6 : (let [events (event-postgres-repo/find-by-template-id
333 6 : (:event-postgres-repo repos)
334 6 : (:uuid template)
335 2 : {})]
336 34 : (doseq [ev events]
337 0 : (when (contains? #{"active" "scheduled"} (:state ev))
338 0 : (notifications-trigger/trigger-debounced! ctx (:uuid ev)))))))))
339 :
340 :
341 : ;; ---- /unlink_template
342 : ;; ------------------------------------------------------------------------
343 :
344 :
345 4 : (defn- handle-unlink-template!
346 : [{:keys [repos telegram-bot goose]
347 : :as ctx}
348 : {:keys [chat-id thread-id sender-tg-id]
349 : :as actor}
350 : public-id]
351 5 : (let [template (commands/resolve-template-by-public-id ctx public-id)]
352 10 : (record-user-cmd! ctx actor "unlink_template" {:template-id (:uuid template)})
353 3 : (cond
354 4 : (nil? template)
355 1 : (do
356 10 : (reply-and-record! ctx actor (l10n/t :en :telegram.reply/template-not-found public-id) nil)
357 7 : (throw (ex-info "template not found" {:type ::abort})))
358 :
359 7 : (not (commands/check-chat-admin? telegram-bot chat-id sender-tg-id))
360 1 : (do
361 2 : (reply-and-record!
362 1 : ctx
363 1 : actor
364 6 : (l10n/t (l10n/resource-locale template) :telegram.reply/admin-required-unlink)
365 5 : {:template-id (:uuid template)})
366 7 : (throw (ex-info "not admin" {:type ::abort})))
367 :
368 : :else
369 1 : (do
370 2 : (template-telegram-link-postgres-repo/delete!
371 3 : (:template-telegram-link-postgres-repo repos)
372 3 : (:uuid template)
373 1 : chat-id
374 1 : thread-id)
375 : ;; Events that relied on this link lose the chat too.
376 27 : (doseq [event-id (telegram-chat-message-postgres-repo/event-ids-with-main-posts
377 3 : (:telegram-chat-message-postgres-repo repos)
378 3 : (:uuid template)
379 1 : chat-id
380 1 : thread-id)]
381 3 : (scheduler/schedule-job
382 1 : goose
383 : `matchscore.jobs.telegram-notifications/remove-unlinked-posts-job
384 4 : {:args [event-id]}))
385 4 : (let [locale (l10n/resource-locale template)
386 6 : summary (linked-templates-message repos chat-id thread-id locale)]
387 2 : (reply-and-record!
388 1 : ctx
389 1 : actor
390 13 : (cond-> (unlinked-message locale template) summary (str "\n\n" summary))
391 5 : {:template-id (:uuid template)}))))))
392 :
393 :
394 : ;; ---- /join, /leave
395 : ;; ---------------------------------------------------------------------------
396 : ;; Disabled together with :join and :leave in matchscore.telegram.commands/known-commands.
397 : ;; Registration from a chat goes through the buttons in matchscore.jobs.telegram-callbacks.
398 :
399 :
400 : #_(defn- jdbc-rows
401 : "Tiny helper used by resolve-chat-event for raw chat lookups across both link tables."
402 : [pg query-map]
403 : (let [ds (or (:datasource pg) pg)]
404 : (->>
405 : (sql/format query-map)
406 : (jdbc/execute! ds)
407 : (mapv utils.db/unqualify-keys))))
408 :
409 :
410 : #_(defn- resolve-chat-event
411 : "Resolves the event a chat (chat-id, thread-id) is linked to.
412 : 1. Direct telegram_event_links row → that event.
413 : 2. Else all template links → the event only when exactly one active/scheduled
414 : event exists. Multiple candidates are ambiguous and return nil."
415 : [{:keys [pg repos]} chat-id thread-id]
416 : (let [effective-thread (or thread-id -1)
417 : event-repo (:event-postgres-repo repos)
418 : direct-rows (jdbc-rows
419 : pg
420 : {:select [:event-id]
421 : :from [:telegram_event_links]
422 : :where [:and [:= :chat-id chat-id] [:= :thread-id effective-thread]]
423 : :order-by [[:created-datetime :asc]]
424 : :limit 1})
425 : direct-event-id (some->
426 : direct-rows
427 : first
428 : :event-id
429 : str)]
430 : (or
431 : (when direct-event-id (event-postgres-repo/find-by-id event-repo direct-event-id {}))
432 : (let [tmpl-rows (jdbc-rows
433 : pg
434 : {:select [:template-id]
435 : :from [:telegram_template_links]
436 : :where [:and [:= :chat-id chat-id] [:= :thread-id effective-thread]]
437 : :order-by [[:created-datetime :asc]]})
438 : events (->>
439 : tmpl-rows
440 : (mapcat
441 : #(event-postgres-repo/find-by-template-id
442 : event-repo
443 : (str (:template-id %))
444 : {}))
445 : (filter #(contains? #{"active" "scheduled"} (:state %)))
446 : (sort-by :datetime-start)
447 : vec)]
448 : (when (= 1 (count events)) (first events))))))
449 :
450 :
451 : #_(defn- send-deep-link-reply!
452 : "Posts a TWA deep-link reply in the chat for an unregistered Telegram user."
453 : [{:keys [config]
454 : :as ctx}
455 : {:keys [chat-id thread-id message-id]
456 : :as _actor}
457 : target]
458 : (let [bot-username (get-in config [:telegram :bot-username])
459 : locale (:locale target)
460 : startapp? (or (:event-public-id target) (:template-public-id target))
461 : url (commands/deep-link-url bot-username startapp?)
462 : body (if url
463 : (l10n/t locale :telegram.reply/open-to-register url)
464 : (l10n/t locale :telegram.reply/open-to-link))
465 : reply (commands/mention-prefixed-text body _actor)]
466 : (if-let [msg-id (commands/reply!
467 : (:telegram-bot ctx)
468 : chat-id
469 : thread-id
470 : (:text reply)
471 : (:parse-mode reply)
472 : message-id)]
473 : (do
474 : (commands/record-msg!
475 : ctx
476 : (cond->
477 : {:chat-id chat-id
478 : :thread-id thread-id
479 : :message-id msg-id
480 : :sender-kind "bot"
481 : :kind "reply"
482 : :text (:text reply)}
483 : (:event-id target) (assoc :event-id (:event-id target))
484 : (:template-id target) (assoc :template-id (:template-id target))))
485 : msg-id)
486 : nil)))
487 :
488 :
489 : #_(defn- join-event!
490 : "Joins the sender into the requested class. Event registration is still
491 : ensured as the backing record for class membership. Both operations are
492 : idempotent: a participant already registered
493 : into the event can still join additional classes; the same class twice is
494 : reported as a friendly 'already in' message instead of an error."
495 : [{:keys [repos]
496 : :as ctx}
497 : actor
498 : event
499 : class]
500 : (let [event-id (:uuid event)
501 : locale (l10n/message-locale repos event)
502 : sender-uuid (:sender-uuid actor)
503 : add-result (add-participant/execute! ctx event-id sender-uuid)
504 : add-err (when (either/left? add-result) (c/extract add-result))
505 : already-event? (= :error.event-participant/conflict (:code add-err))
506 : participant-id (cond (either/right? add-result) (:participant-id (c/extract add-result))
507 : already-event?
508 : (:participant-id
509 : (event-participant-postgres-repo/find-by-event-id-and-user-id
510 : (:event-participant-postgres-repo repos)
511 : event-id
512 : sender-uuid)))
513 : user-name (commands/resolve-user-name ctx sender-uuid)
514 : notify! (fn [class']
515 : (commands/notify-action!
516 : ctx
517 : {:chat-id (:chat-id actor)
518 : :thread-id (:thread-id actor)
519 : :user-name user-name
520 : :action :joined
521 : :locale locale
522 : :event event
523 : :class class'}))]
524 : (cond (nil? participant-id)
525 : (reply-and-record!
526 : ctx
527 : actor
528 : (l10n/t locale :telegram.reply/could-not-join (or (:message add-err) "unknown error"))
529 : {:event-id event-id})
530 :
531 : (nil? class)
532 : (reply-and-record!
533 : ctx
534 : actor
535 : (l10n/t locale :telegram.reply/choose-class-join)
536 : {:event-id event-id})
537 :
538 : :else
539 : (let [cp-result (class-participant-command/register-participant!
540 : ctx
541 : {:class-id (:uuid class)
542 : :participant-id participant-id
543 : :status "registered"
544 : :registered-at (Instant/now)
545 : :source "matchscore"})
546 : cp-err (when (either/left? cp-result) (c/extract cp-result))]
547 : (cond (either/right? cp-result) (notify! class)
548 :
549 : (= :error.class-participant/conflict (:code cp-err))
550 : (reply-and-record!
551 : ctx
552 : actor
553 : (l10n/t locale :telegram.reply/already-in-class (:name class))
554 : {:event-id event-id})
555 :
556 : :else
557 : (do
558 : (t/log!
559 : :warn
560 : {:message "Failed to register into class"
561 : :class-id (:uuid class)
562 : :participant-id participant-id
563 : :error cp-err})
564 : (reply-and-record!
565 : ctx
566 : actor
567 : (l10n/t
568 : locale
569 : :telegram.reply/could-not-join-class
570 : (or (:message cp-err) "unknown error"))
571 : {:event-id event-id})))))))
572 :
573 :
574 : #_(defn- remaining-class-count
575 : [pg event-id participant-id]
576 : (if-not pg
577 : 1
578 : (let [rows (jdbc-rows
579 : pg
580 : {:select [[[:count :*] :remaining-count]]
581 : :from [[:event_class_participants :cp]]
582 : :join [[:event_classes :c] [:= :c.uuid :cp.class_id]]
583 : :where [:and
584 : [:= :c.event_id [:cast event-id :uuid]]
585 : [:= :cp.participant_id [:cast participant-id :uuid]]]
586 : :limit 1})]
587 : (or (:remaining-count (first rows)) 0))))
588 :
589 :
590 : #_(defn- admin-participant? [participant] (boolean (some #{"admin"} (:roles participant))))
591 :
592 :
593 : #_(defn- remove-event-registration-if-last-class!
594 : "Removes the event-level participant row once the participant has no classes left.
595 : Admins are never removed from the event participant list this way -- leaving a
596 : class only drops their player registration, keeping their admin standing intact."
597 : [{:keys [pg]
598 : :as ctx}
599 : event
600 : participant]
601 : (let [participant-id (:participant-id participant)]
602 : (if
603 : (or
604 : (admin-participant? participant)
605 : (not (zero? (remaining-class-count pg (:uuid event) participant-id))))
606 : (either/right nil)
607 : (let [result (remove-participant/execute! ctx (:uuid event) participant-id)]
608 : (when (either/left? result)
609 : (t/log!
610 : :warn
611 : {:message "Failed to remove event participant after leaving last class"
612 : :event-id (:uuid event)
613 : :participant-id participant-id
614 : :error (c/extract result)}))
615 : result))))
616 :
617 :
618 : #_(defn- leave-event!
619 : [{:keys [repos]
620 : :as ctx}
621 : actor
622 : event
623 : class]
624 : (let [event-id (:uuid event)
625 : locale (l10n/message-locale repos event)
626 : sender-uuid (:sender-uuid actor)
627 : existing (event-participant-postgres-repo/find-by-event-id-and-user-id
628 : (:event-participant-postgres-repo repos)
629 : event-id
630 : sender-uuid)
631 : notify! (fn [class']
632 : (let [user-name (commands/resolve-user-name ctx sender-uuid)]
633 : (commands/notify-action!
634 : ctx
635 : {:chat-id (:chat-id actor)
636 : :thread-id (:thread-id actor)
637 : :user-name user-name
638 : :action :left
639 : :locale locale
640 : :event event
641 : :class class'})))]
642 : (cond (nil? existing)
643 : (reply-and-record!
644 : ctx
645 : actor
646 : (l10n/t locale :telegram.reply/not-registered-event)
647 : {:event-id event-id})
648 :
649 : (nil? class)
650 : (reply-and-record!
651 : ctx
652 : actor
653 : (l10n/t locale :telegram.reply/choose-class-leave)
654 : {:event-id event-id})
655 :
656 : class
657 : (let [class-participant (class-participant-postgres-repo/find-by-class-and-participant
658 : (:class-participant-postgres-repo repos)
659 : (:uuid class)
660 : (:participant-id existing))]
661 : (if class-participant
662 : (do
663 : (class-participant-postgres-repo/delete-by-class-and-participant!
664 : (:class-participant-postgres-repo repos)
665 : (:uuid class)
666 : (:participant-id existing))
667 : (let [cleanup-result
668 : (remove-event-registration-if-last-class! ctx event existing)]
669 : (if (either/left? cleanup-result)
670 : (reply-and-record!
671 : ctx
672 : actor
673 : (l10n/t
674 : locale
675 : :telegram.reply/could-not-leave-class
676 : (or (:message (c/extract cleanup-result)) "unknown error"))
677 : {:event-id event-id})
678 : (notify! class))))
679 : (reply-and-record!
680 : ctx
681 : actor
682 : (l10n/t locale :telegram.reply/not-registered-class)
683 : {:event-id event-id})))
684 :
685 : :else nil)))
686 :
687 :
688 : #_(defn- resolve-command-class
689 : [{:keys [repos]
690 : :as ctx}
691 : event
692 : class-public-id]
693 : (if class-public-id
694 : (let [class (commands/resolve-class-by-public-id ctx (:uuid event) class-public-id)]
695 : (if class
696 : {:status :resolved
697 : :class class}
698 : {:status :not-found}))
699 : (let [classes
700 : (class-postgres-repo/find-by-event-id (:class-postgres-repo repos) (:uuid event))]
701 : (if (= 1 (count classes))
702 : {:status :resolved
703 : :class (first classes)}
704 : {:status :choose
705 : :classes classes}))))
706 :
707 :
708 : #_(defn- handle-join!
709 : [ctx
710 : {:keys [chat-id thread-id sender-uuid]
711 : :as actor}
712 : class-public-id]
713 : (let [event (resolve-chat-event ctx chat-id thread-id)]
714 : (record-user-cmd! ctx actor "join" {:event-id (:uuid event)})
715 : (cond
716 : (nil? event) (reply-and-record! ctx actor (l10n/t :en :telegram.reply/chat-not-linked) nil)
717 :
718 : :else
719 : (let [locale (l10n/message-locale (:repos ctx) event)
720 : resolved-class (resolve-command-class ctx event class-public-id)
721 : class (:class resolved-class)
722 : target {:event-id (:uuid event)}]
723 : (case (:status resolved-class)
724 : :not-found
725 : (do
726 : (reply-and-record!
727 : ctx
728 : actor
729 : (l10n/t locale :telegram.reply/class-not-found class-public-id)
730 : target)
731 : (throw (ex-info "class not found" {:type ::abort})))
732 :
733 : :choose
734 : (reply-and-record! ctx actor (l10n/t locale :telegram.reply/choose-class-join) target)
735 :
736 : :resolved
737 : (if sender-uuid
738 : (join-event! ctx actor event class)
739 : (send-deep-link-reply!
740 : ctx
741 : actor
742 : {:event-id (:uuid event)
743 : :event-public-id (:public-id event)
744 : :locale locale})))))))
745 :
746 :
747 : #_(defn- handle-leave!
748 : [ctx
749 : {:keys [chat-id thread-id sender-uuid]
750 : :as actor}
751 : class-public-id]
752 : (let [event (resolve-chat-event ctx chat-id thread-id)]
753 : (record-user-cmd! ctx actor "leave" {:event-id (:uuid event)})
754 : (cond
755 : (nil? event) (reply-and-record! ctx actor (l10n/t :en :telegram.reply/chat-not-linked) nil)
756 :
757 : (nil? sender-uuid)
758 : (reply-and-record!
759 : ctx
760 : actor
761 : (l10n/t (l10n/message-locale (:repos ctx) event) :telegram.reply/open-to-link)
762 : {:event-id (:uuid event)})
763 :
764 : :else
765 : (let [locale (l10n/message-locale (:repos ctx) event)
766 : resolved-class (resolve-command-class ctx event class-public-id)
767 : class (:class resolved-class)
768 : target {:event-id (:uuid event)}]
769 : (case (:status resolved-class)
770 : :not-found
771 : (do
772 : (reply-and-record!
773 : ctx
774 : actor
775 : (l10n/t locale :telegram.reply/class-not-found class-public-id)
776 : target)
777 : (throw (ex-info "class not found" {:type ::abort})))
778 :
779 : :choose
780 : (reply-and-record! ctx actor (l10n/t locale :telegram.reply/choose-class-leave) target)
781 :
782 : :resolved (leave-event! ctx actor event class))))))
783 :
784 :
785 : ;; ---- linking from the bot's private chat
786 : ;; ---------------------------------------------------------------------------
787 :
788 :
789 4 : (defn- wizard-resource
790 : [ctx cmd public-id]
791 4 : (if (= :link_template cmd)
792 4 : (commands/resolve-template-by-public-id ctx public-id)
793 4 : (commands/resolve-event-by-public-id ctx public-id)))
794 :
795 :
796 4 : (defn- start-link-wizard!
797 : "Answers a private `/start lt_<id>` or `/start le_<id>` with a button that lets
798 : the creator pick the group to link. The pick arrives in `process-chat-shared-job`."
799 : [{:keys [redis telegram-bot]
800 : :as ctx}
801 : {:keys [chat-id sender-tg-id sender-uuid]}
802 : {:keys [cmd public-id]}]
803 5 : (let [template? (= :link_template cmd)
804 5 : resource (wizard-resource ctx cmd public-id)
805 5 : locale (if resource (l10n/resource-locale resource) :en)
806 6 : say! #(commands/reply! telegram-bot chat-id nil %)]
807 8 : (cond (nil? sender-uuid) (say! (l10n/t :en :telegram.reply/open-to-link))
808 :
809 4 : (nil? resource)
810 0 : (say!
811 0 : (if template?
812 0 : (l10n/t :en :telegram.reply/template-not-found public-id)
813 0 : (str "Event not found: " public-id)))
814 :
815 6 : (not= (:created-by resource) sender-uuid)
816 2 : (say!
817 2 : (l10n/t
818 1 : locale
819 3 : (if template? :telegram.reply/not-template-creator :telegram.reply/not-event-creator)))
820 :
821 : :else
822 3 : (let [request-id (link-wizard/new-request-id)]
823 2 : (link-wizard/save-request!
824 1 : redis
825 1 : sender-tg-id
826 1 : request-id
827 6 : {:cmd (name cmd)
828 1 : :public-id public-id})
829 2 : (link-wizard/send!
830 1 : telegram-bot
831 1 : chat-id
832 7 : (l10n/t locale :telegram.reply/pick-group (resource-label resource))
833 2 : (link-wizard/pick-group-markup
834 1 : request-id
835 4 : (l10n/t locale :telegram.reply/pick-group-button)))))))
836 :
837 :
838 4 : (defn process-chat-shared-job
839 : "Links the group a user picked with the bot's \"choose a group\" button.
840 :
841 : payload keys:
842 : :chat-id — the private chat the pick was made in
843 : :sender-tg-id — Telegram user id of the sender
844 : :sender-username, :sender-first-name, :sender-last-name — Telegram user display data
845 : :request-id — id of the pending link request, echoed by Telegram
846 : :shared-chat-id — the picked group
847 :
848 : The link itself goes through the same handlers as /link_template and
849 : /link_event, so the bot confirms in the group as it does for the commands. The
850 : chat-admin check runs here first, so someone who is not an admin of the picked
851 : group gets a private answer and nothing is posted there."
852 : [system-components payload]
853 3 : (let [{:keys [pg redis repos goose telegram-bot config]} system-components
854 1 : {:keys [chat-id sender-tg-id request-id shared-chat-id]} payload
855 6 : say! #(link-wizard/send! telegram-bot chat-id % link-wizard/remove-keyboard-markup)
856 5 : request (link-wizard/take-request! redis sender-tg-id request-id)]
857 5 : (if (nil? request)
858 6 : (say! (l10n/t :en :telegram.reply/wizard-expired))
859 6 : (let [cmd (keyword (:cmd request))
860 3 : public-id (:public-id request)
861 2 : sender-uuid (user-query/find-uuid-by-telegram-id
862 3 : (:user-postgres-repo repos)
863 3 : (:user-redis-repo repos)
864 1 : sender-tg-id)
865 9 : ctx {:pg pg
866 1 : :redis redis
867 1 : :repos repos
868 1 : :goose goose
869 1 : :config config
870 1 : :telegram-bot telegram-bot
871 1 : :sender-uuid sender-uuid}
872 5 : resource (wizard-resource ctx cmd public-id)
873 5 : locale (if resource (l10n/resource-locale resource) :en)
874 : ;; The group has no command message to reply to or audit.
875 12 : actor {:chat-id shared-chat-id
876 : :thread-id nil
877 1 : :sender-tg-id sender-tg-id
878 3 : :sender-username (:sender-username payload)
879 3 : :sender-first-name (:sender-first-name payload)
880 3 : :sender-last-name (:sender-last-name payload)
881 1 : :sender-uuid sender-uuid
882 : :message-id nil}]
883 7 : (cond (nil? sender-uuid) (say! (l10n/t :en :telegram.reply/open-to-link))
884 :
885 7 : (not (commands/check-chat-admin? telegram-bot shared-chat-id sender-tg-id))
886 6 : (say! (l10n/t locale :telegram.reply/admin-required-link))
887 :
888 : :else
889 1 : (try
890 4 : (if (= :link_template cmd)
891 5 : (handle-link-template! ctx actor public-id)
892 5 : (handle-link-event! ctx actor public-id))
893 9 : (say! (l10n/t locale :telegram.reply/wizard-done (resource-label resource)))
894 : (catch clojure.lang.ExceptionInfo ei
895 0 : (if (= ::abort (:type (ex-data ei)))
896 0 : (say! (l10n/t locale :telegram.reply/wizard-failed))
897 0 : (throw ei)))))))))
898 :
899 :
900 : ;; ---- disconnecting from the app
901 : ;; ---------------------------------------------------------------------------
902 :
903 :
904 4 : (defn announce-unlinked-job
905 : "Tells a chat that a template or event was disconnected from it in the app, the
906 : way the bot answers /unlink_template and /unlink_event, and records the message
907 : in the audit table. A template notice also lists the templates still linked.
908 :
909 : payload keys:
910 : :kind — \"template\" or \"event\"
911 : :resource-id — UUID of the template or event
912 : :chat-id, :thread-id — the chat (and topic) that was disconnected
913 : :user-id — UUID of the user who disconnected it, mentioned in the notice
914 :
915 : Best effort: when the bot can no longer post there, nothing is sent."
916 : [system-components {:keys [kind resource-id chat-id thread-id user-id]}]
917 2 : (let [{:keys [pg redis repos goose telegram-bot config]} system-components
918 8 : ctx {:pg pg
919 1 : :redis redis
920 1 : :repos repos
921 1 : :goose goose
922 1 : :config config
923 1 : :telegram-bot telegram-bot}
924 3 : template? (= "template" kind)
925 2 : resource (if template?
926 2 : (template-postgres-repo/find-by-id
927 3 : (:template-postgres-repo repos)
928 1 : resource-id
929 1 : {})
930 7 : (event-postgres-repo/find-by-id (:event-postgres-repo repos) resource-id {}))
931 9 : user (when user-id (user-query/get-user (:user-postgres-repo repos) user-id))
932 7 : actor {:chat-id chat-id
933 1 : :thread-id thread-id
934 3 : :sender-tg-id (:telegram-id user)
935 3 : :sender-username (:username user)
936 3 : :sender-first-name (:name user)}]
937 3 : (when resource
938 4 : (let [locale (l10n/resource-locale resource)
939 9 : summary (when template? (linked-templates-message repos chat-id thread-id locale))]
940 2 : (reply-and-record!
941 1 : ctx
942 1 : actor
943 13 : (cond-> (unlinked-message locale resource) summary (str "\n\n" summary))
944 8 : (if template? {:template-id resource-id} {:event-id resource-id}))))))
945 :
946 :
947 : ;; ---- main job entry
948 : ;; --------------------------------------------------------------------------
949 :
950 :
951 4 : (defn- ensure-participant-for-user!
952 : [{:keys [repos]} user-uuid]
953 6 : (when user-uuid
954 4 : (participant-postgres-repo/ensure-person-participant-for-user!
955 6 : (:participant-postgres-repo repos)
956 2 : user-uuid)))
957 :
958 :
959 4 : (defn- safe-command-token
960 : [text]
961 16 : (some->>
962 1 : text
963 3 : (re-find #"^\s*(/[A-Za-z0-9_@-]{1,64})")
964 1 : second))
965 :
966 :
967 4 : (defn process-message-job
968 : "Processes a single Telegram bot command message.
969 :
970 : payload keys:
971 : :chat-id — Telegram chat id (long)
972 : :thread-id — message thread id (long or nil)
973 : :sender-tg-id — Telegram user id of the sender (long)
974 : :sender-username, :sender-first-name, :sender-last-name — Telegram user display data
975 : :message-id — Telegram message id (int)
976 : :text — raw message text (string)"
977 : [system-components payload]
978 4 : (let [{:keys [pg redis repos goose telegram-bot config]} system-components
979 2 : {:keys [chat-id thread-id sender-tg-id message-id text]} payload
980 16 : ctx {:pg pg
981 2 : :redis redis
982 2 : :repos repos
983 2 : :goose goose
984 2 : :config config
985 2 : :telegram-bot telegram-bot}
986 12 : idempotency-key (str "tg:cmd:processed:" chat-id ":" message-id)
987 12 : lock-key (str "tg:cmd:lock:" chat-id ":" message-id)]
988 6 : (cond
989 78 : (car/wcar redis (car/get idempotency-key))
990 22 : (t/log! :debug (str "Duplicate TG command skipped: " idempotency-key))
991 :
992 92 : (not= "OK" (car/wcar redis (car/set lock-key "1" :nx :ex 300)))
993 22 : (t/log! :debug (str "Duplicate TG command skipped (in flight): " lock-key))
994 :
995 : :else
996 2 : (do
997 2 : (try
998 6 : (let [parsed (commands/parse-command
999 2 : text
1000 14 : (get-in system-components [:config :telegram :bot-username]))]
1001 11 : (when (nil? parsed)
1002 4 : (let [command-token (safe-command-token text)]
1003 22 : (t/log!
1004 : :debug
1005 0 : (cond->
1006 0 : {:message "Unknown Telegram command"
1007 0 : :sender-tg-id sender-tg-id}
1008 0 : message-id (assoc :message-id message-id)
1009 0 : command-token (assoc :command-token command-token))))
1010 7 : (throw (ex-info "unknown command" {:type ::unknown-command})))
1011 6 : (let [sender-uuid (user-query/find-uuid-by-telegram-id
1012 6 : (:user-postgres-repo repos)
1013 6 : (:user-redis-repo repos)
1014 2 : sender-tg-id)
1015 10 : cmd-ctx (assoc ctx :sender-uuid sender-uuid)
1016 22 : actor {:chat-id chat-id
1017 2 : :thread-id thread-id
1018 2 : :sender-tg-id sender-tg-id
1019 6 : :sender-username (:sender-username payload)
1020 6 : :sender-first-name (:sender-first-name payload)
1021 6 : :sender-last-name (:sender-last-name payload)
1022 6 : :sender-language-code (:sender-language-code payload)
1023 2 : :sender-uuid sender-uuid
1024 2 : :message-id message-id}
1025 2 : {:keys [cmd args]} parsed]
1026 14 : (when sender-uuid (ensure-participant-for-user! cmd-ctx sender-uuid))
1027 6 : (case cmd
1028 : :link_event
1029 4 : (let [public-id (first args)]
1030 5 : (when (nil? public-id)
1031 0 : (reply-and-record! cmd-ctx actor "Usage: /link_event <public-id>" nil)
1032 0 : (throw (ex-info "missing public-id" {:type ::abort})))
1033 5 : (when (nil? sender-uuid)
1034 0 : (reply-and-record! cmd-ctx actor (l10n/t :en :telegram.reply/open-to-link) nil)
1035 0 : (throw (ex-info "sender not found" {:type ::abort})))
1036 5 : (handle-link-event! cmd-ctx actor public-id))
1037 :
1038 : :unlink_event
1039 4 : (let [public-id (first args)]
1040 5 : (when (nil? public-id)
1041 0 : (reply-and-record! cmd-ctx actor "Usage: /unlink_event <public-id>" nil)
1042 0 : (throw (ex-info "missing public-id" {:type ::abort})))
1043 5 : (handle-unlink-event! cmd-ctx actor public-id))
1044 :
1045 : :link_template
1046 4 : (let [public-id (first args)]
1047 5 : (when (nil? public-id)
1048 0 : (reply-and-record! cmd-ctx actor "Usage: /link_template <public-id>" nil)
1049 0 : (throw (ex-info "missing public-id" {:type ::abort})))
1050 6 : (when (nil? sender-uuid)
1051 9 : (reply-and-record! cmd-ctx actor (l10n/t :en :telegram.reply/open-to-link) nil)
1052 7 : (throw (ex-info "sender not found" {:type ::abort})))
1053 5 : (handle-link-template! cmd-ctx actor public-id))
1054 :
1055 : :unlink_template
1056 4 : (let [public-id (first args)]
1057 6 : (when (nil? public-id)
1058 6 : (reply-and-record! cmd-ctx actor "Usage: /unlink_template <public-id>" nil)
1059 7 : (throw (ex-info "missing public-id" {:type ::abort})))
1060 5 : (handle-unlink-template! cmd-ctx actor public-id))
1061 :
1062 : :bot_health
1063 12 : (commands/reply! (:telegram-bot cmd-ctx) (:chat-id actor) (:thread-id actor) "Ok")
1064 :
1065 : ;; A connect link from the app. In the bot's private chat it starts the
1066 : ;; group picker; in a group (the bot was added through an add-to-group
1067 : ;; link) it links that group directly. Any other private /start
1068 : ;; (including the name link) is answered about the user's name; any
1069 : ;; other /start in a group is not ours to answer.
1070 : :start
1071 8 : (if-let [{:keys [cmd public-id]
1072 : :as target}
1073 22 : (and (number? chat-id) (commands/parse-start-payload (first args)))]
1074 3 : (if (pos? chat-id)
1075 5 : (start-link-wizard! cmd-ctx actor target)
1076 1 : (do
1077 5 : (when (nil? sender-uuid)
1078 0 : (reply-and-record!
1079 0 : cmd-ctx
1080 0 : actor
1081 0 : (l10n/t :en :telegram.reply/open-to-link)
1082 : nil)
1083 0 : (throw (ex-info "sender not found" {:type ::abort})))
1084 3 : (case cmd
1085 5 : :link_template (handle-link-template! cmd-ctx actor public-id)
1086 5 : :link_event (handle-link-event! cmd-ctx actor public-id))))
1087 20 : (when (and (number? chat-id) (pos? chat-id))
1088 14 : (name-jobs/answer-private-start! cmd-ctx actor (first args))))
1089 :
1090 : #_:join
1091 : #_(handle-join! cmd-ctx actor (first args))
1092 : #_:leave
1093 : #_(handle-leave! cmd-ctx actor (first args)))))
1094 : (catch clojure.lang.ExceptionInfo ei
1095 26 : (let [t (:type (ex-data ei))] (when-not (#{::abort ::unknown-command} t) (throw ei)))))
1096 84 : (car/wcar redis (car/set idempotency-key "1" :ex 86400))))))
|