Elffuss BraidHub

kikocis/osiris public

feat(map): add Telegram public-channel OSINT layer

Aggregates recent posts from a curated set of public Telegram
channels (war reporting, fact-checking, geopolitics), geoparses
them against a shared place dictionary and plots them on the map.

Data sourcing is fully keyless: posts are fetched via the
unauthenticated t.me/s/<channel> web preview (no Bot API token,
no MTProto credentials). The default channel list mixes English
and Cyrillic OSINT and is overridable via the optional
OSIRIS_TELEGRAM_CHANNELS env var.

- New shared lib src/lib/geo-dict.ts with EN + Cyrillic + Arabic
  place names and Unicode-aware word-boundary matching.
- New scraper src/lib/telegram-scraper.ts (regex-based, no
  jsdom/cheerio dependency added).
- New route GET /api/telegram-feed with per-channel 5min
  single-flight cache and stale-on-failure fallback.
- New 'Telegram OSINT' toggle in the SURVEILLANCE layer group,
  cyan circle layer with click popup linking back to the post.

Preserves the project's 'works fully without any API keys'
guarantee. No new npm dependencies.
Changeset144dd8715328b6fe3df6d6d607ced7e9069427bc5b36dd757131db3c76ebbe83
AuthorEduardo Maldonado <acevedo.eduardo@outlook.com> · 2026-05-23 22:55 -06:00
CommitterEduardo Maldonado <acevedo.eduardo@outlook.com> · 2026-05-23 22:55 -06:00
Parents20d3b910b1d7

Browse the files at this changeset

6 files changed

