feat: upgrade to v2.0.0 with multi-mirror fallback, new endpoints, and LRU cache

- Add multi-mirror fallback system with 5 mirror domains
- Add LRU cache with configurable TTL per endpoint
- Add response compression (gzip)
- Add Seasons endpoint (/api/seasons/:id)
- Add Watch Order endpoint (/api/watch-order/:id)
- Add Latest Updated endpoint (/api/latest-updated)
- Add Download endpoint (/api/download)
- Add cache stats endpoint (/api/cache/stats)
- Add mirror status/reset endpoints (/api/mirrors, /api/mirrors/reset)
- Add configurable rate limiting with X-RateLimit headers
- Add request timeouts and entity too large handling
- Update documentation with all new endpoints
- Update CHANGELOG.md with v2.0.0 entry
- Update package.json version to 2.0.0
- Add 6 AI agent prompts for development
This commit is contained in:
Shinei Nouzen
2026-07-04 15:07:07 +05:30
parent 30feda703a
commit fe51275db0
51 changed files with 5151 additions and 342 deletions
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractAnimeInfo } from "../extractors/animeInfo.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: ANIME INFO
@@ -51,7 +51,7 @@ const getAnimeInfo = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractAnimeInfo(id);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.info);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractAzList } from "../extractors/azList.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: A-Z LIST
@@ -51,7 +51,7 @@ const getAzList = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractAzList(letter, page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.genres);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractCategory } from "../extractors/category.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: CATEGORY
@@ -55,7 +55,7 @@ const getCategory = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractCategory(category, page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.genres);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+60
View File
@@ -0,0 +1,60 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — download.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for download links endpoint. Returns streaming server
* URLs for downloading anime episodes.
*
* @exports
* getDownloadLinks - Express route handler for GET /api/download
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractDownloadLinks } from "../extractors/download.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
/**
* Handles GET /api/download requests. Returns download links
* for the specified anime episode.
*
* @param {object} req - Express request object
* @param {string} req.query.slug - Anime slug (required)
* @param {number} req.query.ep - Episode number (required)
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with download links
*
* @example
* GET /api/download?slug=naruto-shippuden-c8gov&ep=1
* Response: { success: true, results: { slug, episode, downloads[] } }
*/
const getDownloadLinks = async (req, res, next) => {
try {
const { slug, ep } = req.query;
if (!slug || !ep) {
return res.status(400).json({
success: false,
message: "Both slug and ep parameters are required"
});
}
const cacheKey = `download_${slug}_${ep}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const data = await extractDownloadLinks(slug, parseInt(ep));
setCache(cacheKey, data, TTL.stream);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getDownloadLinks };
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractEpisodeList } from "../extractors/episodeList.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: EPISODE LIST
@@ -52,7 +52,7 @@ const getEpisodeList = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractEpisodeList(id);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.episodes);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -17,7 +17,7 @@
*/
import { extractEpisodeListAjax } from "../extractors/episodeListAjax.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: EPISODE LIST AJAX
@@ -56,7 +56,7 @@ const getEpisodeListAjax = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractEpisodeListAjax(id, style, vrf);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.episodes);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractFilter } from "../extractors/filter.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: FILTER
@@ -57,7 +57,7 @@ const getFilter = async (req, res, next) => {
if (Array.isArray(params.type)) params.type = params.type.join(",");
if (Array.isArray(params.status)) params.status = params.status.join(",");
const data = await extractFilter(params);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.genres);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractHomeInfo } from "../extractors/homeInfo.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: HOME INFO
@@ -44,7 +44,7 @@ const getHomeInfo = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractHomeInfo();
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.home);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+39 -5
View File
@@ -17,8 +17,8 @@
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractNewRelease, extractNewlyAdded } from "../extractors/newRelease.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { extractNewRelease, extractNewlyAdded, extractLatestUpdated } from "../extractors/newRelease.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: NEW RELEASE
@@ -48,7 +48,7 @@ const getNewRelease = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractNewRelease(page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -83,13 +83,47 @@ const getNewlyAdded = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractNewlyAdded(page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getNewRelease, getNewlyAdded };
// ══════════════════════════════════════════════════════════════
// CONTROLLER: LATEST UPDATED
// ══════════════════════════════════════════════════════════════
/**
* Handles GET /api/latest-updated requests. Returns paginated list
* of recently updated anime sorted by last update time.
*
* @param {object} req - Express request object
* @param {number} req.query.page - Page number (default: 1)
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with latest updated anime
*
* @example
* GET /api/latest-updated?page=2
* Response: { success: true, results: { totalPages, data[] } }
*/
const getLatestUpdated = async (req, res, next) => {
try {
const { page = 1 } = req.query;
const cacheKey = `latestupdated_${page}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const data = await extractLatestUpdated(page);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getNewRelease, getNewlyAdded, getLatestUpdated };
// ══════════════════════════════════════════════════════════════ END: newRelease.controller.js
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractPopular } from "../extractors/popular.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: POPULAR
@@ -47,7 +47,7 @@ const getPopular = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractPopular(page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractSchedule } from "../extractors/schedule.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: SCHEDULE
@@ -53,7 +53,7 @@ const getSchedule = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSchedule(date);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.schedule);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+3 -3
View File
@@ -18,7 +18,7 @@
*/
import { extractSearchResults, extractSearchSuggestions } from "../extractors/search.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: SEARCH RESULTS
@@ -52,7 +52,7 @@ const getSearchResults = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSearchResults(keyword, page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.search);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -91,7 +91,7 @@ const getSearchSuggestions = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSearchSuggestions(keyword);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.search);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractSeasons } from "../extractors/seasons.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: SEASONS
@@ -52,7 +52,7 @@ const getSeasons = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSeasons(id);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractSpotlight } from "../extractors/spotlight.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: SPOTLIGHT
@@ -45,7 +45,7 @@ const getSpotlight = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSpotlight();
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.spotlight);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractStatus } from "../extractors/status.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: STATUS
@@ -62,7 +62,7 @@ const getStatus = async (req, res, next) => {
};
const mappedStatus = statusMap[status] || status;
const data = await extractStatus(mappedStatus, page);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.genres);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+4 -4
View File
@@ -19,7 +19,7 @@
*/
import { extractStreamInfo, extractServerList, extractMapperServers } from "../extractors/streamInfo.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: STREAM INFO
@@ -54,7 +54,7 @@ const getStreamInfo = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractStreamInfo(id);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -94,7 +94,7 @@ const getServerList = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractServerList(ids);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -137,7 +137,7 @@ const getMapperServers = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractMapperServers(malId, slug, timestamp);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractSuggestions } from "../extractors/suggestion.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: SUGGESTIONS
@@ -52,7 +52,7 @@ const getSuggestions = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractSuggestions(keyword);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.suggestions);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -16,7 +16,7 @@
*/
import { extractTopTen } from "../extractors/topten.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: TOP TEN
@@ -44,7 +44,7 @@ const getTopTen = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractTopTen();
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractTrending } from "../extractors/trending.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: TRENDING
@@ -45,7 +45,7 @@ const getTrending = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractTrending();
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.trending);
res.json({ success: true, results: data });
} catch (error) {
next(error);
@@ -16,7 +16,7 @@
*/
import { extractTrendingSidebar } from "../extractors/trendingSidebar.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: TRENDING SIDEBAR
@@ -44,7 +44,7 @@ const getTrendingSidebar = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractTrendingSidebar();
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.trending);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractWatchOrder } from "../extractors/watchOrder.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: WATCH ORDER
@@ -53,7 +53,7 @@ const getWatchOrder = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractWatchOrder(id);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+2 -2
View File
@@ -17,7 +17,7 @@
*/
import { extractWatchPage } from "../extractors/watchPage.extractor.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: WATCH PAGE
@@ -54,7 +54,7 @@ const getWatchPage = async (req, res, next) => {
return res.json({ success: true, results: cached });
}
const data = await extractWatchPage(slug, ep);
setCache(cacheKey, data);
setCache(cacheKey, data, TTL.stream);
res.json({ success: true, results: data });
} catch (error) {
next(error);
+187
View File
@@ -0,0 +1,187 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — download.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts download links for anime episodes from anikototv.to.
* Decodes base64 download-data attributes and follows redirects
* to get streaming server URLs.
*
* Download flow:
* 1. Watch page → base64 decode → nekostream.site URL
* 2. nekostream.site → Cloudflare Worker → kwik.cx URL
* 3. kwik.cx → actual download URL (requires browser)
*
* @exports
* extractDownloadLinks
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import axios from "axios";
import { fetchWithMirror } from "../helper/mirror.helper.js";
import { headers } from "../configs/header.config.js";
/**
* Decodes base64 download data from the website
* @param {string} encoded - Base64 encoded string
* @returns {Object} Decoded download data
*/
function decodeDownloadData(encoded) {
try {
const decoded = Buffer.from(encoded, "base64").toString("utf-8");
return JSON.parse(decoded);
} catch (error) {
return null;
}
}
/**
* Follows redirect chain to get the final URL
* @param {string} url - Starting URL
* @returns {Promise<string>} Final URL after redirects
*/
async function followRedirects(url) {
try {
const response = await axios.get(url, {
headers,
maxRedirects: 5,
timeout: 10000
});
return response.request?.res?.responseUrl || response.config?.url || url;
} catch (error) {
// If we get a redirect error, try to extract the location
if (error.response?.headers?.location) {
return error.response.headers.location;
}
return url;
}
}
/**
* Fetches and parses download links for a specific episode.
* Scrapes the watch page to extract download-data attributes
* and follows the redirect chain to get streaming server URLs.
*
* Note: Download data may be loaded dynamically via JavaScript.
* If no download links are found in the initial HTML, try using
* a browser or headless browser to get the full page content.
*
* @param {string} slug - The anime slug (e.g., "kill-blue-gcqj5")
* @param {number} ep - Episode number
* @returns {Promise<Object>} Object with slug, episode, and downloads array
*
* @example
* const downloads = await extractDownloadLinks("kill-blue-gcqj5", 1);
* console.log(downloads.downloads[0].server); // server name
* console.log(downloads.downloads[0].kwikUrl); // kwik.cx URL
*/
const extractDownloadLinks = async (slug, ep) => {
try {
const { data } = await fetchWithMirror(`/watch/${slug}/ep-${ep}`);
// Handle both string HTML and JSON responses
let html = "";
if (typeof data === "string") {
try {
const json = JSON.parse(data);
html = json.result || data;
} catch (e) {
html = data;
}
} else if (data?.result) {
html = data.result;
} else if (data?.data) {
html = data.data;
} else {
html = String(data);
}
const $ = cheerio.load(html);
const downloads = [];
// Find all download buttons with download-data attribute
// Multiple selectors to handle different HTML structures
const selectors = [
"[download-data]",
"li.download-icon",
".download-icon",
"[onclick*='openDownloadModalDownload']",
"[onclick*='openDownloadModal']"
];
for (const selector of selectors) {
$(selector).each((_, el) => {
const encoded = $(el).attr("download-data") || "";
const serverType = $(el).closest(".type").attr("data-type") || "unknown";
const serverLabel = $(el).closest(".type").find("label").text().trim() || serverType;
if (encoded && encoded.length > 10) {
const decoded = decodeDownloadData(encoded);
if (decoded) {
// Extract URLs from the decoded data
for (const [serverGroup, servers] of Object.entries(decoded)) {
for (const [serverName, url] of Object.entries(servers)) {
// Avoid duplicates
const exists = downloads.some(d => d.url === url);
if (!exists) {
// Construct worker URL from nekostream.site URL
const workerUrl = url.includes("nekostream.site")
? url.replace("https://pahe.nekostream.site/", "https://proud-dew-d754.download992.workers.dev/")
: null;
downloads.push({
server: serverName,
serverGroup,
type: serverType,
typeLabel: serverLabel,
url, // nekostream.site URL
workerUrl,
kwikUrl: null, // Will be filled after redirect
note: "Visit kwikUrl in browser to get actual download link"
});
}
}
}
}
}
});
if (downloads.length > 0) break;
}
// Try to follow redirects for each download URL
for (const download of downloads) {
if (download.workerUrl) {
try {
const finalUrl = await followRedirects(download.workerUrl);
if (finalUrl.includes("kwik.cx")) {
download.kwikUrl = finalUrl;
}
} catch (error) {
// If redirect fails, construct a placeholder kwik URL
download.kwikUrl = "https://kwik.cx/f/[requires-browser]";
}
}
}
return {
slug,
episode: ep,
totalDownloads: downloads.length,
downloads,
note: downloads.length > 0
? "kwikUrl requires browser to bypass Cloudflare protection"
: "Download links may be loaded dynamically via JavaScript. Try using a browser."
};
} catch (error) {
throw error;
}
};
export { extractDownloadLinks };
+4 -4
View File
@@ -19,7 +19,7 @@
import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { BASE_URL } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// EPISODE LIST AJAX EXTRACTOR
@@ -42,13 +42,13 @@ import { BASE_URL } from "../configs/dataUrl.js";
*/
const extractEpisodeListAjax = async (animeId, style = "", vrf = "") => {
try {
let url = `${BASE_URL}/ajax/episode/list/${animeId}`;
let path = `/ajax/episode/list/${animeId}`;
const params = [];
if (style) params.push(`style=${style}`);
if (vrf) params.push(`vrf=${vrf}`);
if (params.length) url += `?${params.join("&")}`;
if (params.length) path += `?${params.join("&")}`;
const { data: raw } = await axios.get(url, {
const { data: raw } = await fetchWithMirror(path, {
headers: {
...headers,
"X-Requested-With": "XMLHttpRequest"
+2 -1
View File
@@ -20,6 +20,7 @@ import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js";
import { getCache, setCache } from "../helper/cache.helper.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// HOME INFO EXTRACTOR
@@ -40,7 +41,7 @@ const extractHomeInfo = async () => {
const cached = getCache("home");
if (cached) return cached;
try {
const { data } = await axios.get(URLS.home, { headers });
const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data);
// ---- FEATURE: Extract spotlight carousel items from #hotest section ----
+59 -1
View File
@@ -22,6 +22,7 @@ import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js";
import { extractPages } from "../helper/extractPages.helper.js";
import { countPages } from "../helper/countPages.helper.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// NEW RELEASE EXTRACTION
@@ -160,6 +161,63 @@ const extractNewlyAdded = async (page = 1) => {
}
};
export { extractNewRelease, extractNewlyAdded };
// ══════════════════════════════════════════════════════════════
// LATEST UPDATED EXTRACTION
// ══════════════════════════════════════════════════════════════
/**
* Fetches and parses recently updated anime with pagination.
* Uses the /latest-updated page which shows anime sorted by last update time.
*
* @param {number} page - Page number to fetch (default: 1)
* @returns {Promise<Object>} Object containing totalPages and data array
*
* @example
* const latest = await extractLatestUpdated(1);
* console.log(latest.totalPages);
* console.log(latest.data[0].title);
*/
const extractLatestUpdated = async (page = 1) => {
try {
const $ = await extractPages("/latest-updated", page);
const totalPages = countPages($);
const results = [];
$(".item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".film-name a, .name.d-title").text().trim() ||
$(el).find("a.name").text().trim() || "";
const japaneseTitle = $(el).find(".name.d-title").attr("data-jp") ||
$(el).find("a.name").attr("data-jp") || "";
const sub = parseInt($(el).find(".ep-status.sub span").text().trim()) || 0;
const dub = parseInt($(el).find(".ep-status.dub span").text().trim()) || 0;
const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0;
const type = $(el).find(".type, .fdi-item:nth-child(2)").text().trim() || "";
const rating = $(el).find(".rating, .fdi-item:nth-child(3)").text().trim() || "";
if (slug) {
results.push({
slug,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, data: results };
} catch (error) {
throw error;
}
};
export { extractNewRelease, extractNewlyAdded, extractLatestUpdated };
// ══════════════════════════════════════════════════════════════ END: newRelease.extractor.js
+72 -19
View File
@@ -4,8 +4,9 @@
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts season information for a specific anime via API.
* Returns season data from the internal API endpoint.
* Extracts season information for a specific anime from the
* anikototv.to AJAX endpoint. Returns all seasons/OVAs/specials
* for a given anime series.
*
* @exports
* extractSeasons
@@ -15,30 +16,82 @@
* ======= • ======= • ======= • ======= • =======• =======
*/
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { BASE_URL } from "../configs/dataUrl.js";
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// SEASONS API EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract season data from internal API ----
/**
* Fetches season information for a specific anime from the internal API.
* Returns an array of season objects or empty array on error.
* Fetches and parses season information for an anime.
* Scrapes the AJAX endpoint that returns season carousel HTML.
*
* @param {string} animeId - The anime ID to fetch seasons for
* @returns {Promise<Array<Object>>} Array of season objects or empty array
* @param {string|number} animeId - The numeric anime ID
* @returns {Promise<Object>} Object with animeId, totalSeasons, and seasons array
*
* @example
* const seasons = await extractSeasons("12345");
* console.log(seasons.length); // Number of seasons
* const seasons = await extractSeasons(7174);
* console.log(seasons.totalSeasons); // number of seasons
* console.log(seasons.seasons[0].title); // first season title
*/
const extractSeasons = async (animeId) => {
throw new Error("Seasons endpoint not available - source site does not provide this data");
try {
const { data } = await fetchWithMirror(`/api/seasons/${animeId}`, {
headers: { "X-Requested-With": "XMLHttpRequest" }
});
// Handle both string HTML and JSON responses
let raw = "";
if (typeof data === "string") {
try {
const json = JSON.parse(data);
raw = json.result || data;
} catch (e) {
raw = data;
}
} else if (data?.result) {
raw = data.result;
} else if (data?.data) {
raw = data.data;
}
const $ = cheerio.load(raw);
const seasons = [];
// Try multiple selectors to handle different HTML structures
const selectors = [
".swiper-slide.season",
".seasons .swiper-slide",
"#w-seasons .swiper-slide",
".swiper-slide"
];
for (const selector of selectors) {
$(selector).each((_, el) => {
const link = $(el).find("a").first();
const href = link.attr("href") || "";
const style = link.attr("style") || "";
const poster = style.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || "";
const title = $(el).find(".name").text().trim() ||
link.text().trim() || "";
// Extract slug from href
const slug = href.split("/watch/").pop() || "";
if (slug || title) {
seasons.push({ title, slug, poster, url: href });
}
});
if (seasons.length > 0) break;
}
return {
animeId,
totalSeasons: seasons.length,
seasons
};
} catch (error) {
throw error;
}
};
export { extractSeasons };
// ══════════════════════════════════════════════════════════════ END: seasons.extractor.js
+80 -19
View File
@@ -4,8 +4,9 @@
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts watch order information for a specific anime via API.
* Returns recommended viewing order from the internal API endpoint.
* Extracts watch order and related anime information from the
* anikototv.to AJAX endpoint. Returns related anime with their
* relationship types (sequel, prequel, summary, etc.).
*
* @exports
* extractWatchOrder
@@ -15,30 +16,90 @@
* ======= • ======= • ======= • ======= • =======• =======
*/
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { BASE_URL } from "../configs/dataUrl.js";
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// WATCH ORDER API EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract watch order data from internal API ----
/**
* Fetches watch order information for a specific anime from the internal API.
* Returns an array of watch order objects or empty array on error.
* Fetches and parses watch order / related anime for an anime.
* Scrapes the AJAX endpoint that returns related anime HTML.
*
* @param {string} animeId - The anime ID to fetch watch order for
* @returns {Promise<Array<Object>>} Array of watch order objects or empty array
* @param {string|number} animeId - The numeric anime ID
* @returns {Promise<Object>} Object with animeId, totalRelated, related array
*
* @example
* const watchOrder = await extractWatchOrder("12345");
* console.log(watchOrder[0].title); // First anime in watch order
* const data = await extractWatchOrder(7174);
* console.log(data.totalRelated); // number of related anime
* console.log(data.related[0].title); // first related anime
*/
const extractWatchOrder = async (animeId) => {
throw new Error("Watch order endpoint not available - source site does not provide this data");
try {
const { data } = await fetchWithMirror(`/api/watch-order/${animeId}`, {
headers: { "X-Requested-With": "XMLHttpRequest" }
});
// Handle both string HTML and JSON responses
let raw = "";
if (typeof data === "string") {
try {
const json = JSON.parse(data);
raw = json.result || data;
} catch (e) {
raw = data;
}
} else if (data?.result) {
raw = data.result;
} else if (data?.data) {
raw = data.data;
}
const $ = cheerio.load(raw);
// Extract related anime
const related = [];
// Try multiple selectors
const selectors = [
"#w-related .item",
".item.flexserieslist",
".scaff.side.items .item",
".item"
];
for (const selector of selectors) {
$(selector).each((_, el) => {
const link = $(el).find("a.name").first();
const href = link.attr("href") || "";
const title = link.text().trim() || "";
const poster = $(el).find("img").attr("src") || "";
const slug = href.split("/watch/").pop() || "";
// Extract relationship type
const relationEl = $(el).find(".relation, .serieslabelitem").first();
let relationType = relationEl.text().trim().toLowerCase() ||
relationEl.attr("id") || "related";
if (slug || title) {
related.push({
title,
slug,
poster,
url: href,
relation: relationType
});
}
});
if (related.length > 0) break;
}
return {
animeId,
totalRelated: related.length,
related
};
} catch (error) {
throw error;
}
};
export { extractWatchOrder };
// ══════════════════════════════════════════════════════════════ END: watchOrder.extractor.js
+100 -94
View File
@@ -4,111 +4,117 @@
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* In-memory caching utility for storing and retrieving API responses.
* Implements TTL-based cache invalidation to prevent stale data
* while reducing unnecessary requests to the source site.
* In-memory LRU cache with configurable TTL per endpoint.
* Evicts least recently used entries when max size reached.
* Supports cache statistics and manual invalidation.
*
* @exports
* getCache, setCache, clearCache
* getCache, setCache, clearCache, getCacheStats, LRUCache
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
// ══════════════════════════════════════════════════════════════
// CACHE STORAGE & CONFIGURATION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: In-memory Map-based cache storage ----
/**
* Internal cache storage using JavaScript Map object.
* Stores data with timestamps for TTL-based expiration.
*
* @type {Map<string, {data: any, timestamp: number}>}
*/
const cache = new Map();
// ---- FEATURE: Cache time-to-live configuration (5 minutes) ----
/**
* Cache TTL (Time-To-Live) in milliseconds.
* Default: 5 minutes (300,000 ms).
* After this duration, cached items are considered stale
* and will be removed on next access.
*
* @type {number}
* @default 300000
*/
const CACHE_TTL = 5 * 60 * 1000;
// ---- FEATURE: Maximum cache size ----
const MAX_CACHE_SIZE = 100;
// ══════════════════════════════════════════════════════════════
// CACHE OPERATIONS
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Retrieve cached data by key with TTL validation ----
/**
* Retrieves data from cache if it exists and hasn't expired.
* Automatically removes stale entries on access.
*
* @param {string} key - The cache key to lookup
* @returns {any|null} Cached data if valid, null if expired or missing
*
* @example
* // Get cached anime list
* const data = getCache("anime-list-action");
* if (data) {
* // Use cached data
* }
*/
const getCache = (key) => {
const item = cache.get(key);
if (item && Date.now() - item.timestamp < CACHE_TTL) {
return item.data;
class LRUCache {
constructor(maxSize = 100, defaultTTL = 300000) {
this.cache = new Map();
this.maxSize = maxSize;
this.defaultTTL = defaultTTL;
this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0 };
}
cache.delete(key);
return null;
};
// ---- FEATURE: Store data in cache with current timestamp ----
/**
* Stores data in cache with current timestamp for TTL tracking.
* Overwrites any existing data for the same key.
*
* @param {string} key - The cache key to store under
* @param {any} data - The data to cache (any serializable type)
* @returns {void}
*
* @example
* // Cache anime search results
* setCache("search-one-piece", animeResults);
*/
const setCache = (key, data) => {
// Evict oldest entries if cache is full
if (cache.size >= MAX_CACHE_SIZE) {
const oldestKey = cache.keys().next().value;
cache.delete(oldestKey);
get(key) {
if (!this.cache.has(key)) {
this.stats.misses++;
return undefined;
}
const entry = this.cache.get(key);
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
this.stats.misses++;
return undefined;
}
this.stats.hits++;
this.cache.delete(key);
this.cache.set(key, entry);
return entry.value;
}
cache.set(key, { data, timestamp: Date.now() });
set(key, value, ttl) {
if (this.cache.has(key)) {
this.cache.delete(key);
}
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, {
value,
expiresAt: Date.now() + (ttl || this.defaultTTL)
});
this.stats.sets++;
}
delete(key) {
const existed = this.cache.delete(key);
if (existed) this.stats.deletes++;
return existed;
}
clear() {
const size = this.cache.size;
this.cache.clear();
return size;
}
getStats() {
const total = this.stats.hits + this.stats.misses;
return {
...this.stats,
size: this.cache.size,
hitRate: total > 0 ? ((this.stats.hits / total) * 100).toFixed(2) + '%' : '0%'
};
}
has(key) {
if (!this.cache.has(key)) return false;
const entry = this.cache.get(key);
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
return false;
}
return true;
}
}
const TTL = {
home: 600000,
search: 300000,
info: 600000,
episodes: 300000,
servers: 600000,
stream: 180000,
spotlight: 600000,
trending: 600000,
schedule: 1800000,
genres: 3600000,
suggestions: 300000,
default: 300000
};
// ---- FEATURE: Clear all cached entries from memory ----
/**
* Clears all entries from the cache. Use when:
* - Memory cleanup is needed
* - Force-refreshing all data
* - Application restart/reset
*
* @returns {void}
*
* @example
* // Force refresh all cached data
* clearCache();
*/
const clearCache = () => {
cache.clear();
};
const cache = new LRUCache(
parseInt(process.env.CACHE_MAX_SIZE) || 200,
parseInt(process.env.CACHE_DEFAULT_TTL) || 300000
);
export { getCache, setCache, clearCache };
// ══════════════════════════════════════════════════════════════ END: cache.helper.js
const getCache = (key) => cache.get(key);
const setCache = (key, data, ttl) => cache.set(key, data, ttl);
const clearCache = () => cache.clear();
const getCacheStats = () => cache.getStats();
export { getCache, setCache, clearCache, getCacheStats, LRUCache, TTL };
+10 -58
View File
@@ -5,8 +5,8 @@
*
* @description
* HTTP client utility for fetching and parsing HTML content from
* paginated URLs. Uses axios for HTTP requests and Cheerio for
* DOM parsing, with support for page-based pagination.
* paginated URLs. Uses mirror fallback for resilience and Cheerio
* for DOM parsing, with support for page-based pagination.
*
* @exports
* extractPages
@@ -16,73 +16,26 @@
* ======= • ======= • ======= • ======= • =======• =======
*/
// ══════════════════════════════════════════════════════════════
// DEPENDENCIES
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Cheerio HTML parser import ----
/**
* Cheerio library for server-side DOM manipulation.
* Used to parse and query HTML content from fetched pages.
*
* @type {module:cheerio}
*/
import * as cheerio from "cheerio";
import { fetchWithMirror } from "./mirror.helper.js";
// ---- FEATURE: Axios HTTP client import ----
/**
* Axios HTTP client for making requests to the source site.
* Handles redirects, timeouts, and response parsing.
* Fetches HTML content from a URL with pagination and mirror fallback.
* Automatically tries alternative domains if primary fails.
*
* @type {module:axios}
*/
import axios from "axios";
// ---- FEATURE: Browser-mimicking headers import ----
/**
* Pre-configured HTTP headers to mimic browser requests.
* Imported from header.config.js for consistent usage.
*
* @type {Object}
*/
import { headers } from "../configs/header.config.js";
// ══════════════════════════════════════════════════════════════
// PAGE EXTRACTION FUNCTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Fetch and parse paginated URL content ----
/**
* Fetches HTML content from a URL with optional pagination support.
* Appends page query parameter for pages > 1 and returns parsed
* Cheerio instance for DOM querying.
*
* @param {string} url - Base URL to fetch (without page parameter)
* @param {string} url - Base URL path to fetch (e.g., "/filter?keyword=naruto")
* @param {number} [page=1] - Page number to fetch (1-indexed)
* @returns {Promise<CheerioAPI>} Parsed Cheerio instance of the page
* @throws {Error} If HTTP request fails or returns non-2xx status
*
* @example
* // Fetch first page of search results
* const $ = await extractPages("https://anikototv.to/filter?keyword=one-piece");
*
* @example
* // Fetch second page of genre listing
* const $ = await extractPages(genreUrl, 2);
*
* @note
* WARNING: The site may block requests without proper headers.
* Always use the imported headers configuration.
*
* @note
* TIP: Consider implementing retry logic for failed requests
* in production environments.
* const $ = await extractPages("/filter?keyword=one-piece");
* const $page2 = await extractPages("/filter?keyword=one-piece", 2);
*/
const extractPages = async (url, page = 1) => {
try {
const separator = url.includes("?") ? "&" : "?";
const finalUrl = page > 1 ? `${url}${separator}page=${page}` : url;
const { data } = await axios.get(finalUrl, { headers });
const path = page > 1 ? `${url}${separator}page=${page}` : url;
const { data } = await fetchWithMirror(path);
const $ = cheerio.load(data);
return $;
} catch (error) {
@@ -91,4 +44,3 @@ const extractPages = async (url, page = 1) => {
};
export { extractPages };
// ══════════════════════════════════════════════════════════════ END: extractPages.helper.js
+251
View File
@@ -0,0 +1,251 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — mirror.helper.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Multi-mirror fallback helper for resilient scraping.
* Automatically tries alternative domains if primary is blocked/down.
* Caches working mirror per session for faster subsequent requests.
*
* @exports
* fetchWithMirror, getWorkingMirror, resetMirrorCache
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { getCache, setCache } from "./cache.helper.js";
// ══════════════════════════════════════════════════════════════
// MIRROR CONFIGURATION
// ══════════════════════════════════════════════════════════════
// Default mirrors with names and priority
const DEFAULT_MIRRORS = [
{ url: "https://anikototv.to", name: "Primary", priority: 1 },
{ url: "https://anikoto.cz", name: "Regional CZ", priority: 2 },
{ url: "https://anikoto.me", name: "Short TLD", priority: 3 },
{ url: "https://anikoto.net", name: "Network", priority: 4 },
{ url: "https://anikototv.se", name: "Nordic .se", priority: 5 },
];
// Parse custom mirrors from env or use defaults
function parseMirrors() {
const envMirrors = process.env.MIRROR_DOMAINS;
if (!envMirrors) return DEFAULT_MIRRORS;
return envMirrors.split(",").map((url, index) => ({
url: url.trim(),
name: `Mirror ${index + 1}`,
priority: index + 1
}));
}
const ALL_MIRRORS = parseMirrors();
ALL_MIRRORS.sort((a, b) => a.priority - b.priority);
// Cache key for working mirror
const MIRROR_CACHE_KEY = "working_mirror";
const MIRROR_CACHE_TTL = parseInt(process.env.MIRROR_CACHE_TTL) || 3600000;
// ══════════════════════════════════════════════════════════════
// MIRROR STATE
// ══════════════════════════════════════════════════════════════
let workingMirror = null;
let failedMirrors = new Set();
// ══════════════════════════════════════════════════════════════
// HELPER FUNCTIONS
// ══════════════════════════════════════════════════════════════
/**
* Check if a mirror is accessible
* @param {string} baseUrl - Mirror base URL
* @returns {Promise<boolean>}
*/
async function checkMirror(baseUrl) {
try {
const response = await axios.get(`${baseUrl}/home`, {
headers,
timeout: 10000,
maxRedirects: 5,
});
return response.status === 200;
} catch (error) {
return false;
}
}
/**
* Get the best available mirror
* @returns {Promise<string>} Working mirror base URL
*/
async function getWorkingMirror() {
// Check cache first
const cached = getCache(MIRROR_CACHE_KEY);
if (cached && !failedMirrors.has(cached)) {
workingMirror = cached;
return workingMirror;
}
// Try mirrors in priority order
for (const mirror of ALL_MIRRORS) {
if (failedMirrors.has(mirror.url)) continue;
const isWorking = await checkMirror(mirror.url);
if (isWorking) {
workingMirror = mirror.url;
setCache(MIRROR_CACHE_KEY, mirror.url, MIRROR_CACHE_TTL);
console.log(`[MIRROR] Using: ${mirror.name} (${mirror.url})`);
return mirror.url;
} else {
failedMirrors.add(mirror.url);
console.log(`[MIRROR] Failed: ${mirror.name} (${mirror.url})`);
}
}
// All mirrors failed, reset and try again
failedMirrors.clear();
workingMirror = ALL_MIRRORS[0].url;
console.log(`[MIRROR] All failed, resetting to primary: ${workingMirror}`);
return workingMirror;
}
/**
* Reset mirror cache and failed state
*/
function resetMirrorCache() {
workingMirror = null;
failedMirrors.clear();
setCache(MIRROR_CACHE_KEY, null, 0);
console.log("[MIRROR] Cache reset");
}
/**
* Build URL with current mirror
* @param {string} path - URL path
* @param {string} baseUrl - Optional custom base URL
* @returns {string} Full URL
*/
function buildUrl(path, baseUrl = workingMirror) {
const base = baseUrl || ALL_MIRRORS[0].url;
return `${base}${path}`;
}
/**
* Fetch with automatic mirror fallback
* @param {string} path - URL path to fetch
* @param {object} options - Additional options
* @returns {Promise<{data: string, mirror: string}>}
*/
async function fetchWithMirror(path, options = {}) {
const {
timeout = 15000,
retries = 2,
returnType = "text",
headers: customHeaders = {}
} = options;
// Merge default headers with custom headers
const requestHeaders = { ...headers, ...customHeaders };
let lastError = null;
// Try cached working mirror first
const mirrorsToTry = [];
if (workingMirror && !failedMirrors.has(workingMirror)) {
mirrorsToTry.push(workingMirror);
}
// Add remaining mirrors
for (const mirror of ALL_MIRRORS) {
if (!mirrorsToTry.includes(mirror.url) && !failedMirrors.has(mirror.url)) {
mirrorsToTry.push(mirror.url);
}
}
// If all failed, reset and try all
if (mirrorsToTry.length === 0) {
failedMirrors.clear();
mirrorsToTry.push(...ALL_MIRRORS.map(m => m.url));
}
for (const mirror of mirrorsToTry) {
const url = buildUrl(path, mirror);
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await axios.get(url, {
headers: requestHeaders,
timeout,
responseType: returnType === "text" ? "text" : "json",
});
if (response.status === 200) {
// Update working mirror
if (mirror !== workingMirror) {
workingMirror = mirror;
setCache(MIRROR_CACHE_KEY, mirror, MIRROR_CACHE_TTL);
console.log(`[MIRROR] Switched to: ${mirror}`);
}
return {
data: returnType === "text" ? response.data : response.data,
mirror
};
}
} catch (error) {
lastError = error;
if (attempt < retries) {
// Wait before retry
await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
}
}
}
// Mark mirror as failed after all retries
failedMirrors.add(mirror);
console.log(`[MIRROR] Marked as failed: ${mirror}`);
}
throw new Error(`All mirrors failed. Last error: ${lastError?.message}`);
}
/**
* Get mirror status for all domains
* @returns {Promise<Array>}
*/
async function getMirrorStatus() {
const status = [];
for (const mirror of ALL_MIRRORS) {
const start = Date.now();
const isWorking = await checkMirror(mirror.url);
const latency = Date.now() - start;
status.push({
name: mirror.name,
url: mirror.url,
priority: mirror.priority,
status: isWorking ? "online" : "offline",
latency: `${latency}ms`,
isCurrent: mirror.url === workingMirror,
});
}
return status;
}
export {
fetchWithMirror,
getWorkingMirror,
resetMirrorCache,
buildUrl,
getMirrorStatus,
ALL_MIRRORS
};
+41 -1
View File
@@ -36,12 +36,14 @@ import { getPopular } from "../controllers/popular.controller.js";
import { getFilter } from "../controllers/filter.controller.js";
import { getWatchPage } from "../controllers/watchPage.controller.js";
import { getAzList } from "../controllers/azList.controller.js";
import { getNewRelease, getNewlyAdded } from "../controllers/newRelease.controller.js";
import { getNewRelease, getNewlyAdded, getLatestUpdated } from "../controllers/newRelease.controller.js";
import { getStatus } from "../controllers/status.controller.js";
import { getTrendingSidebar } from "../controllers/trendingSidebar.controller.js";
import { getSeasons } from "../controllers/seasons.controller.js";
import { getWatchOrder } from "../controllers/watchOrder.controller.js";
import { getDownloadLinks } from "../controllers/download.controller.js";
import { categoryRoutes } from "./category.route.js";
import { getMirrorStatus, resetMirrorCache } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// ROUTE REGISTRATION
@@ -193,6 +195,15 @@ app.use((req, res, next) => {
}
});
// ---- FEATURE: Download links for episode ----
app.get("/api/download", async (req, res, next) => {
try {
await getDownloadLinks(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════
// SCHEDULE
// ══════════════════════════════════════════════════════════════
@@ -295,6 +306,15 @@ app.use((req, res, next) => {
}
});
// ---- FEATURE: Recently updated anime (sorted by update time) ----
app.get("/api/latest-updated", async (req, res, next) => {
try {
await getLatestUpdated(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════
// SIDEBAR
// ══════════════════════════════════════════════════════════════
@@ -404,6 +424,22 @@ app.get("/api/stats", (req, res) => {
});
});
// ---- FEATURE: Mirror status and health check ----
app.get("/api/mirrors", async (req, res) => {
try {
const status = await getMirrorStatus();
res.json({ success: true, results: status });
} catch (error) {
jsonError(res, error.message);
}
});
// ---- FEATURE: Reset mirror cache ----
app.post("/api/mirrors/reset", (req, res) => {
resetMirrorCache();
res.json({ success: true, message: "Mirror cache reset" });
});
// ---- FEATURE: OpenAPI specification ----
app.get("/api/openapi", (req, res) => {
res.json({
@@ -427,6 +463,7 @@ app.get("/api/openapi", (req, res) => {
"/episodes/{id}": { get: { summary: "Episode list", tags: ["Episodes"] } },
"/servers": { get: { summary: "Server list", tags: ["Streaming"] } },
"/stream": { get: { summary: "Stream URL", tags: ["Streaming"] } },
"/download": { get: { summary: "Download links", tags: ["Streaming"] } },
"/schedule": { get: { summary: "Anime schedule", tags: ["Schedule"] } },
"/random": { get: { summary: "Random anime", tags: ["Discovery"] } },
"/top-ten": { get: { summary: "Top 10 rankings", tags: ["Rankings"] } },
@@ -440,12 +477,15 @@ app.get("/api/openapi", (req, res) => {
"/status/{name}": { get: { summary: "By status", tags: ["Categories"] } },
"/health": { get: { summary: "Health check", tags: ["System"] } },
"/stats": { get: { summary: "API statistics", tags: ["System"] } },
"/mirrors": { get: { summary: "Mirror status", tags: ["System"] } },
"/mirrors/reset": { post: { summary: "Reset mirror cache", tags: ["System"] } },
"/openapi": { get: { summary: "OpenAPI spec", tags: ["System"] } },
"/watch": { get: { summary: "Watch page data", tags: ["Streaming"] } },
"/search/suggest": { get: { summary: "Search suggestions", tags: ["Search"] } },
"/episodes-ajax/{id}": { get: { summary: "AJAX episode list", tags: ["Episodes"] } },
"/mapper-servers": { get: { summary: "Mapper servers", tags: ["Streaming"] } },
"/newly-added": { get: { summary: "Newly added", tags: ["Releases"] } },
"/latest-updated": { get: { summary: "Recently updated", tags: ["Releases"] } },
"/trending-sidebar": { get: { summary: "Trending sidebar", tags: ["Discovery"] } },
"/seasons/{id}": { get: { summary: "Season data", tags: ["Anime"] } },
"/watch-order/{id}": { get: { summary: "Watch order", tags: ["Anime"] } },