File size: 13,230 Bytes
8b75dd4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | // scraper.js β Anichin.cafe Gacor Scraper
// Logika: Scrape β Parse β Deduplicate β Upsert ke Firebase
require("dotenv").config();
const axios = require("axios");
const cheerio = require("cheerio");
const { getDB } = require("./firebase");
const BASE_URL = process.env.BASE_URL || "https://anichin.cafe";
const DELAY_MS = parseInt(process.env.SCRAPE_DELAY_MS || "1500");
const MAX_CONCURRENT = parseInt(process.env.MAX_CONCURRENT || "3");
// βββ UTILITY βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
const randomDelay = () =>
sleep(DELAY_MS + Math.floor(Math.random() * 1000));
const USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
];
function getRandomUA() {
return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
}
async function fetchPage(url, retries = 3) {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const res = await axios.get(url, {
headers: {
"User-Agent": getRandomUA(),
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7",
Referer: BASE_URL,
Connection: "keep-alive",
},
timeout: 15000,
});
return res.data;
} catch (err) {
const isLast = attempt === retries;
console.warn(`β οΈ Attempt ${attempt}/${retries} failed for ${url}: ${err.message}`);
if (!isLast) await sleep(2000 * attempt); // exponential backoff
else throw err;
}
}
}
// βββ PARSERS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Parse halaman list/catalog anime
* Anichin biasanya pake struktur WordPress + plugin
*/
function parseAnimeList(html) {
const $ = cheerio.load(html);
const animes = [];
// Selector untuk card anime di halaman list
$(".bsx, .bs, article.bs").each((_, el) => {
const $el = $(el);
const title =
$el.find(".tt, h2, .title, a[title]").first().text().trim() ||
$el.find("a").attr("title") ||
"";
const url =
$el.find("a").first().attr("href") || "";
const thumbnail =
$el.find("img").attr("src") ||
$el.find("img").attr("data-src") ||
"";
const score =
parseFloat($el.find(".numscore, .score, .rating").text().trim()) || null;
const status =
$el.find(".statuss, .status").text().trim() || "";
const type =
$el.find(".typez, .type").text().trim() || "";
if (title && url) {
animes.push({
title,
url: url.startsWith("http") ? url : `${BASE_URL}${url}`,
thumbnail,
score,
status,
type,
});
}
});
// Pagination β cari next page URL
const nextPage =
$(".next.page-numbers, a.next, .navigation .next a").attr("href") || null;
return { animes, nextPage };
}
/**
* Parse halaman detail anime
*/
function parseAnimeDetail(html, animeUrl) {
const $ = cheerio.load(html);
const title =
$(".entry-title, h1.title, .animDetail h1").first().text().trim();
const synopsis =
$(".entry-content p, .synops, .desc").first().text().trim();
const thumbnail =
$(".thumbook img, .thumb img, .poster img").attr("src") ||
$(".thumb img").attr("data-src") ||
"";
// Info box (Genre, Studio, Status, dll)
const info = {};
$(".infox .spe span, .infoanime span, .spe span").each((_, el) => {
const text = $(el).text();
const [key, ...val] = text.split(":");
if (key && val.length) {
info[key.trim().toLowerCase()] = val.join(":").trim();
}
});
// Genres
const genres = [];
$(".genxed a, .genres a, .genre a").each((_, el) => {
const g = $(el).text().trim();
if (g) genres.push(g);
});
// Episodes list
const episodes = [];
$("#episode_by_py li, .eplister ul li, .eps li").each((_, el) => {
const $ep = $(el);
const epTitle = $ep.find(".epl-title, .eptitle").text().trim();
const epUrl = $ep.find("a").attr("href") || "";
const epNum =
parseFloat($ep.find(".epl-num").text().trim()) ||
parseFloat(epTitle.replace(/\D/g, "")) ||
null;
const epDate = $ep.find(".epl-date").text().trim() || "";
if (epUrl) {
episodes.push({
number: epNum,
title: epTitle,
url: epUrl.startsWith("http") ? epUrl : `${BASE_URL}${epUrl}`,
date: epDate,
});
}
});
// Sort episodes ascending
episodes.sort((a, b) => (a.number || 0) - (b.number || 0));
return {
title,
url: animeUrl,
synopsis,
thumbnail,
genres,
totalEpisodes: episodes.length,
episodes,
...info,
scrapedAt: new Date().toISOString(),
};
}
/**
* Parse halaman episode (ambil streaming links)
*/
function parseEpisodePage(html) {
const $ = cheerio.load(html);
const streamingLinks = [];
// Tombol server/mirror
$(".mirror .btn, .serverselect a, .mirrorselect a, .soraddl a").each((_, el) => {
const $el = $(el);
const label = $el.text().trim();
const href = $el.attr("href") || $el.attr("data-src") || "";
if (href) streamingLinks.push({ label, url: href });
});
// iFrame embed links
$("iframe[src], .entry-content iframe").each((_, el) => {
const src = $(el).attr("src") || "";
if (src) streamingLinks.push({ label: "embed", url: src });
});
return { streamingLinks };
}
// βββ SCRAPING JOBS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Scrape semua anime dari halaman list dengan pagination
*/
async function scrapeAnimeList(startUrl = `${BASE_URL}/anime/`, maxPages = 10) {
console.log(`\nπ Mulai scrape list anime β max ${maxPages} halaman`);
const db = getDB();
const allAnimes = [];
let currentUrl = startUrl;
let page = 1;
while (currentUrl && page <= maxPages) {
console.log(`π Halaman ${page}: ${currentUrl}`);
try {
const html = await fetchPage(currentUrl);
const { animes, nextPage } = parseAnimeList(html);
console.log(` β Dapet ${animes.length} anime`);
allAnimes.push(...animes);
// Batch upsert ke Firebase
if (animes.length > 0) {
await batchUpsertAnimes(db, animes);
}
currentUrl = nextPage;
page++;
if (currentUrl) await randomDelay();
} catch (err) {
console.error(`β Gagal scrape halaman ${page}: ${err.message}`);
break;
}
}
console.log(`\nβ
List selesai β total ${allAnimes.length} anime discrape`);
return allAnimes;
}
/**
* Scrape detail + episode tiap anime
*/
async function scrapeAnimeDetails(animes) {
console.log(`\nπ Scrape detail untuk ${animes.length} anime...`);
const db = getDB();
// Process dengan concurrency limit
const results = [];
const queue = [...animes];
let active = 0;
let done = 0;
async function processNext() {
if (queue.length === 0) return;
const anime = queue.shift();
active++;
try {
console.log(` [${done + 1}/${animes.length}] ${anime.title}`);
const html = await fetchPage(anime.url);
const detail = parseAnimeDetail(html, anime.url);
// Merge dengan data dari list
const merged = { ...anime, ...detail };
await upsertAnimeDetail(db, merged);
results.push(merged);
} catch (err) {
console.error(` β ${anime.title}: ${err.message}`);
}
done++;
active--;
await randomDelay();
await processNext();
}
// Jalankan N concurrent workers
const workers = Array.from({ length: MAX_CONCURRENT }, () => processNext());
await Promise.all(workers);
console.log(`\nβ
Detail selesai β ${results.length}/${animes.length} berhasil`);
return results;
}
/**
* Scrape episode baru saja (incremental update)
* Cek Firebase β bandingkan episode count β scrape yang kurang
*/
async function scrapeIncrementalUpdates() {
console.log("\nπ Incremental update β cek episode baru...");
const db = getDB();
// Ambil anime yang statusnya "Ongoing" dari Firebase
const snapshot = await db
.collection("animes")
.where("status", "in", ["Ongoing", "ongoing", "Airing"])
.limit(50)
.get();
console.log(` Dapet ${snapshot.size} anime ongoing`);
const toUpdate = [];
snapshot.forEach((doc) => toUpdate.push({ id: doc.id, ...doc.data() }));
for (const anime of toUpdate) {
try {
const html = await fetchPage(anime.url);
const fresh = parseAnimeDetail(html, anime.url);
// Hanya update jika ada episode baru
if (fresh.totalEpisodes > (anime.totalEpisodes || 0)) {
console.log(
` π ${anime.title}: ${anime.totalEpisodes} β ${fresh.totalEpisodes} eps`
);
await upsertAnimeDetail(db, { ...anime, ...fresh });
}
await randomDelay();
} catch (err) {
console.error(` β ${anime.title}: ${err.message}`);
}
}
console.log("β
Incremental update selesai");
}
// βββ FIREBASE OPERATIONS ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Batch upsert anime dasar (title, url, thumbnail, dll)
* Pake slug dari URL sebagai document ID
*/
async function batchUpsertAnimes(db, animes) {
const BATCH_SIZE = 400; // Firestore max 500 per batch
for (let i = 0; i < animes.length; i += BATCH_SIZE) {
const batch = db.batch();
const chunk = animes.slice(i, i + BATCH_SIZE);
chunk.forEach((anime) => {
const slug = extractSlug(anime.url);
const ref = db.collection("animes").doc(slug);
batch.set(
ref,
{
...anime,
slug,
updatedAt: new Date().toISOString(),
},
{ merge: true }
);
});
await batch.commit();
console.log(` πΎ Saved batch ${i / BATCH_SIZE + 1}`);
}
}
/**
* Upsert detail anime lengkap beserta episodes sebagai subcollection
*/
async function upsertAnimeDetail(db, anime) {
const slug = extractSlug(anime.url);
const animeRef = db.collection("animes").doc(slug);
// Pisah episodes dari main doc (biar nggak oversize)
const { episodes, ...animeData } = anime;
// Update main anime document
await animeRef.set(
{
...animeData,
slug,
hasDetails: true,
updatedAt: new Date().toISOString(),
},
{ merge: true }
);
// Upsert episodes ke subcollection
if (episodes && episodes.length > 0) {
const BATCH_SIZE = 400;
for (let i = 0; i < episodes.length; i += BATCH_SIZE) {
const batch = db.batch();
episodes.slice(i, i + BATCH_SIZE).forEach((ep) => {
const epId = `ep-${String(ep.number || i).padStart(4, "0")}`;
const epRef = animeRef.collection("episodes").doc(epId);
batch.set(epRef, { ...ep, animeSlug: slug }, { merge: true });
});
await batch.commit();
}
}
}
/**
* Extract slug dari URL
* e.g. https://anichin.cafe/anime/one-piece/ β one-piece
*/
function extractSlug(url) {
try {
const parts = new URL(url).pathname
.split("/")
.filter(Boolean);
return parts[parts.length - 1] || url;
} catch {
return url.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
}
}
// βββ SEARCH βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function scrapeSearch(query) {
const searchUrl = `${BASE_URL}/?s=${encodeURIComponent(query)}`;
console.log(`π Search: "${query}"`);
const html = await fetchPage(searchUrl);
const { animes } = parseAnimeList(html);
return animes;
}
// βββ EXPORT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
module.exports = {
scrapeAnimeList,
scrapeAnimeDetails,
scrapeIncrementalUpdates,
scrapeSearch,
fetchPage,
parseAnimeList,
parseAnimeDetail,
parseEpisodePage,
extractSlug,
};
// Kalau dirun langsung: node scraper.js
if (require.main === module) {
(async () => {
try {
const animes = await scrapeAnimeList(`${BASE_URL}/anime/`, 5);
await scrapeAnimeDetails(animes.slice(0, 10)); // detail 10 anime pertama
} catch (err) {
console.error("Fatal:", err);
process.exit(1);
}
})();
}
|