| 1 | import { NextResponse } from 'next/server'; |
| 2 | import { fetchChannel, type TelegramPost } from '@/lib/telegram-scraper'; |
| 3 | import { geoparse, hasConflictKeyword } from '@/lib/geo-dict'; |
| 4 | |
| 5 | export const dynamic = 'force-dynamic'; |
| 6 | |
| 7 | /** |
| 8 | * OSIRIS — Telegram Public-Channel OSINT Feed. |
| 9 | * |
| 10 | * Aggregates the most recent text posts from a curated set of public |
| 11 | * Telegram channels (war reporting, fact-checking, geopolitics), filters |
| 12 | * to posts mentioning conflict-relevant keywords, and geoparses them |
| 13 | * against the shared place dictionary so they can be plotted on the map. |
| 14 | * |
| 15 | * All data is fetched via the unauthenticated web preview at `t.me/s/…` |
| 16 | * — no Telegram Bot API token, no MTProto API ID, no key of any kind. |
| 17 | * |
| 18 | * The default channel list can be overridden by setting the |
| 19 | * `OSIRIS_TELEGRAM_CHANNELS` env var to a comma-separated list of |
| 20 | * channel usernames (without `@`). |
| 21 | */ |
| 22 | |
| 23 | // Balanced default set: multi-source aggregators + one official source |
| 24 | // from each side of the Ukraine war so the layer surfaces both viewpoints |
| 25 | // rather than a single narrative. Operators can override via the |
| 26 | // `OSIRIS_TELEGRAM_CHANNELS` env var. |
| 27 | const DEFAULT_CHANNELS = [ |
| 28 | 'osintdefender', // Prominent English-language OSINT aggregator |
| 29 | 'insiderpaper', // English breaking-news wire |
| 30 | 'aljazeeraenglish', // Al Jazeera English — Middle East coverage |
| 31 | 'nexta_live', // Belarus / Ukraine OSINT (Cyrillic, multilingual) |
| 32 | 'war_monitor', // Ukrainian-language war updates |
| 33 | ]; |
| 34 | |
| 35 | const POSTS_PER_CHANNEL = 15; |
| 36 | const CACHE_TTL_MS = 5 * 60 * 1000; |
| 37 | |
| 38 | type CacheEntry = { fetchedAt: number; posts: TelegramPost[] }; |
| 39 | const cache = new Map<string, CacheEntry>(); |
| 40 | const inflight = new Map<string, Promise<TelegramPost[]>>(); |
| 41 | |
| 42 | function activeChannels(): string[] { |
| 43 | const env = process.env.OSIRIS_TELEGRAM_CHANNELS; |
| 44 | if (!env) return DEFAULT_CHANNELS; |
| 45 | return env |
| 46 | .split(',') |
| 47 | .map((s) => s.trim().replace(/^@/, '')) |
| 48 | .filter(Boolean); |
| 49 | } |
| 50 | |
| 51 | async function getChannelCached(channel: string): Promise<TelegramPost[]> { |
| 52 | const cached = cache.get(channel); |
| 53 | if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) { |
| 54 | return cached.posts; |
| 55 | } |
| 56 | const pending = inflight.get(channel); |
| 57 | if (pending) return pending; |
| 58 | |
| 59 | const p = (async () => { |
| 60 | try { |
| 61 | const posts = await fetchChannel(channel, POSTS_PER_CHANNEL); |
| 62 | cache.set(channel, { fetchedAt: Date.now(), posts }); |
| 63 | return posts; |
| 64 | } catch (e) { |
| 65 | console.warn( |
| 66 | '[OSIRIS] Telegram channel fetch failed:', |
| 67 | channel, |
| 68 | e instanceof Error ? e.message : e |
| 69 | ); |
| 70 | // Serve stale on transient failure rather than blinding the layer. |
| 71 | return cached?.posts ?? []; |
| 72 | } finally { |
| 73 | inflight.delete(channel); |
| 74 | } |
| 75 | })(); |
| 76 | |
| 77 | inflight.set(channel, p); |
| 78 | return p; |
| 79 | } |
| 80 | |
| 81 | export async function GET(req: Request) { |
| 82 | const { searchParams } = new URL(req.url); |
| 83 | const filterConflict = searchParams.get('all') !== '1'; |
| 84 | |
| 85 | const channels = activeChannels(); |
| 86 | const channelResults = await Promise.all(channels.map(getChannelCached)); |
| 87 | |
| 88 | const events: Array<{ |
| 89 | id: string; |
| 90 | lat: number; |
| 91 | lng: number; |
| 92 | name: string; |
| 93 | url: string; |
| 94 | html: string; |
| 95 | channel: string; |
| 96 | datetime: string; |
| 97 | type: 'telegram'; |
| 98 | }> = []; |
| 99 | |
| 100 | for (const posts of channelResults) { |
| 101 | for (const post of posts) { |
| 102 | if (filterConflict && !hasConflictKeyword(post.text)) continue; |
| 103 | const match = geoparse(post.text, 0.6); |
| 104 | if (!match) continue; |
| 105 | |
| 106 | const headline = post.text.slice(0, 140).replace(/\s+/g, ' ').trim(); |
| 107 | events.push({ |
| 108 | id: `telegram-${post.id.replace('/', '-')}`, |
| 109 | lat: match.coords[1], |
| 110 | lng: match.coords[0], |
| 111 | name: `[@${post.channel}] ${headline}`, |
| 112 | url: post.url, |
| 113 | html: `<b>@${post.channel}</b><br/>${headline}<br/><a href="${post.url}" target="_blank">Open on Telegram</a>`, |
| 114 | channel: post.channel, |
| 115 | datetime: post.datetime, |
| 116 | type: 'telegram', |
| 117 | }); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | return NextResponse.json( |
| 122 | { |
| 123 | events, |
| 124 | total: events.length, |
| 125 | channels, |
| 126 | timestamp: new Date().toISOString(), |
| 127 | source: 'Telegram public channels (t.me/s)', |
| 128 | }, |
| 129 | { |
| 130 | headers: { |
| 131 | 'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600', |
| 132 | }, |
| 133 | } |
| 134 | ); |
| 135 | } |