Files
tgex-frontend/lib/utils/channel-parser.ts
2026-01-21 22:43:54 +03:00

54 lines
1.7 KiB
TypeScript

// ============================================================================
// Channel URL Parser Utility
// Parses various URL formats and usernames to extract channel username
// ============================================================================
export function parseChannelInput(input: string): string | null {
if (!input || typeof input !== "string") return null;
let cleaned = input.trim();
// Remove @ prefix if present
cleaned = cleaned.replace(/^@/, "");
// Patterns for different URL formats
const patterns: RegExp[] = [
/telemetr\.me\/content\/([a-zA-Z0-9_]+)/, // telemetr.me/content/rian_ru
/telemetr\.me\/([a-zA-Z0-9_]+)/, // telemetr.me/rian_ru (alternative)
/t\.me\/([a-zA-Z0-9_]+)/, // t.me/rian_ru or https://t.me/rian_ru
/tgstat\.ru\/channel\/@?([a-zA-Z0-9_]+)/, // tgstat.ru/channel/@rian_ru or tgstat.ru/channel/rian_ru
/tg\.me\/([a-zA-Z0-9_]+)/, // tg.me/rian_ru
];
for (const pattern of patterns) {
const match = cleaned.match(pattern);
if (match && match[1]) {
return match[1];
}
}
// If it's just a plain username (alphanumeric + underscore)
if (/^[a-zA-Z0-9_]+$/.test(cleaned)) {
return cleaned;
}
return null;
}
// Check if input is a valid channel identifier
export function isValidChannelInput(input: string): boolean {
return parseChannelInput(input) !== null;
}
// Get platform hint from URL (for analytics links)
export function getChannelAnalyticsUrls(username: string): {
telemetr: string;
tgstat: string;
} {
const cleanUsername = username.replace(/^@/, "");
return {
telemetr: `https://telemetr.me/channel/${cleanUsername}`,
tgstat: `https://tgstat.ru/channel/@${cleanUsername}`,
};
}