handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package telegram
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "time"
  8. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  9. )
  10. // Handler executes parsed Commands against the database. It
  11. // is the bridge between incoming bot messages and the
  12. // individuals / subscriptions tables.
  13. //
  14. // Handler is safe to call from multiple goroutines (it
  15. // acquires a fresh connection per call from the pool).
  16. type Handler struct {
  17. Pool *postgres.Pool
  18. Logger *slog.Logger
  19. }
  20. // NewHandler returns a Handler.
  21. func NewHandler(pool *postgres.Pool, logger *slog.Logger) *Handler {
  22. return &Handler{Pool: pool, Logger: logger}
  23. }
  24. // ErrNotLinked is returned when a command requires the
  25. // individual to be linked (telegram_user_id set) but isn't.
  26. // The handler turns this into a "please /start first" reply.
  27. var ErrNotLinked = errors.New("telegram account not linked; run /start <invite_code> first")
  28. // Handle dispatches one parsed command. The returned string
  29. // is the text to reply to the user (may be empty for
  30. // non-applicable commands).
  31. //
  32. // Handle is idempotent w.r.t. /start (re-running with the
  33. // same code is a no-op) and /subscribe (re-running upserts
  34. // the subscription).
  35. func (h *Handler) Handle(ctx context.Context, msg *Message) (string, error) {
  36. if msg == nil || msg.From == nil {
  37. return "", nil
  38. }
  39. cmd := Parse(msg.Text)
  40. h.Logger.Info("telegram command",
  41. "user_id", msg.From.ID,
  42. "chat_id", msg.Chat.ID,
  43. "raw", cmd.Raw,
  44. )
  45. switch {
  46. case cmd.Start != nil:
  47. return h.handleStart(ctx, msg, cmd.Start)
  48. case cmd.Subscribe != nil:
  49. return h.handleSubscribe(ctx, msg, cmd.Subscribe)
  50. case cmd.Unsubscribe != nil:
  51. return h.handleUnsubscribe(ctx, msg, cmd.Unsubscribe)
  52. case cmd.Preferences:
  53. return h.handlePreferences(ctx, msg)
  54. case cmd.Status != nil:
  55. return h.handleStatus(ctx, msg, cmd.Status)
  56. case cmd.Mute != nil:
  57. return h.handleMute(ctx, msg, cmd.Mute)
  58. case cmd.Unmute:
  59. return h.handleUnmute(ctx, msg)
  60. default:
  61. // Unknown / non-command. Don't reply.
  62. return "", nil
  63. }
  64. }
  65. // handleStart links the telegram_user_id to the individual
  66. // whose telegram_invite_code matches.
  67. //
  68. // SPEC §8: "admin must create the individual and issue the
  69. // code first; unknown users are rejected." The handler
  70. // returns a friendly error if the invite code is unknown.
  71. func (h *Handler) handleStart(ctx context.Context, msg *Message, c *StartCmd) (string, error) {
  72. if c.InviteCode == "" {
  73. return "Welcome. Please run /start <your_invite_code> (your admin should have given you the code).", nil
  74. }
  75. // Atomic: claim the invite code for this user, only if it
  76. // hasn't been claimed by someone else.
  77. tag, err := h.Pool.Exec(ctx, `
  78. UPDATE individuals
  79. SET telegram_user_id = $1,
  80. telegram_chat_id = $2::text,
  81. telegram_invite_code = NULL
  82. WHERE telegram_invite_code = $3
  83. AND (telegram_user_id IS NULL OR telegram_user_id = $1)
  84. RETURNING id, full_name
  85. `, msg.From.ID, fmt.Sprintf("%d", msg.Chat.ID), c.InviteCode)
  86. if err != nil {
  87. return "", fmt.Errorf("start update: %w", err)
  88. }
  89. if tag.RowsAffected() == 0 {
  90. // Either unknown code or already linked to a
  91. // different user. Disambiguate.
  92. var existing string
  93. err := h.Pool.QueryRow(ctx, `
  94. SELECT COALESCE(telegram_user_id::text, 'NULL')
  95. FROM individuals WHERE telegram_invite_code = $1
  96. `, c.InviteCode).Scan(&existing)
  97. if err == nil {
  98. return fmt.Sprintf("Invite code %q is already linked to another account.", c.InviteCode), nil
  99. }
  100. return fmt.Sprintf("Unknown invite code %q. Please check with your admin.", c.InviteCode), nil
  101. }
  102. // Fetch the individual to greet them by name.
  103. var name string
  104. _ = h.Pool.QueryRow(ctx, `
  105. SELECT full_name FROM individuals
  106. WHERE telegram_user_id = $1
  107. `, msg.From.ID).Scan(&name)
  108. if name == "" {
  109. name = "operator"
  110. }
  111. return fmt.Sprintf("Linked. Welcome, %s.\n\nRun /preferences to see your current subscriptions, or /subscribe <source_id> [min_severity] to opt in.", name), nil
  112. }
  113. // handleSubscribe requires the individual to be linked
  114. // (we look them up by telegram_user_id). It upserts a
  115. // subscription with the given source_id and min_severity.
  116. func (h *Handler) handleSubscribe(ctx context.Context, msg *Message, c *SubscribeCmd) (string, error) {
  117. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  118. if err != nil {
  119. return err.Error(), nil
  120. }
  121. // Validate the source exists in this company.
  122. var ok bool
  123. err = h.Pool.QueryRow(ctx, `
  124. SELECT EXISTS (
  125. SELECT 1 FROM sources WHERE company_id = $1 AND id = $2
  126. )
  127. `, ind.CompanyID, c.SourceID).Scan(&ok)
  128. if err != nil {
  129. return "", fmt.Errorf("source check: %w", err)
  130. }
  131. if !ok {
  132. return fmt.Sprintf("Unknown source %q for your company. Run /preferences to see what's available.", c.SourceID), nil
  133. }
  134. _, err = h.Pool.Exec(ctx, `
  135. INSERT INTO subscriptions
  136. (individual_id, company_id, source_id, min_severity, channel_mask, status)
  137. VALUES ($1, $2, $3, $4, '["fcm","telegram"]'::jsonb, 'active')
  138. ON CONFLICT (individual_id, source_id) DO UPDATE
  139. SET min_severity = EXCLUDED.min_severity,
  140. status = 'active',
  141. channel_mask = '["fcm","telegram"]'::jsonb
  142. `, ind.ID, ind.CompanyID, c.SourceID, c.MinSeverity)
  143. if err != nil {
  144. return "", fmt.Errorf("subscribe upsert: %w", err)
  145. }
  146. return fmt.Sprintf("Subscribed to %s (min severity: %s).", c.SourceID, c.MinSeverity), nil
  147. }
  148. // handleUnsubscribe soft-deletes a subscription by setting
  149. // status='paused'. We keep the row so /subscribe re-enables
  150. // the same row without a new id.
  151. func (h *Handler) handleUnsubscribe(ctx context.Context, msg *Message, c *UnsubscribeCmd) (string, error) {
  152. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  153. if err != nil {
  154. return err.Error(), nil
  155. }
  156. tag, err := h.Pool.Exec(ctx, `
  157. UPDATE subscriptions
  158. SET status = 'paused'
  159. WHERE individual_id = $1 AND source_id = $2
  160. `, ind.ID, c.SourceID)
  161. if err != nil {
  162. return "", fmt.Errorf("unsubscribe: %w", err)
  163. }
  164. if tag.RowsAffected() == 0 {
  165. return fmt.Sprintf("You were not subscribed to %s.", c.SourceID), nil
  166. }
  167. return fmt.Sprintf("Unsubscribed from %s.", c.SourceID), nil
  168. }
  169. // handlePreferences shows the current subscriptions and
  170. // the global mute_until timestamp.
  171. func (h *Handler) handlePreferences(ctx context.Context, msg *Message) (string, error) {
  172. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  173. if err != nil {
  174. return err.Error(), nil
  175. }
  176. rows, err := h.Pool.Query(ctx, `
  177. SELECT source_id, min_severity, channel_mask, status
  178. FROM subscriptions
  179. WHERE individual_id = $1
  180. ORDER BY source_id
  181. `, ind.ID)
  182. if err != nil {
  183. return "", fmt.Errorf("preferences query: %w", err)
  184. }
  185. defer rows.Close()
  186. var lines []string
  187. for rows.Next() {
  188. var src, minSev, status string
  189. var channels []byte
  190. if err := rows.Scan(&src, &minSev, &channels, &status); err != nil {
  191. return "", err
  192. }
  193. if minSev == "" {
  194. minSev = "any"
  195. }
  196. lines = append(lines, fmt.Sprintf(" • %s [min=%s, channels=%s, %s]",
  197. src, minSev, string(channels), status))
  198. }
  199. if len(lines) == 0 {
  200. lines = append(lines, " (no subscriptions yet)")
  201. }
  202. reply := "Your subscriptions:\n" + joinLines(lines)
  203. if ind.MuteUntil != nil && ind.MuteUntil.After(time.Now()) {
  204. reply += fmt.Sprintf("\n\nMuted until %s UTC.", ind.MuteUntil.UTC().Format("2006-01-02 15:04"))
  205. } else {
  206. reply += "\n\nNot muted."
  207. }
  208. return reply, nil
  209. }
  210. // handleStatus lists the last N deliveries for this
  211. // individual. M3 ships a simple per-individual view.
  212. func (h *Handler) handleStatus(ctx context.Context, msg *Message, c *StatusCmd) (string, error) {
  213. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  214. if err != nil {
  215. return err.Error(), nil
  216. }
  217. rows, err := h.Pool.Query(ctx, `
  218. SELECT alert_id, channel, status, sent_at
  219. FROM deliveries
  220. WHERE individual_id = $1
  221. ORDER BY id DESC
  222. LIMIT $2
  223. `, ind.ID, c.Limit)
  224. if err != nil {
  225. return "", fmt.Errorf("status query: %w", err)
  226. }
  227. defer rows.Close()
  228. var lines []string
  229. for rows.Next() {
  230. var alertID, channel, status string
  231. var sentAt *time.Time
  232. if err := rows.Scan(&alertID, &channel, &status, &sentAt); err != nil {
  233. return "", err
  234. }
  235. ts := "(pending)"
  236. if sentAt != nil {
  237. ts = sentAt.UTC().Format("15:04:05")
  238. }
  239. short := alertID
  240. if len(short) > 12 {
  241. short = short[:12]
  242. }
  243. lines = append(lines, fmt.Sprintf(" • %s %s [%s] %s", ts, short, channel, status))
  244. }
  245. if len(lines) == 0 {
  246. lines = append(lines, " (no deliveries yet)")
  247. }
  248. return "Recent deliveries:\n" + joinLines(lines), nil
  249. }
  250. // handleMute sets mute_until to now+duration (or now+until).
  251. func (h *Handler) handleMute(ctx context.Context, msg *Message, c *MuteCmd) (string, error) {
  252. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  253. if err != nil {
  254. return err.Error(), nil
  255. }
  256. var until time.Time
  257. if c.Duration > 0 {
  258. until = time.Now().UTC().Add(c.Duration)
  259. } else {
  260. until = c.Until
  261. }
  262. _, err = h.Pool.Exec(ctx, `
  263. UPDATE individuals SET mute_until = $1 WHERE id = $2
  264. `, until, ind.ID)
  265. if err != nil {
  266. return "", fmt.Errorf("mute: %w", err)
  267. }
  268. return fmt.Sprintf("Muted until %s UTC.", until.Format("2006-01-02 15:04")), nil
  269. }
  270. // handleUnmute clears mute_until.
  271. func (h *Handler) handleUnmute(ctx context.Context, msg *Message) (string, error) {
  272. ind, err := h.lookupByTelegramUser(ctx, msg.From.ID)
  273. if err != nil {
  274. return err.Error(), nil
  275. }
  276. _, err = h.Pool.Exec(ctx, `
  277. UPDATE individuals SET mute_until = NULL WHERE id = $1
  278. `, ind.ID)
  279. if err != nil {
  280. return "", fmt.Errorf("unmute: %w", err)
  281. }
  282. return "Unmuted.", nil
  283. }
  284. // individual is the small projection of individuals we need
  285. // for command handling.
  286. type individual struct {
  287. ID string
  288. CompanyID string
  289. FullName string
  290. MuteUntil *time.Time
  291. }
  292. // lookupByTelegramUser returns the individual linked to a
  293. // given telegram_user_id, or ErrNotLinked.
  294. func (h *Handler) lookupByTelegramUser(ctx context.Context, telegramUserID int64) (*individual, error) {
  295. var ind individual
  296. err := h.Pool.QueryRow(ctx, `
  297. SELECT id, company_id, full_name, mute_until
  298. FROM individuals
  299. WHERE telegram_user_id = $1
  300. `, telegramUserID).Scan(&ind.ID, &ind.CompanyID, &ind.FullName, &ind.MuteUntil)
  301. if err != nil {
  302. return nil, ErrNotLinked
  303. }
  304. return &ind, nil
  305. }
  306. func joinLines(ls []string) string {
  307. out := ""
  308. for i, s := range ls {
  309. if i > 0 {
  310. out += "\n"
  311. }
  312. out += s
  313. }
  314. return out
  315. }