Files
AniKotoAPI/src/extractors/random.extractor.js
T
Shinei Nouzen 7df5bbcc54 docs: Add box-style headers, section headers, feature markers, JSDoc, inline notes, footers
Added comprehensive documentation following project conventions:

Box-style headers (added/fixed where missing):
- All 17 files now have standard Project/Author/License headers

Section headers (// == == SECTION == ==):
- cache.helper.js: LRU CACHE CLASS, TTL CONFIGURATION, SINGLETON, EXPORTED HELPERS
- download.controller.js: DOWNLOAD LINKS HANDLER
- download.extractor.js: BASE64 DECODER, REDIRECT FOLLOWER, DOWNLOAD LINKS EXTRACTOR
- seasons.extractor.js: SEASONS EXTRACTOR
- watchOrder.extractor.js: WATCH ORDER EXTRACTOR
- extractPages.helper.js: PAGE EXTRACTOR
- pagination.helper.js: PAGINATION METADATA

Feature markers (// --- FEATURE: XYZ ---):
- cache.helper.js: LRU Cache, Per-Endpoint TTL, Cache Get/Set/Clear
- download.controller.js: Download Links
- download.extractor.js: Base64 Download Data Decoder, Redirect Chain Resolver, Download Links Extraction
- seasons.extractor.js: Season Information Extraction
- watchOrder.extractor.js: Watch Order / Related Anime Extraction
- streamResolver.extractor.js: Server Name Normalization, Stream URL Resolution, Batch Stream URL Resolution, M3U8 Quality Parser, Subtitle Track Extractor
- mirror.helper.js: Mirror Domain Configuration, Mirror Health Check, Working Mirror Discovery, Mirror Cache Reset, URL Builder, Resilient Fetch with Mirror Fallback, Mirror Status Reporter
- pagination.helper.js: Pagination Metadata Generator
- creatorInfo.js: Creator Attribution Object, Response Creator Injection Middleware

Function-level JSDoc (added/fixed):
- cache.helper.js: Full JSDoc on all 6 class methods (constructor, get, set, delete, clear, getStats, has) and 4 exported helpers

Inline notes for non-obvious logic:
- cache.helper.js: Lazy expiration, LRU re-insertion, singleton pattern
- download.extractor.js: HTML/JSON hybrid response handling, multiple selectors for different mirrors, redirect fallback
- random.extractor.js: maxRedirects, validateStatus, responseURL extraction
- schedule.extractor.js: Dual selector pattern for different mirror layouts
- animeInfo.extractor.js: Positional .bmeta selector fragility
- homeInfo.extractor.js: Dual selector for different layouts
- mirror.helper.js: 404 vs connection error handling
- animeInfo.controller.js: Accept both id and slug params

Footers (added where missing):
- cache.helper.js, download.controller.js, download.extractor.js, seasons.extractor.js, watchOrder.extractor.js, extractPages.helper.js, mirror.helper.js

All 68 source files now have complete documentation coverage (6/6 checks).
2026-07-28 21:55:14 +05:30

92 lines
3.4 KiB
JavaScript

/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — random.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Fetches a random anime from anikototv.to by following the redirect
* chain from the random endpoint, then extracts the full anime detail
* page metadata from the resolved URL.
*
* @exports
* extractRandom
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// RANDOM ANIME EXTRACTOR
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Fetch a random anime and extract its detail metadata ----
/**
* Hits the random endpoint on anikototv.to which redirects to a random
* anime page. Follows up to 5 redirects, extracts the final URL to get
* the slug, then parses the full anime detail page for metadata.
*
* @returns {Promise<Object>} Random anime data with slug, title, poster, synopsis, etc.
*
* @example
* const random = await extractRandom();
* console.log(random.title); // random anime title
* console.log(random.url); // full resolved URL
*/
const extractRandom = async () => {
try {
const { data, request } = await axios.get(URLS.random, {
headers,
// NOTE: maxRedirects=5 allows following the redirect chain from /random to the final anime page
maxRedirects: 5,
// NOTE: validateStatus < 400 prevents axios from throwing on redirects (3xx)
validateStatus: (status) => status < 400
});
// NOTE: request.responseURL contains the final URL after all redirects
const finalUrl = request?.responseURL || URLS.random;
const slug = finalUrl.split("/watch/").pop() || "";
const $ = cheerio.load(data);
const title = $("h1[itemprop='name'].title.d-title").text().trim() || "";
const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || "";
const poster = $("img[itemprop='image']").attr("src") || "";
const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || "";
const synopsis = $(".synopsis .content").text().trim() || "";
const rating = $("#w-rating .score .value").text().trim() || "";
const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
const genres = [];
$(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => {
genres.push($(el).text().trim());
});
return {
slug,
animeId,
title,
japaneseTitle,
poster,
type,
synopsis,
rating,
genres,
url: finalUrl
};
} catch (error) {
throw error;
}
};
export { extractRandom };
// ══════════════════════════════════════════════════════════════ END: random.extractor.js