/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { ImpersonatedClient } from "../ffi/curl-impersonate.ts"; import { Database } from "bun:sqlite"; import { join } from "node:path"; import { existsSync, mkdirSync } from "node:fs"; import { scrapeFutGgPlayer, FutPlayerSchema, type FutPlayer } from "@aphrody/fut"; import { loadCookieJar, type Cookie } from "../cookies/cookie-loader.ts"; export interface MassiveFutCrawlOptions { concurrency?: number; maxPages?: number; dbPath?: string; jsonPath?: string; onProgress?: (stats: { crawled: number; total: number; success: number; errors: number; lastPlayer?: string; }) => void; } export class MassiveFutCrawler { private client: ImpersonatedClient; private db: Database; private dbPath: string; private jsonPath: string; private concurrency: number; private maxPages: number; private onProgress?: (stats: any) => void; private running = false; private visitedHashes = new Set(); constructor(opts: MassiveFutCrawlOptions = {}) { this.concurrency = opts.concurrency || 6; this.maxPages = opts.maxPages || Infinity; this.onProgress = opts.onProgress; const dataDir = join(import.meta.dir, "../../packages/fut/src/data"); if (!existsSync(dataDir)) { mkdirSync(dataDir, { recursive: true }); } this.dbPath = opts.dbPath || join(dataDir, "fut_extracted_database.sqlite"); this.jsonPath = opts.jsonPath || join(dataDir, "fut_extracted_database.json"); this.client = new ImpersonatedClient({ profile: "chrome131" }); this.db = new Database(this.dbPath); this.initDatabase(); } private initDatabase(): void { this.db.exec(` PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; CREATE TABLE IF NOT EXISTS visited_urls ( url_hash INTEGER PRIMARY KEY, url TEXT NOT NULL, crawled_at TEXT NOT NULL, status TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS players ( id TEXT PRIMARY KEY, name TEXT NOT NULL, rating INTEGER NOT NULL, position TEXT NOT NULL, club TEXT, nation TEXT, league TEXT, playstyles TEXT NOT NULL, playstyles_plus TEXT, pac INTEGER, sho INTEGER, pas INTEGER, dri INTEGER, def INTEGER, phy INTEGER, div INTEGER, han INTEGER, kic INTEGER, ref INTEGER, spd INTEGER, pos INTEGER, skill_moves INTEGER, weak_foot INTEGER, workrate_attack TEXT, workrate_defense TEXT, url TEXT NOT NULL, overall_rating INTEGER, date_of_birth TEXT, height INTEGER, weight INTEGER, foot TEXT, age INTEGER, rarity TEXT, accelerate_type TEXT, gender TEXT, alternative_positions TEXT, acceleration INTEGER, sprint_speed INTEGER, agility INTEGER, balance INTEGER, reactions INTEGER, ball_control INTEGER, dribbling INTEGER, composure INTEGER, jumping INTEGER, stamina INTEGER, strength INTEGER, aggression INTEGER, interceptions INTEGER, heading_accuracy INTEGER, defensive_awareness INTEGER, standing_tackle INTEGER, sliding_tackle INTEGER, vision INTEGER, crossing INTEGER, fk_accuracy INTEGER, short_passing INTEGER, long_passing INTEGER, curve INTEGER, positioning INTEGER, finishing INTEGER, shot_power INTEGER, long_shots INTEGER, volleys INTEGER, penalties INTEGER, gk_diving INTEGER, gk_handling INTEGER, gk_kicking INTEGER, gk_reflexes INTEGER, gk_positioning INTEGER, gk_speed INTEGER ); CREATE TABLE IF NOT EXISTS prices ( url TEXT PRIMARY KEY, price TEXT NOT NULL, last_updated TEXT NOT NULL ); `); const visited = this.db.query("SELECT url_hash FROM visited_urls").all() as { url_hash: number | bigint; }[]; for (const row of visited) { this.visitedHashes.add(BigInt(row.url_hash)); } } /** * Fetch all FC 27 player URLs from the official FUT.GG sitemaps index */ public async discoverAllFc27Urls(): Promise { const allUrls: string[] = []; const sitemapCount = 22; for (let p = 1; p <= sitemapCount; p++) { const sitemapUrl = p === 1 ? "https://www.fut.gg/sitemap-player-detail-27.xml" : `https://www.fut.gg/sitemap-player-detail-27.xml?p=${p}`; try { const res = await this.client.fetch(sitemapUrl); if (!res.ok) continue; const xml = await res.text(); const matches = xml.match(/(.*?)<\/loc>/g); if (matches) { for (const m of matches) { const url = m.replace(/<\/?loc>/g, "").trim(); if (url && url.includes("/players/")) { allUrls.push(url); } } } } catch (err: any) { console.warn(`Failed to fetch sitemap ${sitemapUrl}: ${err.message}`); } } return allUrls; } private getPlayerIdFromUrl(url: string): string { const match = /\/players\/(\d+)/.exec(url); if (match && match[1]) { return match[1]; } return Bun.hash.wyhash(url).toString(); } public async crawlAllFc27(): Promise<{ totalDiscovered: number; crawled: number; success: number; errors: number; }> { this.running = true; // Load cookies to simulate active session let cookieHeader = ""; try { const cookies: Cookie[] = await loadCookieJar("futgg"); cookieHeader = cookies.map((c: Cookie) => `${c.name}=${c.value}`).join("; "); } catch {} console.log("Discovering FC 27 player sitemaps..."); const discoveredUrls = await this.discoverAllFc27Urls(); console.log(`Discovered ${discoveredUrls.length} total FC 27 player URLs.`); // Filter unvisited URLs const queue: string[] = []; for (const u of discoveredUrls) { const h = Bun.hash.wyhash(u); if (!this.visitedHashes.has(h)) { queue.push(u); } } console.log( `Queue size: ${queue.length} unvisited URLs (${discoveredUrls.length - queue.length} already crawled).`, ); let crawledCount = 0; let successCount = 0; let errorCount = 0; const insertVisited = this.db.prepare( "INSERT OR REPLACE INTO visited_urls (url_hash, url, crawled_at, status) VALUES ($hash, $url, $crawled_at, $status)", ); const insertPlayer = this.db.prepare( `INSERT OR REPLACE INTO players ( id, name, rating, position, club, nation, league, playstyles, playstyles_plus, pac, sho, pas, dri, def, phy, div, han, kic, ref, spd, pos, skill_moves, weak_foot, workrate_attack, workrate_defense, url, overall_rating, date_of_birth, height, weight, foot, age, rarity, accelerate_type, gender, alternative_positions, acceleration, sprint_speed, agility, balance, reactions, ball_control, dribbling, composure, jumping, stamina, strength, aggression, interceptions, heading_accuracy, defensive_awareness, standing_tackle, sliding_tackle, vision, crossing, fk_accuracy, short_passing, long_passing, curve, positioning, finishing, shot_power, long_shots, volleys, penalties, gk_diving, gk_handling, gk_kicking, gk_reflexes, gk_positioning, gk_speed ) VALUES ( $id, $name, $rating, $position, $club, $nation, $league, $playstyles, $playstyles_plus, $pac, $sho, $pas, $dri, $def, $phy, $div, $han, $kic, $ref, $spd, $pos, $skill_moves, $weak_foot, $workrate_attack, $workrate_defense, $url, $overall_rating, $date_of_birth, $height, $weight, $foot, $age, $rarity, $accelerate_type, $gender, $alternative_positions, $acceleration, $sprint_speed, $agility, $balance, $reactions, $ball_control, $dribbling, $composure, $jumping, $stamina, $strength, $aggression, $interceptions, $heading_accuracy, $defensive_awareness, $standing_tackle, $sliding_tackle, $vision, $crossing, $fk_accuracy, $short_passing, $long_passing, $curve, $positioning, $finishing, $shot_power, $long_shots, $volleys, $penalties, $gk_diving, $gk_handling, $gk_kicking, $gk_reflexes, $gk_positioning, $gk_speed )`, ); let currentIndex = 0; const totalToCrawl = Math.min(queue.length, this.maxPages); const worker = async () => { while (this.running && currentIndex < totalToCrawl) { const url = queue[currentIndex++]; if (!url) break; const urlHash = Bun.hash.wyhash(url); this.visitedHashes.add(urlHash); crawledCount++; try { const headers: Record = { 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.9", }; if (cookieHeader) headers.cookie = cookieHeader; const res = await this.client.fetch(url, { headers }); if (!res.ok) { throw new Error(`HTTP ${res.status}`); } const html = await res.text(); const player: FutPlayer = await scrapeFutGgPlayer(html, "static"); // Validate with schema const validated = FutPlayerSchema.parse(player); // Save to SQLite (insertPlayer as any).run({ $id: this.getPlayerIdFromUrl(url), $name: validated.name, $rating: validated.overallRating || validated.rating, $position: validated.position, $club: validated.club, $nation: validated.nation, $league: validated.league, $playstyles: JSON.stringify(validated.playstyles), $playstyles_plus: JSON.stringify(validated.playstylesPlus || []), $pac: validated.pac, $sho: validated.sho, $pas: validated.pas, $dri: validated.dri, $def: validated.def, $phy: validated.phy, $div: validated.div, $han: validated.han, $kic: validated.kic, $ref: validated.ref, $spd: validated.spd, $pos: validated.pos, $skill_moves: validated.skillMoves, $weak_foot: validated.weakFoot, $workrate_attack: validated.workrateAttack, $workrate_defense: validated.workrateDefense, $url: url, $overall_rating: validated.overallRating, $date_of_birth: validated.dateOfBirth, $height: validated.height, $weight: validated.weight, $foot: validated.foot, $age: validated.age, $rarity: validated.rarity, $accelerate_type: validated.accelerateType, $gender: validated.gender, $alternative_positions: JSON.stringify( validated.alternativePositions || [], ), $acceleration: validated.acceleration, $sprint_speed: validated.sprintSpeed, $agility: validated.agility, $balance: validated.balance, $reactions: validated.reactions, $ball_control: validated.ballControl, $dribbling: validated.dribbling, $composure: validated.composure, $jumping: validated.jumping, $stamina: validated.stamina, $strength: validated.strength, $aggression: validated.aggression, $interceptions: validated.interceptions, $heading_accuracy: validated.headingAccuracy, $defensive_awareness: validated.defensiveAwareness, $standing_tackle: validated.standingTackle, $sliding_tackle: validated.slidingTackle, $vision: validated.vision, $crossing: validated.crossing, $fk_accuracy: validated.fkAccuracy, $short_passing: validated.shortPassing, $long_passing: validated.longPassing, $curve: validated.curve, $positioning: validated.positioning, $finishing: validated.finishing, $shot_power: validated.shotPower, $long_shots: validated.longShots, $volleys: validated.volleys, $penalties: validated.penalties, $gk_diving: validated.gkDiving, $gk_handling: validated.gkHandling, $gk_kicking: validated.gkKicking, $gk_reflexes: validated.gkReflexes, $gk_positioning: validated.gkPositioning, $gk_speed: validated.gkSpeed, }); insertVisited.run({ $hash: urlHash, $url: url, $crawled_at: new Date().toISOString(), $status: "success", }); successCount++; if (this.onProgress) { this.onProgress({ crawled: crawledCount, total: totalToCrawl, success: successCount, errors: errorCount, lastPlayer: validated.name, }); } if (crawledCount % 100 === 0) { await this.syncJsonDatabase(); } } catch { errorCount++; insertVisited.run({ $hash: urlHash, $url: url, $crawled_at: new Date().toISOString(), $status: "error", }); } } }; // Launch worker pool const workers: Promise[] = []; for (let i = 0; i < this.concurrency; i++) { workers.push(worker()); } await Promise.all(workers); await this.syncJsonDatabase(); return { totalDiscovered: discoveredUrls.length, crawled: crawledCount, success: successCount, errors: errorCount, }; } public async syncJsonDatabase(): Promise { const players = this.db.query("SELECT * FROM players").all() as any[]; const prices = this.db.query("SELECT * FROM prices").all() as any[]; const payload = { extracted_at: new Date().toISOString(), total_players: players.length, players: players.map((p) => ({ ...p, playstyles: p.playstyles ? JSON.parse(p.playstyles) : [], playstylesPlus: p.playstyles_plus ? JSON.parse(p.playstyles_plus) : [], alternativePositions: p.alternative_positions ? JSON.parse(p.alternative_positions) : [], })), prices: prices, }; await Bun.write(this.jsonPath, JSON.stringify(payload, null, 2) + "\n"); } public close(): void { this.running = false; try { this.client.close(); } catch {} } }