File size: 6,470 Bytes
af1bee9
fb43301
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { Button, Group, Text } from '@mantine/core';
import { IconBrandTelegram, IconCircleCheck, IconSearch, IconSend } from '@/components/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { getJson, sendJson } from '../api/client';
import { ErrorAlert, fmtTs } from '../components/common';

/** The Telegram part of GET /api/notifications/settings. */
export interface TelegramState {
  token_set: boolean;
  chat: { chat_id: string; title: string } | null;
  last_delivery: { at: string; ok: boolean; status: number | null; error: string | null } | null;
}
interface FoundChat { chat_id: string; title: string; type: string }
/** GET /api/channels/telegram/status (admin): the two-way bot. */
export interface BotStatus { token_set: boolean; bot_username: string | null; polling: boolean; last_update_at: string | null; linked_users: number }

/** One line on the two-way bot: its name, whether it is listening for messages, and how many people linked a chat. */
export function BotStatusLine() {
  const q = useQuery({ queryKey: ['tg-bot-status'], queryFn: () => getJson<BotStatus>('/api/channels/telegram/status'), refetchInterval: 30_000 });
  const b = q.data;
  if (!b || !b.token_set) return null;
  return (
    <p className="pw-tg-bot" data-testid="tg-bot-status">

      {b.bot_username ? <b>@{b.bot_username}</b> : 'The bot'}{' '}

      <span className="pw-status" data-tone={b.polling ? 'green' : 'orange'}>{b.polling ? 'Listening for messages' : 'Not listening'}</span>

      {b.last_update_at ? ` Last message ${fmtTs(b.last_update_at)}.` : ''}

      {` ${b.linked_users} ${b.linked_users === 1 ? 'person' : 'people'} linked.`}

    </p>
  );
}

/**

 * Telegram, as a short guided setup with live state: the bot token (a Space secret, never typed into the browser), then

 * the chat (found from the /start message the person sent the bot), then a test message.

 */
export function TelegramCard({ tg }: { tg: TelegramState | undefined }) {
  const qc = useQueryClient();
  const refresh = () => { void qc.invalidateQueries({ queryKey: ['notify-settings'] }); void qc.invalidateQueries({ queryKey: ['notifications'] }); };
  const [found, setFound] = useState<FoundChat[] | null>(null);
  const discover = useMutation({
    mutationFn: () => sendJson<{ chats: FoundChat[] }>('POST', '/api/notifications/telegram/discover'),
    onSuccess: (r) => setFound(r?.chats ?? []),
  });
  const choose = useMutation({
    mutationFn: (c: FoundChat) => sendJson<unknown>('POST', '/api/notifications/telegram/chat', { chat_id: c.chat_id, title: c.title }),
    onSuccess: () => { setFound(null); refresh(); },
  });
  const disconnect = useMutation({ mutationFn: () => sendJson<unknown>('DELETE', '/api/notifications/telegram/chat'), onSuccess: refresh });
  const test = useMutation({ mutationFn: () => sendJson<{ queued: boolean; id: number }>('POST', '/api/notifications/test'), onSuccess: refresh });
  const last = tg?.last_delivery;
  const problem = discover.error || choose.error || disconnect.error || test.error;

  return (
    <section className="pw-card pw-tg" aria-labelledby="notify-tg-h" data-testid="notify-telegram">

      <h2 id="notify-tg-h"><IconBrandTelegram size={18} aria-hidden /> Telegram</h2>

      <BotStatusLine />

      <ol className="pw-tg-steps">

        <li data-done={tg?.token_set || undefined}>

          {tg?.token_set

            ? <span className="pw-tg-ok" data-testid="tg-token-set"><IconCircleCheck size={16} aria-hidden /> Bot token is set</span>

            : <span data-testid="tg-token-step">Create a bot with <b>@BotFather</b> (<code>/newbot</code>), then put its token in the Space secret <code>FPT_TELEGRAM_BOT_TOKEN</code> and restart the Space.</span>}

        </li>

        {tg?.token_set && (

          <li data-done={tg.chat ? true : undefined}>

            {tg.chat ? (

              <div className="pw-tg-connected">

                <span className="pw-tg-ok" data-testid="tg-chat">Messages go to <b>{tg.chat.title}</b></span>

                <Group gap="sm">

                  <Button leftSection={<IconSend size={15} aria-hidden />} onClick={() => test.mutate()} loading={test.isPending} data-testid="tg-test">Send a test message</Button>

                  <Button variant="subtle" onClick={() => disconnect.mutate()} loading={disconnect.isPending}>Disconnect</Button>

                </Group>

                {test.isSuccess && <Text size="sm" role="status">Test message queued. It should arrive within a minute.</Text>}

              </div>

            ) : (

              <div className="pw-tg-find">

                <span>Each person links their own chat from their <b>Account</b> page. For a shared team chat that gets every update, send <code>/start</code> to the bot from that chat, then press <b>Find my chat</b>.</span>

                <Button leftSection={<IconSearch size={15} aria-hidden />} onClick={() => discover.mutate()} loading={discover.isPending} data-testid="tg-discover">Find my chat</Button>

                {found && found.length === 0 && <Text size="sm" role="status" data-testid="tg-none">No messages yet: send /start to your bot, then try again.</Text>}

                {found && found.length > 0 && (

                  <ul className="pw-tg-chats" aria-label="Chats that wrote to your bot">

                    {found.map((c) => (

                      <li key={c.chat_id}>

                        <span><b>{c.title}</b> <span className="pw-tg-type">{c.type}</span></span>

                        <Button size="compact-sm" onClick={() => choose.mutate(c)} loading={choose.isPending && choose.variables?.chat_id === c.chat_id}

                          aria-label={`Use this chat: ${c.title}`}>Use this chat</Button>

                      </li>

                    ))}

                  </ul>

                )}

              </div>

            )}

          </li>

        )}

      </ol>

      {last && (

        <p className="pw-tg-last" data-testid="tg-last">

          Last message: <span className="pw-status" data-tone={last.ok ? 'green' : 'red'}>{last.ok ? 'Delivered' : 'Failed'}</span> {fmtTs(last.at)}

          {last.error ? `: ${last.error}` : ''}

        </p>

      )}

      {problem ? <ErrorAlert error={problem} title="Telegram did not answer as expected" /> : null}

    </section>
  );
}