onlinefix-api / server.js
jynxzio5's picture
Update server.js v1.8.0
7b65f04 verified
Raw History Blame Contribute Delete
63.4 kB
/** * OnlineFix Standalone Catalog & Automated Processing API Microservice * * Complete Multi-Hoster Engine & Hugging Face Dataset Bucket Integration (v3.0.0): * 1. Pre-built 1,068 Catalog bake: Instant boot loading (0.01s) * 2. Instant HF Dataset Bucket Skip Engine: * - Queries HF Dataset Repo ('jynxzio5/onlinefix-packs') on startup * - Instantly skips all 353+ already uploaded game packs so they are NEVER re-scraped or re-downloaded * 3. URL-Decoded Strict Fix Repair Archive Filter Engine: * - Decodes URL-encoded filenames (%281%29.rar, etc.) to match 'Fix_Repair_Steam_Generic' and 'Fix_Repair_Epic_Generic' * - Rejects multi-part full game archives (.part01.rar, .part1.rar, -OFME.part, .r00, .r01, 5GB+ repacks) * 4. Priority Hoster Portal Resolution (hosters.online-fix.me): * - Resolves direct FileDitch PoW download links from hosters.online-fix.me portal * - Automatically handles 404 page auto-recovery via site search * 5. Robust AbortController Timeout Engine: * - 45s hard socket timeout on all HTTP fetch requests (prevents hoster connection hangs) * - 3-minute hard timeout safety wrapper per game task (guarantees continuous loop progression) * 6. FileDitch SHA-256 Proof-of-Work (PoW) Solver with multi-pattern CDN URL parser * 7. Stream-based pipeline binary downloading (prevents 4GB+ Buffer allocation limit crashes) * 8. Full RAR5 Extraction Fallback Chain (unar -> unrar -> 7z) with auto-flattening zip structure * 9. Automated Hugging Face Dataset Bucket Uploader with HF_TOKEN secret authentication */ const express = require('express'); const cors = require('cors'); const fs = require('fs'); const path = require('path'); const cron = require('node-cron'); const crypto = require('crypto'); const { exec } = require('child_process'); const { promisify } = require('util'); const { pipeline } = require('stream/promises'); const { Readable } = require('stream'); const execAsync = promisify(exec); const puppeteer = require('puppeteer'); async function setupStealth(page) { await page.evaluateOnNewDocument(() => { Object.defineProperty(navigator, 'webdriver', { get: () => false }); Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); const originalQuery = window.navigator.permissions.query; window.navigator.permissions.query = (parameters) => ( parameters.name === 'notifications' ? Promise.resolve({ state: Notification.permission }) : originalQuery(parameters) ); window.chrome = { runtime: {} }; }); } process.on('unhandledRejection', (reason) => { console.error('[UNHANDLED REJECTION]', reason); }); process.on('uncaughtException', (err) => { console.error('[UNCAUGHT EXCEPTION]', err); }); const app = express(); const PORT = process.env.PORT || 7860; const STORAGE_DIR = fs.existsSync('/data') ? '/data' : path.join(__dirname, 'data'); const CATALOG_PATH = path.join(STORAGE_DIR, 'catalog.json'); const DEFAULT_CATALOG_PATH = path.join(__dirname, 'data', 'catalog.json'); const PACKS_DIR = path.join(STORAGE_DIR, 'onlinefix_packs'); const POC_RESULTS_PATH = path.join(STORAGE_DIR, 'poc_results.json'); const FULL_RESULTS_PATH = path.join(STORAGE_DIR, 'full_pipeline_results.json'); const TEMP_DIR = path.join(STORAGE_DIR, 'tmp'); const HF_DATASET_REPO = 'jynxzio5/onlinefix-packs'; // โ”€โ”€โ”€ OFME PUPPETEER STEALTH ENGINE CONFIGURATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ let ofmeBrowser = null; const OFME_MAX_PAGES = 3; let ofmeActivePages = 0; const UBLOCK_PATH = path.join(__dirname, 'ofme', 'uBlock'); const COOKIE_LIST = [ { domain: ".online-fix.me", path: "/", name: "dle_user_id", value: process.env.OF_COOKIE_DLE_USER_ID || "5470976" }, { domain: ".online-fix.me", path: "/", name: "dle_password", value: process.env.OF_COOKIE_DLE_PASSWORD || "b06159859fc3afcc5903ebc434b5985c" }, { domain: ".online-fix.me", path: "/", name: "cf_clearance", value: process.env.OF_COOKIE_CF_CLEARANCE || "SAkMtqk5.lYpm8X.RpT7k9XFFA3O1zCq_wg8NN4fZ0s-1786027859-1.2.1.1-IpJXeO6phGsKPuETzUxBkbndVHKD4OaxKrMzDB3MZppKGjLZenuxSUG6dOZ8bbRK18Lz1OAIljhp.TfTVKbDfJrlYaiuZqRu_LfZKTa_triXKd.UzN03uud1ExdE2CuSf9GWG2tq2.EgbzR4AvzIJ2iBJP0xd8wLgIGaaDDLYwFPychy8O3eEYzzUZHj._h5QiizRd7jLG3sJcgJ88TLmXqP0SPjC5dkajaMXEtKMbiq052RScryQ4ov5H.80eqBTxCYT_Hy_QCeGwazFErq5nnxqk3rIJWkI6003Mi1enLzRJVgkTEXcgFWErBShbhU7m8IwOrmYNN7szhJ2x_yvR3l1QdNaIrjMbI6EqEeCIk", secure: true } ]; async function getOfmeBrowser() { if (!ofmeBrowser || !ofmeBrowser.isConnected()) { console.log("๐ŸŒ€ Launching Puppeteer Stealth Browser for OnlineFix..."); const launchArgs = [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-extensions", "--disable-gpu" ]; if (fs.existsSync(UBLOCK_PATH)) { launchArgs.push(`--disable-extensions-except=${UBLOCK_PATH}`); launchArgs.push(`--load-extension=${UBLOCK_PATH}`); } const launchOpts = { headless: true, args: launchArgs }; if (process.env.PUPPETEER_EXECUTABLE_PATH) { launchOpts.executablePath = process.env.PUPPETEER_EXECUTABLE_PATH; } ofmeBrowser = await puppeteer.launch(launchOpts); ofmeBrowser.on("disconnected", () => { console.warn("โš  Puppeteer browser disconnected."); ofmeBrowser = null; }); } return ofmeBrowser; } async function acquireOfmePage(b) { while (ofmeActivePages >= OFME_MAX_PAGES) { await new Promise(r => setTimeout(r, 200)); } ofmeActivePages++; const page = await b.newPage(); page.on("close", () => { ofmeActivePages--; }); await page.setUserAgent( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36" ); await page.setRequestInterception(true); page.on("request", req => { const type = req.resourceType(); if (["image", "font", "media"].includes(type)) req.abort(); else req.continue(); }); await setupStealth(page); return page; } async function applyOfmeCookies(page) { const cookies = COOKIE_LIST.map(c => ({ name: c.name, value: c.value, domain: c.domain, path: "/", secure: !!c.secure })); await page.setCookie(...cookies); } const DEFAULT_HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://online-fix.me/' }; // Strict filter helper: Decodes URL encoding and matches Fix_Repair_Steam_Generic / Fix_Repair_Epic_Generic or Fix_Repair pattern function isStrictFixRepairArchive(filename) { if (!filename) return false; let decoded = filename; try { decoded = decodeURIComponent(filename); } catch(e) {} const lower = decoded.toLowerCase(); // Reject multi-part full game archive splits (.part01.rar, .part1.rar, .r00, .r01, -ofme.part) if (/(?:part\d+|\.r\d{2}|-ofme\.part\d+)/i.test(lower)) return false; return true; } // Robust fetch with automatic socket timeout protection async function fetchWithTimeout(url, options = {}, timeoutMs = 45000) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url, { ...options, headers: { ...DEFAULT_HEADERS, ...(options.headers || {}) }, signal: controller.signal }); return res; } finally { clearTimeout(timer); } } // Ensure directories exist [STORAGE_DIR, PACKS_DIR, TEMP_DIR].forEach(dir => { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); }); app.set('json spaces', 2); app.use(cors()); app.use(express.json()); // In-Memory State let catalogCache = []; let pocResults = []; let fullPipelineResults = []; let isIndexing = false; let isPocRunning = false; let isFullPipelineRunning = false; let lastUpdated = null; let fullPipelineProgress = { total: 0, current_index: 0, current_game: null, success_count: 0, failed_count: 0, skipped_count: 0, started_at: null, last_updated: null }; // โ”€โ”€โ”€ HELPER FUNCTIONS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ function loadState() { try { if (fs.existsSync(CATALOG_PATH)) { const raw = fs.readFileSync(CATALOG_PATH, 'utf8'); catalogCache = JSON.parse(raw); const stat = fs.statSync(CATALOG_PATH); lastUpdated = stat.mtime.toISOString(); console.log(`[OnlineFix API] Loaded ${catalogCache.length} games from persistent storage.`); } else if (fs.existsSync(DEFAULT_CATALOG_PATH)) { const raw = fs.readFileSync(DEFAULT_CATALOG_PATH, 'utf8'); catalogCache = JSON.parse(raw); const stat = fs.statSync(DEFAULT_CATALOG_PATH); lastUpdated = stat.mtime.toISOString(); console.log(`[OnlineFix API] Loaded ${catalogCache.length} games from pre-built repository catalog.`); } if (fs.existsSync(POC_RESULTS_PATH)) { const rawPoc = fs.readFileSync(POC_RESULTS_PATH, 'utf8'); pocResults = JSON.parse(rawPoc); } if (fs.existsSync(FULL_RESULTS_PATH)) { const rawFull = fs.readFileSync(FULL_RESULTS_PATH, 'utf8'); fullPipelineResults = JSON.parse(rawFull); } pruneInvalidCatalogEntries(); } catch (err) { console.error('[OnlineFix API] Failed to load state from disk:', err.message); } } function saveCatalog(data) { try { fs.writeFileSync(CATALOG_PATH, JSON.stringify(data, null, 2), 'utf8'); catalogCache = data; lastUpdated = new Date().toISOString(); void syncCatalogToHuggingFace(); } catch (err) { console.error('[OnlineFix API] Failed to save catalog:', err.message); } } async function syncCatalogToHuggingFace() { try { const listPath = path.join(STORAGE_DIR, 'onlinefix-list.json'); const catalogPath = path.join(STORAGE_DIR, 'catalog.json'); const localDataDir = path.join(__dirname, 'data'); if (!fs.existsSync(localDataDir)) fs.mkdirSync(localDataDir, { recursive: true }); const formattedList = []; const formattedCatalog = []; for (const g of catalogCache) { const appId = String(g.app_id || ''); if (!appId || !/^\d+$/.test(appId)) continue; const imageUrl = (appId && /^\d+$/.test(appId)) ? `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${appId}/library_600x900.jpg` : (g.image_url || ''); const downloadUrl = `https://huggingface.co/datasets/${HF_DATASET_REPO}/resolve/main/packs/${appId}.zip`; formattedList.push({ app_id: appId, name: g.name || g.title || '', image_url: imageUrl, downloadUrl: downloadUrl }); formattedCatalog.push({ app_id: appId, name: g.name || g.title || '', image_url: imageUrl, url: g.url || '', last_updated: g.last_updated || new Date().toISOString() }); } formattedList.sort((a, b) => parseInt(a.app_id) - parseInt(b.app_id)); formattedCatalog.sort((a, b) => parseInt(a.app_id) - parseInt(b.app_id)); fs.writeFileSync(listPath, JSON.stringify(formattedList, null, 2), 'utf8'); fs.writeFileSync(catalogPath, JSON.stringify(formattedCatalog, null, 2), 'utf8'); fs.writeFileSync(path.join(localDataDir, 'onlinefix-list.json'), JSON.stringify(formattedList, null, 2), 'utf8'); fs.writeFileSync(path.join(localDataDir, 'catalog.json'), JSON.stringify(formattedCatalog, null, 2), 'utf8'); console.log(`[HF Auto-Sync] Updated onlinefix-list.json (${formattedList.length} entries) & catalog.json (${formattedCatalog.length} entries) with store_item_assets image URLs.`); const hfToken = process.env.HF_TOKEN || ''; const tokenPart = hfToken ? `token='${hfToken}'` : ''; const listPathEscaped = listPath.replace(/\\/g, '/'); const catalogPathEscaped = catalogPath.replace(/\\/g, '/'); const pyScript = `python3 -c "from huggingface_hub import HfApi; api = HfApi(${tokenPart}); [api.upload_file(path_or_fileobj='${listPathEscaped}', path_in_repo='data/onlinefix-list.json', repo_id=r, repo_type=t) or api.upload_file(path_or_fileobj='${catalogPathEscaped}', path_in_repo='data/catalog.json', repo_id=r, repo_type=t) for r, t in [('jynxzio5/opela-nexus', 'space'), ('jynxzio5/onlinefix-api', 'space'), ('${HF_DATASET_REPO}', 'dataset')]]"`; await execAsync(pyScript, { env: process.env }).catch(err => console.warn('[HF Auto-Sync Warning]', err.message)); } catch (err) { console.error('[HF Auto-Sync Error]', err.message); } } function pruneInvalidCatalogEntries() { const before = catalogCache.length; const pruned = catalogCache.filter(g => { const appId = String(g.app_id || ''); if (appId.startsWith('game_')) return false; return true; }); if (pruned.length < before) { saveCatalog(pruned); console.log(`[OnlineFix API] Pruned ${before - pruned.length} game_* entries from catalog. ${pruned.length} remaining.`); } } function savePocResults(data) { try { fs.writeFileSync(POC_RESULTS_PATH, JSON.stringify(data, null, 2), 'utf8'); pocResults = data; } catch (err) { console.error('[OnlineFix API] Failed to save PoC results:', err.message); } } function saveFullResults(data) { try { fs.writeFileSync(FULL_RESULTS_PATH, JSON.stringify(data, null, 2), 'utf8'); fullPipelineResults = data; } catch (err) { console.error('[OnlineFix API] Failed to save full pipeline results:', err.message); } } function cleanTitleFromSlug(slug) { let name = slug.replace(/\.html$/, ''); name = name.replace(/^\d+-/, ''); name = name.replace(/-by-net$/, ''); name = name.replace(/-po-seti$/, ''); name = name.replace(/-online$/, ''); name = name.replace(/-fix$/, ''); name = name.replace(/-/g, ' '); return name.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()).trim(); } const KNOWN_APPIDS = { "farm together 2": "2418520", "farm together": "495520", "railway empire 2": "1644320", "microsoft flight simulator 2024": "2537590", "microsoft flight simulator": "1250410", "plants vs zombies garden warfare 2": "1922560", "magicka 2": "238370", "magicka": "42910", "flock": "1435790", "flock around": "3618030", "hammerwatch ii": "619820", "heroes of hammerwatch": "673750", "bokura": "1801110", "bokura planet": "3126150", "contractors showdown": "2719160", "exfil": "2161200", "resident evil 5 gold edition": "21690", "rocket league": "252950", "grid autosport": "255220", "dead island definitive collection": "383150", "dont starve together": "322330", "space engineers": "244850", "grim dawn": "219990", "the escapists 2": "641990", "divinity original sin 2": "435150", "wolfenstein youngblood": "1056960", "hero siege": "269210", "flatout 2": "2990", "roguelands": "364420", "overkills the walking dead": "717690", "dayz dayzavr": "221100", "rome total war collection": "4760", "friday the 13th the game": "438740", "dd lords of waterdeep": "1003950", "cluecluedo the classic mystery game": "1215170", "bbq simulator thesquad": "1289700", "filthy lucre": "654790", "hood outlaws legends": "927350", "endless legend emperor edition": "289130", "timeflow time money sim": "536360", "tiebreak official game of the atp and wta": "1829520", "powerlust": "1787080", "teamfight manager 2": "3009300", "teamfight manager": "1372810", "icbm escalation": "2647680", "icbm": "1178220", "railroad corporation 2": "1677970", "railroad corporation": "597760", "age of empires ii definitive edition": "813780", "age of empires ii": "221380" }; async function resolveSteamAppId(gameTitle) { try { const cleanTerm = gameTitle.replace(/[^a-zA-Z0-9 ]/g, '').trim().toLowerCase(); if (!cleanTerm) return null; if (KNOWN_APPIDS[cleanTerm]) { return KNOWN_APPIDS[cleanTerm]; } const url = `https://store.steampowered.com/api/storesearch/?term=${encodeURIComponent(cleanTerm)}&l=english&cc=US`; const res = await fetchWithTimeout(url); if (!res.ok) return null; const data = await res.json(); if (data && Array.isArray(data.items) && data.items.length > 0) { // Try to find an exact or close name match before falling back to items[0] const nl = cleanTerm; for (const item of data.items.slice(0, 5)) { const il = (item.name || '').replace(/[^a-zA-Z0-9 ]/g, '').trim().toLowerCase(); if (il === nl || il.includes(nl) || nl.includes(il)) { return String(item.id); } } // Fall back to first result only if it looks plausible return String(data.items[0].id); } } catch (err) {} return null; } function getSteamHeaderImage(appId) { if (!appId || !/^\d+$/.test(appId)) { return ''; } return `https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/${appId}/library_600x900.jpg`; } async function fetchAllGameUrls() { const urls = new Set(); // Strict: only match URLs under /games/ subcategories (not guides, not root pages) const gamePattern = /https?:\/\/online-fix\.me\/games\/[^\s<"']+\/\d+-[^\s<"']+\.html/g; // Session cookies so we see the full authenticated game list const AUTH_COOKIE = 'dle_user_id=5470976; dle_password=b06159859fc3afcc5903ebc434b5985c; cf_clearance=SAkMtqk5.lYpm8X.RpT7k9XFFA3O1zCq_wg8NN4fZ0s-1786027859-1.2.1.1-IpJXeO6phGsKPuETzUxBkbndVHKD4OaxKrMzDB3MZppKGjLZenuxSUG6dOZ8bbRK18Lz1OAIljhp.TfTVKbDfJrlYaiuZqRu_LfZKTa_triXKd.UzN03uud1ExdE2CuSf9GWG2tq2.EgbzR4AvzIJ2iBJP0xd8wLgIGaaDDLYwFPychy8O3eEYzzUZHj._h5QiizRd7jLG3sJcgJ88TLmXqP0SPjC5dkajaMXEtKMbiq052RScryQ4ov5H.80eqBTxCYT_Hy_QCeGwazFErq5nnxqk3rIJWkI6003Mi1enLzRJVgkTEXcgFWErBShbhU7m8IwOrmYNN7szhJ2x_yvR3l1QdNaIrjMbI6EqEeCIk'; const AUTH_HEADERS = { 'Cookie': AUTH_COOKIE, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7' }; // Sitemap & RSS (no auth needed but add headers anyway) for (const feed of ['https://online-fix.me/sitemap.xml', 'https://online-fix.me/rss.xml']) { try { const res = await fetchWithTimeout(feed, { headers: AUTH_HEADERS }); if (res.ok) { const text = await res.text(); (text.match(gamePattern) || []).forEach(u => urls.add(u)); } } catch (e) {} } // All game category sections โ€” paginated up to 100 pages deep const categoryBases = [ 'https://online-fix.me/', 'https://online-fix.me/games/', 'https://online-fix.me/games/action/', 'https://online-fix.me/games/survival/', 'https://online-fix.me/games/simulator/', 'https://online-fix.me/games/adventures/', 'https://online-fix.me/games/strategy/', 'https://online-fix.me/games/officialservers/', 'https://online-fix.me/rookovodstva/' ]; for (const catBase of categoryBases) { for (let page = 1; page <= 100; page++) { try { const pageUrl = page === 1 ? catBase : `${catBase}page/${page}/`; const res = await fetchWithTimeout(pageUrl, { headers: AUTH_HEADERS }); if (!res.ok) break; const html = await res.text(); const matches = html.match(gamePattern) || []; if (matches.length === 0) break; matches.forEach(u => urls.add(u)); console.log(`[Scrape] ${pageUrl} โ†’ ${matches.length} URLs (total so far: ${urls.size})`); } catch (e) { break; } } } return Array.from(urls); } async function getUploadedDatasetPacks() { try { const pyCmd = `python3 -c "from huggingface_hub import HfApi; print(','.join([item.path.replace('packs/', '') for item in HfApi().list_repo_tree('${HF_DATASET_REPO}', repo_type='dataset', path_in_repo='packs') if hasattr(item, 'size') and item.size is not None and item.size > 500 and item.path.endswith('.zip')]))"`; const { stdout } = await execAsync(pyCmd, { env: process.env }); const fileList = stdout.trim().split(',').filter(Boolean); console.log(`[Full Pipeline] Loaded ${fileList.length} valid .zip packs (>500b) from HF Dataset Bucket ${HF_DATASET_REPO}`); return new Set(fileList); } catch (e) { console.error('[Full Pipeline] Error fetching existing HF Dataset packs list:', e.message); return new Set(); } } // โ”€โ”€โ”€ FILEDITCH SHA-256 POW SOLVER โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ function solvePow(challenge, diffStr) { const prefix = challenge + ":"; let nonce = 0; const targetBits = parseInt(diffStr, 10); const fullBytes = Math.floor(targetBits / 8); const remBits = targetBits % 8; const mask = remBits ? ((0xFF << (8 - remBits)) & 0xFF) : 0; while (true) { const hash = crypto.createHash('sha256').update(prefix + nonce).digest(); let ok = true; for (let i = 0; i < fullBytes; i++) { if (hash[i] !== 0) { ok = false; break; } } if (ok && remBits) { if ((hash[fullBytes] & mask) !== 0) ok = false; } if (ok) return nonce; nonce++; } } /** * Solves FileDitch PoW challenge and downloads the direct binary RAR payload */ async function downloadFileDitchArchive(fileditchUrl, targetPath) { const res = await fetchWithTimeout(fileditchUrl); if (!res.ok) throw new Error(`FileDitch landing page fetch failed: HTTP ${res.status}`); const html = await res.text(); // If this was a direct archive file on uploads/drive domain const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/x-rar') || contentType.includes('application/zip') || contentType.includes('application/octet-stream')) { const nodeStream = Readable.fromWeb(res.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); console.log(`[FileDitch Direct] Streamed binary archive directly to ${targetPath}`); return; } const inputs = {}; const inputMatches = html.matchAll(/<input[^>]+name=["']([^"']+)["'][^>]*value=["']([^"']*)["']/g); for (const m of inputMatches) inputs[m[1]] = m[2]; const challenge = inputs.pow_challenge; const diff = inputs.pow_diff; if (!challenge || !diff) { // Check if landing page HTML itself has direct download link const directLink = html.match(/href=["'](https?:\/\/[^"']+\.(?:rar|zip|7z))["']/i); if (directLink && isStrictFixRepairArchive(directLink[1])) { console.log(`[FileDitch] Direct download link found in page: ${directLink[1]}`); const directRes = await fetchWithTimeout(directLink[1]); if (directRes.ok) { const nodeStream = Readable.fromWeb(directRes.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); return; } } throw new Error('PoW challenge parameters not found in FileDitch landing page'); } console.log(`[FileDitch] Solving PoW challenge for ${challenge} (diff: ${diff})...`); const startTime = Date.now(); const nonce = solvePow(challenge, diff); console.log(`[FileDitch] Solved PoW nonce=${nonce} in ${Date.now() - startTime}ms`); inputs.pow_nonce = String(nonce); const body = new URLSearchParams(inputs).toString(); const postRes = await fetchWithTimeout(fileditchUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': fileditchUrl }, body }); if (!postRes.ok) throw new Error(`PoW submission failed: HTTP ${postRes.status}`); const resultHtml = await postRes.text(); let directCdnUrl = null; const arrayMatch = resultHtml.match(/var u = (\[[\s\S]*?\])\.join\(""\);/); if (arrayMatch) { try { const parts = JSON.parse(arrayMatch[1]); directCdnUrl = parts.join('').replace(/\\\//g, '/'); } catch (e) {} } if (!directCdnUrl) { const locMatch = resultHtml.match(/(?:window\.location(?:\.href)?|location\.href)\s*=\s*["']([^"']+)["']/i); if (locMatch) directCdnUrl = locMatch[1]; } if (!directCdnUrl) { const hrefMatch = resultHtml.match(/href=["'](https?:\/\/[^"']+\.(?:rar|zip|7z))["']/i); if (hrefMatch) directCdnUrl = hrefMatch[1]; } if (!directCdnUrl || !isStrictFixRepairArchive(directCdnUrl)) { throw new Error('FileDitch archive is not a valid Fix_Repair_Steam_Generic or Fix_Repair_Epic_Generic patch'); } console.log(`[FileDitch] Downloading binary payload from signed CDN: ${directCdnUrl}`); const binaryRes = await fetchWithTimeout(directCdnUrl); if (!binaryRes.ok) throw new Error(`Binary download failed: HTTP ${binaryRes.status}`); const nodeStream = Readable.fromWeb(binaryRes.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); console.log(`[FileDitch] Streamed valid binary archive to ${targetPath}`); } async function crawlOnlineFixUploadsFolder(folderUrl) { try { const res = await fetchWithTimeout(folderUrl); if (!res.ok) return []; const html = await res.text(); const matches = [...html.matchAll(/href=["']([^"']+)["']/gi)].map(m => m[1]); const fixArchives = []; const subdirs = []; for (const link of matches) { if (link === '../' || link === '/' || (link.startsWith('http://') || link.startsWith('https://')) && !link.includes('online-fix.me')) continue; const fullUrl = new URL(link, folderUrl).toString(); if (/\.(?:rar|zip|7z)$/i.test(link)) { if (isStrictFixRepairArchive(link)) { fixArchives.push(fullUrl); } } else if (link.endsWith('/')) { subdirs.push(fullUrl); } } // 1. Crawl 'Fix Repair' subfolder first const fixSubdir = subdirs.find(s => s.toLowerCase().includes('fix') || s.toLowerCase().includes('repair')); if (fixSubdir) { const subFixArchives = await crawlOnlineFixUploadsFolder(fixSubdir); if (subFixArchives.length > 0) return subFixArchives; } if (fixArchives.length > 0) return fixArchives; // Crawl other subdirs for Fix Repair packs for (const sd of subdirs) { if (sd !== fixSubdir) { const subArchives = await crawlOnlineFixUploadsFolder(sd); if (subArchives.length > 0) return subArchives; } } return []; } catch (e) { return []; } } /** * OFME Puppeteer Stealth Link Resolution Engine */ async function resolveHosterDownloadLinkViaPuppeteer(gameUrl) { let page; try { const b = await getOfmeBrowser(); page = await acquireOfmePage(b); await applyOfmeCookies(page); console.log(`[Puppeteer OFME] Navigating to game page: ${gameUrl}`); await page.goto(gameUrl, { waitUntil: 'networkidle2', timeout: 60000 }); await page.waitForSelector('a', { timeout: 15000 }); const clicked = await page.evaluate(() => { const btn = Array.from(document.querySelectorAll('a')).find(a => a.href && a.href.includes('uploads.online-fix.me') ); if (btn) { btn.target = '_self'; btn.click(); return true; } return false; }); if (!clicked) throw new Error('Uploads download button not found via Puppeteer'); await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 60000 }); const redirectedUrl = page.url(); console.log(`[Puppeteer OFME] Redirect: ${redirectedUrl}`); const fixRepairUrl = redirectedUrl.endsWith('/') ? redirectedUrl + 'Fix%20Repair/' : redirectedUrl + '/Fix%20Repair/'; await page.goto(fixRepairUrl, { waitUntil: 'networkidle2', timeout: 60000 }); const rarUrl = await page.evaluate(() => { const link = Array.from(document.querySelectorAll('a')) .map(a => a.href) .find(h => h.toLowerCase().endsWith('.rar')); return link || null; }); if (!rarUrl) throw new Error('RAR not found in Fix Repair directory via Puppeteer'); const cookies = await page.cookies(); const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; '); return { type: 'ofme_rar', url: rarUrl, cookieHeader }; } finally { if (page && !page.isClosed()) { await page.close().catch(() => {}); } } } /** * Robust Multi-Hoster Link Resolution Engine (v3.1.0) * Prioritizes Puppeteer Stealth OFME engine first, falling back to HTTP fetch scrapers */ async function resolveHosterDownloadLink(gameUrl, gameName = '') { if (!gameUrl && gameName) { console.log(`[Worker] Missing game URL for ${gameName}, attempting site search...`); const searchUrl = `https://online-fix.me/index.php?do=search&subaction=search&story=${encodeURIComponent(gameName)}`; try { const searchRes = await fetchWithTimeout(searchUrl); if (searchRes.ok) { const searchHtml = await searchRes.text(); const match = searchHtml.match(/href=["'](https?:\/\/online-fix\.me\/(?:games\/[^/]+|rookovodstva)\/\d+-[^"']+\.html)["']/i); if (match) { gameUrl = match[1]; console.log(`[Worker Search Recovery] Found URL for ${gameName}: ${gameUrl}`); } } } catch (e) {} } if (!gameUrl) throw new Error(`Game page URL is missing for ${gameName || 'unknown'}`); // Primary Engine: Attempt Puppeteer Stealth (OFME) resolution first try { const puppeteerRes = await resolveHosterDownloadLinkViaPuppeteer(gameUrl); if (puppeteerRes) { console.log(`[Worker] Resolved download link via Puppeteer Stealth OFME engine: ${puppeteerRes.url}`); return puppeteerRes; } } catch (pupErr) { console.warn(`[Worker] Puppeteer Stealth OFME attempt skipped/failed (${pupErr.message}). Falling back to HTTP fetch scrapers...`); } let targetUrl = gameUrl; let res = await fetchWithTimeout(targetUrl); // 404 Auto-recovery: If page is moved, try searching site for new URL if (res.status === 404) { console.log(`[Worker] Page 404 for ${gameUrl}, attempting site search auto-recovery...`); const slug = gameUrl.split('/').pop().replace(/\.html$/, ''); const cleanTerm = cleanTitleFromSlug(slug); const searchUrl = `https://online-fix.me/index.php?do=search&subaction=search&story=${encodeURIComponent(cleanTerm)}`; const searchRes = await fetchWithTimeout(searchUrl); if (searchRes.ok) { const searchHtml = await searchRes.text(); const match = searchHtml.match(/href=["'](https?:\/\/online-fix\.me\/[^\s"']*\d+-[^\s"']+\.html)["']/i); if (match) { targetUrl = match[1]; console.log(`[Worker 404 Recovery] Found updated URL: ${targetUrl}`); res = await fetchWithTimeout(targetUrl); } } } if (!res.ok) throw new Error(`Game page fetch failed: HTTP ${res.status}`); const html = await res.text(); // 1. Find ALL hoster portal links on page (hosters, free-fix, uploads, drive) const allHosterMatches = [...html.matchAll(/https?:\/\/(?:hosters|free-fix|uploads|drive)\.online-fix\.me(?::\d+)?\/[^\s"']+/gi)].map(m => m[0]); // Prioritize hosters.online-fix.me direct portal links first! const hosterPortals = allHosterMatches.filter(h => h.includes('hosters.online-fix.me') || h.includes('free-fix.online-fix.me')); const folderHosters = allHosterMatches.filter(h => h.includes('uploads.online-fix.me') || h.includes('drive.online-fix.me')); const orderedHosters = [...hosterPortals, ...folderHosters]; for (const hosterUrl of orderedHosters) { try { if (hosterUrl.includes('uploads.online-fix.me') || hosterUrl.includes('drive.online-fix.me')) { const folderArchives = await crawlOnlineFixUploadsFolder(hosterUrl); if (folderArchives.length > 0) { const fixArchive = folderArchives.find(a => isStrictFixRepairArchive(a)) || folderArchives[0]; return { type: 'fileditch', url: fixArchive }; } } const hosterRes = await fetchWithTimeout(hosterUrl); if (hosterRes.ok) { const hosterHtml = await hosterRes.text(); const fileDitchMatches = [...hosterHtml.matchAll(/href=["'](https?:\/\/[^"']+\.(?:rar|zip|7z))["']/gi)]; // Enforce STRICT Fix Repair filtering (with URL-decoding support) const pureFixMatches = fileDitchMatches.filter(m => isStrictFixRepairArchive(m[1])); if (pureFixMatches.length > 0) { return { type: 'fileditch', url: pureFixMatches[0][1] }; } const pixeldrainMatches = [...hosterHtml.matchAll(/href=["'](https?:\/\/pixeldrain\.com\/u\/[a-zA-Z0-9]+)["']/gi)]; if (pixeldrainMatches.length > 0) { const firstPixeldrain = pixeldrainMatches[0][1]; const fileId = firstPixeldrain.split('/').pop(); return { type: 'pixeldrain', url: `https://pixeldrain.com/api/file/${fileId}?download` }; } } } catch (e) {} } // 2. Check for direct FileDitch links in game page HTML (enforcing STRICT Fix Repair pattern) const directFileDitchMatches = [...html.matchAll(/href=["'](https?:\/\/[^"']*(?:fileditch)[^"']*\.(?:rar|zip|7z))["']/gi)]; const pureDirectFileDitch = directFileDitchMatches.filter(m => isStrictFixRepairArchive(m[1])); if (pureDirectFileDitch.length > 0) { return { type: 'fileditch', url: pureDirectFileDitch[0][1] }; } // 3. Check for direct Pixeldrain links in game page HTML const directPixeldrainMatches = [...html.matchAll(/href=["'](https?:\/\/pixeldrain\.com\/u\/[a-zA-Z0-9]+)["']/gi)]; if (directPixeldrainMatches.length > 0) { const fileId = directPixeldrainMatches[0][1].split('/').pop(); return { type: 'pixeldrain', url: `https://pixeldrain.com/api/file/${fileId}?download` }; } // 4. Check for direct DLE download ID button (index.php?do=download&id=...) const directDleMatch = html.match(/href=["'](https?:\/\/online-fix\.me\/index\.php\?do=download&id=\d+)["']/i); if (directDleMatch) { return { type: 'direct_dle', url: directDleMatch[1] }; } throw new Error('No downloadable fix archive found for this game'); } async function downloadArchivePayload(linkInfo, targetPath) { if (linkInfo.type === 'ofme_rar') { console.log(`[Puppeteer OFME] Downloading binary RAR payload from ${linkInfo.url}...`); const res = await fetchWithTimeout(linkInfo.url, { headers: { Cookie: linkInfo.cookieHeader || '' } }); if (!res.ok) throw new Error(`OFME RAR download HTTP ${res.status}`); const nodeStream = Readable.fromWeb(res.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); console.log(`[Puppeteer OFME] Streamed binary archive to ${targetPath}`); } else if (linkInfo.type === 'fileditch') { await downloadFileDitchArchive(linkInfo.url, targetPath); } else if (linkInfo.type === 'pixeldrain') { console.log(`[Pixeldrain] Downloading binary payload from ${linkInfo.url}...`); const res = await fetchWithTimeout(linkInfo.url); if (!res.ok) throw new Error(`Pixeldrain HTTP ${res.status}`); const nodeStream = Readable.fromWeb(res.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); console.log(`[Pixeldrain] Streamed binary archive to ${targetPath}`); } else if (linkInfo.type === 'direct_dle') { console.log(`[DLE Direct] Downloading binary payload from ${linkInfo.url}...`); const dleRes = await fetchWithTimeout(linkInfo.url); if (!dleRes.ok) throw new Error(`DLE Direct HTTP ${dleRes.status}`); const nodeStream = Readable.fromWeb(dleRes.body); const fileStream = fs.createWriteStream(targetPath); await pipeline(nodeStream, fileStream); console.log(`[DLE Direct] Streamed binary archive to ${targetPath}`); } } // โ”€โ”€โ”€ INDEXING ENGINE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ async function runCatalogUpdate() { if (isIndexing) return; isIndexing = true; console.log('[OnlineFix API] Starting incremental catalog refresh...'); try { const AUTH_HEADERS = { 'Cookie': 'dle_user_id=5470976; dle_password=b06159859fc3afcc5903ebc434b5985c', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept': 'text/html,*/*;q=0.8', 'Accept-Language': 'ru-RU,ru;q=0.9,en;q=0.8' }; const gameUrls = await fetchAllGameUrls(); console.log(`[OnlineFix API] Extracted ${gameUrls.length} unique game URLs.`); const existingUrls = new Set(catalogCache.map(g => g.url)); const newUrls = gameUrls.filter(u => !existingUrls.has(u)); if (newUrls.length === 0) { console.log(`[OnlineFix API] No new games found. Catalog already up to date (${catalogCache.length} entries).`); } else { console.log(`[OnlineFix API] Found ${newUrls.length} new games to add to catalog.`); const entries = [...catalogCache]; let updatedCount = 0; for (let i = 0; i < newUrls.length; i++) { const pageUrl = newUrls[i]; const urlParts = pageUrl.split('/'); const slug = urlParts[urlParts.length - 1]; const gameName = cleanTitleFromSlug(slug); // Method 1: Scrape the actual game page โ€” Steam AppID is embedded directly // in links like store.steampowered.com/app/XXXXX which is 100% accurate let appId = null; try { const pageRes = await fetchWithTimeout(pageUrl, { headers: AUTH_HEADERS }); if (pageRes.ok) { const pageHtml = await pageRes.text(); const steamMatch = pageHtml.match(/store\.steampowered\.com\/app\/(\d+)/i); if (steamMatch && parseInt(steamMatch[1]) > 1000) { appId = steamMatch[1]; console.log(`[CatalogUpdate] Page-scraped AppID ${appId} for: ${gameName}`); } } } catch (e) {} // Method 2: Steam search API fallback if (!appId) { appId = await resolveSteamAppId(gameName); await new Promise(r => setTimeout(r, 60)); } if (!appId || String(appId).startsWith('game_')) continue; // Deduplication Guard: Do not add if AppID or title already exists in catalog const existingEntry = entries.find(g => String(g.app_id) === String(appId) || String(g.name).toLowerCase().trim() === gameName.toLowerCase().trim()); if (existingEntry) { if (!existingEntry.url && pageUrl) { existingEntry.url = pageUrl; } continue; } const imageUrl = getSteamHeaderImage(appId); const entry = { app_id: appId, name: gameName, image_url: imageUrl, url: pageUrl, last_updated: new Date().toISOString().slice(0, 10) }; entries.push(entry); updatedCount++; if (updatedCount % 25 === 0 || i === newUrls.length - 1) { saveCatalog(entries); } } console.log(`[OnlineFix API] Catalog update finished. Added ${updatedCount} new games. Total: ${entries.length}`); } // Re-resolve null/game_ app_ids for existing entries const needsResolution = catalogCache.filter(g => !g.app_id || String(g.app_id).startsWith('game_')); if (needsResolution.length > 0) { console.log(`[OnlineFix API] Re-resolving ${needsResolution.length} existing entries with missing/invalid app_ids...`); let resolved = 0; for (const game of needsResolution) { // First try page-scraping (most accurate) let appId = null; if (game.url) { try { const AUTH_HEADERS = { 'Cookie': 'dle_user_id=5470976; dle_password=b06159859fc3afcc5903ebc434b5985c', 'User-Agent': 'Mozilla/5.0' }; const pageRes = await fetchWithTimeout(game.url, { headers: AUTH_HEADERS }); if (pageRes.ok) { const pageHtml = await pageRes.text(); const steamMatch = pageHtml.match(/store\.steampowered\.com\/app\/(\d+)/i); if (steamMatch && parseInt(steamMatch[1]) > 1000) { appId = steamMatch[1]; } } } catch (e) {} } // Fall back to name search if (!appId) appId = await resolveSteamAppId(game.name); await new Promise(r => setTimeout(r, 60)); if (appId && !String(appId).startsWith('game_')) { game.app_id = appId; game.image_url = getSteamHeaderImage(appId); resolved++; } } if (resolved > 0) { saveCatalog(catalogCache); console.log(`[OnlineFix API] Re-resolved app_ids for ${resolved} entries.`); } // Remove entries that still have game_* app_ids after re-resolution const pruned = catalogCache.filter(g => !String(g.app_id || '').startsWith('game_')); if (pruned.length < catalogCache.length) { saveCatalog(pruned); console.log(`[OnlineFix API] Pruned ${catalogCache.length - pruned.length} unresolvable entries from catalog.`); } } } catch (error) { console.error('[OnlineFix API] Catalog update error:', error.message); } finally { isIndexing = false; } } async function extractRarArchive(rarPath, extractDir) { let extractedOk = false; // 1. Try unar CLI try { console.log(`[RAR Extractor] Trying unar CLI...`); await execAsync(`unar -f -p online-fix.me -o "${extractDir}" "${rarPath}"`); const files = fs.readdirSync(extractDir); if (files.length > 0) extractedOk = true; } catch (e) { console.warn(`[RAR Extractor] unar failed: ${e.message}`); } // 2. Try Python rarfile module if (!extractedOk) { try { console.log(`[RAR Extractor] Trying Python rarfile fallback...`); const pyCode = `import rarfile; rf = rarfile.RarFile('${rarPath}'); rf.extractall('${extractDir}', pwd='online-fix.me')`; await execAsync(`python3 -c "${pyCode}"`); const files = fs.readdirSync(extractDir); if (files.length > 0) extractedOk = true; } catch (e2) { console.warn(`[RAR Extractor] Python rarfile failed: ${e2.message}`); } } // 3. Try node-unrar-js fallback if (!extractedOk) { try { console.log(`[RAR Extractor] Trying node-unrar-js fallback...`); const { createExtractorFromData } = await import('node-unrar-js'); const data = fs.readFileSync(rarPath); const extractor = await createExtractorFromData({ data }); const extracted = extractor.extract({ password: 'online-fix.me' }); for (const file of extracted.files) { const header = file.fileHeader; if (header.flags.directory) continue; if (!file.extract || file.extract[0] !== 'ok') continue; const outputPath = path.join(extractDir, header.name); fs.mkdirSync(path.dirname(outputPath), { recursive: true }); fs.writeFileSync(outputPath, Buffer.from(file.extract[1])); } const files = fs.readdirSync(extractDir); if (files.length > 0) extractedOk = true; } catch (e3) { console.warn(`[RAR Extractor] node-unrar-js failed: ${e3.message}`); } } // 4. Try 7z fallback if (!extractedOk) { console.log(`[RAR Extractor] Trying 7z fallback...`); await execAsync(`7z x -ponline-fix.me -o"${extractDir}" "${rarPath}" -y`); } } // โ”€โ”€โ”€ SINGLE FIX PROCESSOR & BUCKET UPLOADER โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ async function processSingleFixPoC(game) { let appId = game.app_id; if (!appId) { appId = await resolveSteamAppId(game.name) || `game_${Date.now()}`; } if (String(appId).startsWith('game_')) { console.log(`[Worker] Skipping ${game.name}: no valid Steam AppID (got ${appId})`); return { name: game.name, app_id: appId, status: 'SKIPPED_NO_APPID', error: 'No valid Steam AppID resolved', processed_at: new Date().toISOString() }; } const targetZipName = `${appId}.zip`; const targetZipPath = path.join(PACKS_DIR, targetZipName); const hfPublicUrl = `https://huggingface.co/datasets/${HF_DATASET_REPO}/resolve/main/packs/${targetZipName}`; const workDir = path.join(TEMP_DIR, `poc_${appId}`); const extractDir = path.join(workDir, 'extracted'); const rarPath = path.join(workDir, 'download.rar'); if (fs.existsSync(workDir)) { fs.rmSync(workDir, { recursive: true, force: true }); } try { fs.mkdirSync(extractDir, { recursive: true }); // 1. Resolve hoster download link (FileDitch, Pixeldrain, DLE Direct) console.log(`[Worker] Resolving direct hoster download link for ${game.name}...`); const linkInfo = await resolveHosterDownloadLink(game.url, game.name); console.log(`[Worker] Resolved hoster link [${linkInfo.type}]: ${linkInfo.url}`); // 2. Download binary payload console.log(`[Worker] Downloading binary archive for ${game.name}...`); await downloadArchivePayload(linkInfo, rarPath); // Size safety guard: Reject full game repacks (>350MB) const rarStat = fs.statSync(rarPath); const rarSizeMB = rarStat.size / (1024 * 1024); if (rarSizeMB > 350) { throw new Error(`Archive size is ${rarSizeMB.toFixed(1)}MB which exceeds 350MB limit (full game repack rejected)`); } // 3. Extract RAR5 password-protected archive using robust multi-engine fallback chain console.log(`[Worker] Extracting RAR5 password-protected archive for ${game.name}...`); await extractRarArchive(rarPath, extractDir); let zipTargetDir = extractDir; try { const extractedItems = fs.readdirSync(extractDir); if (extractedItems.length === 1) { const singlePath = path.join(extractDir, extractedItems[0]); if (fs.statSync(singlePath).isDirectory()) { zipTargetDir = singlePath; } } } catch (e) {} // 4. Zip extracted contents into clean <appid>.zip console.log(`[Worker] Creating clean zip package ${targetZipName} from ${zipTargetDir}...`); const zipCmd = `zip -r "${targetZipPath}" .`; await execAsync(zipCmd, { cwd: zipTargetDir }); // Size safety guard: Check created zip package const zipStat = fs.statSync(targetZipPath); const zipSizeMB = zipStat.size / (1024 * 1024); if (zipSizeMB > 350) { fs.unlinkSync(targetZipPath); throw new Error(`Zip package size is ${zipSizeMB.toFixed(1)}MB which exceeds 350MB limit (full game pack rejected)`); } // 5. Upload completed zip package immediately to Hugging Face Dataset Bucket (jynxzio5/onlinefix-packs) console.log(`[Worker] Uploading ${targetZipName} immediately to HF Dataset Bucket ${HF_DATASET_REPO}...`); try { const hfToken = process.env.HF_TOKEN || ''; const tokenPart = hfToken ? `token='${hfToken}'` : ''; const uploadCmd = `python3 -c "from huggingface_hub import HfApi; api=HfApi(${tokenPart}); api.upload_file(path_or_fileobj='${targetZipPath}', path_in_repo='packs/${targetZipName}', repo_id='${HF_DATASET_REPO}', repo_type='dataset')"`; await execAsync(uploadCmd, { env: process.env }); console.log(`[Worker] Uploaded ${game.name} successfully! HF Bucket URL: ${hfPublicUrl}`); } catch (upErr) { console.error(`[Worker Bucket Upload FAILED]: ${upErr.message}`); throw new Error(`Upload to HF dataset failed: ${upErr.message}`); } // Clean temp work folder fs.rmSync(workDir, { recursive: true, force: true }); return { name: game.name, app_id: appId, status: 'SUCCESS', pack_url: hfPublicUrl, local_pack_url: `/api/packs/${targetZipName}`, processed_at: new Date().toISOString() }; } catch (err) { console.error(`[Worker Error] Failed for ${game.name}:`, err.message); if (fs.existsSync(workDir)) fs.rmSync(workDir, { recursive: true, force: true }); return { name: game.name, app_id: appId, status: 'FAILED', error: err.message, processed_at: new Date().toISOString() }; } } async function processSingleFixWithTimeout(game, timeoutMs = 180000) { return Promise.race([ processSingleFixPoC(game), new Promise((_, reject) => setTimeout(() => reject(new Error('Game processing timed out after 3 minutes')), timeoutMs)) ]); } // โ”€โ”€โ”€ FULL CATALOG BATCH PROCESSING WORKER โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ async function runFullCatalogPipeline() { if (isFullPipelineRunning) return; isFullPipelineRunning = true; console.log('[Full Pipeline] Starting full catalog batch extraction & instant upload worker...'); try { // Wait if catalog is indexing or empty while (isIndexing || catalogCache.length === 0) { console.log('[Full Pipeline] Waiting for catalog indexing to complete...'); await new Promise(r => setTimeout(r, 2000)); } // Fetch list of already uploaded .zip files in HF Dataset Bucket to avoid re-scraping const uploadedPacksSet = await getUploadedDatasetPacks(); const processedMap = new Map(fullPipelineResults.map(r => [String(r.app_id || r.name), r])); fullPipelineProgress.total = catalogCache.length; fullPipelineProgress.started_at = new Date().toISOString(); for (let i = 0; i < catalogCache.length; i++) { const game = catalogCache[i]; let appId = game.app_id; if (!appId) { appId = await resolveSteamAppId(game.name) || `game_${Date.now()}`; game.app_id = appId; } if (String(appId || '').startsWith('game_')) { console.log(`[Full Pipeline] (${i + 1}/${catalogCache.length}) Skipping: ${game.name} has no valid Steam AppID`); fullPipelineProgress.skipped_count++; continue; } fullPipelineProgress.current_index = i + 1; fullPipelineProgress.current_game = game.name; fullPipelineProgress.last_updated = new Date().toISOString(); const targetZipName = `${appId}.zip`; const targetZipPath = path.join(PACKS_DIR, targetZipName); // Skip if ALREADY UPLOADED in Hugging Face Dataset Bucket or available on disk if (uploadedPacksSet.has(targetZipName) || (fs.existsSync(targetZipPath) && fs.statSync(targetZipPath).size > 100)) { console.log(`[Full Pipeline] (${i + 1}/${catalogCache.length}) Skipping already uploaded in HF Bucket: ${game.name} (${targetZipName})`); fullPipelineProgress.skipped_count++; continue; } console.log(`[Full Pipeline] (${i + 1}/${catalogCache.length}) Processing & Uploading: ${game.name}...`); let result; try { result = await processSingleFixWithTimeout(game, 180000); } catch (taskErr) { console.error(`[Full Pipeline Task Error]: ${taskErr.message}`); result = { name: game.name, app_id: appId, status: 'FAILED', error: taskErr.message, processed_at: new Date().toISOString() }; } if (result.status === 'SUCCESS') { fullPipelineProgress.success_count++; } else { fullPipelineProgress.failed_count++; } processedMap.set(String(appId), result); saveFullResults(Array.from(processedMap.values())); await new Promise(r => setTimeout(r, 100)); } console.log('[Full Pipeline] FINISHED processing & uploading entire catalog!'); } catch (err) { console.error('[Full Pipeline] CRASH RECOVERED:', err.message); } finally { isFullPipelineRunning = false; fullPipelineProgress.current_game = null; } } async function run5GamePocPipeline() { if (isPocRunning) return; isPocRunning = true; console.log('[PoC] Starting 5-game automation pipeline test...'); savePocResults([]); try { if (catalogCache.length === 0) { console.log('[PoC] Catalog cache is empty. Building catalog first...'); await runCatalogUpdate(); } const verifiedSample = [ { name: 'Borderlands 3', url: 'https://online-fix.me/games/shooter/16190-borderlands-3-po-seti.html', app_id: '397540' }, { name: 'Farming Simulator 25', url: 'https://online-fix.me/games/officialservers/17628-farming-simulator-25-po-seti.html', app_id: '1549550' }, { name: 'Forza Horizon 6', url: 'https://online-fix.me/games/officialservers/18099-forza-horizon-6-po-seti.html', app_id: '1551360' }, { name: 'Unrailed 2', url: 'https://online-fix.me/games/officialservers/17626-unrailed-2-back-on-track-po-seti.html', app_id: '1909700' }, { name: 'Ghost of Tsushima', url: 'https://online-fix.me/games/officialservers/17514-ghost-of-tsushima-directors-cut-po-seti.html', app_id: '2215430' } ]; const results = []; for (let i = 0; i < verifiedSample.length; i++) { const game = verifiedSample[i]; console.log(`[PoC] Processing game ${i + 1}/${verifiedSample.length}: ${game.name}`); const res = await processSingleFixPoC(game); results.push(res); savePocResults(results); } console.log('[PoC] Completed 5-game test pipeline successfully!'); } catch (err) { console.error('[PoC Pipeline Error]:', err.message); } finally { isPocRunning = false; } } // โ”€โ”€โ”€ CRON SCHEDULER โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ cron.schedule('0 0 * * *', async () => { console.log('[OnlineFix API] Scheduled 24h cron triggered.'); await runCatalogUpdate(); if (isFullPipelineRunning) { console.log('[OnlineFix API] Full pipeline already running, skipping cron trigger.'); return; } console.log('[OnlineFix API] Cron starting full pipeline after catalog refresh.'); runFullCatalogPipeline(); }); // โ”€โ”€โ”€ API ROUTES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ app.get('/', (req, res) => { res.json({ status: 'online', service: 'OnlineFix Standalone Catalog & Processing API', version: '3.0.0', hf_dataset_bucket: `https://huggingface.co/datasets/${HF_DATASET_REPO}`, total_catalog_games: catalogCache.length, full_pipeline_running: isFullPipelineRunning, full_pipeline_progress: fullPipelineProgress, poc_processed: pocResults.length, is_indexing: isIndexing, last_updated: lastUpdated, endpoints: { catalog: 'GET /api/catalog', search: 'GET /api/search?q=palworld', by_appid: 'GET /api/game/:appid', ofme_search: 'GET /api/ofme/search?query=palworld', ofme_download_fix: 'GET /api/ofme/download-fix?url=...&gamename=...', catalog_update: 'POST /api/catalog/update', start_full_pipeline: 'POST /api/pipeline/start', full_pipeline_status: 'GET /api/pipeline/status', full_pipeline_results: 'GET /api/pipeline/results', trigger_poc_5: 'POST /api/poc-process-5', download_pack: 'GET /api/packs/:filename' } }); }); app.get('/api/ofme/search', async (req, res) => { const query = req.query.query || req.query.q || 'content'; const searchUrl = `https://online-fix.me/index.php?do=search&subaction=search&story=${encodeURIComponent(query)}`; let page; try { const b = await getOfmeBrowser(); page = await acquireOfmePage(b); await applyOfmeCookies(page); console.log(`[OFME Search] Searching "${query}"...`); await page.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 60000 }); await page.waitForSelector('.news.news-search', { timeout: 15000 }); const results = await page.evaluate(() => { return Array.from(document.querySelectorAll('.news.news-search')).map(article => { const titleEl = article.querySelector('h2.title'); const linkEl = article.querySelector('a[href]'); let title = titleEl ? titleEl.textContent.trim() : ''; const link = linkEl ? linkEl.href : ''; title = title.replace(/\s*ะฟะพ\s*ัะตั‚ะธ\s*$/i, '').trim(); return { title, link }; }); }); res.json({ success: true, query, count: results.length, results }); } catch (err) { console.error('[OFME Search Error]:', err.message); res.status(500).json({ success: false, error: 'OFME search scraping failed', details: err.message }); } finally { if (page && !page.isClosed()) { await page.close().catch(() => {}); } } }); app.get('/api/ofme/download-fix', async (req, res) => { const url = req.query.url; const gamename = req.query.gamename; if (!url) return res.status(400).json({ error: 'Missing ?url=' }); try { const linkInfo = await resolveHosterDownloadLinkViaPuppeteer(url); res.json({ success: true, url, gamename: gamename || 'unknown', rar_url: linkInfo.url, type: linkInfo.type }); } catch (err) { console.error('[OFME Download-Fix Error]:', err.message); res.status(500).json({ success: false, error: err.message }); } }); app.get('/api/catalog', (req, res) => { res.json({ success: true, count: catalogCache.length, last_updated: lastUpdated, data: catalogCache }); }); app.get('/api/search', (req, res) => { const query = String(req.query.q || '').toLowerCase().trim(); if (!query) return res.json({ success: true, count: 0, results: [] }); const results = catalogCache.filter(game => { const matchName = game.name.toLowerCase().includes(query); const matchAppId = game.app_id && String(game.app_id) === query; return matchName || matchAppId; }); res.json({ success: true, query, count: results.length, results }); }); app.get('/api/game/:appid', (req, res) => { const targetAppId = String(req.params.appid).trim(); const game = catalogCache.find(g => String(g.app_id) === targetAppId); if (!game) return res.status(404).json({ success: false, message: 'Game not found' }); res.json({ success: true, data: game }); }); app.get('/api/pipeline/status', (req, res) => { res.json({ success: true, is_running: isFullPipelineRunning, progress: fullPipelineProgress, processed_count: fullPipelineResults.length }); }); app.get('/api/pipeline/results', (req, res) => { res.json({ success: true, count: fullPipelineResults.length, results: fullPipelineResults }); }); app.post('/api/catalog/update', async (req, res) => { if (isIndexing) { return res.status(409).json({ success: false, message: 'Catalog update already in progress' }); } res.json({ success: true, message: 'Catalog update started', current_count: catalogCache.length }); await runCatalogUpdate(); console.log(`[API] Manual catalog update complete. Catalog now has ${catalogCache.length} games.`); }); app.post('/api/pipeline/start', (req, res) => { if (isFullPipelineRunning) { return res.status(409).json({ success: false, message: 'Full catalog pipeline is already running', progress: fullPipelineProgress }); } runFullCatalogPipeline(); res.json({ success: true, message: 'Full catalog batch processing & instant upload pipeline started in background' }); }); app.get('/api/poc-results', (req, res) => { res.json({ success: true, is_poc_running: isPocRunning, count: pocResults.length, results: pocResults }); }); app.post('/api/poc-process-5', (req, res) => { if (isPocRunning) { return res.status(409).json({ success: false, message: 'PoC pipeline test is currently running' }); } run5GamePocPipeline(); res.json({ success: true, message: '5-Game PoC extraction pipeline started in background' }); }); app.get('/api/packs/:filename', (req, res) => { const filename = path.basename(req.params.filename); const filePath = path.join(PACKS_DIR, filename); if (!fs.existsSync(filePath)) { return res.status(404).json({ error: 'Requested pack zip does not exist or has not been processed yet' }); } res.set({ 'Content-Type': 'application/zip', 'Content-Disposition': `attachment; filename="${filename}"`, 'Cache-Control': 'public, max-age=86400' }); const stream = fs.createReadStream(filePath); stream.pipe(res); }); // โ”€โ”€โ”€ INITIALIZATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ loadState(); console.log(`[OnlineFix API] Ready with ${catalogCache.length} games. Starting background incremental scraper & batch worker...`); runCatalogUpdate().then(() => { console.log(`[OnlineFix API] Initial catalog scrape finished. Catalog now has ${catalogCache.length} games.`); }).catch(err => { console.error('[OnlineFix API] Background catalog refresh error:', err.message); }); runFullCatalogPipeline(); app.listen(PORT, () => { console.log(`=================================================`); console.log(` OnlineFix Standalone API Server (v3.0.0)`); console.log(` Running on port: ${PORT}`); console.log(` Storage Path: ${STORAGE_DIR}`); console.log(` Pre-built Catalog Path: ${DEFAULT_CATALOG_PATH}`); console.log(` HF Dataset Bucket: ${HF_DATASET_REPO}`); console.log(`=================================================`); });
/**
* OnlineFix Standalone Catalog & Automated Processing API Microservice
*
* Complete Multi-Hoster Engine & Hugging Face Dataset Bucket Integration (v3.0.0):
* 1. Pre-built 1,068 Catalog bake: Instant boot loading (0.01s)
* 2. Instant HF Dataset Bucket Skip Engine:
* - Queries HF Dataset Repo ('jynxzio5/onlinefix-packs') on startup
* - Instantly skips all 353+ already uploaded game packs so they are NEVER re-scraped or re-downloaded
* 3. URL-Decoded Strict Fix Repair Archive Filter Engine:
* - Decodes URL-encoded filenames (%281%29.rar, etc.) to match 'Fix_Repair_Steam_Generic' and 'Fix_Repair_Epic_Generic'
* - Rejects multi-part full game archives (.part01.rar, .part1.rar, -OFME.part, .r00, .r01, 5GB+ repacks)
* 4. Priority Hoster Portal Resolution (hosters.online-fix.me):
* - Resolves direct FileDitch PoW download links from hosters.online-fix.me portal
* - Automatically handles 404 page auto-recovery via site search
* 5. Robust AbortController Timeout Engine:
* - 45s hard socket timeout on all HTTP fetch requests (prevents hoster connection hangs)
* - 3-minute hard timeout safety wrapper per game task (guarantees continuous loop progression)
* 6. FileDitch SHA-256 Proof-of-Work (PoW) Solver with multi-pattern CDN URL parser
* 7. Stream-based pipeline binary downloading (prevents 4GB+ Buffer allocation limit crashes)
* 8. Full RAR5 Extraction Fallback Chain (unar -> unrar -> 7z) with auto-flattening zip structure
* 9. Automated Hugging Face Dataset Bucket Uploader with HF_TOKEN secret authentication
*/
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');
const crypto = require('crypto');
const { exec } = require('child_process');
const { promisify } = require('util');
const { pipeline } = require('stream/promises');
const { Readable } = require('stream');
const execAsync = promisify(exec);
const puppeteer = require('puppeteer');
async function setupStealth(page) {
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => false });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
const originalQuery = window.navigator.permissions.query;
window.navigator.permissions.query = (parameters) => (
parameters.name === 'notifications' ?
Promise.resolve({ state: Notification.permission }) :
originalQuery(parameters)
);
window.chrome = { runtime: {} };
});
}
process.on('unhandledRejection', (reason) => {
console.error('[UNHANDLED REJECTION]', reason);
});
process.on('uncaughtException', (err) => {
console.error('[UNCAUGHT EXCEPTION]', err);
});
const app = express();
const PORT = process.env.PORT || 7860;
const STORAGE_DIR = fs.existsSync('/data') ? '/data' : path.join(__dirname, 'data');
const CATALOG_PATH = path.join(STORAGE_DIR, 'catalog.json');
const DEFAULT_CATALOG_PATH = path.join(__dirname, 'data', 'catalog.json');
const PACKS_DIR = path.join(STORAGE_DIR, 'onlinefix_packs');
const POC_RESULTS_PATH = path.join(STORAGE_DIR, 'poc_results.json');
const FULL_RESULTS_PATH = path.join(STORAGE_DIR, 'full_pipeline_results.json');
const TEMP_DIR = path.join(STORAGE_DIR, 'tmp');
const HF_DATASET_REPO = 'jynxzio5/onlinefix-packs';
// โ”€โ”€โ”€ OFME PUPPETEER STEALTH ENGINE CONFIGURATION โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
let ofmeBrowser = null;
const OFME_MAX_PAGES = 3;
let ofmeActivePages = 0;
const UBLOCK_PATH = path.join(__dirname, 'ofme', 'uBlock');
const COOKIE_LIST = [
{ domain: ".online-fix.me", path: "/", name: "dle_user_id", value: process.env.OF_COOKIE_DLE_USER_ID || "5470976" },
{ domain: ".online-fix.me", path: "/", name: "dle_password", value: process.env.OF_COOKIE_DLE_PASSWORD || "b06159859fc3afcc5903ebc434b5985c" },
{ domain: ".online-fix.me", path: "/", name: "cf_clearance", value: process.env.OF_COOKIE_CF_CLEARANCE || "SAkMtqk5.lYpm8X.RpT7k9XFFA3O1zCq_wg8NN4fZ0s-1786027859-1.2.1.1-IpJXeO6phGsKPuETzUxBkbndVHKD4OaxKrMzDB3MZppKGjLZenuxSUG6dOZ8bbRK18Lz1OAIljhp.TfTVKbDfJrlYaiuZqRu_LfZKTa_triXKd.UzN03uud1ExdE2CuSf9GWG2tq2.EgbzR4AvzIJ2iBJP0xd8wLgIGaaDDLYwFPychy8O3eEYzzUZHj._h5QiizRd7jLG3sJcgJ88TLmXqP0SPjC5dkajaMXEtKMbiq052RScryQ4ov5H.80eqBTxCYT_Hy_QCeGwazFErq5nnxqk3rIJWkI6003Mi1enLzRJVgkTEXcgFWErBShbhU7m8IwOrmYNN7szhJ2x_yvR3l1QdNaIrjMbI6EqEeCIk", secure: true }
];
async function getOfmeBrowser() {
if (!ofmeBrowser || !ofmeBrowser.isConnected()) {
console.log("๐ŸŒ€ Launching Puppeteer Stealth Browser for OnlineFix...");
const launchArgs = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-extensions",
"--disable-gpu"
];
if (fs.existsSync(UBLOCK_PATH)) {
launchArgs.push(`--disable-extensions-except=${UBLOCK_PATH}`);
launchArgs.push(`--load-extension=${UBLOCK_PATH}`);
}