const express = require('express'); const { createCanvas, loadImage } = require('canvas'); const cors = require('cors'); const Tesseract = require('tesseract.js'); const compression = require('compression'); const crypto = require('crypto'); const http = require('http'); const https = require('https'); const app = express(); app.use(cors()); app.use(compression({ filter: (req, res) => { // PNG zaten sıkıştırılmış, tekrar gzip yapmak boşa CPU yakıyor if (res.getHeader('Content-Type') === 'image/png') return false; return compression.filter(req, res); }, level: 1 // En hızlı gzip seviyesi })); app.use(express.json()); // ───────────────────────────────────────────── // KEEP-ALIVE AGENTS FOR EXTREMELY FAST FETCHES // ───────────────────────────────────────────── const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 256, keepAliveMsecs: 30000, scheduling: 'fifo' }); const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 256, keepAliveMsecs: 30000, scheduling: 'fifo' }); // ───────────────────────────────────────────── // TASK QUEUES // ───────────────────────────────────────────── class TaskQueue { constructor(concurrency = 1) { this.concurrency = concurrency; this.running = 0; this.queue = []; } add(task) { return new Promise((resolve, reject) => { this.queue.push({ task, resolve, reject }); this.next(); }); } next() { if (this.running >= this.concurrency || this.queue.length === 0) return; this.running++; const { task, resolve, reject } = this.queue.shift(); task().then(resolve).catch(reject).finally(() => { this.running--; this.next(); }); } isBusy() { return this.running >= this.concurrency; } } // vCPU Limit of 2: Canvas native C++ threads + daha düşük PNG compression = daha fazla paralel iş const canvasQueue = new TaskQueue(5); // ───────────────────────────────────────────── // CANVAS POOL - Reuse canvas objects to avoid GC pressure // ───────────────────────────────────────────── class CanvasPool { constructor() { this.pools = new Map(); // 'WxH' -> [canvas] } acquire(width, height) { const key = `${width}x${height}`; const pool = this.pools.get(key); if (pool && pool.length > 0) return pool.pop(); return createCanvas(width, height); } release(canvas) { const key = `${canvas.width}x${canvas.height}`; if (!this.pools.has(key)) this.pools.set(key, []); const pool = this.pools.get(key); if (pool.length < 8) { const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); pool.push(canvas); } } } const canvasPool = new CanvasPool(); // Pre-warm font rendering to eliminate cold-start penalty function prewarmFonts() { const c = createCanvas(1, 1); const ctx = c.getContext('2d'); const fonts = [ '14px sans-serif', '16px sans-serif', '18px sans-serif', '20px sans-serif', '24px sans-serif', '36px sans-serif', '42px sans-serif', 'bold 14px sans-serif', 'bold 16px sans-serif', 'bold 18px sans-serif', 'bold 20px sans-serif', 'bold 24px sans-serif', 'bold 36px sans-serif', 'bold 42px sans-serif', 'italic 18px sans-serif' ]; for (const f of fonts) { ctx.font = f; ctx.fillText('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 0, 0); } console.log('[Canvas] Fonts pre-warmed ✓'); } // ───────────────────────────────────────────── // HIGH-CAPACITY LRU CACHE (18GB RAM available) // ───────────────────────────────────────────── class CacheStore { constructor(maxSize = 10000, defaultTtlMs = 600000) { this.maxSize = maxSize; this.defaultTtlMs = defaultTtlMs; this.store = new Map(); } get(key) { const item = this.store.get(key); if (!item) return null; if (Date.now() > item.expiry) { this.store.delete(key); return null; } return item.value; } set(key, value, ttlMs = this.defaultTtlMs) { if (this.store.size >= this.maxSize) { // Evict oldest (Map preserves insertion order) const oldestKey = this.store.keys().next().value; this.store.delete(oldestKey); } this.store.set(key, { value, expiry: Date.now() + ttlMs }); } clear() { this.store.clear(); } get size() { return this.store.size; } } // ─── ULTRA-AGGRESSIVE CACHE SIZES (18GB RAM) ─── const ocrUrlCache = new CacheStore(100000, 1800000); // URL → OCR sonucu (30 dakika) const ocrHashCache = new CacheStore(200000, 7200000); // MD5 → OCR sonucu (2 saat) const pHashCache = new CacheStore(200000, 21600000); // pHash → scam bilgisi (6 saat) const remoteImageCache = new CacheStore(20000, 3600000); // Avatar/icon image nesneleri (1 saat) const canvasRenderCache = new CacheStore(50000, 300000); // Rendered PNG buffer (5 dakika) // In-flight request deduplication map to combine concurrent identical requests const inflightOCR = new Map(); const inflightCanvas = new Map(); // ───────────────────────────────────────────── // WARM TESSERACT SCHEDULER // ───────────────────────────────────────────── let ocrScheduler = null; let ocrReady = false; async function initOCR() { try { console.log('[OCR] Workers starting (Offline mode, Local tessdata)...'); ocrScheduler = Tesseract.createScheduler(); // 2 parallel workers optimized for 2 vCPU const workers = await Promise.all([ Tesseract.createWorker('eng', 1, { langPath: '/app/tessdata', cachePath: '/app/tessdata', cacheMethod: 'readOnly', gzip: true }), Tesseract.createWorker('eng', 1, { langPath: '/app/tessdata', cachePath: '/app/tessdata', cacheMethod: 'readOnly', gzip: true }) ]); workers.forEach(w => ocrScheduler.addWorker(w)); ocrReady = true; console.log('[OCR] 2 workers ready with local tessdata ✓'); } catch (err) { console.error('[OCR] Worker initialization error:', err.message); ocrReady = false; } } async function runOCR(imageBufferOrUrl) { if (ocrReady && ocrScheduler) { return ocrScheduler.addJob('recognize', imageBufferOrUrl); } return Tesseract.recognize(imageBufferOrUrl, 'eng', { langPath: '/app/tessdata', gzip: true }); } // ───────────────────────────────────────────── // IMAGE PROCESSING & UTILS // ───────────────────────────────────────────── function simpleHash(str) { let h = 0; for (let i = 0; i < str.length; i++) { h = Math.imul(31, h) + str.charCodeAt(i) | 0; } return (h >>> 0).toString(16); } class DownloadError extends Error { constructor(message) { super(message); this.name = "DownloadError"; this.isDownloadError = true; } } // Fetch image buffer with short timeout & custom keep-alive agent async function fetchImageBuffer(imageUrl) { const isHttps = imageUrl.startsWith('https'); const agent = isHttps ? httpsAgent : httpAgent; const res = await fetch(imageUrl, { signal: AbortSignal.timeout(3000), // 3s strict timeout for 1000ms total budget headers: { 'User-Agent': 'Mozilla/5.0 SeireiGuardMediaScan/1.0' }, agent }); if (!res.ok) throw new DownloadError(`HTTP ${res.status}`); return Buffer.from(await res.arrayBuffer()); } // Pre-process: sadece grayscale, boyut küçültme YOK (metin okunabilirliği için) async function preprocessImageForOCR(buffer) { try { const img = await loadImage(buffer); const width = img.width; const height = img.height; const canvas = createCanvas(width, height); const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // Sadece grayscale dönüşümü const imgData = ctx.getImageData(0, 0, width, height); const data = imgData.data; for (let i = 0; i < data.length; i += 4) { const gray = Math.round(0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]); data[i] = gray; data[i + 1] = gray; data[i + 2] = gray; } ctx.putImageData(imgData, 0, 0); return canvas.toBuffer('image/jpeg', { quality: 0.75 }); } catch (err) { console.warn('[Preprocessing] Failed, using raw buffer instead:', err.message); return buffer; } } // Compute pHash for fuzzy matching async function computePHashFromBuffer(buf) { try { let pixelData; try { const sharp = require('sharp'); const { data } = await sharp(buf) .resize(8, 8, { fit: 'fill' }) .grayscale() .raw() .toBuffer({ resolveWithObject: true }); pixelData = data; } catch { const img = await loadImage(buf); const c = createCanvas(8, 8); const ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0, 8, 8); const d = ctx.getImageData(0, 0, 8, 8).data; pixelData = []; for (let i = 0; i < d.length; i += 4) { pixelData.push(Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2])); } } const avg = pixelData.reduce((s, v) => s + v, 0) / pixelData.length; return pixelData.map(p => p >= avg ? '1' : '0').join(''); } catch (err) { console.warn('[pHash] Failed:', err.message); return null; } } function backgroundAddPHash(imageUrl, isScam, reason, keywords) { fetchImageBuffer(imageUrl) .then(buf => computePHashFromBuffer(buf)) .then(hash => { if (hash) { pHashCache.set(hash, { isScam, reason: reason || null, keywords: keywords || [] }); } }) .catch(err => console.warn('[Background pHash] Error:', err.message)); } function hammingDistance(h1, h2) { if (!h1 || !h2 || h1.length !== h2.length) return 999; let d = 0; for (let i = 0; i < h1.length; i++) if (h1[i] !== h2[i]) d++; return d; } function findSimilarInCache(hash, threshold = 10) { // Map entries are fast to iterate for (const [cachedHash, entry] of pHashCache.store.entries()) { const dist = hammingDistance(hash, cachedHash); if (dist <= threshold) return { ...entry, distance: dist }; } return null; } // ───────────────────────────────────────────── // KEYWORD / SCAM DETECTION // ───────────────────────────────────────────── const FAST_KEYWORDS = [ "promo code", "withdraw", "claim your reward", "crypto", "nft", "mrbeast", "fuzewin", "xcom/", "free nitro", "airdrop", "mint now", "usdt", "giveaway", "free money", "claim now", "twogamb.at", "bonus", "free usdt", "congratulations", "reward received", "activate code", "successfully received", "receive usdt", "hasobet", "withdrawal success", "cryptocurrency casino", "tether", "your withdrawal", "promo code:", "claim reward", "connect wallet", "binance", "coinbase", "trading bot", "investment", "double your", "guaranteed profit", "passive income" ]; const SCAM_KEYWORDS = [ "usdt", "giveaway", "withdrawal", "successfully received", "receive usdt", "promo code", "congratulations", "reward received", "activate code", "mrbeast", "free money", "claim your reward", "claim now", "twogamb.at", "bonus", "gift", "airdrop", "crypto", "free usdt", "withdraw", "hasobet", "withdrawal success", "cryptocurrency casino", "tether", "your withdrawal", "was successful", "claim reward", "connect wallet", "trading bot", "investment", "double your", "guaranteed profit", "passive income", "rakeback", "deposit", "casino" ]; const scamRules = [ { pattern: /nitro/i, keywords: ["free", "gift", "claim", "promo", "steam", "giveaway", "distribution", "discorx", "dlscord", "get", "link", "claim nitro"], minKeywords: 1, reason: "Şüpheli Nitro Hediyesi/Kampanyası" }, { pattern: /qr|verify|scan|dogrulama|doğrulama/i, keywords: ["discord settings", "mobile", "camera", "developer", "options", "safety", "scan", "qr code", "barkod"], minKeywords: 2, reason: "Şüpheli QR Kod/Doğrulama Yönlendirmesi" }, { pattern: /game|test|play|download|indir/i, keywords: ["developer", "unity", "unreal", "test my", "my new", "feedback", "executable", ".exe", ".zip", "run", "beta"], minKeywords: 2, reason: "Şüpheli Oyun/Yazılım İndirme Talebi" }, { pattern: /airdrop|crypto|nft|solana|ethereum|eth|btc/i, keywords: ["free", "claim", "wallet", "connect", "drop", "giveaway", "whitelist", "mint"], minKeywords: 1, reason: "Şüpheli Kripto/NFT Dağıtımı" }, { pattern: /verification|verify|captcha|restorecord|wick/i, keywords: ["click", "link", "server", "join", "verify to", "gain access", "doğrula", "dogrula", "tıkla", "tıklayın"], minKeywords: 1, reason: "Şüpheli Doğrulama/Captcha Kimlik Avı" }, { pattern: /casino|gambling|bet|hasobet|stake|slots|roulette|poker/i, keywords: ["bonus", "promo", "deposit", "withdraw", "rakeback", "vip", "reward", "code", "launch", "activate", "claim"], minKeywords: 1, reason: "Şüpheli Kripto Casino/Bahis Dolandırıcılığı" }, { pattern: /withdrawal|transaction|received|success|transfer/i, keywords: ["usdt", "tether", "$2", "$5", "$1", "wallet", "trx", "ton", "completed", "continue", "funds"], minKeywords: 1, reason: "Sahte Para Çekme/İşlem Ekran Görüntüsü" } ]; function fastKeywordCheck(text) { if (!text) return null; const lower = text.toLowerCase(); const found = []; for (const kw of FAST_KEYWORDS) { if (lower.includes(kw)) found.push(kw); } return found.length > 0 ? { isScam: true, reason: "Hızlı Keyword Eşleşmesi", keywords: found } : null; } function checkTextForScam(text) { if (!text) return null; const lower = text.toLowerCase(); const foundKeywords = []; for (const kw of SCAM_KEYWORDS) { if (lower.includes(kw)) foundKeywords.push(kw); } if (foundKeywords.length > 0) { return { isScam: true, reason: "Zararlı/Scam Kelime Eşleşmesi", keywords: foundKeywords }; } for (const rule of scamRules) { if (rule.pattern.test(lower)) { const ruleMatches = rule.keywords.filter(kw => lower.includes(kw)); if (ruleMatches.length >= rule.minKeywords) { return { isScam: true, reason: rule.reason, keywords: ruleMatches }; } } } return null; } // Loaded Image Cacher to prevent downloading avatars and icons multiple times async function fetchAndCacheImage(url) { if (!url) return null; const cached = remoteImageCache.get(url); if (cached) return cached; try { const buffer = await fetchImageBuffer(url); const img = await loadImage(buffer); remoteImageCache.set(url, img); return img; } catch { return null; } } // ───────────────────────────────────────────── // FORWARD // ───────────────────────────────────────────── async function attemptForward(req, res, path) { const otherSpaceUrl = process.env.OTHER_SPACE_URL; if (!otherSpaceUrl) return false; if (req.headers['x-no-redirect'] === 'true' || req.query.no_redirect === 'true') return false; try { let targetHost = otherSpaceUrl.endsWith('/') ? otherSpaceUrl.slice(0, -1) : otherSpaceUrl; console.log(`[Forward] → ${targetHost}${path}`); const headers = { 'Content-Type': 'application/json', 'x-no-redirect': 'true' }; if (req.headers['authorization']) headers['authorization'] = req.headers['authorization']; const response = await fetch(`${targetHost}${path}`, { method: 'POST', headers, body: JSON.stringify(req.body), signal: AbortSignal.timeout(6000) }); if (response.ok) { const data = await response.json(); data.forwarded = true; data.forwarded_to = targetHost; res.json(data); return true; } } catch (err) { console.error(`[Forward Error] ${err.message}`); } return false; } // ───────────────────────────────────────────── // ROUTES // ───────────────────────────────────────────── app.get('/', (req, res) => res.send("Seirei Partner Stat API is running at maximum efficiency.")); app.get('/health', (req, res) => { res.json({ status: 'ok', ocr_ready: ocrReady, ocr_workers: ocrReady ? 2 : 0, caches: { ocr_url_cache: ocrUrlCache.size, ocr_hash_cache: ocrHashCache.size, phash_cache: pHashCache.size, remote_image_cache: remoteImageCache.size, canvas_render_cache: canvasRenderCache.size }, canvas_queue: { running: canvasQueue.running, pending: canvasQueue.queue.length } }); }); // Helper to handle canvas requests with high speed rendering cache function handleCanvasRequest(req, res, routeKey, renderFn) { const startTime = Date.now(); const reqHash = simpleHash(JSON.stringify(req.body)); const cacheKey = `${routeKey}:${reqHash}`; // Check render cache (5 dakika TTL) const cachedBuffer = canvasRenderCache.get(cacheKey); if (cachedBuffer) { res.set('Content-Type', 'image/png'); res.set('X-Cache', 'HIT'); res.set('X-Response-Time', `${Date.now() - startTime}ms`); return res.send(cachedBuffer); } // Deduplicate in-flight requests if (inflightCanvas.has(cacheKey)) { return inflightCanvas.get(cacheKey) .then(buf => { res.set('Content-Type', 'image/png'); res.set('X-Cache', 'DEDUP'); res.set('X-Response-Time', `${Date.now() - startTime}ms`); res.send(buf); }) .catch(e => res.status(500).json({ error: e.toString() })); } if (canvasQueue.isBusy()) { attemptForward(req, res, req.path).then(forwarded => { if (!forwarded) { // If forward fails, queue it locally queueRender(); } }); } else { queueRender(); } function queueRender() { const renderPromise = canvasQueue.add(async () => { return renderFn(req.body); }); inflightCanvas.set(cacheKey, renderPromise); renderPromise .then(buf => { inflightCanvas.delete(cacheKey); canvasRenderCache.set(cacheKey, buf); res.set('Content-Type', 'image/png'); res.set('X-Cache', 'MISS'); res.set('X-Response-Time', `${Date.now() - startTime}ms`); res.send(buf); }) .catch(e => { inflightCanvas.delete(cacheKey); res.status(500).json({ error: e.toString() }); }); } } // ── Partner Stat Canvas ────────────────────── app.post('/api/partnerstat', (req, res) => { handleCanvasRequest(req, res, 'partnerstat', async (body) => { const { username, avatar, createdOn, joinedOn, stats } = body; const width = 800, height = 350; const canvas = canvasPool.acquire(width, height); const ctx = canvas.getContext('2d'); ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height); ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 100); if (avatar) { const img = await fetchAndCacheImage(avatar); if (img) { ctx.save(); ctx.beginPath(); ctx.arc(60, 50, 40, 0, Math.PI * 2); ctx.closePath(); ctx.clip(); ctx.drawImage(img, 20, 10, 80, 80); ctx.restore(); } } ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif'; ctx.fillText(username || "Bilinmeyen Kullanıcı", 120, 55); ctx.fillStyle = '#b5bac1'; ctx.font = '16px sans-serif'; ctx.fillText(`Kayıt: ${createdOn || '-'} • Katılım: ${joinedOn || '-'}`, 120, 85); ctx.fillStyle = '#ffffff'; ctx.font = 'bold 24px sans-serif'; ctx.fillText(body.title || 'Partnerlik İstatistikleri', 30, 150); const drawStatBox = (x, y, w, h, label, value, color) => { ctx.fillStyle = '#1e1f22'; ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(x, y, w, h, 10); else ctx.rect(x, y, w, h); ctx.fill(); ctx.fillStyle = '#b5bac1'; ctx.font = '16px sans-serif'; ctx.fillText(label, x + 20, y + 30); ctx.fillStyle = color; ctx.font = 'bold 42px sans-serif'; ctx.fillText(value.toString(), x + 20, y + 80); }; drawStatBox(30, 180, 170, 120, 'Son 24 Saat', stats?.['1d'] || 0, '#57f287'); drawStatBox(220, 180, 170, 120, 'Son 7 Gün', stats?.['7d'] || 0, '#fee75c'); drawStatBox(410, 180, 170, 120, 'Son 30 Gün', stats?.['30d'] || 0, '#eb459e'); drawStatBox(600, 180, 170, 120, 'Toplam', stats?.['total'] || 0, '#5865F2'); ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif'; ctx.fillText(body.footer || 'Seirei Partner Takip Sistemi', 30, 335); const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE }); canvasPool.release(canvas); return buf; }); }); // ── Partner Leaderboard Canvas ─────────────── app.post('/api/partnerlb', (req, res) => { handleCanvasRequest(req, res, 'partnerlb', async (body) => { const { guildName, guildIcon, weekly, total } = body; const width = 900, height = 650; const canvas = canvasPool.acquire(width, height); const ctx = canvas.getContext('2d'); ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height); ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 120); if (guildIcon) { const img = await fetchAndCacheImage(guildIcon); if (img) { ctx.save(); ctx.beginPath(); ctx.arc(70, 60, 45, 0, Math.PI * 2); ctx.closePath(); ctx.clip(); ctx.drawImage(img, 25, 15, 90, 90); ctx.restore(); } } ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif'; ctx.fillText(body.title || 'Partnerlik Liderlik Sıralaması', 140, 55); ctx.fillStyle = '#b5bac1'; ctx.font = '20px sans-serif'; ctx.fillText(guildName || "Sunucu İstatistikleri", 140, 90); const drawColumn = (x, title, data, color) => { const colWidth = 410; ctx.fillStyle = '#1e1f22'; ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(x, 140, colWidth, 470, 15); else ctx.rect(x, 140, colWidth, 470); ctx.fill(); ctx.fillStyle = color; ctx.font = 'bold 24px sans-serif'; ctx.fillText(title, x + 20, 180); ctx.strokeStyle = '#3f4147'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(x + 20, 195); ctx.lineTo(x + colWidth - 20, 195); ctx.stroke(); let y = 230; if (!data || data.length === 0) { ctx.fillStyle = '#80848e'; ctx.font = 'italic 18px sans-serif'; ctx.fillText('Veri bulunamadı.', x + 20, y); } else { data.slice(0, 10).forEach((item, i) => { ctx.fillStyle = i < 3 ? color : '#313338'; ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(x + 20, y - 22, 35, 35, 8); else ctx.rect(x + 20, y - 22, 35, 35); ctx.fill(); ctx.fillStyle = i < 3 ? '#1e1f22' : '#ffffff'; ctx.font = 'bold 18px sans-serif'; ctx.textAlign = 'center'; ctx.fillText((i + 1).toString(), x + 37.5, y + 3); ctx.textAlign = 'left'; ctx.fillStyle = '#ffffff'; ctx.font = '18px sans-serif'; const name = item.username.length > 20 ? item.username.substring(0, 17) + '...' : item.username; ctx.fillText(name, x + 70, y + 2); ctx.fillStyle = color; ctx.font = 'bold 18px sans-serif'; ctx.textAlign = 'right'; ctx.fillText(`${item.count} partner`, x + colWidth - 20, y + 2); ctx.textAlign = 'left'; y += 42; }); } }; drawColumn(30, '📅 Bu Hafta (7 Gün)', weekly, '#fee75c'); drawColumn(460, '👑 Tüm Zamanlar', total, '#5865F2'); ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif'; ctx.fillText(body.footer || 'Seirei System Guard • Otomatik Raporlama', 30, 635); const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE }); canvasPool.release(canvas); return buf; }); }); // ── Arena Leaderboard Canvas ───────────────── app.post('/api/arenalb', (req, res) => { handleCanvasRequest(req, res, 'arenalb', async (body) => { const { guildName, guildIcon, rankings } = body; const width = 900, height = 700; const canvas = canvasPool.acquire(width, height); const ctx = canvas.getContext('2d'); ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height); ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 120); if (guildIcon) { const img = await fetchAndCacheImage(guildIcon); if (img) { ctx.save(); ctx.beginPath(); ctx.arc(70, 60, 45, 0, Math.PI * 2); ctx.closePath(); ctx.clip(); ctx.drawImage(img, 25, 15, 90, 90); ctx.restore(); } } ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif'; ctx.fillText('Anime Arenası Puan Sıralaması', 140, 55); ctx.fillStyle = '#b5bac1'; ctx.font = '20px sans-serif'; ctx.fillText(guildName || "Sunucu Arenası", 140, 90); const colWidth = 840; ctx.fillStyle = '#1e1f22'; ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(30, 140, colWidth, 520, 15); else ctx.rect(30, 140, colWidth, 520); ctx.fill(); let y = 190; if (!rankings || rankings.length === 0) { ctx.fillStyle = '#80848e'; ctx.font = 'italic 18px sans-serif'; ctx.fillText('Henüz veri bulunamadı.', 60, y); } else { for (let i = 0; i < Math.min(rankings.length, 10); i++) { const char = rankings[i]; if (i % 2 === 0) { ctx.fillStyle = '#232428'; ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(40, y - 35, colWidth - 20, 45, 8); else ctx.rect(40, y - 35, colWidth - 20, 45); ctx.fill(); } ctx.fillStyle = i === 0 ? '#fee75c' : i === 1 ? '#b5bac1' : i === 2 ? '#e67e22' : '#ffffff'; ctx.font = 'bold 20px sans-serif'; ctx.fillText(`${i + 1}.`, 60, y); if (char.imageUrl) { const img = await fetchAndCacheImage(char.imageUrl); if (img) { ctx.save(); ctx.beginPath(); ctx.arc(110, y - 8, 18, 0, Math.PI * 2); ctx.closePath(); ctx.clip(); ctx.drawImage(img, 92, y - 26, 36, 36); ctx.restore(); } } ctx.fillStyle = '#ffffff'; ctx.font = '20px sans-serif'; const displayName = char.name.length > 35 ? char.name.substring(0, 32) + '...' : char.name; ctx.fillText(displayName, 145, y); ctx.fillStyle = '#5865F2'; ctx.font = 'bold 20px sans-serif'; ctx.textAlign = 'right'; ctx.fillText(`${char.score} Puan`, width - 60, y); ctx.textAlign = 'left'; y += 50; } } ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif'; ctx.fillText('Seirei Anime Arena • ⚔️ En İyiler', 30, 685); const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE }); canvasPool.release(canvas); return buf; }); }); // ── OCR / MediaGuard ───────────────────────── app.post('/check', async (req, res) => { const { image_url, message_content } = req.body; if (!image_url) { return res.status(400).json({ is_scam: false, error: "image_url is required", status: "failed" }); } // ── KATMAN 1: Caption keyword (0ms) if (message_content) { const captionHit = fastKeywordCheck(message_content); if (captionHit) { console.log(`[K1-Caption] Hit: ${captionHit.keywords.join(', ')}`); backgroundAddPHash(image_url, true, captionHit.reason, captionHit.keywords); return res.json({ is_scam: true, detected_text: "", found_keywords: captionHit.keywords, threat_reason: captionHit.reason, source: "caption_keyword", status: "success" }); } } // ── KATMAN 2: URL keyword (0ms) const urlHit = fastKeywordCheck(decodeURIComponent(image_url)); if (urlHit) { console.log(`[K2-URL] Hit: ${urlHit.keywords.join(', ')}`); backgroundAddPHash(image_url, true, urlHit.reason, urlHit.keywords); return res.json({ is_scam: true, detected_text: "", found_keywords: urlHit.keywords, threat_reason: urlHit.reason, source: "url_keyword", status: "success" }); } // ── KATMAN 2b: URL-Level Cache check (0ms) const cachedOcrByUrl = ocrUrlCache.get(image_url); if (cachedOcrByUrl) { console.log(`[K2b-URLCache] Hit for ${image_url}`); return res.json({ ...cachedOcrByUrl, source: "ocr_url_cache" }); } // Deduplicate in-flight requests for the exact same image URL if (inflightOCR.has(image_url)) { console.log(`[DEDUP] Joining existing OCR scan for URL: ${image_url}`); return inflightOCR.get(image_url) .then(result => res.json({ ...result, source: "ocr_dedup" })) .catch(err => res.status(500).json({ error: err.message })); } // Create the task promise const scanPromise = (async () => { // ── GÖRSELİ BİR KEZ İNDİR let imageBuffer = null; try { imageBuffer = await fetchImageBuffer(image_url); } catch (err) { console.warn('[Fetch] Failed to download:', err.message); if (err.isDownloadError || err.name === 'AbortError') { throw new DownloadError(err.name === 'AbortError' ? 'İndirme zaman aşımına uğradı.' : err.message); } } if (!imageBuffer) { throw new DownloadError("Görsel indirilemedi."); } // Compute MD5 for exact duplicate file checking (even with different URL) const imageMd5 = crypto.createHash('md5').update(imageBuffer).digest('hex'); // ── KATMAN 2c: Hash-Level Cache check (0ms) const cachedOcrByHash = ocrHashCache.get(imageMd5); if (cachedOcrByHash) { console.log(`[K2c-HashCache] Hit for MD5: ${imageMd5}`); // Save to URL Cache too ocrUrlCache.set(image_url, cachedOcrByHash); return cachedOcrByHash; } // ── KATMAN 3+5 PARALEL: pHash + OCR Preprocess aynı anda (~50ms tasarruf) let pHash = null; let processedBuffer = null; try { // pHash ve OCR preprocessing'i paralel başlat const [pHashResult, preprocessResult] = await Promise.allSettled([ computePHashFromBuffer(imageBuffer), preprocessImageForOCR(imageBuffer) ]); pHash = pHashResult.status === 'fulfilled' ? pHashResult.value : null; processedBuffer = preprocessResult.status === 'fulfilled' ? preprocessResult.value : imageBuffer; // pHash cache kontrolü if (pHash) { const similar = findSimilarInCache(pHash, 10); if (similar) { console.log(`[K3-pHash] Cache hit, distance: ${similar.distance}, isScam: ${similar.isScam}`); const result = { is_scam: similar.isScam, detected_text: "", found_keywords: similar.keywords || [], threat_reason: similar.isScam ? `Bilinen scam görseline benziyor (${similar.distance} bit fark)` : null, status: "success" }; ocrUrlCache.set(image_url, result); ocrHashCache.set(imageMd5, result); return result; } } } catch (err) { console.warn('[K3-Parallel] Skipped:', err.message); processedBuffer = processedBuffer || imageBuffer; } // ── KATMAN 4: Forward (if OCR workers not ready) if (!ocrReady) { const tempRes = { json: (data) => data, status: () => ({ json: (data) => data }) }; const forwarded = await attemptForward({ body: req.body, headers: req.headers, query: req.query }, tempRes, '/check'); if (forwarded) return forwarded; } // ── KATMAN 5: Warm OCR (~200-500ms with 300px preprocessing) try { console.log(`[K5-OCR] Scanning (preprocessed)...`); const result = await runOCR(processedBuffer); const text = result.data?.text || ""; const scamCheck = checkTextForScam(text); const isScam = !!scamCheck; const responseData = { is_scam: isScam, detected_text: text, found_keywords: scamCheck?.keywords || [], threat_reason: scamCheck?.reason || null, status: "success" }; // Cache in all caches (URL, Hash, pHash) ocrUrlCache.set(image_url, responseData); ocrHashCache.set(imageMd5, responseData); if (pHash) { pHashCache.set(pHash, { isScam, reason: scamCheck?.reason || null, keywords: scamCheck?.keywords || [] }); } console.log(`[K5-OCR] Complete - isScam: ${isScam}, reason: ${scamCheck?.reason || 'none'}`); return responseData; } catch (err) { console.error('[K5-OCR] Error:', err.message); // Last fallback to forward const tempRes = { json: (data) => data, status: () => ({ json: (data) => data }) }; const forwarded = await attemptForward({ body: req.body, headers: req.headers, query: req.query }, tempRes, '/check'); if (forwarded) return forwarded; throw err; } })(); // Store the promise in inflight map to deduplicate inflightOCR.set(image_url, scanPromise); try { const result = await scanPromise; inflightOCR.delete(image_url); return res.json({ ...result, source: "ocr" }); } catch (err) { inflightOCR.delete(image_url); if (err.isDownloadError) { return res.status(200).json({ is_scam: false, error: "Görsel indirilemedi.", details: err.message, status: "failed", download_failed: true }); } return res.status(500).json({ is_scam: false, error: "Görsel işlenemedi.", details: err.toString(), status: "failed" }); } }); // ───────────────────────────────────────────── // START // ───────────────────────────────────────────── const port = process.env.PORT || 7860; // Pre-warm everything before accepting traffic prewarmFonts(); // Pre-allocate canvas pools for common sizes [{ w: 800, h: 350 }, { w: 900, h: 650 }, { w: 900, h: 700 }].forEach(({ w, h }) => { for (let i = 0; i < 3; i++) { const c = createCanvas(w, h); canvasPool.release(c); } }); console.log('[Canvas] Pool pre-allocated for 3 sizes (3 each) ✓'); initOCR().then(() => { app.listen(port, () => console.log(`[Server] Listening on port ${port} - TURBO MODE ✓`)); }).catch(err => { console.error('[Startup] OCR init failed, starting anyway:', err.message); app.listen(port, () => console.log(`[Server] Listening on port ${port} (OCR degraded)`)); });