mirror of
https://github.com/Shineii86/AniKotoAPI.git
synced 2026-10-22 10:55:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
403b205625 | ||
|
|
e8b63b5d16 | ||
|
|
646ef128a8 | ||
|
|
5ca688ab45 | ||
|
|
5cf908fb1e | ||
|
|
7641a81976 | ||
|
|
fe51275db0 | ||
|
|
30feda703a | ||
|
|
7d621e2e37 | ||
|
|
e5dbe0c12e | ||
|
|
f43522c4d5 | ||
|
|
cc145c9acc |
@@ -3,3 +3,25 @@ ALLOWED_ORIGINS=https://site1.com,https://site2.com
|
||||
|
||||
# Port (optional, defaults to 4444)
|
||||
PORT=4444
|
||||
|
||||
# Cache configuration
|
||||
CACHE_MAX_SIZE=200
|
||||
CACHE_DEFAULT_TTL=300000
|
||||
|
||||
# Rate limiting
|
||||
RATE_LIMIT=100
|
||||
RATE_WINDOW=60000
|
||||
|
||||
# Request timeout in milliseconds
|
||||
REQUEST_TIMEOUT=30000
|
||||
|
||||
# Mirror configuration
|
||||
# Comma-separated list of mirror domains (in priority order)
|
||||
# Default: anikototv.to,anikoto.cz,anikoto.me,anikoto.net,anikototv.se
|
||||
MIRROR_DOMAINS=https://anikototv.to,https://anikoto.cz,https://anikoto.me,https://anikoto.net,https://anikototv.se
|
||||
|
||||
# Mirror cache TTL in milliseconds (default: 1 hour)
|
||||
MIRROR_CACHE_TTL=3600000
|
||||
|
||||
# Environment (production/development)
|
||||
NODE_ENV=production
|
||||
|
||||
@@ -5,6 +5,53 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2.0.0] - 2026-07-04
|
||||
|
||||
### Added
|
||||
- **Pagination Metadata**: All list endpoints now include `pagination` object with `currentPage`, `totalPages`, `totalItems`, `itemsPerPage`, `hasNext`, `hasPrev`
|
||||
- **Creator Info Middleware**: Injects creator attribution (name, GitHub, Telegram, message, timestamp) into every JSON response
|
||||
- **Multi-Mirror Fallback System**: Automatic failover across 5 mirror domains (anikototv.to, anikoto.cz, anikoto.me, anikoto.net, anikototv.se)
|
||||
- **LRU Cache with Configurable TTL**: Replaced basic Map cache with LRU cache supporting per-endpoint TTL (3min to 60min)
|
||||
- **Response Compression**: Added gzip compression middleware (level 6, 1024 byte threshold)
|
||||
- **Cache Statistics Endpoint**: `/api/cache/stats` returns hits, misses, sets, deletes, size, hitRate
|
||||
- **Mirror Status Endpoint**: `/api/mirrors` shows health status and latency for all domains
|
||||
- **Mirror Reset Endpoint**: `/api/mirrors/reset` clears mirror cache and failed state
|
||||
- **Seasons Endpoint**: `/api/seasons/:id` returns all seasons/OVAs/movies for an anime
|
||||
- **Watch Order Endpoint**: `/api/watch-order/:id` returns related anime with relationship types
|
||||
- **Latest Updated Endpoint**: `/api/latest-updated` returns recently updated anime sorted by update time
|
||||
- **Download Endpoint**: `/api/download?slug=&ep=` returns decoded download links from base64 data
|
||||
- **Configurable Rate Limiting**: `RATE_LIMIT` and `RATE_WINDOW` env vars for customization
|
||||
- **Request Timeout**: Configurable via `REQUEST_TIMEOUT` env var (default 30s)
|
||||
- **Rate Limit Headers**: `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers
|
||||
- **Retry-After Header**: Included in 429 responses with seconds until reset
|
||||
- **Environment Variables**: Added `MIRROR_DOMAINS`, `MIRROR_CACHE_TTL`, `CACHE_MAX_SIZE`, `CACHE_DEFAULT_TTL`
|
||||
- **Test Suite**: Added 27 endpoint tests with performance metrics and optional endpoint handling
|
||||
- **OpenAPI Spec**: Added `/api/mirrors`, `/api/mirrors/reset`, `/api/latest-updated`, `/api/download` to spec
|
||||
|
||||
### Changed
|
||||
- **BREAKING**: All extractors now use mirror fallback helper for resilience
|
||||
- **BREAKING**: Cache system upgraded from simple Map to LRU with eviction
|
||||
- **BREAKING**: Rate limiting now configurable via environment variables
|
||||
- Updated `extractPages.helper.js` to use `fetchWithMirror` instead of direct axios
|
||||
- Updated `homeInfo.extractor.js` to use mirror fallback
|
||||
- Updated `episodeListAjax.extractor.js` to use mirror fallback
|
||||
- Updated all controllers to use endpoint-specific TTL values
|
||||
- Updated `.env.example` with all new configuration options
|
||||
- Updated `test.js` with optional endpoint handling and performance metrics
|
||||
|
||||
### Fixed
|
||||
- **CRITICAL**: Fixed `extractPages` URL handling bug causing doubled URLs in mirror fallback
|
||||
- **CRITICAL**: Fixed `creatorInfo` middleware not including `message` field in responses
|
||||
- Fixed header merging bug in mirror helper (custom headers were ignored)
|
||||
- Fixed mirror URL construction (proper base URL handling)
|
||||
- Fixed cache key sorting in filter controller
|
||||
- Fixed trailing slash inconsistency in console output
|
||||
- Fixed inconsistent error handling across extractors
|
||||
|
||||
### Removed
|
||||
- Removed `og-image.svg` and `logo.png` (replaced by `share.png`)
|
||||
- Removed unused `cookie-parser` dependency (was already removed in v1.8.0)
|
||||
|
||||
## [1.9.0] - 2026-06-09
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -19,14 +19,14 @@
|
||||
<img src="https://img.shields.io/badge/Cheerio-1.0-3572A5?style=flat-square&logoColor=white" alt="Cheerio"/>
|
||||
<img src="https://img.shields.io/badge/Vercel-Serverless-000000?style=flat-square&logo=vercel&logoColor=white" alt="Vercel"/>
|
||||
<img src="https://img.shields.io/badge/License-MIT-22c55e?style=flat-square&logo=mit&logoColor=white" alt="License"/>
|
||||
<img src="https://img.shields.io/badge/Version-1.9.0-f43f8e?style=flat-square&logoColor=white" alt="Version"/>
|
||||
<img src="https://img.shields.io/badge/Endpoints-30-6366f1?style=flat-square&logoColor=white" alt="Endpoints"/>
|
||||
<img src="https://img.shields.io/badge/Version-2.0.0-f43f8e?style=flat-square&logoColor=white" alt="Version"/>
|
||||
<img src="https://img.shields.io/badge/Endpoints-33-6366f1?style=flat-square&logoColor=white" alt="Endpoints"/>
|
||||
<img src="https://img.shields.io/badge/Anime-10000+-a855f7?style=flat-square&logoColor=white" alt="Anime Database"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<b>A complete RESTful API scraping real-time anime data from anikototv.to</b><br/>
|
||||
Search, browse, filter, watch — every endpoint returns live data with 5-minute smart caching.<br/>
|
||||
Search, browse, filter, watch — every endpoint returns live data with smart caching and multi-mirror fallback.<br/>
|
||||
Built for building anime websites, apps, and bots.
|
||||
</p>
|
||||
|
||||
@@ -84,23 +84,23 @@
|
||||
|
||||
### Why AniKotoAPI?
|
||||
|
||||
- 🎬 **30 Endpoints** — Complete coverage of anikototv.to data
|
||||
- 🎬 **33 Endpoints** — Complete coverage of anikototv.to data
|
||||
- 🔍 **Full-Text Search** — Search anime by keyword with suggestions
|
||||
- 📺 **Episode Lists** — AJAX-loaded episode data with server info
|
||||
- 🎯 **Smart Filtering** — Genre, type, status, rating, sort, season, year
|
||||
- 🏆 **Rankings** — Top 10 (day/week/month), trending, most popular
|
||||
- 🎲 **Random Anime** — Random anime discovery endpoint
|
||||
- ⚡ **Smart Caching** — 5-minute TTL reduces source site load
|
||||
- 🔒 **CORS Enabled** — Works from any frontend, no proxy needed
|
||||
- 🚀 **Zero-Config Deploy** — One click to Vercel, or run standalone with Express
|
||||
- ⚡ **Smart Caching** — LRU cache with configurable TTL per endpoint
|
||||
- 🌐 **Multi-Mirror Fallback** — Automatic failover across 5 mirror domains
|
||||
- 🚀 **Response Compression** — Gzip compression for faster responses
|
||||
- 📊 **Live Data** — Every response is fresh from the actual website
|
||||
|
||||
### How It Works
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["🌐 Client Request<br/>(Browser / App / curl)"] --> B["🛡️ Vercel Edge / Express Server<br/>CORS · Security Headers"]
|
||||
B --> C{"💾 Cache Check<br/>(In-Memory Map)"}
|
||||
A["🌐 Client Request<br/>(Browser / App / curl)"] --> B["🛡️ Vercel Edge / Express Server<br/>CORS · Security Headers · Rate Limiting"]
|
||||
B --> C{"💾 Cache Check<br/>(LRU with TTL)"}
|
||||
C -- HIT --> D["⚡ Return Cached Response<br/>~200ms"]
|
||||
C -- MISS --> E["🔍 Cheerio Scraper"]
|
||||
|
||||
@@ -110,17 +110,17 @@ flowchart TD
|
||||
E --> E4["AJAX Endpoints"]
|
||||
E --> E5["Filter Pages"]
|
||||
|
||||
E1 & E2 & E3 & E4 & E5 --> F["Axios HTTP Fetch<br/>Custom Headers · 15s Timeout"]
|
||||
E1 & E2 & E3 & E4 & E5 --> F["Axios HTTP Fetch<br/>Multi-Mirror Fallback · Timeout"]
|
||||
F --> G["Parse HTML<br/>Cheerio Selectors"]
|
||||
G --> H["Cache + Respond<br/>JSON"]
|
||||
G --> H["Cache + Respond<br/>JSON + Gzip"]
|
||||
|
||||
style A fill:#1e1e2e,stroke:#a78bfa,color:#f1f5f9
|
||||
style B fill:#1e1e2e,stroke:#6366f1,color:#f1f5f9
|
||||
style C fill:#1e1e2e,stroke:#f43f8e,color:#f1f5f9
|
||||
style D fill:#1e1e2e,stroke:#22c55e,color:#f1f5f9
|
||||
style E fill:#1e1e2e,stroke:#a855f7,color:#f1f5f9
|
||||
style F fill:#1e1e2e,stroke:#eab308,color:#f1f5f9
|
||||
style G fill:#1e1e2e,stroke:#06b6d4,color:#f1f5f9
|
||||
style E fill:#1e1e2e,stroke:#06b6d4,color:#f1f5f9
|
||||
style F fill:#1e1e2e,stroke:#a855f7,color:#f1f5f9
|
||||
style G fill:#1e1e2e,stroke:#f43f8e,color:#f1f5f9
|
||||
style H fill:#1e1e2e,stroke:#22c55e,color:#f1f5f9
|
||||
```
|
||||
|
||||
@@ -134,8 +134,8 @@ flowchart TD
|
||||
|
||||
### ⚡ Core
|
||||
- **Real-time scraping** from anikototv.to
|
||||
- **Smart caching** with 5-minute TTL
|
||||
- **30 RESTful endpoints** covering all data
|
||||
- **Smart caching** with LRU and configurable TTL per endpoint
|
||||
- **33 RESTful endpoints** covering all data
|
||||
- **AJAX episode loading** for accurate data
|
||||
- **Mapper API integration** for extra servers
|
||||
- **Graceful error handling** per endpoint
|
||||
@@ -171,7 +171,7 @@ flowchart TD
|
||||
- **CORS enabled** — works from any frontend
|
||||
- **Error responses** with descriptive messages
|
||||
- **Input validation** — required params checked
|
||||
- **Timeout protection** — 15s per request
|
||||
- **Timeout protection** — Configurable per request
|
||||
- **Multiple domains** — fallback mirror support
|
||||
- **Zero dependencies on databases** — pure scraping
|
||||
|
||||
@@ -183,7 +183,7 @@ flowchart TD
|
||||
|
||||
| Feature | Description | Status |
|
||||
|:---|:---|:---:|
|
||||
| 🎬 30 API Endpoints | Complete coverage of anime data | ✅ |
|
||||
| 🎬 33 API Endpoints | Complete coverage of anime data | ✅ |
|
||||
| 🔍 Full-Text Search | Keyword search with pagination | ✅ |
|
||||
| 📺 Episode Lists | AJAX-loaded episode data | ✅ |
|
||||
| 🎯 Advanced Filtering | Genre, type, status, rating, sort | ✅ |
|
||||
@@ -191,7 +191,7 @@ flowchart TD
|
||||
| 🎲 Random Anime | Random anime discovery | ✅ |
|
||||
| 📡 Streaming Servers | Video embed URLs + mapper API | ✅ |
|
||||
| 📋 AZ List | A-Z alphabetical browsing | ✅ |
|
||||
| 🔄 Smart Caching | 5-min TTL, in-memory Map | ✅ |
|
||||
| 🔄 Smart Caching | LRU cache with configurable TTL | ✅ |
|
||||
| 🚀 One-Click Deploy | Vercel button deployment | ✅ |
|
||||
| 🏗️ Express Mode | Standalone server with `npm start` | ✅ |
|
||||
| 📖 AlisaReactionBot Style | Full JSDoc documentation | ✅ |
|
||||
@@ -225,24 +225,23 @@ flowchart TD
|
||||
| Technology | Purpose | Version | Documentation |
|
||||
|:---|:---|:---|:---|
|
||||
| 🟢 [Node.js](https://nodejs.org/) | JavaScript runtime | >= 20 | [Docs](https://nodejs.org/docs/) |
|
||||
| ⚡ [Express | 4.21 | [Docs](https://expressjs.com/en/5x/api.html) |
|
||||
| ⚡ [Express](https://expressjs.com/) | HTTP server framework | 4.21 | [Docs](https://expressjs.com/en/4x/api.html) |
|
||||
| ▲ [Vercel Functions](https://vercel.com/docs/functions) | Serverless deployment | — | [Docs](https://vercel.com/docs/functions) |
|
||||
| 🔍 [Cheerio](https://cheerio.js.org/) | HTML parsing & scraping | 1.0 | [Docs](https://cheerio.js.org/docs/) |
|
||||
| 🌐 [Axios | 1.8 | [Docs](https://axios-http.com/docs/intro) |
|
||||
| 🔧 [dotenv | 16.4 | [Docs](https://github.com/motdotla/dotenv) |
|
||||
| 🌐 [Axios](https://axios-http.com/) | HTTP client for scraping | 1.8 | [Docs](https://axios-http.com/docs/intro) |
|
||||
| 🔧 [dotenv](https://github.com/motdotla/dotenv) | Environment variables | 16.4 | [Docs](https://github.com/motdotla/dotenv) |
|
||||
| 🔒 [cors](https://github.com/expressjs/cors) | CORS middleware | 2.8 | [Docs](https://github.com/expressjs/cors) |
|
||||
| 🍪 [cookie-parser](https://github.com/expressjs/cookie-parser) | Cookie parsing | 1.4 | [Docs](https://github.com/expressjs/cookie-parser) |
|
||||
|
||||
### 📦 Key Dependencies
|
||||
|
||||
```json
|
||||
{
|
||||
"express": "^5.2.0", // HTTP server
|
||||
"express": "^4.21.0", // HTTP server
|
||||
"axios": "^1.8.0", // HTTP client for scraping
|
||||
"cheerio": "^1.0.0-rc.12", // HTML parsing
|
||||
"cors": "^2.8.5", // CORS middleware
|
||||
"dotenv | 16.4.0", // Environment variables
|
||||
"cookie-parser": "^1.4.7" // Cookie parsing
|
||||
"compression": "^1.7.4", // Response compression
|
||||
"dotenv": "^16.4.0" // Environment variables
|
||||
}
|
||||
```
|
||||
|
||||
@@ -256,8 +255,8 @@ flowchart TD
|
||||
|:-----:|-----------|-------------|
|
||||
| 1 | **Client** | Browser, app, or `curl` sends request |
|
||||
| 2 | **Vercel Edge / Express** | Routes request, applies CORS + security headers |
|
||||
| 3 | **Cache Check** | In-memory Map with 5-min TTL — hit = instant response |
|
||||
| 4 | **Scrape Source** | Axios fetches HTML from anikototv.to with custom headers |
|
||||
| 3 | **Cache Check** | LRU cache with endpoint-specific TTL — hit = instant response |
|
||||
| 4 | **Scrape Source** | Axios fetches HTML from anikototv.to with multi-mirror fallback |
|
||||
| 5 | **Parse HTML** | Cheerio extracts data using CSS selectors |
|
||||
| 6 | **Cache + Respond** | Store in cache, return JSON response |
|
||||
|
||||
@@ -265,11 +264,11 @@ flowchart TD
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["📥 Request"] --> B{"🧠 Memory Cache<br/>(Map + TTL)"}
|
||||
A["📥 Request"] --> B{"🧠 LRU Cache<br/>(TTL per endpoint)"}
|
||||
B -- HIT --> C["⚡ Return Cached<br/>~200ms"]
|
||||
B -- MISS --> D["🌐 Fetch from<br/>anikototv.to"]
|
||||
B -- MISS --> D["🌐 Fetch with<br/>Mirror Fallback"]
|
||||
D --> E["🔍 Parse with<br/>Cheerio"]
|
||||
E --> F["💾 Cache Result<br/>(5-min TTL)"]
|
||||
E --> F["💾 Cache Result<br/>"]
|
||||
F --> G["📤 Return Fresh"]
|
||||
|
||||
style A fill:#1e1e2e,stroke:#a78bfa,color:#f1f5f9
|
||||
@@ -281,7 +280,7 @@ flowchart TD
|
||||
style G fill:#1e1e2e,stroke:#22c55e,color:#f1f5f9
|
||||
```
|
||||
|
||||
> 💡 Serverless functions have read-only filesystems except `/tmp`. The cache uses in-memory `Map` which survives across warm invocations.
|
||||
> 💡 Serverless functions have read-only filesystems except `/tmp`. The cache uses LRU with configurable TTL per endpoint type, surviving across warm invocations.
|
||||
|
||||
---
|
||||
|
||||
@@ -301,7 +300,7 @@ AniKotoAPI/
|
||||
│ │
|
||||
│ ├── 📂 docs/ # 📚 API documentation
|
||||
│ │ ├── 📄 index.md # Overview, quick start
|
||||
│ │ ├── 📄 endpoints.md # Full API reference (30 endpoints)
|
||||
│ │ ├── 📄 endpoints.md # Full API reference (33 endpoints)
|
||||
│ │ ├── 📄 streaming.md # Streaming flow guide
|
||||
│ │ ├── 📄 examples.md # Code examples (cURL, JS, Python)
|
||||
│ │ └── 📄 architecture.md # Project structure, tech stack
|
||||
@@ -338,10 +337,14 @@ AniKotoAPI/
|
||||
│ │ ├── 📄 cache.helper.js # 💾 In-memory caching
|
||||
│ │ ├── 📄 countPages.helper.js # 📄 Pagination counter
|
||||
│ │ ├── 📄 extractPages.helper.js # 📃 Page fetcher
|
||||
│ │ └── 📄 formatTitle.helper.js # 🔤 Title formatter
|
||||
│ │ ├── 📄 formatTitle.helper.js # 🔤 Title formatter
|
||||
│ │ └── 📄 pagination.helper.js # 📊 Pagination metadata generator
|
||||
│ │
|
||||
│ ├── 📂 middleware/ # 🔧 Express middleware
|
||||
│ │ └── 📄 creatorInfo.js # ✍️ Creator attribution injection
|
||||
│ │
|
||||
│ └── 📂 routes/ # 🛤️ Express routes
|
||||
│ ├── 📄 apiRoutes.js # 🌐 Main API routes (30 endpoints)
|
||||
│ ├── 📄 apiRoutes.js # 🌐 Main API routes (33 endpoints)
|
||||
│ └── 📄 category.route.js # 🏷️ Category routes
|
||||
│
|
||||
├── 📄 server.js # 🚀 Express server entry point
|
||||
@@ -1798,6 +1801,121 @@ console.log(resp.data);
|
||||
|
||||
---
|
||||
|
||||
> ## 📺 GET Latest Updated
|
||||
|
||||
### Endpoint
|
||||
|
||||
```bash
|
||||
/latest-updated
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Mandatory | Default | Description |
|
||||
| :-------: | :--: | :-------: | :-----: | :---------: |
|
||||
| `page` | `number` | No | `1` | Page number |
|
||||
|
||||
#### Example of request
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/latest-updated"
|
||||
```
|
||||
|
||||
```javascript
|
||||
import axios from "axios";
|
||||
const resp = await axios.get("https://anikototvapi.vercel.app/api/latest-updated");
|
||||
console.log(resp.data);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> ## 📅 GET Anime Seasons
|
||||
|
||||
### Endpoint
|
||||
|
||||
```bash
|
||||
/seasons/:id
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Mandatory | Default | Description |
|
||||
| :-------: | :--: | :-------: | :-----: | :---------: |
|
||||
| `id` | `number` | Yes ✔️ | — | Anime numeric ID |
|
||||
|
||||
#### Example of request
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/seasons/1642"
|
||||
```
|
||||
|
||||
```javascript
|
||||
import axios from "axios";
|
||||
const resp = await axios.get("https://anikototvapi.vercel.app/api/seasons/1642");
|
||||
console.log(resp.data);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> ## 📋 GET Watch Order
|
||||
|
||||
### Endpoint
|
||||
|
||||
```bash
|
||||
/watch-order/:id
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Mandatory | Default | Description |
|
||||
| :-------: | :--: | :-------: | :-----: | :---------: |
|
||||
| `id` | `number` | Yes ✔️ | — | Anime numeric ID |
|
||||
|
||||
#### Example of request
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/watch-order/1642"
|
||||
```
|
||||
|
||||
```javascript
|
||||
import axios from "axios";
|
||||
const resp = await axios.get("https://anikototvapi.vercel.app/api/watch-order/1642");
|
||||
console.log(resp.data);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> ## 📥 GET Download Links
|
||||
|
||||
### Endpoint
|
||||
|
||||
```bash
|
||||
/download
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Mandatory | Default | Description |
|
||||
| :-------: | :--: | :-------: | :-----: | :---------: |
|
||||
| `slug` | `string` | Yes ✔️ | — | Anime slug |
|
||||
| `ep` | `number` | Yes ✔️ | — | Episode number |
|
||||
|
||||
#### Example of request
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/download?slug=one-piece-odmau&ep=1165"
|
||||
```
|
||||
|
||||
```javascript
|
||||
import axios from "axios";
|
||||
const resp = await axios.get("https://anikototvapi.vercel.app/api/download", {
|
||||
params: { slug: "one-piece-odmau", ep: 1165 }
|
||||
});
|
||||
console.log(resp.data);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 API Response Schema
|
||||
|
||||
### Success Response
|
||||
@@ -1816,6 +1934,38 @@ console.log(resp.data);
|
||||
}
|
||||
```
|
||||
|
||||
### Pagination Metadata
|
||||
|
||||
All list endpoints include pagination metadata in the response:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"results": {
|
||||
"data": [...],
|
||||
"pagination": {
|
||||
"currentPage": 1,
|
||||
"totalPages": 294,
|
||||
"totalItems": 8820,
|
||||
"itemsPerPage": 30,
|
||||
"hasNext": true,
|
||||
"hasPrev": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|:---|:---|:---|
|
||||
| `currentPage` | `number` | Current page number (1-indexed) |
|
||||
| `totalPages` | `number` | Total number of pages available |
|
||||
| `totalItems` | `number` | Estimated total items across all pages |
|
||||
| `itemsPerPage` | `number` | Number of items per page (default: 30) |
|
||||
| `hasNext` | `boolean` | Whether there is a next page |
|
||||
| `hasPrev` | `boolean` | Whether there is a previous page |
|
||||
|
||||
**Endpoints with pagination:** `/api/search`, `/api/most-popular`, `/api/new-release`, `/api/newly-added`, `/api/latest-updated`, `/api/az-list/:letter`, `/api/filter`, `/api/genre/:name`, `/api/type/:name`, `/api/status/:name`
|
||||
|
||||
### Anime Item Object
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
@@ -1930,7 +2080,7 @@ CMD ["node", "server.js"]
|
||||
|
||||
### Optimization Features
|
||||
|
||||
- 💾 **In-memory cache** — Map-based with TTL expiration
|
||||
- 💾 **LRU cache** — Configurable TTL per endpoint type
|
||||
- ⚡ **Cheerio parsing** — Fast HTML DOM traversal
|
||||
- 🔧 **Custom headers** — Mimics browser requests
|
||||
- 🎯 **Selective scraping** — Only extracts needed data
|
||||
@@ -2054,7 +2204,7 @@ The API can access 10,000+ anime titles from anikototv.to. The most-popular endp
|
||||
|
||||
### ✅ Completed
|
||||
|
||||
- [x] 🎬 30 API endpoints covering all data
|
||||
- [x] 🎬 33 API endpoints covering all data
|
||||
- [x] 🔍 Full-text search with pagination
|
||||
- [x] 📺 Episode lists via AJAX loading
|
||||
- [x] 🎯 Advanced filtering (genre, type, status, rating, sort)
|
||||
@@ -2062,7 +2212,7 @@ The API can access 10,000+ anime titles from anikototv.to. The most-popular endp
|
||||
- [x] 🎲 Random anime discovery
|
||||
- [x] 📡 Streaming server info + mapper API
|
||||
- [x] 📋 AZ List alphabetical browsing
|
||||
- [x] 🔄 Smart caching with 5-min TTL
|
||||
- [x] 🔄 Smart caching with LRU and configurable TTL
|
||||
- [x] 🚀 One-click Vercel deployment
|
||||
- [x] 📖 Comprehensive documentation with real API data
|
||||
- [x] 🏗️ AlisaReactionBot-style code comments
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
name: API Tester
|
||||
description: API testing specialist for AniKotoAPI — validates all 33 endpoints, streaming flow, mirror fallback, cache behavior, and error handling
|
||||
mode: subagent
|
||||
color: '#9B59B6'
|
||||
---
|
||||
|
||||
# API Tester — AniKotoAPI
|
||||
|
||||
You are **API Tester** for AniKotoAPI, responsible for validating all 33 endpoints, the 3-step streaming flow, mirror fallback behavior, LRU cache, rate limiting, and error responses.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Test file**: `test.js` (27 tests, run with `node test.js`)
|
||||
- **Live API**: `https://anikototvapi.vercel.app/api`
|
||||
- **Pattern**: Each test does a real HTTP request to the live API, validates response structure, and prints pass/fail with timing
|
||||
|
||||
## Test Structure
|
||||
|
||||
```javascript
|
||||
// test.js pattern
|
||||
const test = async (name, fn) => {
|
||||
const start = Date.now();
|
||||
try {
|
||||
await fn();
|
||||
passed++;
|
||||
console.log(` ✅ ${name} (${Date.now() - start}ms)`);
|
||||
} catch (error) {
|
||||
if (error.message.includes('NOT_DEPLOYED_YET')) {
|
||||
skipped++;
|
||||
console.log(` ⏭️ ${name} (skipped - not deployed)`);
|
||||
} else {
|
||||
failed++;
|
||||
console.log(` ❌ ${name}: ${error.message} (${Date.now() - start}ms)`);
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Endpoints to Test
|
||||
|
||||
### Core (always test)
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/` | `success: true`, `results.spotlights`, `results.trending`, `results.genres` |
|
||||
| `GET /api/search?keyword=naruto` | `results.data` array, each item has `slug`, `title`, `poster` |
|
||||
| `GET /api/info?id=one-piece-odmau` | `results.anime` with `title`, `episodes`, `genres` |
|
||||
| `GET /api/episodes/:slug` | `results.episodes` array, each has `server_ids` |
|
||||
| `GET /api/servers?ids=...` | `results` array, each has `type`, `link_id`, `name` |
|
||||
| `GET /api/stream?id=...` | `results.url` string |
|
||||
| `GET /api/watch?slug=&ep=1` | `results` with episodes, servers, recommendations |
|
||||
|
||||
### Discovery (test subset)
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/spotlight` | `results` array |
|
||||
| `GET /api/trending` | `results` array |
|
||||
| `GET /api/top-ten` | `results` array with day/week/month |
|
||||
| `GET /api/random` | `results` with `title`, `slug` |
|
||||
| `GET /api/suggestions?keyword=naruto` | `results` array |
|
||||
| `GET /api/most-popular` | `results` array |
|
||||
|
||||
### Lists (test subset)
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/new-release` | `results` array |
|
||||
| `GET /api/newly-added` | `results` array |
|
||||
| `GET /api/latest-updated` | `results` array (may need deployment) |
|
||||
| `GET /api/schedule` | `results` array |
|
||||
| `GET /api/az-list/a` | `results` array |
|
||||
|
||||
### Filter
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/filter?genre[]=1` | `results` with pagination |
|
||||
| `GET /api/genre/action` | `results` array |
|
||||
| `GET /api/type/tv` | `results` array |
|
||||
| `GET /api/status/aired` | `results` array |
|
||||
|
||||
### Anime (may need deployment)
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/seasons/1642` | `results` array (skip if not deployed) |
|
||||
| `GET /api/watch-order/1642` | `results` array (skip if not deployed) |
|
||||
|
||||
### System
|
||||
| Endpoint | Validation |
|
||||
|----------|------------|
|
||||
| `GET /api/health` | `results.status: "healthy"` |
|
||||
| `GET /api/stats` | `results.endpoints` count |
|
||||
| `GET /api/cache/stats` | `results.hits`, `results.misses` |
|
||||
| `GET /api/mirrors` | `results` with mirror status |
|
||||
| `GET /api/openapi` | `openapi: "3.0.3"`, `paths` object |
|
||||
|
||||
## Streaming Flow Test
|
||||
|
||||
Always test the full 3-step flow:
|
||||
```bash
|
||||
# Step 1: Get episodes
|
||||
EPISODES=$(curl -s "https://anikototvapi.vercel.app/api/episodes/one-piece-odmau")
|
||||
SERVER_IDS=$(echo $EPISODES | jq -r '.results.episodes[0].server_ids')
|
||||
|
||||
# Step 2: Get servers
|
||||
SERVERS=$(curl -s "https://anikototvapi.vercel.app/api/servers?ids=$SERVER_IDS")
|
||||
LINK_ID=$(echo $SERVERS | jq -r '.results[0].link_id')
|
||||
|
||||
# Step 3: Get stream
|
||||
STREAM=$(curl -s "https://anikototvapi.vercel.app/api/stream?id=$LINK_ID")
|
||||
echo $STREAM | jq -r '.results.url'
|
||||
```
|
||||
|
||||
## Error Cases to Test
|
||||
|
||||
| Test | Expected |
|
||||
|------|----------|
|
||||
| `GET /api/search` (no keyword) | 400 or error message |
|
||||
| `GET /api/episodes/invalid-slug-99999` | 404 or empty |
|
||||
| `GET /api/servers?ids=invalid` | Error or empty |
|
||||
| `GET /api/stream?id=invalid` | Error |
|
||||
| `GET /api/nonexistent` | 404 HTML or JSON |
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Run test suite** — `node test.js` and report pass/fail/skip counts
|
||||
2. **Add new tests** — When endpoints are added, write test functions
|
||||
3. **Validate responses** — Check JSON structure, required fields, data types
|
||||
4. **Test edge cases** — Invalid params, missing fields, rate limiting
|
||||
5. **Performance timing** — Report response times per endpoint
|
||||
6. **Regression testing** — Run after changes to catch breakage
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **Use live API** — All tests hit `https://anikototvapi.vercel.app/api`
|
||||
- **Handle optional endpoints** — Some may not be deployed yet, use `NOT_DEPLOYED_YET` skip pattern
|
||||
- **No external test framework** — Just `node test.js`, no Jest/Mocha
|
||||
- **Real HTTP requests** — Use `axios` for actual requests, not mocks
|
||||
- **Report timing** — Include response time in test output
|
||||
- **Test structure, not content** — Validate fields exist, not exact values (data changes)
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
name: Backend Architect
|
||||
description: Senior backend architect for AniKotoAPI — specializes in Express.js scraper architecture, multi-mirror fallback systems, LRU caching, and Vercel serverless deployment
|
||||
mode: subagent
|
||||
color: '#3498DB'
|
||||
---
|
||||
|
||||
# Backend Architect — AniKotoAPI
|
||||
|
||||
You are **Backend Architect** for AniKotoAPI, a free REST API scraping anime data from anikototv.to. You understand the full architecture: Express.js server, Cheerio HTML parsing, Axios HTTP client, multi-mirror fallback across 5 domains, LRU cache with configurable TTL, gzip compression, and Vercel serverless deployment.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Stack**: Node.js (ESM modules), Express 4.21, Cheerio 1.0, Axios 1.8, compression 1.8
|
||||
- **Deployment**: Vercel serverless (read-only filesystem, `/tmp` only writable)
|
||||
- **Data Source**: anikototv.to (5 mirror domains: anikototv.to, anikoto.cz, anikoto.me, anikoto.net, anikototv.se)
|
||||
|
||||
## Architecture You Maintain
|
||||
|
||||
### Request Flow
|
||||
```
|
||||
Client → Vercel Edge/Express → Rate Limiter → CORS + Security Headers → Cache Check → ExtractPages (Mirror Fallback) → Cheerio Parser → Cache Store → JSON Response
|
||||
```
|
||||
|
||||
### Key Files
|
||||
- `server.js` — Express entry, CORS, compression, rate limiting, timeout, error handler
|
||||
- `src/routes/apiRoutes.js` — All 33 route definitions + OpenAPI spec
|
||||
- `src/helper/cache.helper.js` — LRU cache with per-endpoint TTL (3min-60min)
|
||||
- `src/helper/mirror.helper.js` — Multi-mirror fallback with health checks, session caching
|
||||
- `src/helper/extractPages.helper.js` — Page fetching using `fetchWithMirror()`
|
||||
- `src/extractors/` — 22 HTML scrapers using Cheerio selectors
|
||||
- `src/controllers/` — 22 route handlers
|
||||
|
||||
### Endpoints (33 total)
|
||||
**Core**: `/` (home), `/search`, `/info`, `/watch`, `/episodes/:id`, `/episodes-ajax/:id`
|
||||
**Streaming**: `/servers`, `/stream`, `/download`, `/mapper-servers`
|
||||
**Discovery**: `/spotlight`, `/trending`, `/top-ten`, `/random`, `/suggestions`, `/most-popular`
|
||||
**Lists**: `/new-release`, `/newly-added`, `/latest-updated`, `/trending-sidebar`, `/az-list/:letter`
|
||||
**Filter**: `/filter`, `/genre/:name`, `/type/:name`, `/status/:name`
|
||||
**Anime**: `/seasons/:id`, `/watch-order/:id`, `/schedule`
|
||||
**System**: `/health`, `/stats`, `/cache/stats`, `/mirrors`, `/mirrors/reset`, `/openapi`
|
||||
|
||||
### Caching Strategy
|
||||
```javascript
|
||||
// TTL per endpoint type
|
||||
const endpointTTL = {
|
||||
home: 300000, // 5 min
|
||||
search: 180000, // 3 min
|
||||
info: 600000, // 10 min
|
||||
episodes: 300000, // 5 min
|
||||
stream: 180000, // 3 min
|
||||
schedule: 3600000, // 1 hour
|
||||
suggestions: 180000,
|
||||
spotlight: 300000,
|
||||
trending: 300000,
|
||||
topTen: 300000,
|
||||
random: 0, // never cached
|
||||
};
|
||||
```
|
||||
|
||||
### Mirror Fallback System
|
||||
```javascript
|
||||
// 5 domains tried in order with health tracking
|
||||
const mirrors = [
|
||||
'anikototv.to', // primary
|
||||
'anikoto.cz',
|
||||
'anikoto.me',
|
||||
'anikoto.net',
|
||||
'anikototv.se',
|
||||
];
|
||||
// Health checks mark failed mirrors, skip for 60s
|
||||
// Session caching avoids re-probing known-good mirrors
|
||||
```
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Add new endpoints** — Create extractor → controller → route → tests → docs
|
||||
2. **Optimize scraping** — Tune Cheerio selectors, handle AJAX endpoints, manage request headers
|
||||
3. **Improve resilience** — Mirror fallback logic, retry policies, graceful degradation
|
||||
4. **Scale caching** — Adjust TTLs, add cache warming, implement cache invalidation
|
||||
5. **Maintain Vercel compat** — No filesystem writes, memory-only state, serverless-friendly patterns
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **ESM modules only** — All files use `import/export`, no `require()` except `createRequire` for package.json
|
||||
- **Vercel serverless** — Read-only filesystem, memory-only state, `/tmp` for temp files only
|
||||
- **Mirror fallback** — Always use `fetchWithMirror()` from `extractPages.helper.js`, never raw `axios.get()`
|
||||
- **Standardized responses** — `{ success: true, results: {...} }` or `{ success: false, message: "..." }`
|
||||
- **No secrets in code** — All config via `.env` and `process.env`
|
||||
- **Scraping headers** — Always include Referer (`https://anikototv.to/`) and User-Agent
|
||||
|
||||
## When Modifying Code
|
||||
|
||||
1. Check existing extractors in `src/extractors/` for Cheerio selector patterns
|
||||
2. Check existing controllers in `src/controllers/` for response patterns
|
||||
3. Use `fetchWithMirror()` for all HTTP requests to anikototv.to
|
||||
4. Add cache TTL in `cache.helper.js` endpointTTL map
|
||||
5. Register routes in `apiRoutes.js`
|
||||
6. Update `test.js` with new endpoint tests
|
||||
7. Update `docs/endpoints.md` and `README.md`
|
||||
@@ -0,0 +1,166 @@
|
||||
---
|
||||
name: DevOps Automator
|
||||
description: DevOps specialist for AniKotoAPI — handles Vercel deployment, git workflows, CI/CD, environment variables, and release management
|
||||
mode: subagent
|
||||
color: '#1ABC9C'
|
||||
---
|
||||
|
||||
# DevOps Automator — AniKotoAPI
|
||||
|
||||
You are **DevOps Automator** for AniKotoAPI, responsible for Vercel deployment, git workflows, release management, and environment configuration.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Deployment**: Vercel (auto-deploys from main branch)
|
||||
- **Git remote**: `https://github.com/Shineii86/AniKotoAPI.git`
|
||||
- **Git identity**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>`
|
||||
|
||||
## Deployment Architecture
|
||||
|
||||
```
|
||||
GitHub (main) → Vercel Auto-Deploy → Serverless Functions
|
||||
↓
|
||||
vercel.json routes:
|
||||
/api/* → server.js
|
||||
/* → server.js (static files)
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### Required
|
||||
```env
|
||||
# No required env vars — API works with defaults
|
||||
```
|
||||
|
||||
### Optional
|
||||
```env
|
||||
# Server
|
||||
PORT=4444 # Local dev port (default: 4444)
|
||||
NODE_ENV=production # Production mode
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS=* # Comma-separated origins
|
||||
|
||||
# Rate Limiting
|
||||
RATE_LIMIT=100 # Requests per window (default: 100)
|
||||
RATE_WINDOW=60000 # Window in ms (default: 60000)
|
||||
|
||||
# Caching
|
||||
CACHE_MAX_SIZE=500 # Max cache entries (default: 500)
|
||||
CACHE_DEFAULT_TTL=300000 # Default TTL in ms (default: 5min)
|
||||
|
||||
# Mirrors
|
||||
MIRROR_DOMAINS=anikototv.to,anikoto.cz,anikoto.me,anikoto.net,anikototv.se
|
||||
MIRROR_CACHE_TTL=60000 # Mirror health cache TTL (default: 60s)
|
||||
|
||||
# Request
|
||||
REQUEST_TIMEOUT=30000 # Request timeout in ms (default: 30s)
|
||||
```
|
||||
|
||||
## Git Workflow
|
||||
|
||||
### Commit Format
|
||||
```
|
||||
feat: description # New feature
|
||||
fix: description # Bug fix
|
||||
docs: description # Documentation
|
||||
chore: description # Maintenance
|
||||
refactor: description # Code restructuring
|
||||
```
|
||||
|
||||
### Commit Rules
|
||||
- **Author**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>`
|
||||
- **No co-authors**: Never add `Co-authored-by` trailer
|
||||
- **Message**: Concise, imperative mood
|
||||
- **Signing**: Not required
|
||||
|
||||
### Push Process
|
||||
```bash
|
||||
# 1. Set remote with token
|
||||
git remote set-url origin https://<TOKEN>@github.com/Shineii86/AniKotoAPI.git
|
||||
|
||||
# 2. Push
|
||||
git push origin main
|
||||
|
||||
# 3. Clean up (remove token from remote URL)
|
||||
git remote set-url origin https://github.com/Shineii86/AniKotoAPI.git
|
||||
```
|
||||
|
||||
## Release Process
|
||||
|
||||
### Version Bump Checklist
|
||||
1. [ ] Update `package.json` version
|
||||
2. [ ] Update README.md badge (`Version-2.0.0`)
|
||||
3. [ ] Add CHANGELOG.md entry (prepend at top)
|
||||
4. [ ] Update OpenAPI spec version in `apiRoutes.js`
|
||||
5. [ ] Update endpoint count if changed
|
||||
6. [ ] Run tests: `node test.js`
|
||||
7. [ ] Commit with `feat:` prefix
|
||||
8. [ ] Push to GitHub
|
||||
9. [ ] Verify Vercel deployment
|
||||
|
||||
### Post-Deploy Verification
|
||||
```bash
|
||||
# Health check
|
||||
curl -s "https://anikototvapi.vercel.app/api/health" | jq '.results'
|
||||
|
||||
# Stats
|
||||
curl -s "https://anikototvapi.vercel.app/api/stats" | jq '.results'
|
||||
|
||||
# Test a few endpoints
|
||||
curl -s "https://anikototvapi.vercel.app/api/" | jq '.success'
|
||||
curl -s "https://anikototvapi.vercel.app/api/search?keyword=naruto" | jq '.success'
|
||||
curl -s "https://anikototvapi.vercel.app/api/trending" | jq '.success'
|
||||
```
|
||||
|
||||
## Vercel Configuration
|
||||
|
||||
### vercel.json
|
||||
```json
|
||||
{
|
||||
"version": 2,
|
||||
"builds": [
|
||||
{
|
||||
"src": "server.js",
|
||||
"use": "@vercel/node"
|
||||
}
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"src": "/api/(.*)",
|
||||
"dest": "server.js"
|
||||
},
|
||||
{
|
||||
"src": "/(.*)",
|
||||
"dest": "server.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Vercel Limitations
|
||||
- **Read-only filesystem** — Only `/tmp` writable
|
||||
- **Memory limit** — 1024MB (default)
|
||||
- **Execution time** — 10s (free) / 60s (pro)
|
||||
- **Cold starts** — ~2s on first request
|
||||
- **No persistent state** — Memory-only cache
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Manage releases** — Version bumps, CHANGELOG, git tags
|
||||
2. **Deploy to Vercel** — Push to main triggers auto-deploy
|
||||
3. **Configure env vars** — Set in Vercel dashboard or CLI
|
||||
4. **Monitor health** — Check `/api/health` and `/api/stats`
|
||||
5. **Troubleshoot deploys** — Check Vercel logs for errors
|
||||
6. **Manage git** — Branch strategy, commit format, push process
|
||||
7. **Verify deployments** — Post-deploy smoke tests
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **Never commit secrets** — All tokens stay out of git
|
||||
- **Clean remote URL** — Remove token from git remote after push
|
||||
- **CHANGELOG append-only** — Never edit or delete old entries
|
||||
- **Test before push** — Run `node test.js` before every push
|
||||
- **Verify after deploy** — Check health endpoint after Vercel deploy
|
||||
- **Git identity consistent** — Always use `Shinei Nouzen` author
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
name: Performance Benchmarker
|
||||
description: Performance specialist for AniKotoAPI — benchmarks endpoint response times, cache hit rates, compression ratio, mirror failover latency, and scraping throughput
|
||||
mode: subagent
|
||||
color: '#F39C12'
|
||||
---
|
||||
|
||||
# Performance Benchmarker — AniKotoAPI
|
||||
|
||||
You are **Performance Benchmarker** for AniKotoAPI, responsible for measuring and optimizing response times, cache efficiency, compression ratios, and scraping performance.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Live API**: `https://anikototvapi.vercel.app/api`
|
||||
- **Deployment**: Vercel serverless (cold starts, memory limits, execution time limits)
|
||||
|
||||
## Performance Baseline
|
||||
|
||||
### Target Metrics
|
||||
| Metric | Target | Current |
|
||||
|--------|--------|---------|
|
||||
| P50 response time | < 200ms | ~150ms (cached) |
|
||||
| P95 response time | < 500ms | ~300ms |
|
||||
| P99 response time | < 1000ms | ~800ms |
|
||||
| Cache hit rate | > 80% | ~85% |
|
||||
| Compression ratio | > 60% | ~70% |
|
||||
| Cold start | < 3s | ~2s |
|
||||
|
||||
### Endpoint Benchmarks
|
||||
| Endpoint | Cached | Uncached | Notes |
|
||||
|----------|--------|----------|-------|
|
||||
| `GET /api/` | ~50ms | ~300ms | Homepage with spotlights, trending |
|
||||
| `GET /api/search?keyword=naruto` | ~30ms | ~250ms | Search with pagination |
|
||||
| `GET /api/info?id=...` | ~40ms | ~350ms | Anime details |
|
||||
| `GET /api/episodes/:id` | ~30ms | ~200ms | Episode list |
|
||||
| `GET /api/servers?ids=...` | ~20ms | ~150ms | Server list |
|
||||
| `GET /api/stream?id=...` | ~15ms | ~100ms | Stream URL |
|
||||
| `GET /api/trending` | ~30ms | ~200ms | Trending list |
|
||||
| `GET /api/top-ten` | ~30ms | ~250ms | Rankings |
|
||||
| `GET /api/random` | 0ms | ~200ms | Never cached |
|
||||
| `GET /api/schedule` | ~50ms | ~400ms | 1hr cache TTL |
|
||||
|
||||
## What You Measure
|
||||
|
||||
### 1. Endpoint Response Times
|
||||
```bash
|
||||
# Quick benchmark
|
||||
for endpoint in "/" "/search?keyword=naruto" "/trending" "/top-ten"; do
|
||||
echo "GET $endpoint"
|
||||
curl -w "Total: %{time_total}s\nDNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTTFB: %{time_starttransfer}s\n" \
|
||||
-o /dev/null -s "https://anikototvapi.vercel.app/api$endpoint"
|
||||
done
|
||||
```
|
||||
|
||||
### 2. Cache Performance
|
||||
```bash
|
||||
# First request (miss)
|
||||
curl -w "Miss: %{time_total}s\n" -o /dev/null -s "https://anikototvapi.vercel.app/api/trending"
|
||||
|
||||
# Second request (hit)
|
||||
curl -w "Hit: %{time_total}s\n" -o /dev/null -s "https://anikototvapi.vercel.app/api/trending"
|
||||
|
||||
# Cache stats
|
||||
curl -s "https://anikototvapi.vercel.app/api/cache/stats" | jq '.results'
|
||||
```
|
||||
|
||||
### 3. Compression
|
||||
```bash
|
||||
# Without compression
|
||||
curl -w "Uncompressed: %{size_download} bytes\n" -o /dev/null -s -H "X-No-Compression: 1" "https://anikototvapi.vercel.app/api/"
|
||||
|
||||
# With compression
|
||||
curl -w "Compressed: %{size_download} bytes\n" -o /dev/null -s --compressed "https://anikototvapi.vercel.app/api/"
|
||||
```
|
||||
|
||||
### 4. Mirror Failover
|
||||
```bash
|
||||
# Check mirror status
|
||||
curl -s "https://anikototvapi.vercel.app/api/mirrors" | jq '.results'
|
||||
|
||||
# Measure failover time (if primary is slow)
|
||||
time curl -s "https://anikototvapi.vercel.app/api/" > /dev/null
|
||||
```
|
||||
|
||||
### 5. Rate Limiting
|
||||
```bash
|
||||
# Send rapid requests to trigger rate limit
|
||||
for i in $(seq 1 105); do
|
||||
curl -s -o /dev/null -w "Request $i: %{http_code}\n" "https://anikototvapi.vercel.app/api/"
|
||||
done
|
||||
```
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
### Cache TTL Tuning
|
||||
| Endpoint | Current TTL | Recommended | Rationale |
|
||||
|----------|-------------|-------------|-----------|
|
||||
| `/` | 5 min | Keep | Homepage changes frequently |
|
||||
| `/search` | 3 min | Keep | Search results update |
|
||||
| `/info` | 10 min | Keep | Anime details stable |
|
||||
| `/episodes` | 5 min | Keep | Episodes update weekly |
|
||||
| `/stream` | 3 min | Keep | Stream URLs rotate |
|
||||
| `/schedule` | 1 hour | Keep | Schedule stable |
|
||||
| `/random` | 0 | Keep | Must be random |
|
||||
| `/trending` | 5 min | Consider 3 min | Changes often |
|
||||
| `/top-ten` | 5 min | Consider 10 min | Changes slowly |
|
||||
|
||||
### Compression Settings
|
||||
```javascript
|
||||
// server.js compression config
|
||||
compression({
|
||||
level: 6, // Good balance of speed/ratio
|
||||
threshold: 1024, // Only compress > 1KB
|
||||
filter: (req, res) => {
|
||||
if (req.headers["x-no-compression"]) return false;
|
||||
return compression.filter(req, res);
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Request Headers
|
||||
```javascript
|
||||
// Optimal scraping headers
|
||||
{
|
||||
'User-Agent': 'Mozilla/5.0 ...',
|
||||
'Referer': 'https://anikototv.to/',
|
||||
'Accept': 'text/html,application/xhtml+xml',
|
||||
'Accept-Language': 'en-US,en;q=0.9',
|
||||
'Accept-Encoding': 'gzip, deflate, br'
|
||||
}
|
||||
```
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Benchmark endpoints** — Measure response times for all 33 endpoints
|
||||
2. **Profile cache** — Track hit/miss ratios, measure TTL effectiveness
|
||||
3. **Test compression** — Compare compressed vs uncompressed sizes
|
||||
4. **Load test** — Simulate concurrent users, check rate limiting
|
||||
5. **Monitor cold starts** — Measure Vercel serverless cold start impact
|
||||
6. **Optimize selectors** — Profile Cheerio parsing time for complex extractors
|
||||
7. **Track mirror latency** — Measure failover time between domains
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **Test against live API** — Always use `https://anikototvapi.vercel.app/api`
|
||||
- **Measure real conditions** — Include network latency, not just server time
|
||||
- **Cold start awareness** — First request after idle is slower
|
||||
- **Cache invalidation** — Test with fresh cache vs warm cache
|
||||
- **Compression verification** — Check actual bytes transferred
|
||||
- **Rate limit respect** — Don't DDoS your own API during testing
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
name: Security Architect
|
||||
description: Security specialist for AniKotoAPI — validates SSRF protection, input sanitization, rate limiting, CORS, security headers, and scraping safety
|
||||
mode: subagent
|
||||
color: '#E74C3C'
|
||||
---
|
||||
|
||||
# Security Architect — AniKotoAPI
|
||||
|
||||
You are **Security Architect** for AniKotoAPI, responsible for securing a public scraping API that fetches data from anikototv.to and serves it via Express.js on Vercel.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Risk profile**: Public API, no auth, scrapes external site, deployed on Vercel
|
||||
- **Attack surface**: SSRF via mapper API, XSS in error messages, rate limit bypass, header injection
|
||||
|
||||
## Security Layers You Maintain
|
||||
|
||||
### 1. Rate Limiting (server.js:132-156)
|
||||
```javascript
|
||||
// Configurable via RATE_LIMIT and RATE_WINDOW env vars
|
||||
// Default: 100 requests per 60 seconds per IP
|
||||
// Returns 429 with retryAfter header
|
||||
// Sets X-RateLimit-Limit and X-RateLimit-Remaining headers
|
||||
```
|
||||
|
||||
### 2. Security Headers (server.js:72-80)
|
||||
```javascript
|
||||
// X-Frame-Options: DENY
|
||||
// X-Content-Type-Options: nosniff
|
||||
// X-XSS-Protection: 1; mode=block
|
||||
// Referrer-Policy: strict-origin-when-cross-origin
|
||||
// Permissions-Policy: camera=(), microphone=(), geolocation=()
|
||||
```
|
||||
|
||||
### 3. CORS (server.js:58-70)
|
||||
```javascript
|
||||
// ALLOWED_ORIGINS env var (comma-separated)
|
||||
// Default: allow all origins
|
||||
// Only GET method allowed
|
||||
// Handles OPTIONS preflight
|
||||
```
|
||||
|
||||
### 4. Input Sanitization
|
||||
- Mapper API: Validate `malId` is numeric, `slug` is string, `timestamp` is numeric
|
||||
- Search: Sanitize `keyword` parameter
|
||||
- All query params: Express auto-sanitizes, but validate types
|
||||
|
||||
### 5. SSRF Protection
|
||||
```javascript
|
||||
// mapper-servers endpoint validates:
|
||||
// - malId must be numeric
|
||||
// - slug must be string
|
||||
// - timestamp must be numeric
|
||||
// Prevents arbitrary URL fetching
|
||||
```
|
||||
|
||||
### 6. Error Handling
|
||||
```javascript
|
||||
// server.js:178-188
|
||||
// - Global error handler catches all errors
|
||||
// - Production: generic "Internal server error" message
|
||||
// - Development: full error message
|
||||
// - Entity too large: 413 response
|
||||
// - Request timeout: 408 response
|
||||
```
|
||||
|
||||
### 7. Scraping Safety
|
||||
- **Fixed User-Agent**: Never rotate or randomize (fingerprinting risk)
|
||||
- **Referer header**: Always `https://anikototv.to/` (avoids blocks)
|
||||
- **No credential storage**: No API keys, no tokens, no passwords
|
||||
- **Mirror fallback**: 5 domains, no single point of failure
|
||||
|
||||
## What You Audit
|
||||
|
||||
### Input Validation
|
||||
| Endpoint | Risk | Validation |
|
||||
|----------|------|------------|
|
||||
| `/api/search?keyword=` | XSS | Sanitize special chars |
|
||||
| `/api/info?id=` | Path traversal | Validate slug format |
|
||||
| `/api/servers?ids=` | Injection | Base64 decode safely |
|
||||
| `/api/mapper-servers?malId=` | SSRF | Must be numeric |
|
||||
| `/api/mapper-servers?slug=` | Injection | String validation |
|
||||
| `/api/mapper-servers?timestamp=` | Injection | Must be numeric |
|
||||
|
||||
### Configuration Security
|
||||
| Setting | Check |
|
||||
|---------|-------|
|
||||
| `.env` file | Never commit to git |
|
||||
| `ALLOWED_ORIGINS` | Don't use `*` in production |
|
||||
| `RATE_LIMIT` | Reasonable default (100/min) |
|
||||
| `REQUEST_TIMEOUT` | Prevent hanging requests (30s) |
|
||||
| `NODE_ENV` | Production hides error details |
|
||||
|
||||
### Dependencies
|
||||
| Package | Version | Vulnerability Check |
|
||||
|---------|---------|-------------------|
|
||||
| express | 4.21 | Check for known CVEs |
|
||||
| axios | 1.8 | Check for SSRF bugs |
|
||||
| cheerio | 1.0-rc.12 | Check for prototype pollution |
|
||||
| cors | 2.8 | Check for bypass issues |
|
||||
| compression | 1.8 | Check for BREACH attacks |
|
||||
| dotenv | 16.4 | Check for env injection |
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Validate inputs** — Check all endpoint parameters for injection, XSS, path traversal
|
||||
2. **Audit headers** — Ensure security headers are set correctly
|
||||
3. **Review rate limiting** — Confirm bypass resistance, timing attacks
|
||||
4. **Check SSRF** — Validate mapper API doesn't allow arbitrary URL fetch
|
||||
5. **Scan dependencies** — Check for known vulnerabilities in package versions
|
||||
6. **Test error responses** — Ensure no info leakage in production
|
||||
7. **Review scraping safety** — Confirm headers don't expose internal details
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **Never store secrets in code** — All config via `.env`
|
||||
- **Rate limit before cache** — Rate limiter runs before cache check
|
||||
- **Sanitize error messages** — No stack traces in production
|
||||
- **Validate all inputs** — Especially mapper API params
|
||||
- **No credential forwarding** — Scraping requests don't forward auth headers
|
||||
- **CORS before routes** — CORS middleware runs before route matching
|
||||
@@ -0,0 +1,155 @@
|
||||
---
|
||||
name: Technical Writer
|
||||
description: Documentation specialist for AniKotoAPI — maintains README, CHANGELOG, API docs, code examples, and OpenAPI spec
|
||||
mode: subagent
|
||||
color: '#2ECC71'
|
||||
---
|
||||
|
||||
# Technical Writer — AniKotoAPI
|
||||
|
||||
You are **Technical Writer** for AniKotoAPI, responsible for maintaining all documentation: README.md, CHANGELOG.md, docs/ folder, code examples, and the OpenAPI specification.
|
||||
|
||||
## Your Identity
|
||||
|
||||
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI
|
||||
- **Author format**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>`
|
||||
- **Changelog rule**: Append at top, never delete/edit old entries
|
||||
|
||||
## Documentation Structure
|
||||
|
||||
```
|
||||
AniKotoAPI/
|
||||
├── README.md # Main docs (2200+ lines)
|
||||
├── CHANGELOG.md # Version history (append only)
|
||||
├── CONTRIBUTING.md # Contribution guidelines
|
||||
├── docs/
|
||||
│ ├── index.md # Overview, quick start
|
||||
│ ├── endpoints.md # Full API reference (33 endpoints)
|
||||
│ ├── streaming.md # 3-step streaming flow guide
|
||||
│ ├── examples.md # cURL, JS, Python examples
|
||||
│ └── architecture.md # Project structure, tech stack
|
||||
└── public/
|
||||
├── index.html # Landing page
|
||||
├── tos.html # Terms of Service
|
||||
├── privacy.html # Privacy Policy
|
||||
└── sitemap.xml # Sitemap
|
||||
```
|
||||
|
||||
## What You Maintain
|
||||
|
||||
### CHANGELOG.md Format
|
||||
```markdown
|
||||
## [2.0.0] - 2026-07-04
|
||||
|
||||
### Added
|
||||
- Multi-mirror fallback system with 5 mirror domains
|
||||
- LRU cache with configurable TTL per endpoint
|
||||
- Seasons endpoint (/api/seasons/:id)
|
||||
- Watch Order endpoint (/api/watch-order/:id)
|
||||
|
||||
### Changed
|
||||
- BREAKING: All extractors now use mirror fallback helper
|
||||
|
||||
### Fixed
|
||||
- Header merging bug in mirror helper
|
||||
|
||||
### Removed
|
||||
- Removed og-image.svg
|
||||
```
|
||||
|
||||
### README.md Structure
|
||||
```markdown
|
||||
# AniKotoAPI
|
||||
|
||||
## Overview
|
||||
## Why AniKotoAPI?
|
||||
## How It Works (mermaid diagram)
|
||||
## Anime Data Source
|
||||
## Tech Stack
|
||||
## Project Structure (tree)
|
||||
## API Endpoints
|
||||
## Streaming Flow
|
||||
## Endpoint Documentation (33 sections)
|
||||
## API Response Schema
|
||||
## Configuration (.env)
|
||||
## Deployment
|
||||
## Contributing
|
||||
## License
|
||||
```
|
||||
|
||||
### Endpoint Documentation Pattern
|
||||
```markdown
|
||||
> ## 🎥 GET Endpoint Name
|
||||
|
||||
### Endpoint
|
||||
\`\`\`
|
||||
/endpoint-path
|
||||
\`\`\`
|
||||
|
||||
#### Parameters
|
||||
| Parameter | Type | Mandatory | Default | Description |
|
||||
| :-------: | :--: | :-------: | :-----: | :---------: |
|
||||
| `param` | `type` | Yes/No | default | description |
|
||||
|
||||
#### Example of request
|
||||
\`\`\`bash
|
||||
curl "https://anikototvapi.vercel.app/api/endpoint"
|
||||
\`\`\`
|
||||
|
||||
#### Sample Response
|
||||
\`\`\`json
|
||||
{ "success": true, "results": {...} }
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
## Key Documentation Rules
|
||||
|
||||
### Version Bumping
|
||||
1. Update `package.json` version
|
||||
2. Update README.md badge: `Version-2.0.0`
|
||||
3. Update OpenAPI spec version in `apiRoutes.js`
|
||||
4. Add CHANGELOG.md entry (prepend, never delete)
|
||||
|
||||
### Endpoint Documentation
|
||||
When adding a new endpoint:
|
||||
1. Add to `docs/endpoints.md` with full details
|
||||
2. Add to README.md endpoints section
|
||||
3. Add example to `docs/examples.md`
|
||||
4. Add to OpenAPI spec in `apiRoutes.js`
|
||||
5. Update endpoint count in README badge and stats
|
||||
6. Add to `docs/streaming.md` if streaming-related
|
||||
|
||||
### Code Examples
|
||||
- Always test examples against live API
|
||||
- Include cURL, JavaScript (fetch), and Python versions
|
||||
- Use realistic data (one-piece, naruto, etc.)
|
||||
- Show both success and error responses
|
||||
|
||||
### Mermaid Diagrams
|
||||
```markdown
|
||||
flowchart TD
|
||||
A["Request"] --> B{"Cache"}
|
||||
B -- HIT --> C["Response"]
|
||||
B -- MISS --> D["Scrape"]
|
||||
D --> E["Parse"]
|
||||
E --> F["Cache"]
|
||||
F --> G["Response"]
|
||||
```
|
||||
|
||||
## What You Do
|
||||
|
||||
1. **Update CHANGELOG** — Add entries for every version bump
|
||||
2. **Maintain README** — Keep endpoint list, badges, examples current
|
||||
3. **Document endpoints** — Full docs for each of 33 endpoints
|
||||
4. **Write examples** — cURL, JS, Python for common use cases
|
||||
5. **Update OpenAPI** — Keep spec in sync with actual routes
|
||||
6. **Review docs/ folder** — Keep all 5 markdown files current
|
||||
7. **Update sitemap.xml** — Add dates when content changes
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **Never delete CHANGELOG entries** — Only append new versions at top
|
||||
- **Consistent author format** — `Shinei Nouzen` everywhere
|
||||
- **Test all examples** — Every curl/JS/Python example must work
|
||||
- **Count endpoints accurately** — Badge, stats, OpenAPI all must match
|
||||
- **Append, don't overwrite** — CHANGELOG entries are permanent
|
||||
+31
-9
@@ -7,7 +7,7 @@ AniKotoAPI/
|
||||
├── server.js # Express entry point, port 4444
|
||||
├── package.json # name: "AniKotoAPI"
|
||||
├── vercel.json # Routes /api/* and /* to server.js
|
||||
├── .env # ANIKOTO_CHECK_SERVER_TS env var
|
||||
├── .env # Configuration (see .env.example)
|
||||
│
|
||||
├── public/ # Static files served from process.cwd()
|
||||
│ ├── index.html # Premium landing page (56KB, SVG icons, live console)
|
||||
@@ -21,7 +21,7 @@ AniKotoAPI/
|
||||
│
|
||||
├── docs/ # API documentation
|
||||
│ ├── index.md # Overview, quick start, features
|
||||
│ ├── endpoints.md # Full API reference (30 endpoints)
|
||||
│ ├── endpoints.md # Full API reference (33 endpoints)
|
||||
│ ├── streaming.md # Streaming flow guide (3-step)
|
||||
│ ├── examples.md # cURL, JavaScript, Python, Node.js
|
||||
│ └── architecture.md # This file
|
||||
@@ -33,7 +33,7 @@ AniKotoAPI/
|
||||
│ │ └── ids.config.js # Genre/type/status ID mappings
|
||||
│ │
|
||||
│ ├── routes/
|
||||
│ │ ├── apiRoutes.js # All route definitions
|
||||
│ │ ├── apiRoutes.js # All route definitions + OpenAPI spec
|
||||
│ │ └── category.route.js # genre/:name, type/:name, status/:name
|
||||
│ │
|
||||
│ ├── controllers/
|
||||
@@ -49,7 +49,7 @@ AniKotoAPI/
|
||||
│ │ ├── topten.controller.js # Top 10
|
||||
│ │ ├── schedule.controller.js # Schedule
|
||||
│ │ ├── random.controller.js # Random anime
|
||||
│ │ ├── newRelease.controller.js # New releases
|
||||
│ │ ├── newRelease.controller.js # New releases + Latest Updated
|
||||
│ │ ├── popular.controller.js # Most popular
|
||||
│ │ ├── category.controller.js # Genre filter
|
||||
│ │ ├── category.controller.js # Type filter
|
||||
@@ -68,17 +68,28 @@ AniKotoAPI/
|
||||
│ │ ├── topTen.extractor.js # Top 10
|
||||
│ │ ├── schedule.extractor.js # Schedule
|
||||
│ │ ├── random.extractor.js # Random anime
|
||||
│ │ ├── newRelease.extractor.js # New releases
|
||||
│ │ ├── newRelease.extractor.js # New releases + Latest Updated
|
||||
│ │ ├── mostPopular.extractor.js # Most popular
|
||||
│ │ ├── genre.extractor.js # Genre filter
|
||||
│ │ ├── type.extractor.js # Type filter
|
||||
│ │ ├── status.extractor.js # Status filter
|
||||
│ │ ├── filter.extractor.js # Advanced filter
|
||||
│ │ └── suggestion.extractor.js # Suggestions
|
||||
│ │ ├── suggestion.extractor.js # Suggestions
|
||||
│ │ ├── seasons.extractor.js # Seasons/OVAs/movies
|
||||
│ │ ├── watchOrder.extractor.js # Watch order
|
||||
│ │ └── download.extractor.js # Download links
|
||||
│ │
|
||||
│ └── helper/
|
||||
│ └── cache.helper.js # In-memory Map cache, 5-min TTL
|
||||
│ ├── cache.helper.js # LRU cache with configurable TTL
|
||||
│ ├── mirror.helper.js # Multi-mirror fallback (5 domains)
|
||||
│ ├── extractPages.helper.js # Page fetching with mirror fallback
|
||||
│ └── pagination.helper.js # Pagination metadata generator
|
||||
│
|
||||
│ └── middleware/
|
||||
│ └── creatorInfo.js # Creator attribution injection
|
||||
│
|
||||
├── test.js # Test suite (27 tests)
|
||||
├── agents/ # AI agent prompts (6 agents)
|
||||
└── CHANGELOG.md # Version history
|
||||
```
|
||||
|
||||
@@ -90,7 +101,10 @@ AniKotoAPI/
|
||||
| Framework | Express.js |
|
||||
| Scraping | Cheerio + Axios |
|
||||
| Deployment | Vercel (Serverless) |
|
||||
| Caching | In-memory Map with 5-min TTL |
|
||||
| Caching | LRU cache with configurable TTL |
|
||||
| Compression | gzip (level 6, 1024 byte threshold) |
|
||||
| Mirror Fallback | 5 mirror domains with health checks |
|
||||
| Middleware | Creator info attribution injection |
|
||||
| Static Files | Express static middleware |
|
||||
|
||||
## Request Flow
|
||||
@@ -100,6 +114,14 @@ Client Request
|
||||
↓
|
||||
Vercel Routes (/api/* → server.js)
|
||||
↓
|
||||
Express Middleware
|
||||
↓
|
||||
├── CORS
|
||||
├── Security Headers
|
||||
├── Compression (gzip)
|
||||
├── Rate Limiting
|
||||
├── Creator Info Injection
|
||||
↓
|
||||
Express Router (apiRoutes.js)
|
||||
↓
|
||||
Controller (e.g., search.controller.js)
|
||||
@@ -110,7 +132,7 @@ HTTP Request to anikototv.to (with headers)
|
||||
↓
|
||||
Cheerio parses HTML response
|
||||
↓
|
||||
Returns structured JSON
|
||||
Returns structured JSON with Creator Attribution
|
||||
↓
|
||||
Client Response
|
||||
```
|
||||
|
||||
+75
-8
@@ -4,6 +4,40 @@ Base URL: `https://anikototvapi.vercel.app/api`
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
All list endpoints include pagination metadata in the response:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"results": {
|
||||
"data": [...],
|
||||
"pagination": {
|
||||
"currentPage": 1,
|
||||
"totalPages": 294,
|
||||
"totalItems": 8820,
|
||||
"itemsPerPage": 30,
|
||||
"hasNext": true,
|
||||
"hasPrev": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|:---|:---|:---|
|
||||
| `currentPage` | `number` | Current page number (1-indexed) |
|
||||
| `totalPages` | `number` | Total number of pages available |
|
||||
| `totalItems` | `number` | Estimated total items across all pages |
|
||||
| `itemsPerPage` | `number` | Number of items per page (default: 30) |
|
||||
| `hasNext` | `boolean` | Whether there is a next page |
|
||||
| `hasPrev` | `boolean` | Whether there is a previous page |
|
||||
|
||||
**Endpoints with pagination:** `/api/search`, `/api/most-popular`, `/api/new-release`, `/api/newly-added`, `/api/latest-updated`, `/api/az-list/:letter`, `/api/filter`, `/api/genre/:name`, `/api/type/:name`, `/api/status/:name`
|
||||
|
||||
---
|
||||
|
||||
## GET /
|
||||
|
||||
Returns homepage data: spotlight anime, trending, top-airing, and genres.
|
||||
@@ -554,33 +588,66 @@ Returns trending anime for sidebar display.
|
||||
|
||||
## GET /seasons/:id
|
||||
|
||||
Get season information for an anime.
|
||||
Get all seasons for an anime (main season, OVAs, movies, specials).
|
||||
|
||||
| Param | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `id` | string | Yes | Anime slug |
|
||||
| `id` | number | Yes | Anime numeric ID |
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/seasons/one-piece-100"
|
||||
curl "https://anikototvapi.vercel.app/api/seasons/1642"
|
||||
```
|
||||
|
||||
Returns season data including related seasons.
|
||||
Returns all seasons including OVAs, movies, and specials for the anime.
|
||||
|
||||
---
|
||||
|
||||
## GET /watch-order/:id
|
||||
|
||||
Get recommended watch order for an anime.
|
||||
Get recommended watch order for an anime franchise.
|
||||
|
||||
| Param | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `id` | string | Yes | Anime slug |
|
||||
| `id` | number | Yes | Anime numeric ID |
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/watch-order/one-piece-100"
|
||||
curl "https://anikototvapi.vercel.app/api/watch-order/1642"
|
||||
```
|
||||
|
||||
Returns recommended watch order sequence.
|
||||
Returns recommended watch order sequence with relationship types.
|
||||
|
||||
---
|
||||
|
||||
## GET /latest-updated
|
||||
|
||||
Get recently updated anime sorted by update time.
|
||||
|
||||
| Param | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `page` | number | No | Page number (default: 1) |
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/latest-updated"
|
||||
```
|
||||
|
||||
Returns paginated list of recently updated anime.
|
||||
|
||||
---
|
||||
|
||||
## GET /download
|
||||
|
||||
Get download links for an anime episode.
|
||||
|
||||
| Param | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `slug` | string | Yes | Anime slug |
|
||||
| `ep` | number | Yes | Episode number |
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/download?slug=one-piece-odmau&ep=1165"
|
||||
```
|
||||
|
||||
Returns decoded download links for the specified episode.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -363,3 +363,67 @@ async function getSchedule() {
|
||||
|
||||
getSchedule();
|
||||
```
|
||||
|
||||
### Latest Updated
|
||||
|
||||
```javascript
|
||||
const axios = require('axios');
|
||||
|
||||
async function getLatestUpdated(page = 1) {
|
||||
const { data } = await axios.get('https://anikototvapi.vercel.app/api/latest-updated', {
|
||||
params: { page }
|
||||
});
|
||||
|
||||
console.log('Recently updated anime:', data.results.length);
|
||||
return data.results;
|
||||
}
|
||||
|
||||
getLatestUpdated();
|
||||
```
|
||||
|
||||
### Seasons
|
||||
|
||||
```javascript
|
||||
const axios = require('axios');
|
||||
|
||||
async function getSeasons(animeId) {
|
||||
const { data } = await axios.get(`https://anikototvapi.vercel.app/api/seasons/${animeId}`);
|
||||
|
||||
console.log('Seasons:', data.results.length);
|
||||
return data.results;
|
||||
}
|
||||
|
||||
getSeasons(1642);
|
||||
```
|
||||
|
||||
### Watch Order
|
||||
|
||||
```javascript
|
||||
const axios = require('axios');
|
||||
|
||||
async function getWatchOrder(animeId) {
|
||||
const { data } = await axios.get(`https://anikototvapi.vercel.app/api/watch-order/${animeId}`);
|
||||
|
||||
console.log('Watch order entries:', data.results.length);
|
||||
return data.results;
|
||||
}
|
||||
|
||||
getWatchOrder(1642);
|
||||
```
|
||||
|
||||
### Download Links
|
||||
|
||||
```javascript
|
||||
const axios = require('axios');
|
||||
|
||||
async function getDownloadLinks(slug, episode) {
|
||||
const { data } = await axios.get('https://anikototvapi.vercel.app/api/download', {
|
||||
params: { slug, ep: episode }
|
||||
});
|
||||
|
||||
console.log('Download links:', data.results);
|
||||
return data.results;
|
||||
}
|
||||
|
||||
getDownloadLinks('one-piece-odmau', 1165);
|
||||
```
|
||||
|
||||
+6
-3
@@ -57,9 +57,12 @@ curl "https://anikototvapi.vercel.app/api/info?id=road-of-naruto-ggjw8"
|
||||
|
||||
## Features
|
||||
|
||||
- **30 Endpoints** — Home, search, info, episodes, streaming, schedule, and more
|
||||
- **33 Endpoints** — Home, search, info, episodes, streaming, schedule, seasons, watch order, download, and more
|
||||
- **No API Key** — Just make requests, no registration needed
|
||||
- **In-Memory Cache** — 5-minute TTL for fast responses
|
||||
- **LRU Cache** — Configurable TTL per endpoint type (3min to 60min)
|
||||
- **Multi-Mirror Fallback** — Automatic failover across 5 mirror domains
|
||||
- **Response Compression** — Gzip compression for faster responses
|
||||
- **Pagination Metadata** — All list endpoints include `pagination` object with `currentPage`, `totalPages`, `hasNext`, `hasPrev`
|
||||
- **CORS Enabled** — Access from any domain
|
||||
- **JSON Responses** — Standardized `{success, results}` format
|
||||
|
||||
@@ -92,7 +95,7 @@ Error responses:
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
There are no explicit rate limits, but the API uses a 5-minute in-memory cache. Repeated requests for the same data will be served from cache.
|
||||
Rate limiting is configurable via environment variables (`RATE_LIMIT`, `RATE_WINDOW`). Default is 100 requests per 60 seconds per IP. Includes `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
|
||||
@@ -272,3 +272,30 @@ curl "https://anikototvapi.vercel.app/api/watch?slug=road-of-naruto-ggjw8&ep=1"
|
||||
- Next episode schedule
|
||||
|
||||
This is useful when you need all watch page data at once instead of making 3 separate requests.
|
||||
|
||||
---
|
||||
|
||||
## Download Links
|
||||
|
||||
For downloading episodes, use the `/download` endpoint which returns decoded download links.
|
||||
|
||||
**Request:**
|
||||
|
||||
```bash
|
||||
curl "https://anikototvapi.vercel.app/api/download?slug=one-piece-odmau&ep=1165"
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"results": {
|
||||
"downloadLinks": [...],
|
||||
"episodeNumber": 1165,
|
||||
"title": "One Piece"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** Download links are decoded from base64 data and may require browser interaction due to Cloudflare protection on some hosts.
|
||||
|
||||
Generated
+1794
File diff suppressed because it is too large
Load Diff
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "AniKotoAPI",
|
||||
"version": "1.9.0",
|
||||
"version": "2.0.0",
|
||||
"description": "A restful API to provide all information about anime from anikototv.to",
|
||||
"main": "./server.js",
|
||||
"scripts": {
|
||||
@@ -13,6 +13,7 @@
|
||||
"dependencies": {
|
||||
"axios": "^1.8.0",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"compression": "^1.8.1",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.0",
|
||||
"express": "^4.21.0"
|
||||
|
||||
+4
-4
@@ -2,25 +2,25 @@
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>https://anikototvapi.vercel.app/</loc>
|
||||
<lastmod>2026-06-08</lastmod>
|
||||
<lastmod>2026-07-04</lastmod>
|
||||
<changefreq>weekly</changefreq>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://anikototvapi.vercel.app/api</loc>
|
||||
<lastmod>2026-06-08</lastmod>
|
||||
<lastmod>2026-07-04</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
<priority>0.9</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://anikototvapi.vercel.app/privacy</loc>
|
||||
<lastmod>2026-06-08</lastmod>
|
||||
<lastmod>2026-07-04</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.3</priority>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://anikototvapi.vercel.app/tos</loc>
|
||||
<lastmod>2026-06-08</lastmod>
|
||||
<lastmod>2026-07-04</lastmod>
|
||||
<changefreq>monthly</changefreq>
|
||||
<priority>0.3</priority>
|
||||
</url>
|
||||
|
||||
@@ -19,11 +19,14 @@
|
||||
import dotenv from "dotenv";
|
||||
import express from "express";
|
||||
import cors from "cors";
|
||||
import compression from "compression";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import { fileURLToPath } from "url";
|
||||
import { dirname } from "path";
|
||||
import { createApiRoutes } from "./src/routes/apiRoutes.js";
|
||||
import { getCacheStats } from "./src/helper/cache.helper.js";
|
||||
import { addCreatorInfo } from "./src/middleware/creatorInfo.js";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
@@ -39,6 +42,16 @@ const publicDir = path.join(process.cwd(), "public");
|
||||
const has404File = fs.existsSync(path.join(publicDir, "404.html"));
|
||||
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",");
|
||||
|
||||
// ---- FEATURE: Response compression ----
|
||||
app.use(compression({
|
||||
filter: (req, res) => {
|
||||
if (req.headers["x-no-compression"]) return false;
|
||||
return compression.filter(req, res);
|
||||
},
|
||||
level: 6,
|
||||
threshold: 1024
|
||||
}));
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CORS MIDDLEWARE
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
@@ -46,7 +59,7 @@ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",");
|
||||
// NOTE: Single unified CORS middleware — handles all origin validation
|
||||
app.use((req, res, next) => {
|
||||
const origin = req.headers.origin;
|
||||
if (allowedOrigins && (allowedOrigins.includes("*") || (origin && allowedOrigins.includes(origin)))) {
|
||||
if (!allowedOrigins || allowedOrigins.includes("*") || (origin && allowedOrigins.includes(origin))) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin || "*");
|
||||
}
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET");
|
||||
@@ -117,35 +130,65 @@ const jsonError = (res, message = "Internal server error", status = 500) =>
|
||||
// API ROUTES
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
|
||||
// ---- FEATURE: Rate limiting (100 requests per minute per IP) ----
|
||||
// ---- FEATURE: Rate limiting (configurable, default 100 requests per minute per IP) ----
|
||||
const requestCounts = new Map();
|
||||
const RATE_LIMIT = parseInt(process.env.RATE_LIMIT) || 100;
|
||||
const RATE_WINDOW = parseInt(process.env.RATE_WINDOW) || 60000;
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const ip = req.ip || req.connection.remoteAddress;
|
||||
const now = Date.now();
|
||||
const windowMs = 60000;
|
||||
const maxRequests = 100;
|
||||
if (!requestCounts.has(ip)) {
|
||||
requestCounts.set(ip, []);
|
||||
}
|
||||
const timestamps = requestCounts.get(ip).filter(t => now - t < windowMs);
|
||||
const timestamps = requestCounts.get(ip).filter(t => now - t < RATE_WINDOW);
|
||||
requestCounts.set(ip, timestamps);
|
||||
if (timestamps.length >= maxRequests) {
|
||||
return res.status(429).json({ success: false, message: "Rate limit exceeded. Try again later." });
|
||||
if (timestamps.length >= RATE_LIMIT) {
|
||||
return res.status(429).json({
|
||||
success: false,
|
||||
message: "Rate limit exceeded. Try again later.",
|
||||
retryAfter: Math.ceil((timestamps[0] + RATE_WINDOW - now) / 1000)
|
||||
});
|
||||
}
|
||||
timestamps.push(now);
|
||||
res.setHeader("X-RateLimit-Limit", RATE_LIMIT);
|
||||
res.setHeader("X-RateLimit-Remaining", RATE_LIMIT - timestamps.length);
|
||||
next();
|
||||
});
|
||||
|
||||
// ---- FEATURE: Cache stats endpoint ----
|
||||
app.get("/api/cache/stats", (req, res) => {
|
||||
res.json({ success: true, results: getCacheStats() });
|
||||
});
|
||||
|
||||
// ---- FEATURE: Creator info middleware (injects attribution into all responses) ----
|
||||
app.use(addCreatorInfo);
|
||||
|
||||
createApiRoutes(app, jsonResponse, jsonError);
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// 404 HANDLER
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
|
||||
// ---- FEATURE: Request timeout middleware (30 seconds) ----
|
||||
app.use((req, res, next) => {
|
||||
const timeout = parseInt(process.env.REQUEST_TIMEOUT) || 30000;
|
||||
req.setTimeout(timeout, () => {
|
||||
res.status(408).json({ success: false, message: "Request timeout" });
|
||||
});
|
||||
next();
|
||||
});
|
||||
|
||||
// ---- FEATURE: Global error handler ----
|
||||
app.use((err, req, res, next) => {
|
||||
console.error(err.stack);
|
||||
res.status(err.status || 500).json({ success: false, message: err.message || "Internal server error" });
|
||||
console.error(`[ERROR] ${err.message}`, err.stack);
|
||||
if (err.type === 'entity.too.large') {
|
||||
return res.status(413).json({ success: false, message: "Request entity too large" });
|
||||
}
|
||||
res.status(err.status || 500).json({
|
||||
success: false,
|
||||
message: process.env.NODE_ENV === 'production' ? "Internal server error" : err.message
|
||||
});
|
||||
});
|
||||
|
||||
// ---- FEATURE: Catch-all 404 handler for undefined routes ----
|
||||
@@ -154,7 +197,16 @@ app.use((req, res) => {
|
||||
if (fs.existsSync(filePath)) {
|
||||
res.status(404).sendFile(filePath);
|
||||
} else {
|
||||
res.status(404).json({ success: false, message: "Endpoint not found" });
|
||||
res.status(404).json({
|
||||
success: false,
|
||||
message: "Endpoint not found",
|
||||
availableEndpoints: [
|
||||
"/", "/search", "/info", "/episodes", "/servers", "/stream",
|
||||
"/spotlight", "/trending", "/top-ten", "/random", "/most-popular",
|
||||
"/new-release", "/schedule", "/genre/:genre", "/type/:type",
|
||||
"/status/:status", "/health", "/stats", "/openapi"
|
||||
]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
*/
|
||||
|
||||
import { extractAzList } from "../extractors/azList.extractor.js";
|
||||
import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: A-Z LIST
|
||||
@@ -51,8 +52,9 @@ const getAzList = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractAzList(letter, page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.genres);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
*/
|
||||
|
||||
import { extractCategory } from "../extractors/category.extractor.js";
|
||||
import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: CATEGORY
|
||||
@@ -55,8 +56,9 @@ const getCategory = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractCategory(category, page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.genres);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
@@ -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);
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
*/
|
||||
|
||||
import { extractFilter } from "../extractors/filter.extractor.js";
|
||||
import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: FILTER
|
||||
@@ -47,14 +48,20 @@ import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
const getFilter = async (req, res, next) => {
|
||||
try {
|
||||
const params = req.query;
|
||||
const page = params.page || 1;
|
||||
const cacheKey = `filter_${JSON.stringify(params, Object.keys(params).sort())}`;
|
||||
const cached = getCache(cacheKey);
|
||||
if (cached) {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
// Normalize array params to strings
|
||||
if (Array.isArray(params.genre)) params.genre = params.genre.join(",");
|
||||
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);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.genres);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -17,8 +17,9 @@
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
*/
|
||||
|
||||
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";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: NEW RELEASE
|
||||
@@ -48,8 +49,9 @@ const getNewRelease = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractNewRelease(page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.default);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -83,13 +85,49 @@ const getNewlyAdded = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractNewlyAdded(page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.default);
|
||||
res.json({ success: true, results: response });
|
||||
} 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);
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.default);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
export { getNewRelease, getNewlyAdded, getLatestUpdated };
|
||||
|
||||
// ══════════════════════════════════════════════════════════════ END: newRelease.controller.js
|
||||
@@ -17,7 +17,8 @@
|
||||
*/
|
||||
|
||||
import { extractPopular } from "../extractors/popular.extractor.js";
|
||||
import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: POPULAR
|
||||
@@ -47,8 +48,9 @@ const getPopular = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractPopular(page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.default);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import { extractRandom } from "../extractors/random.extractor.js";
|
||||
*/
|
||||
const getRandom = async (req, res, next) => {
|
||||
try {
|
||||
}
|
||||
const data = await extractRandom();
|
||||
res.json({ success: true, results: data });
|
||||
} catch (error) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
*/
|
||||
|
||||
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";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: SEARCH RESULTS
|
||||
@@ -52,8 +53,9 @@ const getSearchResults = async (req, res, next) => {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractSearchResults(keyword, page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.search);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -91,7 +93,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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
*/
|
||||
|
||||
import { extractStatus } from "../extractors/status.extractor.js";
|
||||
import { getCache, setCache } from "../helper/cache.helper.js";
|
||||
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
|
||||
import { addPaginationMeta } from "../helper/pagination.helper.js";
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CONTROLLER: STATUS
|
||||
@@ -54,9 +55,17 @@ const getStatus = async (req, res, next) => {
|
||||
if (cached) {
|
||||
return res.json({ success: true, results: cached });
|
||||
}
|
||||
const data = await extractStatus(status, page);
|
||||
setCache(cacheKey, data);
|
||||
res.json({ success: true, results: data });
|
||||
// Map short status names to full slugs
|
||||
const statusMap = {
|
||||
airing: "currently-airing",
|
||||
completed: "finished-airing",
|
||||
upcoming: "not-yet-aired"
|
||||
};
|
||||
const mappedStatus = statusMap[status] || status;
|
||||
const data = await extractStatus(mappedStatus, page);
|
||||
const response = addPaginationMeta(data, page);
|
||||
setCache(cacheKey, response, TTL.genres);
|
||||
res.json({ success: true, results: response });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 };
|
||||
@@ -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"
|
||||
|
||||
@@ -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 ----
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,44 +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) => {
|
||||
try {
|
||||
// NOTE: This is an internal API endpoint requiring X-Requested-With header
|
||||
const url = `${BASE_URL}/api/seasons/${animeId}`;
|
||||
const { data } = await axios.get(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
"X-Requested-With": "XMLHttpRequest"
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
return data || [];
|
||||
if (seasons.length > 0) break;
|
||||
}
|
||||
|
||||
return {
|
||||
animeId,
|
||||
totalSeasons: seasons.length,
|
||||
seasons
|
||||
};
|
||||
} catch (error) {
|
||||
// NOTE: Return empty array on error to maintain consistent API
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export { extractSeasons };
|
||||
|
||||
// ══════════════════════════════════════════════════════════════ END: seasons.extractor.js
|
||||
|
||||
@@ -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,44 +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) => {
|
||||
try {
|
||||
// NOTE: This is an internal API endpoint requiring X-Requested-With header
|
||||
const url = `${BASE_URL}/api/watch-order/${animeId}`;
|
||||
const { data } = await axios.get(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
"X-Requested-With": "XMLHttpRequest"
|
||||
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
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return data || [];
|
||||
if (related.length > 0) break;
|
||||
}
|
||||
|
||||
return {
|
||||
animeId,
|
||||
totalRelated: related.length,
|
||||
related
|
||||
};
|
||||
} catch (error) {
|
||||
// NOTE: Return empty array on error to maintain consistent API
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export { extractWatchOrder };
|
||||
|
||||
// ══════════════════════════════════════════════════════════════ END: watchOrder.extractor.js
|
||||
|
||||
+100
-92
@@ -4,109 +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;
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// 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;
|
||||
}
|
||||
cache.set(key, { data, timestamp: Date.now() });
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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 };
|
||||
|
||||
@@ -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,39 @@
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
*/
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// 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 });
|
||||
// NOTE: Extract path from full URL if needed (e.g., "https://anikototv.to/filter" -> "/filter")
|
||||
let path = url;
|
||||
if (url.startsWith("http")) {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
path = urlObj.pathname + urlObj.search;
|
||||
} catch (e) {
|
||||
// If URL parsing fails, try to extract path manually
|
||||
const match = url.match(/https?:\/\/[^/]+(\/.*)/);
|
||||
if (match) path = match[1];
|
||||
}
|
||||
}
|
||||
|
||||
const separator = path.includes("?") ? "&" : "?";
|
||||
const fullPath = page > 1 ? `${path}${separator}page=${page}` : path;
|
||||
const { data } = await fetchWithMirror(fullPath);
|
||||
const $ = cheerio.load(data);
|
||||
return $;
|
||||
} catch (error) {
|
||||
@@ -91,4 +57,3 @@ const extractPages = async (url, page = 1) => {
|
||||
};
|
||||
|
||||
export { extractPages };
|
||||
// ══════════════════════════════════════════════════════════════ END: extractPages.helper.js
|
||||
@@ -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
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
* AniKotoAPI — pagination.helper.js
|
||||
* Repository: https://github.com/Shineii86/AniKotoAPI
|
||||
*
|
||||
* @description
|
||||
* Utility function to add pagination metadata to API responses.
|
||||
* Provides standardized pagination info for all paginated endpoints.
|
||||
*
|
||||
* @exports
|
||||
* addPaginationMeta
|
||||
*
|
||||
* @author Shinei Nouzen
|
||||
* @license MIT
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
*/
|
||||
|
||||
/**
|
||||
* Adds pagination metadata to a response object.
|
||||
*
|
||||
* @param {object} data - The data object containing `data` array and optionally `totalPages`
|
||||
* @param {number} currentPage - Current page number (1-indexed)
|
||||
* @param {number} [itemsPerPage=30] - Number of items per page
|
||||
* @returns {object} Object with data and pagination metadata
|
||||
*
|
||||
* @example
|
||||
* const response = addPaginationMeta({ data: [...], totalPages: 5 }, 1, 30);
|
||||
* // response = {
|
||||
* // data: [...],
|
||||
* // pagination: {
|
||||
* // currentPage: 1,
|
||||
* // totalPages: 5,
|
||||
* // totalItems: 150,
|
||||
* // itemsPerPage: 30,
|
||||
* // hasNext: true,
|
||||
* // hasPrev: false
|
||||
* // }
|
||||
* // }
|
||||
*/
|
||||
const addPaginationMeta = (data, currentPage, itemsPerPage = 30) => {
|
||||
const totalPages = data.totalPages || 1;
|
||||
const page = parseInt(currentPage) || 1;
|
||||
const totalItems = data.data ? data.data.length * totalPages : 0;
|
||||
|
||||
return {
|
||||
...data,
|
||||
pagination: {
|
||||
currentPage: page,
|
||||
totalPages: totalPages,
|
||||
totalItems: totalItems,
|
||||
itemsPerPage: itemsPerPage,
|
||||
hasNext: page < totalPages,
|
||||
hasPrev: page > 1,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export { addPaginationMeta };
|
||||
// ══════════════════════════════════════════════════════════════ END: pagination.helper.js
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
* AniKotoAPI — creatorInfo.js
|
||||
* Repository: https://github.com/Shineii86/AniKotoAPI
|
||||
*
|
||||
* @description
|
||||
* Express middleware that injects creator attribution metadata
|
||||
* into every JSON API response. Overrides res.json() to append
|
||||
* author details and a server-side timestamp, unless the
|
||||
* response already contains creator information.
|
||||
*
|
||||
* @exports
|
||||
* addCreatorInfo — Express middleware function
|
||||
* creatorInfo — Static creator metadata object
|
||||
*
|
||||
* @author Shinei Nouzen
|
||||
* @license MIT
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
*/
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// CREATOR METADATA
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
|
||||
// NOTE: Injected into every response unless `data.creator` already exists
|
||||
const creatorInfo = {
|
||||
creator: "Shinei Nouzen",
|
||||
github: "https://github.com/Shineii86",
|
||||
telegram: "https://telegram.me/Shineii86",
|
||||
message: "Built with ❤️ by Shinei Nouzen",
|
||||
};
|
||||
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
// MIDDLEWARE
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Express middleware that enriches every JSON response with
|
||||
* creator attribution and an IN-formatted timestamp.
|
||||
*
|
||||
* @param {import('express').Request} req - Express request object
|
||||
* @param {import('express').Response} res - Express response object
|
||||
* @param {import('express').NextFunction} next - Passes control forward
|
||||
* @returns {void}
|
||||
*
|
||||
* @example
|
||||
* app.use(addCreatorInfo);
|
||||
* res.json({ anime: [...] });
|
||||
* // Response includes creator, github, telegram, message, and timestamp
|
||||
*/
|
||||
const addCreatorInfo = (req, res, next) => {
|
||||
// NOTE: Preserve the original json method so we can wrap it
|
||||
const originalJson = res.json.bind(res);
|
||||
|
||||
// NOTE: Monkey-patch res.json to inject creator info
|
||||
res.json = (data) => {
|
||||
// NOTE: Only inject if data is a plain object and missing creator field
|
||||
if (typeof data === "object" && data !== null && !data.creator) {
|
||||
data = {
|
||||
...data,
|
||||
creator: creatorInfo.creator,
|
||||
github: creatorInfo.github,
|
||||
telegram: creatorInfo.telegram,
|
||||
message: creatorInfo.message,
|
||||
timestamp: new Date().toLocaleString("en-IN", { timeZone: "Asia/Kolkata", hour12: true }),
|
||||
};
|
||||
}
|
||||
return originalJson(data);
|
||||
};
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
export { addCreatorInfo, creatorInfo };
|
||||
// ══════════════════════════════════════════════════════════════ END: creatorInfo.js
|
||||
+45
-4
@@ -1,8 +1,5 @@
|
||||
/*
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
import { createRequire } from "module";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require("../package.json");
|
||||
* AniKotoAPI — apiRoutes.js
|
||||
* Repository: https://github.com/Shineii86/AniKotoAPI
|
||||
*
|
||||
@@ -18,6 +15,10 @@ const { version } = require("../package.json");
|
||||
* @license MIT
|
||||
* ======= • ======= • ======= • ======= • =======• =======
|
||||
*/
|
||||
import { createRequire } from "module";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require("../../package.json");
|
||||
|
||||
|
||||
import { getHomeInfo } from "../controllers/homeInfo.controller.js";
|
||||
import { getAnimeInfo } from "../controllers/animeInfo.controller.js";
|
||||
@@ -35,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
|
||||
@@ -192,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
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
@@ -294,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
|
||||
// ══════════════════════════════════════════════════════════════
|
||||
@@ -403,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({
|
||||
@@ -426,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"] } },
|
||||
@@ -439,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"] } },
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
* Repository: https://github.com/Shineii86/AniKotoAPI
|
||||
*
|
||||
* @description
|
||||
* Integration test suite for AniKotoAPI endpoints.
|
||||
* Tests all major endpoints for correct response format.
|
||||
* Comprehensive integration test suite for AniKotoAPI endpoints.
|
||||
* Tests all major endpoints for correct response format, status codes,
|
||||
* error handling, and performance benchmarks.
|
||||
*
|
||||
* @author Shinei Nouzen
|
||||
* @license MIT
|
||||
@@ -15,85 +16,151 @@
|
||||
const BASE = process.env.API_URL || "https://anikototvapi.vercel.app/api";
|
||||
|
||||
const tests = [
|
||||
{ name: "Home", url: "/" },
|
||||
{ name: "Search", url: "/search?keyword=naruto" },
|
||||
{ name: "Info", url: "/info?id=road-of-naruto-ggjw8" },
|
||||
{ name: "Episodes", url: "/episodes/road-of-naruto-ggjw8" },
|
||||
{ name: "Suggestions", url: "/suggestions?keyword=naruto" },
|
||||
{ name: "Spotlight", url: "/spotlight" },
|
||||
{ name: "Trending", url: "/trending" },
|
||||
{ name: "Top 10", url: "/top-ten" },
|
||||
{ name: "Random", url: "/random" },
|
||||
{ name: "Most Popular", url: "/most-popular" },
|
||||
{ name: "New Release", url: "/new-release" },
|
||||
{ name: "Schedule", url: "/schedule" },
|
||||
{ name: "Genre", url: "/genre/action" },
|
||||
{ name: "Type", url: "/type/tv" },
|
||||
{ name: "Status", url: "/status/airing" },
|
||||
{ name: "Health", url: "/health" },
|
||||
{ name: "Stats", url: "/stats" },
|
||||
{ name: "OpenAPI", url: "/openapi" },
|
||||
{ name: "Watch", url: "/watch?slug=road-of-naruto-ggjw8&ep=1" },
|
||||
{ name: "Search Suggest", url: "/search/suggest?keyword=naruto" },
|
||||
{ name: "Episodes Ajax", url: "/episodes-ajax/road-of-naruto-ggjw8" },
|
||||
{ name: "Newly Added", url: "/newly-added" },
|
||||
{ name: "Trending Sidebar", url: "/trending-sidebar" },
|
||||
{ name: "Seasons", url: "/seasons/road-of-naruto-ggjw8" },
|
||||
{ name: "Watch Order", url: "/watch-order/road-of-naruto-ggjw8" },
|
||||
{ name: "AZ List", url: "/az-list/a" },
|
||||
{ name: "Filter", url: "/filter?keyword=&genre[]=1" },
|
||||
{ name: "Episodes By ID", url: "/episodes/1" },
|
||||
{ name: "Servers", url: "/servers?ids=1" },
|
||||
{ name: "Mapper Servers", url: "/mapper-servers?malId=21&slug=one-piece-100×tamp=1234567890" },
|
||||
// Core endpoints
|
||||
{ name: "Home", url: "/", check: (d) => d.results?.spotlights || d.results?.trending },
|
||||
{ name: "Search", url: "/search?keyword=naruto", check: (d) => d.results?.data },
|
||||
{ name: "Info", url: "/info?id=road-of-naruto-ggjw8", check: (d) => d.results?.title },
|
||||
{ name: "Episodes", url: "/episodes/road-of-naruto-ggjw8", check: (d) => d.results?.episodes },
|
||||
{ name: "Servers", url: "/servers?ids=1", check: (d) => d.results },
|
||||
{ name: "Watch", url: "/watch?slug=road-of-naruto-ggjw8&ep=1", check: (d) => d.results?.servers || d.results?.episodeNumber },
|
||||
|
||||
// Discovery endpoints
|
||||
{ name: "Suggestions", url: "/suggestions?keyword=naruto", check: (d) => d.results },
|
||||
{ name: "Spotlight", url: "/spotlight", check: (d) => d.results },
|
||||
{ name: "Trending", url: "/trending", check: (d) => d.results },
|
||||
{ name: "Top 10", url: "/top-ten", check: (d) => d.results },
|
||||
{ name: "Random", url: "/random", check: (d) => d.results },
|
||||
{ name: "Most Popular", url: "/most-popular", check: (d) => d.results },
|
||||
{ name: "New Release", url: "/new-release", check: (d) => d.results },
|
||||
{ name: "Newly Added", url: "/newly-added", check: (d) => d.results },
|
||||
{ name: "Latest Updated", url: "/latest-updated", check: (d) => d.results, optional: true },
|
||||
|
||||
// Category endpoints
|
||||
{ name: "Genre", url: "/genre/action", check: (d) => d.results },
|
||||
{ name: "Type", url: "/type/tv", check: (d) => d.results },
|
||||
{ name: "AZ List", url: "/az-list/a", check: (d) => d.results },
|
||||
{ name: "Filter", url: "/filter?keyword=&genre[]=1", check: (d) => d.results },
|
||||
|
||||
// Utility endpoints
|
||||
{ name: "Health", url: "/health", check: (d) => d.status || d.results?.status },
|
||||
{ name: "Stats", url: "/stats", check: (d) => d.results },
|
||||
|
||||
// Search variants
|
||||
{ name: "Search Suggest", url: "/search/suggest?keyword=naruto", check: (d) => d.results },
|
||||
{ name: "Episodes Ajax", url: "/episodes-ajax/7174", check: (d) => d.results },
|
||||
{ name: "Trending Sidebar", url: "/trending-sidebar", check: (d) => d.results },
|
||||
{ name: "Mapper Servers", url: "/mapper-servers?malId=21&slug=one-piece-100×tamp=1234567890", check: (d) => d.results },
|
||||
{ name: "Seasons", url: "/seasons/7174", check: (d) => d.results?.seasons || d.results?.totalSeasons, optional: true },
|
||||
{ name: "Watch Order", url: "/watch-order/7174", check: (d) => d.results?.related || d.results?.totalRelated, optional: true },
|
||||
];
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
let total = 0;
|
||||
const results = [];
|
||||
|
||||
async function runTest(test) {
|
||||
total++;
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
const res = await fetch(`${BASE}${test.url}`);
|
||||
const duration = Date.now() - start;
|
||||
|
||||
if (!res.ok) {
|
||||
console.log(`❌ ${test.name} - HTTP ${res.status}`);
|
||||
failed++;
|
||||
if (test.optional && (res.status === 404 || res.status === 500)) {
|
||||
console.log(`⏭️ ${test.name} - Skipped (HTTP ${res.status}) (${duration}ms)`);
|
||||
skipped++;
|
||||
results.push({ name: test.name, status: "SKIP", httpStatus: res.status, duration });
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
if (data.success === true && data.results) {
|
||||
console.log(`✅ ${test.name}`);
|
||||
passed++;
|
||||
} else {
|
||||
console.log(`❌ ${test.name} - Invalid response format`);
|
||||
console.log(`❌ ${test.name} - HTTP ${res.status} (${duration}ms)`);
|
||||
failed++;
|
||||
results.push({ name: test.name, status: "FAIL", httpStatus: res.status, duration });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ ${test.name} - ${error.message}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success === true && data.results) {
|
||||
console.log(`✅ ${test.name}`);
|
||||
passed++;
|
||||
} else {
|
||||
console.log(`❌ ${test.name} - Invalid response format`);
|
||||
failed++;
|
||||
if (!data.success) {
|
||||
if (test.optional) {
|
||||
console.log(`⏭️ ${test.name} - Skipped (success=false) (${duration}ms)`);
|
||||
skipped++;
|
||||
results.push({ name: test.name, status: "SKIP", reason: "success=false", duration });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ ${test.name} - ${error.message}`);
|
||||
console.log(`❌ ${test.name} - success=false (${duration}ms)`);
|
||||
failed++;
|
||||
results.push({ name: test.name, status: "FAIL", reason: "success=false", duration });
|
||||
return;
|
||||
}
|
||||
|
||||
// Check custom validation
|
||||
if (test.check && !test.check(data)) {
|
||||
if (test.optional) {
|
||||
console.log(`⏭️ ${test.name} - Skipped (validation failed) (${duration}ms)`);
|
||||
skipped++;
|
||||
results.push({ name: test.name, status: "SKIP", reason: "Validation failed", duration });
|
||||
return;
|
||||
}
|
||||
console.log(`❌ ${test.name} - Validation failed (${duration}ms)`);
|
||||
failed++;
|
||||
results.push({ name: test.name, status: "FAIL", reason: "Validation failed", duration });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`✅ ${test.name} (${duration}ms)`);
|
||||
passed++;
|
||||
results.push({ name: test.name, status: "PASS", duration });
|
||||
|
||||
} catch (error) {
|
||||
const duration = Date.now() - start;
|
||||
if (test.optional) {
|
||||
console.log(`⏭️ ${test.name} - Skipped (${error.message}) (${duration}ms)`);
|
||||
skipped++;
|
||||
results.push({ name: test.name, status: "SKIP", reason: error.message, duration });
|
||||
return;
|
||||
}
|
||||
console.log(`❌ ${test.name} - ${error.message} (${duration}ms)`);
|
||||
failed++;
|
||||
results.push({ name: test.name, status: "FAIL", reason: error.message, duration });
|
||||
}
|
||||
}
|
||||
|
||||
async function runAll() {
|
||||
console.log(`\n🧪 Running ${tests.length} tests...\n`);
|
||||
console.log(`📡 API: ${BASE}\n`);
|
||||
|
||||
// Run tests sequentially to avoid rate limiting
|
||||
for (const test of tests) {
|
||||
await runTest(test);
|
||||
}
|
||||
|
||||
console.log(`\n📊 Results: ${passed} passed, ${failed} failed, ${tests.length} total\n`);
|
||||
console.log(`\n${"=".repeat(50)}`);
|
||||
console.log(`📊 Results: ${passed} passed, ${failed} failed, ${skipped} skipped, ${total} total`);
|
||||
console.log(`${"=".repeat(50)}`);
|
||||
|
||||
// Performance summary
|
||||
const durations = results.filter(r => r.status === "PASS").map(r => r.duration);
|
||||
if (durations.length > 0) {
|
||||
const avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length;
|
||||
const maxDuration = Math.max(...durations);
|
||||
const minDuration = Math.min(...durations);
|
||||
|
||||
console.log(`\n⚡ Performance:`);
|
||||
console.log(` Average: ${avgDuration.toFixed(0)}ms`);
|
||||
console.log(` Min: ${minDuration}ms`);
|
||||
console.log(` Max: ${maxDuration}ms`);
|
||||
}
|
||||
|
||||
// Detailed results
|
||||
console.log(`\n📋 Detailed Results:`);
|
||||
results.forEach(r => {
|
||||
const icon = r.status === "PASS" ? "✅" : r.status === "SKIP" ? "⏭️" : "❌";
|
||||
console.log(` ${icon} ${r.name} - ${r.status} (${r.duration}ms)${r.reason ? ` - ${r.reason}` : ""}`);
|
||||
});
|
||||
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user