added src/app/api/telegram-feed/route.ts +135 −0
@@ -0,0 +1,135 @@
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+}
modified src/app/page.tsx +6 −0
@@ -125,6 +125,7 @@
125125 radiation: false,
126126 infrastructure: false,
127127 global_incidents: true,
128+ telegram_intel: false,
128129 war_alerts: false,
129130 gps_jamming: false,
130131 day_night: true,
@@ -349,6 +350,11 @@
349350 fetchEndpoint('/api/gdelt', d => ({ gdelt: d.events }));
350351 layerFetchedRef.current.add('gdelt');
351352 }
353+ // Telegram OSINT public-channel feed
354+ if (activeLayers.telegram_intel && !layerFetchedRef.current.has('telegram')) {
355+ fetchEndpoint('/api/telegram-feed', d => ({ telegram: d.events }));
356+ layerFetchedRef.current.add('telegram');
357+ }
352358
353359 }, [activeLayers]);
354360
modified src/components/LayerPanel.tsx +2 −1
@@ -5,7 +5,7 @@
55 import {
66 Plane, Satellite, Activity, Globe, Radio, Eye,
77 Shield, Sun, AlertTriangle, Camera, Flame, Target,
8- CloudLightning, Radiation, Tv, Anchor, Ship, Newspaper,
8+ CloudLightning, Radiation, Tv, Anchor, Ship, Newspaper, Send,
99 ChevronDown, ChevronUp, ToggleLeft, ToggleRight,
1010 } from 'lucide-react';
1111
@@ -44,6 +44,7 @@
4444 { key: 'cctv', label: 'CCTV Cameras', icon: Camera, color: '#39FF14', dataKey: 'cameras' },
4545 { key: 'live_news', label: 'Live News Feeds', icon: Tv, color: '#FF4081', dataKey: 'live_feeds' },
4646 { key: 'news_intel', label: 'SIGINT News (RSS)', icon: Newspaper, color: '#D4AF37', dataKey: 'news' },
47+ { key: 'telegram_intel', label: 'Telegram OSINT', icon: Send, color: '#00BFFF', dataKey: 'telegram' },
4748 ],
4849 },
4950 {
modified src/components/OsirisMap.tsx +41 −2
@@ -109,7 +109,7 @@
109109 createDot(map, 'dot-cctv', '#39FF14', 10);
110110
111111 // Sources
112- const sources = ['flights','military','jets','private-fl','satellites','earthquakes','gdelt','gps-jamming','day-night','cctv','fires','weather','infrastructure','maritime','maritime-choke','maritime-ships','live-news','sigint-news','conflict-zones', 'war-alerts-targets', 'war-alerts-lines', 'balloons', 'radiation', 'ip-sweep-devices', 'ip-sweep-pulse', 'ip-sweep-connections', 'scan-targets'];
112+ const sources = ['flights','military','jets','private-fl','satellites','earthquakes','gdelt','telegram','gps-jamming','day-night','cctv','fires','weather','infrastructure','maritime','maritime-choke','maritime-ships','live-news','sigint-news','conflict-zones', 'war-alerts-targets', 'war-alerts-lines', 'balloons', 'radiation', 'ip-sweep-devices', 'ip-sweep-pulse', 'ip-sweep-connections', 'scan-targets'];
113113 sources.forEach(s => map.addSource(s, { type: 'geojson', data: EMPTY_FC }));
114114
115115 // ── CONFLICT ZONES — small warning markers (not polygons) ──
@@ -223,6 +223,17 @@
223223 'circle-radius': 4, 'circle-color': '#FF3D3D', 'circle-opacity': 0.5, 'circle-stroke-width': 1, 'circle-stroke-color': '#FF3D3D', 'circle-stroke-opacity': 0.3,
224224 }});
225225
226+ // Telegram OSINT feed — geoparsed posts from public channels
227+ map.addLayer({ id: 'telegram-glow', type: 'circle', source: 'telegram', paint: {
228+ 'circle-radius': ['interpolate',['linear'],['zoom'], 1,6, 5,10, 10,16],
229+ 'circle-color': '#00BFFF', 'circle-opacity': 0.12, 'circle-blur': 1,
230+ }});
231+ map.addLayer({ id: 'telegram-dots', type: 'circle', source: 'telegram', paint: {
232+ 'circle-radius': ['interpolate',['linear'],['zoom'], 1,3.5, 5,5, 10,7],
233+ 'circle-color': '#00BFFF', 'circle-opacity': 0.85,
234+ 'circle-stroke-width': 1, 'circle-stroke-color': '#00BFFF', 'circle-stroke-opacity': 0.4,
235+ }});
236+
226237 // GPS Jamming
227238 map.addLayer({ id: 'jam-fill', type: 'circle', source: 'gps-jamming', paint: { 'circle-radius': 30, 'circle-color': '#FF0000', 'circle-opacity': 0.15, 'circle-blur': 1 }});
228239 map.addLayer({ id: 'jam-label', type: 'symbol', source: 'gps-jamming', layout: {
@@ -564,6 +575,24 @@
564575 </div>`);
565576 });
566577
578+ // ── Telegram OSINT feed (geoparsed public-channel posts) ──
579+ map.on('click', 'telegram-dots', e => {
580+ if (!e.features?.length) return;
581+ const p = e.features[0].properties as any;
582+ const coords = (e.features[0].geometry as any).coordinates;
583+ const channel = p.channel || 'channel';
584+ const when = p.datetime ? new Date(p.datetime).toUTCString() : '';
585+ popup(coords, `<div style="${pStyle}border:1px solid rgba(0,191,255,0.35);">
586+ <div style="color:#00BFFF;font-size:12px;font-weight:700;margin-bottom:6px;">✉️ TELEGRAM @${channel}</div>
587+ <div style="font-size:9px;color:#E8E6E0;margin-bottom:8px;line-height:1.4;">${p.name||'(no text)'}</div>
588+ ${when ? `<div style="font-size:8px;color:#5C5A54;margin-bottom:8px;">${when}</div>` : ''}
589+ <div style="display:flex;gap:6px;">
590+ ${p.url ? `<a href="${p.url}" target="_blank" style="${linkStyle}color:#00BFFF;border:1px solid rgba(0,191,255,0.4);background:rgba(0,191,255,0.1);">OPEN POST</a>` : ''}
591+ <a href="https://www.google.com/maps/@${coords[1]},${coords[0]},12z" target="_blank" style="${linkStyle}color:#448AFF;border:1px solid rgba(68,138,255,0.4);background:rgba(68,138,255,0.1);">MAP</a>
592+ </div>
593+ </div>`);
594+ });
595+
567596 // ── Global Event / Conflict Markers ──
568597 map.on('click', 'conflict-icons', e => {
569598 if (!e.features?.length) return;
@@ -582,7 +611,7 @@
582611
583612
584613 // ── Generic hover for clickables ──
585- ['conflict-icons','cctv-dots','eq-circles','sat-dots','fires-heat','gdelt-dots','weather-dots','infra-dots','maritime-dots','choke-dots','news-dots','sigint-news-dots','balloon-dots','rad-dots','ship-dots','sweep-device-dots','scan-targets-dots'].forEach(layer => {
614+ ['conflict-icons','cctv-dots','eq-circles','sat-dots','fires-heat','gdelt-dots','telegram-dots','weather-dots','infra-dots','maritime-dots','choke-dots','news-dots','sigint-news-dots','balloon-dots','rad-dots','ship-dots','sweep-device-dots','scan-targets-dots'].forEach(layer => {
586615 map.on('mouseenter', layer, () => { map.getCanvas().style.cursor = 'pointer'; });
587616 map.on('mouseleave', layer, () => { map.getCanvas().style.cursor = ''; });
588617 });
@@ -822,6 +851,15 @@
822851 setGeo('gdelt', activeLayers.global_incidents && data.gdelt ? data.gdelt.map((e: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [e.lng, e.lat] }, properties: { name: e.name } })) : []);
823852 }, [mapReady, data.gdelt, activeLayers.global_incidents, setGeo]);
824853
854+ useEffect(() => {
855+ if (!mapReady) return;
856+ setGeo('telegram', activeLayers.telegram_intel && data.telegram ? data.telegram.map((e: any) => ({
857+ type: 'Feature',
858+ geometry: { type: 'Point', coordinates: [e.lng, e.lat] },
859+ properties: { name: e.name, url: e.url, channel: e.channel, datetime: e.datetime },
860+ })) : []);
861+ }, [mapReady, data.telegram, activeLayers.telegram_intel, setGeo]);
862+
825863 useEffect(() => {
826864 if (!mapReady) return;
827865 setGeo('gps-jamming', activeLayers.gps_jamming && data.gps_jamming ? data.gps_jamming.map((z: any) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [z.lng, z.lat] }, properties: { severity: z.severity } })) : []);
@@ -914,6 +952,7 @@
914952 setVis(['eq-circles','eq-label'], activeLayers.earthquakes);
915953 setVis(['sat-dots'], activeLayers.satellites);
916954 setVis(['gdelt-dots'], activeLayers.global_incidents);
955+ setVis(['telegram-glow','telegram-dots'], activeLayers.telegram_intel);
917956 setVis(['jam-fill','jam-label'], activeLayers.gps_jamming);
918957 setVis(['day-night-fill'], activeLayers.day_night);
919958 setVis(['fl-commercial'], activeLayers.flights);
added src/lib/geo-dict.ts +305 −0
@@ -0,0 +1,305 @@
1+/**
2+ * Lightweight place-name → coordinate dictionary for OSINT geoparsing of
3+ * unstructured text (news headlines, Telegram posts, RSS items).
4+ *
5+ * Coordinates are `[lng, lat]` to match the GeoJSON convention used by the
6+ * map layer code. Names are matched as whole-word, case-insensitive, against
7+ * the input text. Multi-word names (e.g. "tel aviv", "san francisco") are
8+ * checked before single-word names so the longer label wins when both are
9+ * present in the same sentence.
10+ *
11+ * This is intentionally a curated, hand-maintained list rather than a full
12+ * gazetteer — full geocoding requires an external service (Nominatim,
13+ * OpenCage) which is out of scope for the keyless OSINT pipeline. The list
14+ * covers the regions most heavily reported on by the OSINT channels we
15+ * aggregate (active conflicts, geopolitical hotspots, capitals).
16+ */
17+
18+const PLACES: Record<string, [number, number]> = {
19+ // Ukraine / Russia conflict
20+ 'ukraine': [31.1656, 48.3794],
21+ 'kyiv': [30.5234, 50.4501],
22+ 'kiev': [30.5234, 50.4501],
23+ 'kharkiv': [36.2304, 49.9935],
24+ 'kherson': [32.6175, 46.6354],
25+ 'odesa': [30.7233, 46.4825],
26+ 'odessa': [30.7233, 46.4825],
27+ 'lviv': [24.0297, 49.8397],
28+ 'mariupol': [37.5407, 47.0971],
29+ 'donetsk': [37.8028, 48.0159],
30+ 'luhansk': [39.3344, 48.5740],
31+ 'crimea': [34.1024, 44.9521],
32+ 'sevastopol': [33.5256, 44.6166],
33+ 'zaporizhzhia': [35.1396, 47.8388],
34+ 'avdiivka': [37.7470, 48.1396],
35+ 'bakhmut': [38.0001, 48.5957],
36+ 'belgorod': [36.5853, 50.5972],
37+ 'kursk': [36.1947, 51.7373],
38+ 'rostov': [39.7187, 47.2357],
39+ 'russia': [37.6173, 55.7558],
40+ 'moscow': [37.6173, 55.7558],
41+ 'saint petersburg': [30.3158, 59.9343],
42+ 'st petersburg': [30.3158, 59.9343],
43+
44+ // Middle East
45+ 'gaza': [34.4668, 31.5017],
46+ 'rafah': [34.2553, 31.2968],
47+ 'khan younis': [34.3026, 31.3470],
48+ 'west bank': [35.2611, 31.9466],
49+ 'jerusalem': [35.2137, 31.7683],
50+ 'tel aviv': [34.7818, 32.0853],
51+ 'haifa': [34.9896, 32.7940],
52+ 'israel': [34.8516, 31.0461],
53+ 'palestine': [35.2332, 31.9522],
54+ 'lebanon': [35.8623, 33.8547],
55+ 'beirut': [35.5018, 33.8938],
56+ 'syria': [38.9968, 34.8021],
57+ 'damascus': [36.2765, 33.5138],
58+ 'aleppo': [37.1343, 36.2021],
59+ 'iran': [53.6880, 32.4279],
60+ 'tehran': [51.3890, 35.6892],
61+ 'iraq': [43.6793, 33.2232],
62+ 'baghdad': [44.3661, 33.3152],
63+ 'yemen': [47.5868, 15.5527],
64+ "sana'a": [44.2066, 15.3694],
65+ 'sanaa': [44.2066, 15.3694],
66+ 'houthi': [44.2066, 15.3694],
67+ 'red sea': [38.0000, 20.0000],
68+ 'bab el-mandeb': [43.3170, 12.5800],
69+ 'hormuz': [56.2510, 26.5667],
70+ 'jordan': [36.2384, 30.5852],
71+ 'amman': [35.9106, 31.9454],
72+ 'saudi arabia': [45.0792, 23.8859],
73+ 'riyadh': [46.6753, 24.7136],
74+ 'uae': [53.8478, 23.4241],
75+ 'dubai': [55.2708, 25.2048],
76+ 'qatar': [51.1839, 25.3548],
77+ 'doha': [51.5310, 25.2854],
78+
79+ // Africa
80+ 'sudan': [30.2176, 12.8628],
81+ 'khartoum': [32.5599, 15.5007],
82+ 'darfur': [24.0000, 13.0000],
83+ 'south sudan': [31.3070, 6.8770],
84+ 'libya': [17.2283, 26.3351],
85+ 'tripoli': [13.1913, 32.8872],
86+ 'mali': [-3.9962, 17.5707],
87+ 'niger': [8.0817, 17.6078],
88+ 'burkina faso': [-1.5616, 12.2383],
89+ 'sahel': [4.0000, 16.0000],
90+ 'somalia': [46.1996, 5.1521],
91+ 'mogadishu': [45.3438, 2.0469],
92+ 'ethiopia': [40.4897, 9.1450],
93+ 'tigray': [38.9000, 13.5000],
94+ 'drc': [21.7587, -4.0383],
95+ 'congo': [21.7587, -4.0383],
96+ 'goma': [29.2350, -1.6792],
97+ 'kivu': [28.8500, -1.6800],
98+ 'nigeria': [8.6753, 9.0820],
99+ 'lagos': [3.3792, 6.5244],
100+ 'egypt': [30.8025, 26.8206],
101+ 'cairo': [31.2357, 30.0444],
102+ 'morocco': [-7.0926, 31.7917],
103+
104+ // Asia
105+ 'china': [116.4074, 39.9042],
106+ 'beijing': [116.4074, 39.9042],
107+ 'shanghai': [121.4737, 31.2304],
108+ 'hong kong': [114.1694, 22.3193],
109+ 'taiwan': [120.9605, 23.6978],
110+ 'taipei': [121.5654, 25.0330],
111+ 'taiwan strait': [119.4500, 24.5000],
112+ 'korea': [127.7669, 35.9078],
113+ 'seoul': [126.9780, 37.5665],
114+ 'pyongyang': [125.7625, 39.0392],
115+ 'dmz': [126.6800, 38.3200],
116+ 'japan': [138.2529, 36.2048],
117+ 'tokyo': [139.6917, 35.6895],
118+ 'okinawa': [127.6809, 26.2125],
119+ 'philippines': [121.7740, 12.8797],
120+ 'manila': [120.9842, 14.5995],
121+ 'south china sea': [114.0000, 14.0000],
122+ 'myanmar': [95.9560, 21.9162],
123+ 'burma': [95.9560, 21.9162],
124+ 'rakhine': [93.5000, 20.0000],
125+ 'thailand': [100.9925, 15.8700],
126+ 'vietnam': [108.2772, 14.0583],
127+ 'india': [78.9629, 20.5937],
128+ 'delhi': [77.2090, 28.6139],
129+ 'pakistan': [69.3451, 30.3753],
130+ 'kashmir': [76.5762, 33.7782],
131+ 'afghanistan': [67.7100, 33.9391],
132+ 'kabul': [69.2075, 34.5553],
133+
134+ // Americas
135+ 'usa': [-95.7129, 37.0902],
136+ 'us': [-95.7129, 37.0902],
137+ 'washington': [-77.0369, 38.9072],
138+ 'new york': [-74.0060, 40.7128],
139+ 'mexico': [-102.5528, 23.6345],
140+ 'mexico city': [-99.1332, 19.4326],
141+ 'haiti': [-72.2852, 18.9712],
142+ 'port-au-prince': [-72.3074, 18.5944],
143+ 'cuba': [-77.7812, 21.5218],
144+ 'venezuela': [-66.5897, 6.4238],
145+ 'caracas': [-66.9036, 10.4806],
146+ 'colombia': [-74.2973, 4.5709],
147+ 'brazil': [-51.9253, -14.2350],
148+ 'argentina': [-63.6167, -38.4161],
149+
150+ // Europe
151+ 'germany': [10.4515, 51.1657],
152+ 'berlin': [13.4050, 52.5200],
153+ 'france': [2.2137, 46.2276],
154+ 'paris': [2.3522, 48.8566],
155+ 'uk': [-3.4359, 55.3781],
156+ 'london': [-0.1276, 51.5074],
157+ 'spain': [-3.7492, 40.4637],
158+ 'madrid': [-3.7038, 40.4168],
159+ 'italy': [12.5674, 41.8719],
160+ 'rome': [12.4964, 41.9028],
161+ 'poland': [19.1451, 51.9194],
162+ 'warsaw': [21.0122, 52.2297],
163+ 'baltic': [20.0000, 58.0000],
164+ 'baltic states': [25.0000, 56.0000],
165+ 'finland': [25.7482, 61.9241],
166+ 'helsinki': [24.9384, 60.1699],
167+ 'sweden': [18.6435, 60.1282],
168+ 'norway': [8.4689, 60.4720],
169+ 'romania': [24.9668, 45.9432],
170+ 'bulgaria': [25.4858, 42.7339],
171+ 'turkey': [35.2433, 38.9637],
172+ 'ankara': [32.8541, 39.9334],
173+ 'istanbul': [28.9784, 41.0082],
174+ 'greece': [21.8243, 39.0742],
175+ 'serbia': [21.0059, 44.0165],
176+ 'belgrade': [20.4489, 44.7866],
177+ 'kosovo': [20.9020, 42.6026],
178+ 'bosnia': [17.6791, 43.9159],
179+ 'georgia': [43.3569, 42.3154],
180+ 'tbilisi': [44.7833, 41.7151],
181+ 'armenia': [45.0382, 40.0691],
182+ 'azerbaijan': [47.5769, 40.1431],
183+ 'nagorno-karabakh': [46.7517, 39.8366],
184+
185+ // ─── Cyrillic (Russian / Ukrainian) — top conflict-zone names ───
186+ 'украина': [31.1656, 48.3794],
187+ 'україна': [31.1656, 48.3794],
188+ 'киев': [30.5234, 50.4501],
189+ 'київ': [30.5234, 50.4501],
190+ 'харьков': [36.2304, 49.9935],
191+ 'харків': [36.2304, 49.9935],
192+ 'херсон': [32.6175, 46.6354],
193+ 'одесса': [30.7233, 46.4825],
194+ 'одеса': [30.7233, 46.4825],
195+ 'львов': [24.0297, 49.8397],
196+ 'львів': [24.0297, 49.8397],
197+ 'мариуполь': [37.5407, 47.0971],
198+ 'маріуполь': [37.5407, 47.0971],
199+ 'донецк': [37.8028, 48.0159],
200+ 'донецьк': [37.8028, 48.0159],
201+ 'луганск': [39.3344, 48.5740],
202+ 'луганськ': [39.3344, 48.5740],
203+ 'крым': [34.1024, 44.9521],
204+ 'крим': [34.1024, 44.9521],
205+ 'севастополь': [33.5256, 44.6166],
206+ 'запорожье': [35.1396, 47.8388],
207+ 'запоріжжя': [35.1396, 47.8388],
208+ 'бахмут': [38.0001, 48.5957],
209+ 'авдеевка': [37.7470, 48.1396],
210+ 'авдіївка': [37.7470, 48.1396],
211+ 'белгород': [36.5853, 50.5972],
212+ 'белгородская': [36.5853, 50.5972],
213+ 'белгородській': [36.5853, 50.5972],
214+ 'курск': [36.1947, 51.7373],
215+ 'россия': [37.6173, 55.7558],
216+ 'росія': [37.6173, 55.7558],
217+ 'москва': [37.6173, 55.7558],
218+ 'санкт-петербург': [30.3158, 59.9343],
219+ 'питер': [30.3158, 59.9343],
220+ 'беларусь': [27.9534, 53.7098],
221+ 'минск': [27.5615, 53.9006],
222+ 'мінськ': [27.5615, 53.9006],
223+
224+ // ─── Arabic — Middle-East conflict zones ───
225+ 'غزة': [34.4668, 31.5017],
226+ 'فلسطين': [35.2332, 31.9522],
227+ 'إسرائيل': [34.8516, 31.0461],
228+ 'القدس': [35.2137, 31.7683],
229+ 'بيروت': [35.5018, 33.8938],
230+ 'لبنان': [35.8623, 33.8547],
231+ 'دمشق': [36.2765, 33.5138],
232+ 'سوريا': [38.9968, 34.8021],
233+ 'بغداد': [44.3661, 33.3152],
234+ 'العراق': [43.6793, 33.2232],
235+ 'صنعاء': [44.2066, 15.3694],
236+ 'اليمن': [47.5868, 15.5527],
237+ 'طهران': [51.3890, 35.6892],
238+ 'إيران': [53.6880, 32.4279],
239+ 'القاهرة': [31.2357, 30.0444],
240+ 'مصر': [30.8025, 26.8206],
241+ 'الخرطوم': [32.5599, 15.5007],
242+ 'السودان': [30.2176, 12.8628],
243+};
244+
245+// Pre-sort keys longest-first so multi-word labels match before substrings.
246+const SORTED_KEYS = Object.keys(PLACES).sort((a, b) => b.length - a.length);
247+
248+export interface GeoMatch {
249+ /** Place name as it appears in the dictionary. */
250+ place: string;
251+ /** `[lng, lat]` (GeoJSON order). */
252+ coords: [number, number];
253+}
254+
255+/**
256+ * Returns the first place from the dictionary mentioned in `text`, or `null`
257+ * when nothing matches. Whole-word, case-insensitive. Longer multi-word
258+ * labels take precedence over shorter ones (e.g. "tel aviv" beats "israel"
259+ * if both appear).
260+ *
261+ * Applies small random jitter (`±jitter` degrees, default 0) so multiple
262+ * events that all map to the same capital don't stack into a single pixel.
263+ */
264+export function geoparse(text: string, jitter = 0): GeoMatch | null {
265+ if (!text) return null;
266+ const lower = text.toLowerCase();
267+ for (const key of SORTED_KEYS) {
268+ // Escape regex metacharacters in the key. ASCII `\b` doesn't work for
269+ // Cyrillic/Arabic, so we use Unicode-aware lookarounds: the match must
270+ // be preceded and followed by something that is *not* a letter in any
271+ // script (the `u` flag makes `\p{L}` Unicode-aware).
272+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
273+ const re = new RegExp(`(^|[^\\p{L}])${escaped}(?=[^\\p{L}]|$)`, 'iu');
274+ if (re.test(lower)) {
275+ const [lng, lat] = PLACES[key];
276+ const jLng = jitter ? (Math.random() - 0.5) * 2 * jitter : 0;
277+ const jLat = jitter ? (Math.random() - 0.5) * 2 * jitter : 0;
278+ return { place: key, coords: [lng + jLng, lat + jLat] };
279+ }
280+ }
281+ return null;
282+}
283+
284+/**
285+ * Conflict / OSINT-relevant keyword set. Used to filter raw feeds down to
286+ * posts likely to be reporting on incidents rather than off-topic chatter.
287+ */
288+export const CONFLICT_KEYWORDS = [
289+ // English
290+ 'attack', 'strike', 'missile', 'drone', 'war', 'troops', 'military',
291+ 'protest', 'riot', 'police', 'clash', 'bomb', 'killed', 'forces',
292+ 'shelling', 'artillery', 'airstrike', 'casualties', 'wounded', 'siege',
293+ 'invasion', 'offensive', 'frontline', 'ceasefire', 'sanctions', 'sanctioned',
294+ // Cyrillic (RU/UA)
295+ 'удар', 'обстрел', 'обстріл', 'ракет', 'дрон', 'война', 'війна',
296+ 'погиб', 'загину', 'войск', 'військ', 'атак', 'наступ', 'фронт',
297+ // Arabic
298+ 'هجوم', 'ضربة', 'صاروخ', 'حرب', 'قصف', 'قتل', 'جنود',
299+];
300+
301+export function hasConflictKeyword(text: string): boolean {
302+ if (!text) return false;
303+ const lower = text.toLowerCase();
304+ return CONFLICT_KEYWORDS.some((kw) => lower.includes(kw));
305+}
added src/lib/telegram-scraper.ts +101 −0
@@ -0,0 +1,101 @@
1+/**
2+ * Telegram public-channel scraper.
3+ *
4+ * Fetches the public web preview at `https://t.me/s/<channel>` (no auth,
5+ * no Bot API token, no MTProto) and extracts the most recent posts from
6+ * the HTML. Only channels that have web preview enabled are reachable
7+ * this way — most well-known OSINT channels do.
8+ *
9+ * The scraper parses with regex rather than a full DOM library to avoid
10+ * pulling in `jsdom` / `cheerio` just for a handful of fields. The Telegram
11+ * widget markup is stable and well-formed enough for this to be safe.
12+ */
13+
14+export interface TelegramPost {
15+ /** `<channel>/<post-id>` — unique across the scraper. */
16+ id: string;
17+ /** Channel username (without `@`). */
18+ channel: string;
19+ /** Plain-text body with HTML stripped and `<br>` converted to newlines. */
20+ text: string;
21+ /** Permalink to the post on t.me. */
22+ url: string;
23+ /** ISO-8601 timestamp from the `<time datetime=...>` attribute. */
24+ datetime: string;
25+ /** View counter as displayed (e.g. `"40.9K"`), or `undefined` if absent. */
26+ views?: string;
27+}
28+
29+const POST_WRAP_RE = /<div class="tgme_widget_message_wrap[^"]*"[\s\S]*?<\/div>\s*<\/div>/g;
30+const TEXT_RE = /<div class="tgme_widget_message_text[^"]*"[^>]*>([\s\S]*?)<\/div>/;
31+const DATE_HREF_RE = /<a class="tgme_widget_message_date"[^>]*href="(https:\/\/t\.me\/[^"]+)"/;
32+const TIME_RE = /<time[^>]*datetime="([^"]+)"/;
33+const VIEWS_RE = /<span class="tgme_widget_message_views">([^<]+)<\/span>/;
34+const POST_DATA_RE = /data-post="([^"]+)"/;
35+
36+function stripHtml(html: string): string {
37+ return html
38+ .replace(/<br\s*\/?>/gi, '\n')
39+ .replace(/<a\s[^>]*>([\s\S]*?)<\/a>/gi, '$1')
40+ .replace(/<[^>]+>/g, '')
41+ .replace(/&nbsp;/g, ' ')
42+ .replace(/&amp;/g, '&')
43+ .replace(/&lt;/g, '<')
44+ .replace(/&gt;/g, '>')
45+ .replace(/&quot;/g, '"')
46+ .replace(/&#39;/g, "'")
47+ .replace(/\n{3,}/g, '\n\n')
48+ .trim();
49+}
50+
51+/**
52+ * Fetches and parses a single channel. Returns up to `limit` of the most
53+ * recent posts (Telegram's web preview returns them oldest-first, so we
54+ * slice from the tail).
55+ */
56+export async function fetchChannel(
57+ channel: string,
58+ limit = 20
59+): Promise<TelegramPost[]> {
60+ const safe = channel.replace(/^@/, '').trim();
61+ if (!/^[a-zA-Z][a-zA-Z0-9_]{2,31}$/.test(safe)) {
62+ throw new Error(`Invalid Telegram channel name: ${channel}`);
63+ }
64+
65+ const res = await fetch(`https://t.me/s/${safe}`, {
66+ signal: AbortSignal.timeout(10_000),
67+ headers: {
68+ // Telegram serves the widget HTML to ordinary browser UAs. A bare
69+ // `node-fetch` UA sometimes gets a stripped response.
70+ 'User-Agent': 'Mozilla/5.0 (compatible; OsirisOSINT/1.0; +https://osirisai.live)',
71+ Accept: 'text/html,application/xhtml+xml',
72+ },
73+ });
74+ if (!res.ok) throw new Error(`t.me/${safe} HTTP ${res.status}`);
75+ const html = await res.text();
76+
77+ const posts: TelegramPost[] = [];
78+ const wrappers = html.match(POST_WRAP_RE) || [];
79+ for (const wrap of wrappers) {
80+ const textMatch = wrap.match(TEXT_RE);
81+ const timeMatch = wrap.match(TIME_RE);
82+ const linkMatch = wrap.match(DATE_HREF_RE);
83+ const dataMatch = wrap.match(POST_DATA_RE);
84+ const viewsMatch = wrap.match(VIEWS_RE);
85+
86+ // Skip media-only posts (no text body) — geoparse needs words.
87+ if (!textMatch || !timeMatch || !linkMatch || !dataMatch) continue;
88+
89+ posts.push({
90+ id: dataMatch[1],
91+ channel: safe,
92+ text: stripHtml(textMatch[1]),
93+ url: linkMatch[1],
94+ datetime: timeMatch[1],
95+ views: viewsMatch?.[1]?.trim(),
96+ });
97+ }
98+
99+ // Telegram returns oldest-first; the freshest posts are at the tail.
100+ return posts.slice(-limit).reverse();
101+}