File size: 1,418 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { normalizeTelegramLookupTarget, parseTelegramTarget } from "../../../telegram/targets.js";

const TELEGRAM_PREFIX_RE = /^(telegram|tg):/i;

function normalizeTelegramTargetBody(raw: string): string | undefined {
  const trimmed = raw.trim();
  if (!trimmed) {
    return undefined;
  }

  const prefixStripped = trimmed.replace(TELEGRAM_PREFIX_RE, "").trim();
  if (!prefixStripped) {
    return undefined;
  }

  const parsed = parseTelegramTarget(trimmed);
  const normalizedChatId = normalizeTelegramLookupTarget(parsed.chatId);
  if (!normalizedChatId) {
    return undefined;
  }

  const keepLegacyGroupPrefix = /^group:/i.test(prefixStripped);
  const hasTopicSuffix = /:topic:\d+$/i.test(prefixStripped);
  const chatSegment = keepLegacyGroupPrefix ? `group:${normalizedChatId}` : normalizedChatId;
  if (parsed.messageThreadId == null) {
    return chatSegment;
  }
  const threadSuffix = hasTopicSuffix
    ? `:topic:${parsed.messageThreadId}`
    : `:${parsed.messageThreadId}`;
  return `${chatSegment}${threadSuffix}`;
}

export function normalizeTelegramMessagingTarget(raw: string): string | undefined {
  const normalizedBody = normalizeTelegramTargetBody(raw);
  if (!normalizedBody) {
    return undefined;
  }
  return `telegram:${normalizedBody}`.toLowerCase();
}

export function looksLikeTelegramTargetId(raw: string): boolean {
  return normalizeTelegramTargetBody(raw) !== undefined;
}