| 1 | import { NextResponse } from 'next/server'; |
| 2 | import crypto from 'crypto'; |
| 3 | |
| 4 | /** |
| 5 | * OSIRIS — Military-Grade Intelligence API |
| 6 | * Fetches Telegram OSINT feeds directly, with a failsafe fallback |
| 7 | * to traditional intelligence sources if Telegram blocks the IP. |
| 8 | */ |
| 9 | |
| 10 | const TELEGRAM_CHANNELS = [ |
| 11 | 'OSINTtechnical', |
| 12 | 'Faytuks', |
| 13 | 'Liveuamap', |
| 14 | 'CyberKnow' |
| 15 | ]; |
| 16 | |
| 17 | const FALLBACK_FEEDS = { |
| 18 | BBC: 'https://feeds.bbci.co.uk/news/world/rss.xml', |
| 19 | AlJazeera: 'https://www.aljazeera.com/xml/rss/all.xml', |
| 20 | GDACS: 'https://www.gdacs.org/xml/rss.xml' |
| 21 | }; |
| 22 | |
| 23 | const RISK_KEYWORDS = ['war','missile','strike','attack','crisis','tension','military','conflict','defense','clash','nuclear','invasion','bomb','drone','weapon','sanctions','ceasefire','escalation', 'killed', 'destroyed', 'operation', 'casualty', 'frontline', 'threat']; |
| 24 | |
| 25 | const KEYWORD_COORDS: Record<string, [number, number]> = { |
| 26 | 'ukraine': [49.487, 31.272], 'kyiv': [50.450, 30.523], 'russia': [61.524, 105.318], |
| 27 | 'moscow': [55.755, 37.617], 'israel': [31.046, 34.851], 'gaza': [31.416, 34.333], |
| 28 | 'iran': [32.427, 53.688], 'lebanon': [33.854, 35.862], 'syria': [34.802, 38.996], |
| 29 | 'yemen': [15.552, 48.516], 'china': [35.861, 104.195], 'taiwan': [23.697, 120.960], |
| 30 | 'united states': [38.907, -77.036], 'europe': [48.800, 2.300], 'middle east': [31.500, 34.800] |
| 31 | }; |
| 32 | |
| 33 | function scoreRisk(text: string): number { |
| 34 | const lower = text.toLowerCase(); |
| 35 | let score = 1; |
| 36 | for (const kw of RISK_KEYWORDS) { |
| 37 | if (lower.includes(kw)) score += 2; |
| 38 | } |
| 39 | return Math.min(10, score); |
| 40 | } |
| 41 | |
| 42 | function findCoords(text: string): [number, number] | null { |
| 43 | const lower = text.toLowerCase(); |
| 44 | for (const [keyword, coords] of Object.entries(KEYWORD_COORDS)) { |
| 45 | if (lower.includes(keyword)) return coords; |
| 46 | } |
| 47 | return null; |
| 48 | } |
| 49 | |
| 50 | function parseTelegramHTML(html: string, channel: string): any[] { |
| 51 | const items: any[] = []; |
| 52 | const messageBlockRegex = /<div class="tgme_widget_message_wrap js-widget_message_wrap"[\s\S]*?<\/div>\s*<\/div>\s*<\/div>/gi; |
| 53 | let blockMatch; |
| 54 | |
| 55 | while ((blockMatch = messageBlockRegex.exec(html)) !== null) { |
| 56 | const blockHtml = blockMatch[0]; |
| 57 | const textRegex = /<div class="tgme_widget_message_text[^>]*>([\s\S]*?)<\/div>/i; |
| 58 | const textMatch = blockHtml.match(textRegex); |
| 59 | if (!textMatch) continue; |
| 60 | |
| 61 | let text = textMatch[1].replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '').replace(/"/g, '"').replace(/&/g, '&').trim(); |
| 62 | if (!text || text.length < 10) continue; |
| 63 | |
| 64 | const dateRegex = /<a class="tgme_widget_message_date" href="(https:\/\/t\.me\/[^"]+)".*?<time datetime="([^"]+)"/i; |
| 65 | const dateMatch = blockHtml.match(dateRegex); |
| 66 | const link = dateMatch ? dateMatch[1] : `https://t.me/${channel}`; |
| 67 | const pubDate = dateMatch ? dateMatch[2] : new Date().toISOString(); |
| 68 | |
| 69 | const title = text.split('\n')[0].substring(0, 100); |
| 70 | |
| 71 | items.push({ title, description: text, link, pubDate, source: `t.me/${channel}` }); |
| 72 | } |
| 73 | return items; |
| 74 | } |
| 75 | |
| 76 | function parseRSSItems(xml: string, sourceName: string): any[] { |
| 77 | const items: any[] = []; |
| 78 | const itemRegex = /<item>([\s\S]*?)<\/item>/gi; |
| 79 | let match; |
| 80 | |
| 81 | while ((match = itemRegex.exec(xml)) !== null) { |
| 82 | const itemXml = match[1]; |
| 83 | const getTag = (tag: string) => { |
| 84 | const m = itemXml.match(new RegExp(`<${tag}[^>]*><!\\[CDATA\\[([\\s\\S]*?)\\]\\]><\\/${tag}>|<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`, 'i')); |
| 85 | return (m?.[1] || m?.[2] || '').trim(); |
| 86 | }; |
| 87 | |
| 88 | let title = getTag('title').replace(/<[^>]+>/g, ''); |
| 89 | let desc = getTag('description').replace(/<[^>]+>/g, '').replace(/"/g, '"'); |
| 90 | |
| 91 | items.push({ |
| 92 | title: title.length > 100 ? title.substring(0, 100) + '...' : title, |
| 93 | description: desc, |
| 94 | link: getTag('link'), |
| 95 | pubDate: getTag('pubDate') || new Date().toISOString(), |
| 96 | source: sourceName |
| 97 | }); |
| 98 | } |
| 99 | return items; |
| 100 | } |
| 101 | |
| 102 | export async function GET() { |
| 103 | try { |
| 104 | const feedPromises = TELEGRAM_CHANNELS.map(async (channel) => { |
| 105 | try { |
| 106 | const res = await fetch(`https://t.me/s/${channel}`, { |
| 107 | signal: AbortSignal.timeout(8000), |
| 108 | headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } |
| 109 | }); |
| 110 | if (!res.ok) return []; |
| 111 | const html = await res.text(); |
| 112 | return parseTelegramHTML(html, channel).slice(-8); |
| 113 | } catch { return []; } |
| 114 | }); |
| 115 | |
| 116 | const feedResults = await Promise.allSettled(feedPromises); |
| 117 | const allArticles: any[] = []; |
| 118 | |
| 119 | for (const result of feedResults) { |
| 120 | if (result.status === 'fulfilled') allArticles.push(...result.value); |
| 121 | } |
| 122 | |
| 123 | // FAILSAFE: If Telegram completely blocks the IP, fall back to traditional RSS |
| 124 | if (allArticles.length === 0) { |
| 125 | const fallbackPromises = Object.entries(FALLBACK_FEEDS).map(async ([source, url]) => { |
| 126 | try { |
| 127 | const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); |
| 128 | if (!res.ok) return []; |
| 129 | const xml = await res.text(); |
| 130 | return parseRSSItems(xml, source).slice(0, 5); |
| 131 | } catch { return []; } |
| 132 | }); |
| 133 | |
| 134 | const fallbackResults = await Promise.allSettled(fallbackPromises); |
| 135 | for (const result of fallbackResults) { |
| 136 | if (result.status === 'fulfilled') allArticles.push(...result.value); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | const newsItems = allArticles.map(article => { |
| 141 | const riskScore = scoreRisk(article.description || article.title); |
| 142 | const coords = findCoords(article.description || article.title); |
| 143 | |
| 144 | return { |
| 145 | id: crypto.createHash('md5').update((article.link || '') + (article.pubDate || '')).digest('hex'), |
| 146 | title: article.title, |
| 147 | description: article.description, |
| 148 | link: article.link, |
| 149 | published: article.pubDate, |
| 150 | source: article.source, |
| 151 | risk_score: riskScore, |
| 152 | coords: coords ? [coords[0], coords[1]] : null, |
| 153 | coords_default: !coords, |
| 154 | machine_assessment: riskScore >= 8 ? "AI Analysis indicates elevated tactical priority based on OSINT stream patterns." : null, |
| 155 | }; |
| 156 | }); |
| 157 | |
| 158 | newsItems.sort((a, b) => new Date(b.published).getTime() - new Date(a.published).getTime()); |
| 159 | |
| 160 | return NextResponse.json({ |
| 161 | news: newsItems, |
| 162 | total: newsItems.length, |
| 163 | timestamp: new Date().toISOString(), |
| 164 | }, { |
| 165 | headers: { |
| 166 | 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=120', |
| 167 | }, |
| 168 | }); |
| 169 | } catch (error) { |
| 170 | return NextResponse.json({ news: [], error: 'Failed to fetch intel' }, { status: 500 }); |
| 171 | } |
| 172 | } |