Compare commits

...
9 Commits
Author SHA1 Message Date
Shinei Nouzen fb62184688 docs: Update all documentation for v2.2.0 — 38 endpoints, streaming resolver, proxy
README.md:
- Version badge: 2.1.0 → 2.2.0
- Endpoint count: 33 → 38
- Feature table: added stream URL resolution, M3U8 proxy, season/epMin/epMax filters
- Streaming section: added /stream/resolve, /stream/qualities, /stream/proxy docs
- Project structure: updated controller/extractor/helper file lists
- Dependencies: removed cors, updated dep list
- Changelog highlights: added v2.2.0 entry
- Completed checklist: added 38 endpoints, streaming resolver, proxy, diagnostic sweep

docs/endpoints.md:
- Added 8 new endpoint sections: upcoming, top-rankings, recently-updated, completed,
  stream/resolve, stream/qualities, stream/proxy, stream/ts-proxy

docs/streaming.md:
- Added Stream URL Resolution section (Step 4)
- Added M3U8 quality parsing docs
- Added M3U8 proxy docs with CORS-free playback explanation
- Updated troubleshooting table

docs/architecture.md:
- Updated project structure with all new files (streamResolver, parseListItem, etc.)
- Updated streaming flow diagram with resolver/proxy steps
- Updated dependencies table

docs/examples.md:
- Added curl examples for upcoming, top-rankings, recently-updated, completed
- Added stream resolver, qualities, proxy examples

CHANGELOG.md:
- Updated v2.2.0 entry with M3U8/TS proxy, mirror fix, all bug fixes

agents/:
- Updated api-tester.md: 36 → 38 endpoints
- Updated technical-writer.md: 36 → 38 endpoints
- Updated performance-benchmarker.md: 36 → 38 endpoints
2026-07-28 21:01:43 +05:30
Shinei Nouzen d391908467 feat: Add M3U8/TS proxy, fix mirror fallback, fix seasons/watch-order
New endpoints:
- GET /api/stream/proxy?url= — M3U8 playlist proxy with URL rewriting
  Rewrites relative .m3u8 and .ts URLs to proxy endpoints
  Adds CORS headers for cross-origin playback
  Validates allowed streaming domains
- GET /api/stream/ts-proxy?url= — TS video segment proxy
  Proxies .ts segments with proper Content-Type and caching

Fixes:
- seasons.extractor.js: Now extracts from watch page sidebar instead of broken AJAX endpoint
- watchOrder.extractor.js: Now extracts from watch page sidebar (trending/related)
- mirror.helper.js: 404 responses no longer mark mirrors as failed
  Only connection errors trigger mirror failover
  Endpoint-specific 404s break immediately without retry

38 total endpoints, 34/34 passing with 0 errors
2026-07-28 20:52:49 +05:30
Shinei Nouzen 21384dc30f docs: Update CHANGELOG with streaming resolver features 2026-07-28 20:42:41 +05:30
Shinei Nouzen bdf7e96ce9 feat: Add streaming URL resolver, quality detection, and server normalization
New endpoints:
- GET /api/stream/resolve — Resolves actual m3u8/mp4 URLs from embed player URLs
  Follows chain: vidtube.site → megaplay API → m3u8 playlist
  Returns url, type, qualities, subtitles, skipData
- GET /api/stream/qualities — Parses M3U8 playlists for available quality options
  Returns sorted quality list with resolution, bandwidth, URLs

New extractors:
- streamResolver.extractor.js — Full stream resolution pipeline
  - resolveStreamUrl(): Resolves embed → actual video URL
  - parseM3u8Qualities(): Parses master playlists for qualities
  - normalizeServerName(): Maps VidPlay-1 → vidplay, HD-1 → hd
  - extractSubtitles(): Extracts subtitle tracks from API responses

Enhancements:
- streamInfo.extractor.js: Added session establishment before AJAX calls
- Server list now includes normalizedName field for each server
- Stream info now includes type (hls/mp4) and backup URL
- Server list includes typeLabel (SUB/HSUB/DUB)
- Session cookies properly maintained for AJAX stream endpoints

Architecture:
- Embed API domain mapping (vidtube.site → megaplay-1.buzz)
- M3U8 parser supports master and media playlists
- Subtitle extraction from multiple API response formats
- 36 total endpoints (was 34)
2026-07-28 20:40:17 +05:30
Shinei Nouzen e8c942a773 chore: Update test.js and agents to v2.2.0 with all 36 endpoints
- test.js: Add 9 new tests (upcoming, top-rankings, recently-updated, completed, cache/stats, mirrors, openapi, download, status)
- test.js: Fix slugs (one-piece-odmau, correct episode links)
- test.js: 36 total tests (was 26)
- agents/: Update all 6 agent files from v2.0.0 to v2.2.0
- agents/api-tester.md: Update endpoint table with new endpoints
- agents/backend-architect.md: Update file counts and endpoint list
- agents/technical-writer.md: Update documentation structure for 36 endpoints
2026-07-28 20:21:41 +05:30
Shinei Nouzen d0432e1654 fix: Bug fixes from full API diagnostic sweep — all 33 endpoints now 200 OK
- Fix /api/watch 500: correct URL path format (slug/ep-N -> slug/ep-N)
- Fix /api/info: accept both ?id= and ?slug= query params
- Fix /api/status/airing 500: map short status names (ongoing/airing/completed) to correct slugs
- Fix /api/top-rankings: correct selectors (#top-anime .scaff.side.items a.item) + extract rank from rankN class
- Fix /api/completed: correct selectors (section.top-table[data-name='completed'] a.item)
- Fix /api/recently-updated: correct selectors (#recent-update .ani.items .item) + client-side tab filtering
- Fix parseListItem: detect self-as-anchor (<a> elements) + fallback slug extraction
- Fix category extractor: add status name mapping (ongoing->currently-airing, etc.)
- Add /api/cache/stats endpoint for LRU cache diagnostics
- 33 endpoints verified: 0 errors, 0 timeouts
2026-07-28 20:17:58 +05:30
Shinei Nouzen fd29b02158 feat: Add new endpoints and enhance filter — v2.2.0
New Endpoints (4 new routes):
- GET /api/upcoming — upcoming anime releases from homepage
- GET /api/top-rankings?sort=top|newest — ranked anime with sort modes
- GET /api/recently-updated?tab=all|dub|sub — filtered recent updates
- GET /api/completed — finished anime series from homepage

Enhanced Filter (/api/filter):
- Added source parameter (18 source material types)
- Added epMin/epMax for episode range filtering
- Added excludeWatchlist parameter for logged-in users
- Added season parameter (spring/summer/fall/winter)

New Config IDs:
- SOURCE_IDS: 18 source material type mappings
- SEASON_IDS: 4 broadcast season mappings
- EXTENDED_TYPE_IDS: Added tv-short and tv-special types

Total endpoints: 34 (was 30)
OpenAPI spec updated with new endpoints
CHANGELOG.md updated with comprehensive change history
2026-07-28 19:45:25 +05:30
Shinei Nouzen a8f1917ce7 feat: v2.2.0 — Modularize codebase, unify mirror fallback, harden security
Major Changes:
- Add shared parseListItem.helper.js for unified list parsing (DRY)
- Migrate all 22 extractors to use fetchWithMirror() for consistent mirror fallback
- Remove unused cors dependency (custom CORS middleware handles it)
- Fix middleware ordering: timeout now registered before routes
- Fix CORS to allow POST for /api/mirrors/reset endpoint
- Remove redundant cache check in homeInfo extractor

New Features:
- Request ID tracking (X-Request-Id header) for debugging
- Graceful shutdown handling (SIGTERM/SIGINT) with 10s timeout
- CSP and HSTS security headers
- Rate limiter cleanup interval (every 5 min) to prevent memory leak
- Request body size limits (10kb) via express.json()

Security:
- Content-Security-Policy header for XSS protection
- Strict-Transport-Security for HTTPS enforcement
- X-Permitted-Cross-Domain-Policies: none
- Body size limits to prevent large payload attacks

Code Quality:
- All files follow strict documentation style (box headers, section separators,
  feature markers, JSDoc params/returns, inline notes, module footers)
- Eliminated ~200 lines of duplicated code across 8+ extractors
- Updated CHANGELOG.md with comprehensive change history
2026-07-28 19:28:21 +05:30
Shinei Nouzen 7f07833c14 Update README.md 2026-07-25 20:07:35 +05:30
53 changed files with 2307 additions and 697 deletions
+59
View File
@@ -5,6 +5,65 @@ 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/), 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). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.2.0] - 2026-07-28
### Added
- **Stream Resolve Endpoint**: `GET /api/stream/resolve?id=&slug=` — Resolves actual m3u8/mp4 URLs from embed player URLs (vidtube.site → megaplay API → m3u8 playlist)
- **Stream Qualities Endpoint**: `GET /api/stream/qualities?url=` — Parses M3U8 playlists for available quality options with resolution, bandwidth, and URLs
- **M3U8 Proxy Endpoint**: `GET /api/stream/proxy?url=` — Rewrites M3U8 playlists to proxy through API for CORS-free HLS playback
- **TS Proxy Endpoint**: `GET /api/stream/ts-proxy?url=` — Proxies `.ts` video segments with proper `Content-Type: video/mp2t` and CORS headers
- **Stream Resolver Extractor**: Full pipeline for resolving actual video URLs from embed pages
- **M3U8 Quality Parser**: Parses master playlists to extract quality options sorted by resolution
- **Server Name Normalization**: Maps display names to clean identifiers (VidPlay-1 → vidplay, HD-1 → hd)
- **Subtitle Extraction**: Extracts subtitle tracks from streaming API responses
- **Embed API Domain Mapping**: Maps vidtube.site → megaplay-1.buzz for stream resolution
- **Shared Helper**: New `parseListItem.helper.js` for unified anime list item parsing across all extractors
- **Graceful Shutdown**: Server now handles SIGTERM/SIGINT signals for clean shutdown
- **Request ID Tracking**: Every request gets a unique `X-Request-Id` header for debugging
- **CSP Headers**: Added `Content-Security-Policy` header for XSS protection
- **HSTS Headers**: Added `Strict-Transport-Security` header for HTTPS enforcement
- **Body Size Limits**: Added `express.json({ limit: '10kb' })` to prevent large payload attacks
- **Rate Limiter Cleanup**: Automatic cleanup of stale IP entries every 5 minutes
- **Uncaught Exception Handler**: Added handler for uncaught exceptions with graceful shutdown
- **Upcoming Anime Endpoint**: `GET /api/upcoming` — upcoming anime releases from homepage
- **Top Anime Rankings Endpoint**: `GET /api/top-rankings?sort=top|newest` — ranked anime with sort modes
- **Recently Updated Tabs Endpoint**: `GET /api/recently-updated?tab=all|dub|sub` — filtered updates
- **Completed Anime Endpoint**: `GET /api/completed` — finished anime series from homepage
- **Enhanced Filter**: Added `source`, `epMin`, `epMax`, `excludeWatchlist` parameters to `/api/filter`
- **Source IDs Config**: New `SOURCE_IDS` mapping for 18 source material types
- **Season IDs Config**: New `SEASON_IDS` mapping for 4 broadcast seasons
- **Extended Type IDs**: Added `tv-short` and `tv-special` type mappings
### Changed
- **Mirror Fallback**: All 22+ extractors now use `fetchWithMirror()` for consistent mirror fallback
- **Mirror Helper**: 404 responses no longer mark mirrors as failed — only connection errors trigger failover
- **Seasons Extractor**: Rewritten to extract from watch page sidebar (AJAX endpoints don't exist on source site)
- **Watch Order Extractor**: Rewritten to extract from watch page sidebar trending/related sections
- **Stream Info Extractor**: Now establishes session before AJAX calls, normalizes server names, adds type field
- **Code Deduplication**: Extracted shared list item parsing logic into `parseListItem.helper.js`, eliminating ~200 lines of duplicated code across 8+ extractors
- **Documentation**: All files follow strict documentation style — box-style headers, section separators, feature markers, JSDoc params/returns, inline notes, and module footers
- **Version**: Bumped to 2.2.0
- **Package**: Removed unused `cors` dependency (custom CORS middleware used instead)
- **README**: Updated all endpoint counts, features, and streaming flow documentation
- **Docs**: Updated endpoints.md, streaming.md, architecture.md, examples.md with new endpoints
### Fixed
- **Middleware Order**: Moved request timeout middleware before routes to properly catch timeouts
- **CORS POST**: Fixed CORS to allow POST method for `/api/mirrors/reset` endpoint
- **HomeInfo Cache**: Removed redundant cache check in `homeInfo.extractor.js` (controller already handles caching)
- **Error Handler**: Added `res.headersSent` check to prevent double response on timeout
- **Unused Imports**: Removed unused `cheerio`, `axios`, `headers` imports from extractors that now use `fetchWithMirror`
- **Watch Page Path**: Fixed `/api/watch` 500 error — path format changed from `/slug/ep` to `/slug/ep-N`
- **Info Endpoint**: Now accepts both `?id=` and `?slug=` params for flexibility
- **Status Names**: Fixed `/api/status/airing` 500 — added status name mapping (ongoing→currently-airing, completed→finished-airing)
- **Top Rankings**: Fixed selectors to match actual HTML (`#top-anime .scaff.side.items a.item`) with rank class extraction
- **Completed Anime**: Fixed selectors for `section.top-table[data-name='completed']`
- **Recently Updated**: Fixed selectors for `#recent-update .ani.items .item` with client-side tab filtering
### Removed
- **Unused Dependency**: Removed `cors` package from dependencies (custom middleware handles CORS)
- **Dead Code**: Removed redundant cache check in `homeInfo.extractor.js`
## [2.1.0] - 2026-07-05 ## [2.1.0] - 2026-07-05
### Changed ### Changed
+193 -23
View File
@@ -1,6 +1,9 @@
> [!NOTE]
> **API MAYBE Temporarily Paused** due to suspiciously too many requests. My hosted version of this API is only for testing purposes. You MUST host your own instance to use the API.
<div align="center"> <div align="center">
<img src="https://capsule-render.vercel.app/api?type=waving&height=300&color=gradient&text=AniKotoAPI&fontAlignY=30&fontSize=90&desc=Real-Time%20Anime%20Streaming%20Data%20API&descSize=30" /> <img src="https://capsule-render.vercel.app/api?type=waving&height=300&color=gradient&text=𝘼𝙣𝙞𝙆𝙤𝙩𝙤𝘼𝙋𝙄&fontAlignY=30&fontSize=100&desc=𝖱𝖾𝖺𝗅-𝖳𝗂𝗆𝖾%20𝖠𝗇𝗂𝗆𝖾%20𝖲𝗍𝗋𝖾𝖺𝗆𝗂𝗇𝗀%20𝖣𝖺𝗍𝖺%20𝖠𝖯𝖨&descSize=30" />
</div> </div>
@@ -19,8 +22,8 @@
<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/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/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/License-MIT-22c55e?style=flat-square&logo=mit&logoColor=white" alt="License"/>
<img src="https://img.shields.io/badge/Version-2.1.0-f43f8e?style=flat-square&logoColor=white" alt="Version"/> <img src="https://img.shields.io/badge/Version-2.2.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/Endpoints-38-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"/> <img src="https://img.shields.io/badge/Anime-10000+-a855f7?style=flat-square&logoColor=white" alt="Anime Database"/>
</p> </p>
@@ -84,7 +87,7 @@
### Why AniKotoAPI? ### Why AniKotoAPI?
- 🎬 **33 Endpoints** — Complete coverage of anikototv.to data - 🎬 **38 Endpoints** — Complete coverage of anikototv.to data
- 🔍 **Full-Text Search** — Search anime by keyword with suggestions - 🔍 **Full-Text Search** — Search anime by keyword with suggestions
- 📺 **Episode Lists** — AJAX-loaded episode data with server info - 📺 **Episode Lists** — AJAX-loaded episode data with server info
- 🎯 **Smart Filtering** — Genre, type, status, rating, sort, season, year - 🎯 **Smart Filtering** — Genre, type, status, rating, sort, season, year
@@ -159,10 +162,13 @@ flowchart TD
### 📺 Streaming ### 📺 Streaming
- **Watch page** — full episode data with servers - **Watch page** — full episode data with servers
- **Stream info** — video embed URLs via AJAX - **Stream info** — video embed URLs via AJAX
- **Server list** — all available streaming servers - **Stream URL Resolution** — resolve embed URLs to actual m3u8/mp4
- **Server list** — all available streaming servers with normalized names
- **Mapper API** — gogoanime/anivibe server sources - **Mapper API** — gogoanime/anivibe server sources
- **Episode navigation** — prev/next episode data - **Episode navigation** — prev/next episode data
- **Next episode schedule** — countdown timer data - **Next episode schedule** — countdown timer data
- **M3U8 Proxy** — CORS-free HLS playlist proxy with URL rewriting
- **TS Proxy** — CORS-free video segment proxy
</td> </td>
<td> <td>
@@ -183,18 +189,20 @@ flowchart TD
| Feature | Description | Status | | Feature | Description | Status |
|:---|:---|:---:| |:---|:---|:---:|
| 🎬 33 API Endpoints | Complete coverage of anime data | ✅ | | 🎬 38 API Endpoints | Complete coverage of anime data | ✅ |
| 🔍 Full-Text Search | Keyword search with pagination | ✅ | | 🔍 Full-Text Search | Keyword search with pagination | ✅ |
| 📺 Episode Lists | AJAX-loaded episode data | ✅ | | 📺 Episode Lists | AJAX-loaded episode data | ✅ |
| 🎯 Advanced Filtering | Genre, type, status, rating, sort | ✅ | | 🎯 Advanced Filtering | Genre, type, status, rating, sort, season | ✅ |
| 🏆 Top 10 Rankings | Day/week/month leaderboards | ✅ | | 🏆 Top 10 Rankings | Day/week/month leaderboards | ✅ |
| 🎲 Random Anime | Random anime discovery | ✅ | | 🎲 Random Anime | Random anime discovery | ✅ |
| 📡 Streaming Servers | Video embed URLs + mapper API | ✅ | | 📡 Streaming Servers | Video embed URLs + mapper API | ✅ |
| 🔗 Stream URL Resolution | Resolve embed URLs to m3u8/mp4 | ✅ |
| 📋 AZ List | A-Z alphabetical browsing | ✅ | | 📋 AZ List | A-Z alphabetical browsing | ✅ |
| 🔄 Smart Caching | LRU cache with configurable TTL | ✅ | | 🔄 Smart Caching | LRU cache with configurable TTL | ✅ |
| 🌐 M3U8 Proxy | CORS-free HLS proxy with URL rewriting | ✅ |
| 🚀 One-Click Deploy | Vercel button deployment | ✅ | | 🚀 One-Click Deploy | Vercel button deployment | ✅ |
| 🏗️ Express Mode | Standalone server with `npm start` | ✅ | | 🏗️ Express Mode | Standalone server with `npm start` | ✅ |
| 📖 AlisaReactionBot Style | Full JSDoc documentation | ✅ | | 📖 Full JSDoc Docs | Complete documentation coverage | ✅ |
--- ---
@@ -230,7 +238,6 @@ flowchart TD
| 🔍 [Cheerio](https://cheerio.js.org/) | HTML parsing & scraping | 1.0 | [Docs](https://cheerio.js.org/docs/) | | 🔍 [Cheerio](https://cheerio.js.org/) | HTML parsing & scraping | 1.0 | [Docs](https://cheerio.js.org/docs/) |
| 🌐 [Axios](https://axios-http.com/) | HTTP client for scraping | 1.8 | [Docs](https://axios-http.com/docs/intro) | | 🌐 [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) | | 🔧 [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) |
### 📦 Key Dependencies ### 📦 Key Dependencies
@@ -239,7 +246,6 @@ flowchart TD
"express": "^4.21.0", // HTTP server "express": "^4.21.0", // HTTP server
"axios": "^1.8.0", // HTTP client for scraping "axios": "^1.8.0", // HTTP client for scraping
"cheerio": "^1.0.0-rc.12", // HTML parsing "cheerio": "^1.0.0-rc.12", // HTML parsing
"cors": "^2.8.5", // CORS middleware
"compression": "^1.7.4", // Response compression "compression": "^1.7.4", // Response compression
"dotenv": "^16.4.0" // Environment variables "dotenv": "^16.4.0" // Environment variables
} }
@@ -300,8 +306,8 @@ AniKotoAPI/
│ │ │ │
│ ├── 📂 docs/ # 📚 API documentation │ ├── 📂 docs/ # 📚 API documentation
│ │ ├── 📄 index.md # Overview, quick start │ │ ├── 📄 index.md # Overview, quick start
│ │ ├── 📄 endpoints.md # Full API reference (33 endpoints) │ │ ├── 📄 endpoints.md # Full API reference (38 endpoints)
│ │ ├── 📄 streaming.md # Streaming flow guide │ │ ├── 📄 streaming.md # Streaming flow guide + proxy
│ │ ├── 📄 examples.md # Code examples (cURL, JS, Python) │ │ ├── 📄 examples.md # Code examples (cURL, JS, Python)
│ │ └── 📄 architecture.md # Project structure, tech stack │ │ └── 📄 architecture.md # Project structure, tech stack
│ │ │ │
@@ -310,41 +316,47 @@ AniKotoAPI/
│ ├── 📂 configs/ # 🔧 Configuration files │ ├── 📂 configs/ # 🔧 Configuration files
│ │ ├── 📄 dataUrl.js # 🌐 URL patterns for anikototv.to │ │ ├── 📄 dataUrl.js # 🌐 URL patterns for anikototv.to
│ │ ├── 📄 header.config.js # 📋 Request headers │ │ ├── 📄 header.config.js # 📋 Request headers
│ │ └── 📄 ids.config.js # 🏷️ Genre/Type/Status/Rating ID mappings │ │ └── 📄 ids.config.js # 🏷️ Genre/Type/Status/Source/Season ID mappings
│ │ │ │
│ ├── 📂 controllers/ # 🎮 Route handlers (22 files) │ ├── 📂 controllers/ # 🎮 Route handlers (24 files)
│ │ ├── 📄 homeInfo.controller.js │ │ ├── 📄 homeInfo.controller.js
│ │ ├── 📄 animeInfo.controller.js │ │ ├── 📄 animeInfo.controller.js
│ │ ├── 📄 search.controller.js │ │ ├── 📄 search.controller.js
│ │ ├── 📄 episodeList.controller.js │ │ ├── 📄 episodeList.controller.js
│ │ ├── 📄 episodeListAjax.controller.js │ │ ├── 📄 episodeListAjax.controller.js
│ │ ├── 📄 streamInfo.controller.js │ │ ├── 📄 streamInfo.controller.js
│ │ ├── 📄 streamResolver.controller.js # 🆕 Stream URL resolution + quality detection
│ │ ├── 📄 filter.controller.js │ │ ├── 📄 filter.controller.js
│ │ ├── 📄 watchPage.controller.js │ │ ├── 📄 watchPage.controller.js
│ │ └── 📄 ... (14 more) │ │ └── 📄 ... (15 more)
│ │ │ │
│ ├── 📂 extractors/ # 🔍 HTML scrapers (22 files) │ ├── 📂 extractors/ # 🔍 HTML scrapers (26 files)
│ │ ├── 📄 homeInfo.extractor.js # 🏠 Home page data │ │ ├── 📄 homeInfo.extractor.js # 🏠 Home page data
│ │ ├── 📄 search.extractor.js # 🔍 Search results │ │ ├── 📄 search.extractor.js # 🔍 Search results
│ │ ├── 📄 animeInfo.extractor.js # 📺 Anime details │ │ ├── 📄 animeInfo.extractor.js # 📺 Anime details
│ │ ├── 📄 streamInfo.extractor.js # 📡 Streaming servers │ │ ├── 📄 streamInfo.extractor.js # 📡 Streaming servers
│ │ ├── 📄 streamResolver.extractor.js # 🔗 Stream URL resolution, M3U8 parser
│ │ ├── 📄 filter.extractor.js # 🎯 Filtered results │ │ ├── 📄 filter.extractor.js # 🎯 Filtered results
│ │ ├── 📄 watchPage.extractor.js # ▶️ Watch page data │ │ ├── 📄 watchPage.extractor.js # ▶️ Watch page data
│ │ ├── 📄 seasons.extractor.js # 📅 Season info from watch page
│ │ ├── 📄 watchOrder.extractor.js # 📋 Watch order from sidebar
│ │ ├── 📄 episodeList.extractor.js # 📋 Episode lists │ │ ├── 📄 episodeList.extractor.js # 📋 Episode lists
│ │ └── 📄 ... (15 more) │ │ └── 📄 ... (16 more)
│ │ │ │
│ ├── 📂 helper/ # 🛠️ Utility functions │ ├── 📂 helper/ # 🛠️ Utility functions
│ │ ├── 📄 cache.helper.js # 💾 In-memory caching │ │ ├── 📄 cache.helper.js # 💾 In-memory caching
│ │ ├── 📄 countPages.helper.js # 📄 Pagination counter │ │ ├── 📄 countPages.helper.js # 📄 Pagination counter
│ │ ├── 📄 extractPages.helper.js # 📃 Page fetcher │ │ ├── 📄 extractPages.helper.js # 📃 Page fetcher
│ │ ├── 📄 formatTitle.helper.js # 🔤 Title formatter │ │ ├── 📄 formatTitle.helper.js # 🔤 Title formatter
│ │ ├── 📄 mirror.helper.js # 🌐 Multi-mirror fallback (5 domains)
│ │ ├── 📄 parseListItem.helper.js # 📋 Shared list item parser
│ │ └── 📄 pagination.helper.js # 📊 Pagination metadata generator │ │ └── 📄 pagination.helper.js # 📊 Pagination metadata generator
│ │ │ │
│ ├── 📂 middleware/ # 🔧 Express middleware │ ├── 📂 middleware/ # 🔧 Express middleware
│ │ └── 📄 creatorInfo.js # ✍️ Creator attribution injection │ │ └── 📄 creatorInfo.js # ✍️ Creator attribution injection
│ │ │ │
│ └── 📂 routes/ # 🛤️ Express routes │ └── 📂 routes/ # 🛤️ Express routes
│ ├── 📄 apiRoutes.js # 🌐 Main API routes (33 endpoints) │ ├── 📄 apiRoutes.js # 🌐 Main API routes (38 endpoints)
│ └── 📄 category.route.js # 🏷️ Category routes │ └── 📄 category.route.js # 🏷️ Category routes
│ │
├── 📄 server.js # 🚀 Express server entry point ├── 📄 server.js # 🚀 Express server entry point
@@ -448,6 +460,21 @@ curl "https://anikototvapi.vercel.app/api/servers?ids=dXNCT3hNQzk3THhSTW8ySnM5..
curl "https://anikototvapi.vercel.app/api/stream?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..." curl "https://anikototvapi.vercel.app/api/stream?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
``` ```
### Stream URL Resolution
The `/api/stream` endpoint returns an embed URL. To get the actual video URL (m3u8/mp4):
```bash
# Resolve embed URL to actual stream URL
curl "https://anikototvapi.vercel.app/api/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
# Get quality options from an M3U8 playlist
curl "https://anikototvapi.vercel.app/api/stream/qualities?url=https://example.com/playlist.m3u8"
# Proxy M3U8 playlist (rewrites URLs for CORS-free playback)
curl "https://anikototvapi.vercel.app/api/stream/proxy?url=https://example.com/playlist.m3u8"
```
### Dub & Sub Switch ### Dub & Sub Switch
Servers have a `type` field — use it to pick sub or dub: Servers have a `type` field — use it to pick sub or dub:
@@ -1974,6 +2001,144 @@ console.log(resp.data);
--- ---
> ## 🔗 GET Stream URL Resolution
### Endpoint
```bash
/stream/resolve
```
#### Parameters
| Parameter | Type | Mandatory | Default | Description |
| :-------: | :--: | :-------: | :-----: | :---------: |
| `id` | `string` | Yes ✔️ | — | `link_id` from `/servers` response |
| `slug` | `string` | No | — | Anime slug (for watch page session) |
#### Example of request
```bash
curl "https://anikototvapi.vercel.app/api/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
```
```javascript
import axios from "axios";
const resp = await axios.get("https://anikototvapi.vercel.app/api/stream/resolve", {
params: { id: "yourLinkId" }
});
console.log(resp.data);
```
#### Sample Response
```json
{
"success": true,
"results": {
"url": "https://vid-tube.site/hls/b32de9d4a3230c95f52948373e6e1549.m3u8",
"type": "hls",
"server": "HD-1",
"subtitles": []
}
}
```
---
> ## 📊 GET Stream Qualities
### Endpoint
```bash
/stream/qualities
```
#### Parameters
| Parameter | Type | Mandatory | Default | Description |
| :-------: | :--: | :-------: | :-----: | :---------: |
| `url` | `string` | Yes ✔️ | — | M3U8 playlist URL |
#### Example of request
```bash
curl "https://anikototvapi.vercel.app/api/stream/qualities?url=https://example.com/playlist.m3u8"
```
#### Sample Response
```json
{
"success": true,
"results": {
"qualities": [
{ "url": "https://example.com/360.m3u8", "quality": "360p", "width": 640, "height": 360, "bandwidth": 800000, "codec": "avc1" },
{ "url": "https://example.com/480.m3u8", "quality": "480p", "width": 854, "height": 480, "bandwidth": 1400000, "codec": "avc1" },
{ "url": "https://example.com/720.m3u8", "quality": "720p", "width": 1280, "height": 720, "bandwidth": 2800000, "codec": "avc1" }
]
}
}
```
---
> ## 🌐 GET Stream Proxy (M3U8)
### Endpoint
```bash
/stream/proxy
```
Rewrites relative URLs inside an M3U8 playlist to proxy through the API, adding CORS headers for cross-origin playback.
#### Parameters
| Parameter | Type | Mandatory | Default | Description |
| :-------: | :--: | :-------: | :-----: | :---------: |
| `url` | `string` | Yes ✔️ | — | M3U8 playlist URL |
#### Example of request
```bash
curl "https://anikototvapi.vercel.app/api/stream/proxy?url=https://example.com/playlist.m3u8"
```
#### Sample Response
Raw M3U8 content with URLs rewritten to `https://anikototvapi.vercel.app/api/stream/proxy?url=...` and `https://anikototvapi.vercel.app/api/stream/ts-proxy?url=...` for `.ts` segments.
---
> ## 🎬 GET Stream TS Proxy
### Endpoint
```bash
/stream/ts-proxy
```
Proxies `.ts` video segments with proper `Content-Type: video/mp2t` and CORS headers.
#### Parameters
| Parameter | Type | Mandatory | Default | Description |
| :-------: | :--: | :-------: | :-----: | :---------: |
| `url` | `string` | Yes ✔️ | — | `.ts` segment URL |
#### Example of request
```bash
curl "https://anikototvapi.vercel.app/api/stream/ts-proxy?url=https://example.com/segment.ts"
```
#### Sample Response
Binary video segment data with `Content-Type: video/mp2t` and `Access-Control-Allow-Origin: *`.
---
## 📋 API Response Schema ## 📋 API Response Schema
### Success Response ### Success Response
@@ -2022,7 +2187,7 @@ All list endpoints include pagination metadata in the response:
| `hasNext` | `boolean` | Whether there is a next page | | `hasNext` | `boolean` | Whether there is a next page |
| `hasPrev` | `boolean` | Whether there is a previous 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` **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`, `/api/upcoming`, `/api/top-rankings`, `/api/recently-updated`, `/api/completed`
### Anime Item Object ### Anime Item Object
@@ -2151,6 +2316,7 @@ CMD ["node", "server.js"]
| Version | Date | Key Changes | | Version | Date | Key Changes |
|:---|:---|:---| |:---|:---|:---|
| **2.2.0** | 2026-07-28 | Streaming resolver, M3U8/TS proxy, 5 new endpoints, bug fixes, full diagnostic sweep |
| **1.7.2** | 2026-06-08 | Full rebrand AniKotoAPI → AniKotoAPI, docs folder with real data, streaming fix | | **1.7.2** | 2026-06-08 | Full rebrand AniKotoAPI → AniKotoAPI, docs folder with real data, streaming fix |
| **1.7.1** | 2026-06-08 | Updated Vercel URL to anikototvapi.vercel.app | | **1.7.1** | 2026-06-08 | Updated Vercel URL to anikototvapi.vercel.app |
| **1.7.0** | 2026-06-08 | Premium landing page with SVG icons, live console, particles, glassmorphism | | **1.7.0** | 2026-06-08 | Premium landing page with SVG icons, live console, particles, glassmorphism |
@@ -2262,21 +2428,25 @@ The API can access 10,000+ anime titles from anikototv.to. The most-popular endp
### ✅ Completed ### ✅ Completed
- [x] 🎬 33 API endpoints covering all data - [x] 🎬 38 API endpoints covering all data
- [x] 🔍 Full-text search with pagination - [x] 🔍 Full-text search with pagination
- [x] 📺 Episode lists via AJAX loading - [x] 📺 Episode lists via AJAX loading
- [x] 🎯 Advanced filtering (genre, type, status, rating, sort) - [x] 🎯 Advanced filtering (genre, type, status, rating, sort, season, year)
- [x] 🏆 Top 10 rankings (day/week/month) - [x] 🏆 Top 10 rankings (day/week/month)
- [x] 🎲 Random anime discovery - [x] 🎲 Random anime discovery
- [x] 📡 Streaming server info + mapper API - [x] 📡 Streaming server info + mapper API
- [x] 🔗 Stream URL resolution (embed → m3u8/mp4)
- [x] 🌐 M3U8 proxy for CORS-free HLS playback
- [x] 📋 AZ List alphabetical browsing - [x] 📋 AZ List alphabetical browsing
- [x] 📅 Seasons and watch order extraction
- [x] 🔄 Smart caching with LRU and configurable TTL - [x] 🔄 Smart caching with LRU and configurable TTL
- [x] 🚀 One-click Vercel deployment - [x] 🚀 One-click Vercel deployment
- [x] 📖 Comprehensive documentation with real API data - [x] 📖 Comprehensive documentation with real API data
- [x] 🏗️ AlisaReactionBot-style code comments - [x] 🏗️ Full JSDoc documentation coverage
- [x] 🌐 Premium landing page with SVG icons - [x] 🌐 Premium landing page with SVG icons
- [x] 📱 PWA manifest and Open Graph image - [x] 📱 PWA manifest and Open Graph image
- [x] 📚 Full docs/ folder with examples - [x] 📚 Full docs/ folder with examples
- [x] 🐛 Full diagnostic sweep — all 34 endpoints passing
--- ---
@@ -2430,5 +2600,5 @@ Free to use, modify, and distribute — see the [LICENSE](LICENSE) file for deta
<p align="center"> <p align="center">
<b>Made With ❤️ For The Anime Community</b> <b>Made With ❤️ For The Anime Community</b>
<br/><br/> <br/><br/>
<sub>© 2026 Shineii86. All Rights Reserved.</sub> <sub>© Shinei Nouzen. All Rights Reserved.</sub>
</p> </p>
+25 -28
View File
@@ -1,18 +1,18 @@
--- ---
name: API Tester name: API Tester
description: API testing specialist for AniKotoAPI — validates all 33 endpoints, streaming flow, mirror fallback, cache behavior, and error handling description: API testing specialist for AniKotoAPI — validates all 38 endpoints, streaming flow, mirror fallback, cache behavior, and error handling
mode: subagent mode: subagent
color: '#9B59B6' color: '#9B59B6'
--- ---
# API Tester — AniKotoAPI # 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. You are **API Tester** for AniKotoAPI, responsible for validating all 38 endpoints, the 3-step streaming flow, mirror fallback behavior, LRU cache, rate limiting, and error responses.
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Test file**: `test.js` (27 tests, run with `node test.js`) - **Test file**: `test.js` (38 tests, run with `node test.js`)
- **Live API**: `https://anikototvapi.vercel.app/api` - **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 - **Pattern**: Each test does a real HTTP request to the live API, validates response structure, and prints pass/fail with timing
@@ -45,44 +45,41 @@ const test = async (name, fn) => {
|----------|------------| |----------|------------|
| `GET /api/` | `success: true`, `results.spotlights`, `results.trending`, `results.genres` | | `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/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/info?id=one-piece-odmau` | `results.title`, `results.animeId` |
| `GET /api/episodes/:slug` | `results.episodes` array, each has `server_ids` | | `GET /api/episodes/:slug` | `results.episodes` array |
| `GET /api/servers?ids=...` | `results` array, each has `type`, `link_id`, `name` | | `GET /api/servers?ids=...` | `results` array |
| `GET /api/stream?id=...` | `results.url` string | | `GET /api/watch?slug=&ep=1` | `results` with servers, episodeNumber |
| `GET /api/watch?slug=&ep=1` | `results` with episodes, servers, recommendations | | `GET /api/download?slug=&ep=1` | `results` with download links (optional) |
### Discovery (test subset) ### Discovery (test subset)
| Endpoint | Validation | | Endpoint | Validation |
|----------|------------| |----------|------------|
| `GET /api/spotlight` | `results` array | | `GET /api/spotlight` | `results` array |
| `GET /api/trending` | `results` array | | `GET /api/trending` | `results` array |
| `GET /api/top-ten` | `results` array with day/week/month | | `GET /api/top-ten` | `results` object with day/week/month |
| `GET /api/random` | `results` with `title`, `slug` | | `GET /api/random` | `results` with `title`, `slug` |
| `GET /api/suggestions?keyword=naruto` | `results` array | | `GET /api/suggestions?keyword=naruto` | `results` array |
| `GET /api/most-popular` | `results` array | | `GET /api/most-popular` | `results` object |
| `GET /api/upcoming` | `results` array |
| `GET /api/top-rankings` | `results` array with rank positions |
| `GET /api/recently-updated` | `results` array |
| `GET /api/completed` | `results` array |
### Lists (test subset) ### Lists
| Endpoint | Validation | | Endpoint | Validation |
|----------|------------| |----------|------------|
| `GET /api/new-release` | `results` array | | `GET /api/new-release` | `results` object |
| `GET /api/newly-added` | `results` array | | `GET /api/newly-added` | `results` object |
| `GET /api/latest-updated` | `results` array (may need deployment) | | `GET /api/latest-updated` | `results` object |
| `GET /api/schedule` | `results` array |
| `GET /api/az-list/a` | `results` array |
### Filter ### Filter
| Endpoint | Validation | | Endpoint | Validation |
|----------|------------| |----------|------------|
| `GET /api/filter?genre[]=1` | `results` with pagination | | `GET /api/filter?keyword=naruto` | `results` with pagination |
| `GET /api/genre/action` | `results` array | | `GET /api/genre/action` | `results` with data, totalPages |
| `GET /api/type/tv` | `results` array | | `GET /api/type/tv` | `results` with data, totalPages |
| `GET /api/status/aired` | `results` array | | `GET /api/status/airing` | `results` with data, totalPages |
| `GET /api/az-list/a` | `results` with data, totalPages |
### 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 ### System
| Endpoint | Validation | | Endpoint | Validation |
@@ -90,7 +87,7 @@ const test = async (name, fn) => {
| `GET /api/health` | `results.status: "healthy"` | | `GET /api/health` | `results.status: "healthy"` |
| `GET /api/stats` | `results.endpoints` count | | `GET /api/stats` | `results.endpoints` count |
| `GET /api/cache/stats` | `results.hits`, `results.misses` | | `GET /api/cache/stats` | `results.hits`, `results.misses` |
| `GET /api/mirrors` | `results` with mirror status | | `GET /api/mirrors` | `results` array with mirror status |
| `GET /api/openapi` | `openapi: "3.0.3"`, `paths` object | | `GET /api/openapi` | `openapi: "3.0.3"`, `paths` object |
## Streaming Flow Test ## Streaming Flow Test
+8 -5
View File
@@ -11,7 +11,7 @@ You are **Backend Architect** for AniKotoAPI, a free REST API scraping anime dat
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Stack**: Node.js (ESM modules), Express 4.21, Cheerio 1.0, Axios 1.8, compression 1.8 - **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) - **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) - **Data Source**: anikototv.to (5 mirror domains: anikototv.to, anikoto.cz, anikoto.me, anikoto.net, anikototv.se)
@@ -25,17 +25,20 @@ Client → Vercel Edge/Express → Rate Limiter → CORS + Security Headers →
### Key Files ### Key Files
- `server.js` — Express entry, CORS, compression, rate limiting, timeout, error handler - `server.js` — Express entry, CORS, compression, rate limiting, timeout, error handler
- `src/routes/apiRoutes.js` — All 33 route definitions + OpenAPI spec - `src/routes/apiRoutes.js` — All 36 route definitions + OpenAPI spec
- `src/helper/cache.helper.js` — LRU cache with per-endpoint TTL (3min-60min) - `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/mirror.helper.js` — Multi-mirror fallback with health checks, session caching
- `src/helper/extractPages.helper.js` — Page fetching using `fetchWithMirror()` - `src/helper/extractPages.helper.js` — Page fetching using `fetchWithMirror()`
- `src/extractors/` — 22 HTML scrapers using Cheerio selectors - `src/helper/parseListItem.helper.js` — Shared list item parser (DRY across extractors)
- `src/controllers/` — 22 route handlers - `src/extractors/` — 26 HTML scrapers using Cheerio selectors
- `src/controllers/` — 26 route handlers
- `src/configs/ids.config.js` — Genre/Type/Status/Rating/Sort/Source/Season ID mappings
### Endpoints (33 total) ### Endpoints (36 total)
**Core**: `/` (home), `/search`, `/info`, `/watch`, `/episodes/:id`, `/episodes-ajax/:id` **Core**: `/` (home), `/search`, `/info`, `/watch`, `/episodes/:id`, `/episodes-ajax/:id`
**Streaming**: `/servers`, `/stream`, `/download`, `/mapper-servers` **Streaming**: `/servers`, `/stream`, `/download`, `/mapper-servers`
**Discovery**: `/spotlight`, `/trending`, `/top-ten`, `/random`, `/suggestions`, `/most-popular` **Discovery**: `/spotlight`, `/trending`, `/top-ten`, `/random`, `/suggestions`, `/most-popular`
**New**: `/upcoming`, `/top-rankings`, `/recently-updated`, `/completed`
**Lists**: `/new-release`, `/newly-added`, `/latest-updated`, `/trending-sidebar`, `/az-list/:letter` **Lists**: `/new-release`, `/newly-added`, `/latest-updated`, `/trending-sidebar`, `/az-list/:letter`
**Filter**: `/filter`, `/genre/:name`, `/type/:name`, `/status/:name` **Filter**: `/filter`, `/genre/:name`, `/type/:name`, `/status/:name`
**Anime**: `/seasons/:id`, `/watch-order/:id`, `/schedule` **Anime**: `/seasons/:id`, `/watch-order/:id`, `/schedule`
+1 -1
View File
@@ -11,7 +11,7 @@ You are **DevOps Automator** for AniKotoAPI, responsible for Vercel deployment,
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Deployment**: Vercel (auto-deploys from main branch) - **Deployment**: Vercel (auto-deploys from main branch)
- **Git remote**: `https://github.com/Shineii86/AniKotoAPI.git` - **Git remote**: `https://github.com/Shineii86/AniKotoAPI.git`
- **Git identity**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>` - **Git identity**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>`
+2 -2
View File
@@ -11,7 +11,7 @@ You are **Performance Benchmarker** for AniKotoAPI, responsible for measuring an
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Live API**: `https://anikototvapi.vercel.app/api` - **Live API**: `https://anikototvapi.vercel.app/api`
- **Deployment**: Vercel serverless (cold starts, memory limits, execution time limits) - **Deployment**: Vercel serverless (cold starts, memory limits, execution time limits)
@@ -133,7 +133,7 @@ compression({
## What You Do ## What You Do
1. **Benchmark endpoints** — Measure response times for all 33 endpoints 1. **Benchmark endpoints** — Measure response times for all 38 endpoints
2. **Profile cache** — Track hit/miss ratios, measure TTL effectiveness 2. **Profile cache** — Track hit/miss ratios, measure TTL effectiveness
3. **Test compression** — Compare compressed vs uncompressed sizes 3. **Test compression** — Compare compressed vs uncompressed sizes
4. **Load test** — Simulate concurrent users, check rate limiting 4. **Load test** — Simulate concurrent users, check rate limiting
+1 -1
View File
@@ -11,7 +11,7 @@ You are **Security Architect** for AniKotoAPI, responsible for securing a public
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Risk profile**: Public API, no auth, scrapes external site, deployed on Vercel - **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 - **Attack surface**: SSRF via mapper API, XSS in error messages, rate limit bypass, header injection
+5 -5
View File
@@ -11,7 +11,7 @@ You are **Technical Writer** for AniKotoAPI, responsible for maintaining all doc
## Your Identity ## Your Identity
- **Project**: AniKotoAPI v2.0.0 — https://github.com/Shineii86/AniKotoAPI - **Project**: AniKotoAPI v2.2.0 — https://github.com/Shineii86/AniKotoAPI
- **Author format**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>` - **Author format**: `Shinei Nouzen <157171073+Shineii86@users.noreply.github.com>`
- **Changelog rule**: Append at top, never delete/edit old entries - **Changelog rule**: Append at top, never delete/edit old entries
@@ -24,7 +24,7 @@ AniKotoAPI/
├── CONTRIBUTING.md # Contribution guidelines ├── CONTRIBUTING.md # Contribution guidelines
├── docs/ ├── docs/
│ ├── index.md # Overview, quick start │ ├── index.md # Overview, quick start
│ ├── endpoints.md # Full API reference (33 endpoints) │ ├── endpoints.md # Full API reference (38 endpoints)
│ ├── streaming.md # 3-step streaming flow guide │ ├── streaming.md # 3-step streaming flow guide
│ ├── examples.md # cURL, JS, Python examples │ ├── examples.md # cURL, JS, Python examples
│ └── architecture.md # Project structure, tech stack │ └── architecture.md # Project structure, tech stack
@@ -69,7 +69,7 @@ AniKotoAPI/
## Project Structure (tree) ## Project Structure (tree)
## API Endpoints ## API Endpoints
## Streaming Flow ## Streaming Flow
## Endpoint Documentation (33 sections) ## Endpoint Documentation (36 sections)
## API Response Schema ## API Response Schema
## Configuration (.env) ## Configuration (.env)
## Deployment ## Deployment
@@ -106,7 +106,7 @@ curl "https://anikototvapi.vercel.app/api/endpoint"
### Version Bumping ### Version Bumping
1. Update `package.json` version 1. Update `package.json` version
2. Update README.md badge: `Version-2.0.0` 2. Update README.md badge: `Version-2.2.0`
3. Update OpenAPI spec version in `apiRoutes.js` 3. Update OpenAPI spec version in `apiRoutes.js`
4. Add CHANGELOG.md entry (prepend, never delete) 4. Add CHANGELOG.md entry (prepend, never delete)
@@ -140,7 +140,7 @@ flowchart TD
1. **Update CHANGELOG** — Add entries for every version bump 1. **Update CHANGELOG** — Add entries for every version bump
2. **Maintain README** — Keep endpoint list, badges, examples current 2. **Maintain README** — Keep endpoint list, badges, examples current
3. **Document endpoints** — Full docs for each of 33 endpoints 3. **Document endpoints** — Full docs for each of 38 endpoints
4. **Write examples** — cURL, JS, Python for common use cases 4. **Write examples** — cURL, JS, Python for common use cases
5. **Update OpenAPI** — Keep spec in sync with actual routes 5. **Update OpenAPI** — Keep spec in sync with actual routes
6. **Review docs/ folder** — Keep all 5 markdown files current 6. **Review docs/ folder** — Keep all 5 markdown files current
+43 -20
View File
@@ -21,8 +21,8 @@ AniKotoAPI/
│ │
├── docs/ # API documentation ├── docs/ # API documentation
│ ├── index.md # Overview, quick start, features │ ├── index.md # Overview, quick start, features
│ ├── endpoints.md # Full API reference (33 endpoints) │ ├── endpoints.md # Full API reference (38 endpoints)
│ ├── streaming.md # Streaming flow guide (3-step) │ ├── streaming.md # Streaming flow guide + resolver/proxy
│ ├── examples.md # cURL, JavaScript, Python, Node.js │ ├── examples.md # cURL, JavaScript, Python, Node.js
│ └── architecture.md # This file │ └── architecture.md # This file
│ │
@@ -30,65 +30,76 @@ AniKotoAPI/
│ ├── configs/ │ ├── configs/
│ │ ├── dataUrl.js # URL patterns, BASE_URL: https://anikototv.to │ │ ├── dataUrl.js # URL patterns, BASE_URL: https://anikototv.to
│ │ ├── header.config.js # Request headers (User-Agent, Referer, etc.) │ │ ├── header.config.js # Request headers (User-Agent, Referer, etc.)
│ │ └── ids.config.js # Genre/type/status ID mappings │ │ └── ids.config.js # Genre/type/status/source/season ID mappings
│ │ │ │
│ ├── routes/ │ ├── routes/
│ │ ├── apiRoutes.js # All route definitions + OpenAPI spec │ │ ├── apiRoutes.js # All route definitions + OpenAPI spec (38 endpoints)
│ │ └── category.route.js # genre/:name, type/:name, status/:name │ │ └── category.route.js # genre/:name, type/:name, status/:name
│ │ │ │
│ ├── controllers/ │ ├── controllers/
│ │ ├── homeInfo.controller.js # Homepage data │ │ ├── homeInfo.controller.js # Homepage data
│ │ ├── search.controller.js # Anime search │ │ ├── search.controller.js # Anime search
│ │ ├── animeInfo.controller.js # Anime info │ │ ├── animeInfo.controller.js # Anime info (accepts ?id= or ?slug=)
│ │ ├── episodeList.controller.js # Episode list │ │ ├── episodeList.controller.js # Episode list
│ │ ├── episodeListAjax.controller.js # AJAX episode list
│ │ ├── servers.controller.js # Server list │ │ ├── servers.controller.js # Server list
│ │ ├── stream.controller.js # Stream URL │ │ ├── stream.controller.js # Stream URL
│ │ ├── streamResolver.controller.js # 🆕 Stream URL resolution + quality detection
│ │ ├── suggestion.controller.js # Anime suggestions │ │ ├── suggestion.controller.js # Anime suggestions
│ │ ├── spotlight.controller.js # Spotlight anime │ │ ├── spotlight.controller.js # Spotlight anime
│ │ ├── trending.controller.js # Trending anime │ │ ├── trending.controller.js # Trending anime
│ │ ├── topten.controller.js # Top 10 │ │ ├── topten.controller.js # Top 10
│ │ ├── topAnimeRankings.controller.js # 🆕 Top rankings
│ │ ├── upcomingAnime.controller.js # 🆕 Upcoming anime
│ │ ├── recentlyUpdatedTabs.controller.js # 🆕 Recently updated with tabs
│ │ ├── completedAnime.controller.js # 🆕 Completed anime
│ │ ├── schedule.controller.js # Schedule │ │ ├── schedule.controller.js # Schedule
│ │ ├── random.controller.js # Random anime │ │ ├── random.controller.js # Random anime
│ │ ├── newRelease.controller.js # New releases + Latest Updated │ │ ├── newRelease.controller.js # New releases + Latest Updated
│ │ ├── popular.controller.js # Most popular │ │ ├── popular.controller.js # Most popular
│ │ ├── category.controller.js # Genre filter │ │ ├── category.controller.js # Genre/Type/Status filter
│ │ ├── category.controller.js # Type filter
│ │ ├── category.controller.js # Status filter
│ │ └── filter.controller.js # Advanced filter │ │ └── filter.controller.js # Advanced filter
│ │ │ │
│ ├── extractors/ │ ├── extractors/
│ │ ├── home.extractor.js # Homepage extraction │ │ ├── homeInfo.extractor.js # Homepage extraction
│ │ ├── search.extractor.js # Search results │ │ ├── search.extractor.js # Search results
│ │ ├── info.extractor.js # Anime details │ │ ├── animeInfo.extractor.js # Anime details
│ │ ├── episodeList.extractor.js # Episode list + server_ids │ │ ├── episodeList.extractor.js # Episode list + server_ids
│ │ ├── episodeListAjax.extractor.js # AJAX episode list
│ │ ├── serverList.extractor.js # Server list │ │ ├── serverList.extractor.js # Server list
│ │ ├── streamInfo.extractor.js # Stream URL extraction │ │ ├── streamInfo.extractor.js # Stream URL extraction (with session cookies)
│ │ ├── streamResolver.extractor.js # 🆕 Stream URL resolution, M3U8 parser, server normalization
│ │ ├── spotlight.extractor.js # Spotlight anime │ │ ├── spotlight.extractor.js # Spotlight anime
│ │ ├── trending.extractor.js # Trending anime │ │ ├── trending.extractor.js # Trending anime
│ │ ├── topTen.extractor.js # Top 10 │ │ ├── topTen.extractor.js # Top 10
│ │ ├── topAnimeRankings.extractor.js # 🆕 Top rankings from sidebar
│ │ ├── upcomingAnime.extractor.js # 🆕 Upcoming anime
│ │ ├── recentlyUpdatedTabs.extractor.js # 🆕 Recently updated with tab filtering
│ │ ├── completedAnime.extractor.js # 🆕 Completed anime from top-table
│ │ ├── schedule.extractor.js # Schedule │ │ ├── schedule.extractor.js # Schedule
│ │ ├── random.extractor.js # Random anime │ │ ├── random.extractor.js # Random anime
│ │ ├── newRelease.extractor.js # New releases + Latest Updated │ │ ├── newRelease.extractor.js # New releases + Latest Updated
│ │ ├── mostPopular.extractor.js # Most popular │ │ ├── mostPopular.extractor.js # Most popular
│ │ ├── genre.extractor.js # Genre filter │ │ ├── genre.extractor.js # Genre filter
│ │ ├── type.extractor.js # Type filter │ │ ├── filter.extractor.js # Advanced filter (with source/season params)
│ │ ├── status.extractor.js # Status filter
│ │ ├── filter.extractor.js # Advanced filter
│ │ ├── suggestion.extractor.js # Suggestions │ │ ├── suggestion.extractor.js # Suggestions
│ │ ├── seasons.extractor.js # Seasons/OVAs/movies │ │ ├── seasons.extractor.js # Seasons from watch page sidebar
│ │ ├── watchOrder.extractor.js # Watch order │ │ ├── watchOrder.extractor.js # Watch order from watch page sidebar
│ │ └── download.extractor.js # Download links │ │ └── download.extractor.js # Download links
│ │ │ │
│ └── helper/ │ └── helper/
│ ├── cache.helper.js # LRU cache with configurable TTL │ ├── cache.helper.js # LRU cache with configurable TTL
│ ├── mirror.helper.js # Multi-mirror fallback (5 domains) │ ├── mirror.helper.js # Multi-mirror fallback (5 domains, 404-safe)
│ ├── extractPages.helper.js # Page fetching with mirror fallback │ ├── extractPages.helper.js # Page fetching with mirror fallback
│ ├── formatTitle.helper.js # Title formatter
│ ├── countPages.helper.js # Pagination counter
│ ├── parseListItem.helper.js # 🆕 Shared list item parser with self-anchor detection
│ └── pagination.helper.js # Pagination metadata generator │ └── pagination.helper.js # Pagination metadata generator
│ │
│ └── middleware/ │ └── middleware/
│ └── creatorInfo.js # Creator attribution injection │ └── creatorInfo.js # Creator attribution injection
│ │
├── test.js # Test suite (27 tests) ├── test.js # Test suite (38 tests)
├── agents/ # AI agent prompts (6 agents) ├── agents/ # AI agent prompts (6 agents)
└── CHANGELOG.md # Version history └── CHANGELOG.md # Version history
``` ```
@@ -150,7 +161,19 @@ Client Response
↓ ↓
/api/stream?id={link_id} /api/stream?id={link_id}
↓ ↓
Returns: url (stream link), skipData (intro/outro timestamps) Returns: url (embed URL), skipData (intro/outro timestamps)
↓
/api/stream/resolve?id={link_id} ← 🆕 Resolve to actual video URL
↓
Returns: url (m3u8/mp4), type, server name, subtitles
↓
/api/stream/qualities?url={m3u8_url} ← 🆕 Get quality options
↓
Returns: qualities array with resolution, bandwidth, codec
↓
/api/stream/proxy?url={m3u8_url} ← 🆕 CORS-free proxy
↓
Returns: rewritten M3U8 with proxy URLs
``` ```
## Caching Strategy ## Caching Strategy
@@ -229,6 +252,6 @@ Error responses:
| express | ^4.21.0 | Web framework | | express | ^4.21.0 | Web framework |
| cheerio | ^1.0.0-rc.12 | HTML parsing | | cheerio | ^1.0.0-rc.12 | HTML parsing |
| axios | ^1.8.0 | HTTP requests | | axios | ^1.8.0 | HTTP requests |
| cors | ^2.8.5 | CORS headers |
| cookie-parser | ^1.4.7 | Cookie parsing | | cookie-parser | ^1.4.7 | Cookie parsing |
| dotenv | ^16.4.0 | Environment variables | | dotenv | ^16.4.0 | Environment variables |
| compression | ^1.7.4 | Response compression |
+130
View File
@@ -666,3 +666,133 @@ curl "https://anikototvapi.vercel.app/api/az-list/a"
``` ```
Returns paginated list of anime starting with the specified letter. Returns paginated list of anime starting with the specified letter.
---
## GET /upcoming
Get upcoming anime sorted by air date.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `page` | number | No | Page number (default: 1) |
```bash
curl "https://anikototvapi.vercel.app/api/upcoming"
```
Returns paginated list of upcoming anime with sub/dub counts, type, and rating.
---
## GET /top-rankings
Get top-ranked anime (source site's top section).
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `page` | number | No | Page number (default: 1) |
```bash
curl "https://anikototvapi.vercel.app/api/top-rankings"
```
Returns paginated list with rank numbers extracted from CSS classes.
---
## GET /recently-updated
Get recently updated anime. Supports tab filtering.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `tab` | string | No | Filter: `sub`, `dub`, `all` (default: `all`) |
| `page` | number | No | Page number (default: 1) |
```bash
curl "https://anikototvapi.vercel.app/api/recently-updated"
```
Returns paginated list from `#recent-update` section with client-side tab filtering.
---
## GET /completed
Get completed anime sorted by score.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `page` | number | No | Page number (default: 1) |
```bash
curl "https://anikototvapi.vercel.app/api/completed"
```
Returns paginated list of finished anime from `section.top-table[data-name='completed']`.
---
## GET /stream/resolve
Resolve an embed URL to actual video URL (m3u8/mp4).
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | Yes | `link_id` from `/servers` response |
| `slug` | string | No | Anime slug (for session cookies) |
```bash
curl "https://anikototvapi.vercel.app/api/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
```
Returns resolved URL, type (hls/mp4), server name, and subtitle URLs.
---
## GET /stream/qualities
Parse M3U8 playlist for available quality options.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `url` | string | Yes | M3U8 playlist URL |
```bash
curl "https://anikototvapi.vercel.app/api/stream/qualities?url=https://example.com/playlist.m3u8"
```
Returns array of quality objects with url, quality label, resolution, bandwidth, and codec.
---
## GET /stream/proxy
M3U8 playlist proxy — rewrites relative URLs to proxy endpoints for CORS-free playback.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `url` | string | Yes | M3U8 playlist URL |
```bash
curl "https://anikototvapi.vercel.app/api/stream/proxy?url=https://example.com/playlist.m3u8"
```
Returns rewritten M3U8 content with all `.m3u8` and `.ts` URLs pointing to proxy endpoints.
---
## GET /stream/ts-proxy
TS video segment proxy — serves `.ts` segments with proper Content-Type and CORS headers.
| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `url` | string | Yes | `.ts` segment URL |
```bash
curl "https://anikototvapi.vercel.app/api/stream/ts-proxy?url=https://example.com/segment.ts"
```
Returns binary video segment with `Content-Type: video/mp2t` and `Access-Control-Allow-Origin: *`.
+37
View File
@@ -427,3 +427,40 @@ async function getDownloadLinks(slug, episode) {
getDownloadLinks('one-piece-odmau', 1165); getDownloadLinks('one-piece-odmau', 1165);
``` ```
### Upcoming Anime
```bash
curl "https://anikototvapi.vercel.app/api/upcoming"
```
### Top Rankings
```bash
curl "https://anikototvapi.vercel.app/api/top-rankings"
```
### Recently Updated
```bash
curl "https://anikototvapi.vercel.app/api/recently-updated?tab=sub"
```
### Completed Anime
```bash
curl "https://anikototvapi.vercel.app/api/completed"
```
### Stream URL Resolution
```bash
# Resolve embed URL to actual video URL
curl "https://anikototvapi.vercel.app/api/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
# Get quality options
curl "https://anikototvapi.vercel.app/api/stream/qualities?url=https://example.com/playlist.m3u8"
# Proxy M3U8 for CORS-free playback
curl "https://anikototvapi.vercel.app/api/stream/proxy?url=https://example.com/playlist.m3u8"
```
+59 -1
View File
@@ -251,7 +251,65 @@ player.source = {
| "No episodes found" | Check the anime ID is correct (use `/api/search` first to find slug, then use animeId) | | "No episodes found" | Check the anime ID is correct (use `/api/search` first to find slug, then use animeId) |
| "No servers found" | The `server_ids` may be invalid, try another episode | | "No servers found" | The `server_ids` may be invalid, try another episode |
| Stream URL 403 | Some servers require specific referrer headers | | Stream URL 403 | Some servers require specific referrer headers |
| CORS error | Use a proxy or access from server-side | | CORS error | Use `/api/stream/proxy` endpoint to proxy M3U8 playlists |
---
## Stream URL Resolution (v2.2.0)
The `/api/stream` endpoint returns an **embed URL** (e.g., `vidtube.site/stream/...`). To get the **actual video URL** (m3u8/mp4), use the resolver:
### Step 4: Resolve Embed URL to Video URL
```bash
# Resolve embed URL to actual stream URL
curl "https://anikototvapi.vercel.app/api/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZr..."
```
```json
{
"success": true,
"results": {
"url": "https://vid-tube.site/hls/b32de9d4a3230c95f52948373e6e1549.m3u8",
"type": "hls",
"server": "HD-1",
"subtitles": []
}
}
```
### Get Quality Options
```bash
curl "https://anikototvapi.vercel.app/api/stream/qualities?url=https://example.com/playlist.m3u8"
```
```json
{
"success": true,
"results": {
"qualities": [
{ "url": "https://example.com/360.m3u8", "quality": "360p", "width": 640, "height": 360 },
{ "url": "https://example.com/720.m3u8", "quality": "720p", "width": 1280, "height": 720 }
]
}
}
```
### M3U8 Proxy (CORS-Free Playback)
Browser video players often can't fetch M3U8 playlists directly due to CORS. Use the proxy:
```bash
# Proxy rewrites all relative URLs to go through our API
curl "https://anikototvapi.vercel.app/api/stream/proxy?url=https://example.com/playlist.m3u8"
```
The proxy:
1. Fetches the M3U8 playlist
2. Rewrites relative `.m3u8` URLs → `https://anikototvapi.vercel.app/api/stream/proxy?url=...`
3. Rewrites `.ts` segment URLs → `https://anikototvapi.vercel.app/api/stream/ts-proxy?url=...`
4. Returns the rewritten M3U8 content with CORS headers
--- ---
+2 -29
View File
@@ -1,18 +1,17 @@
{ {
"name": "AniKotoAPI", "name": "AniKotoAPI",
"version": "1.9.0", "version": "2.2.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "AniKotoAPI", "name": "AniKotoAPI",
"version": "1.9.0", "version": "2.2.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"axios": "^1.8.0", "axios": "^1.8.0",
"cheerio": "^1.0.0-rc.12", "cheerio": "^1.0.0-rc.12",
"compression": "^1.8.1", "compression": "^1.8.1",
"cors": "^2.8.5",
"dotenv": "^16.4.0", "dotenv": "^16.4.0",
"express": "^4.21.0" "express": "^4.21.0"
}, },
@@ -389,23 +388,6 @@
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/cors": {
"version": "2.8.6",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
"integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/css-select": { "node_modules/css-select": {
"version": "5.2.2", "version": "5.2.2",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz",
@@ -1270,15 +1252,6 @@
"url": "https://github.com/fb55/nth-check?sponsor=1" "url": "https://github.com/fb55/nth-check?sponsor=1"
} }
}, },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.13.4", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+1 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "AniKotoAPI", "name": "AniKotoAPI",
"version": "2.1.0", "version": "2.2.0",
"description": "A restful API to provide all information about anime from anikototv.to", "description": "A restful API to provide all information about anime from anikototv.to",
"main": "./server.js", "main": "./server.js",
"scripts": { "scripts": {
@@ -14,7 +14,6 @@
"axios": "^1.8.0", "axios": "^1.8.0",
"cheerio": "^1.0.0-rc.12", "cheerio": "^1.0.0-rc.12",
"compression": "^1.8.1", "compression": "^1.8.1",
"cors": "^2.8.5",
"dotenv": "^16.4.0", "dotenv": "^16.4.0",
"express": "^4.21.0" "express": "^4.21.0"
}, },
+78 -15
View File
@@ -18,10 +18,10 @@
import dotenv from "dotenv"; import dotenv from "dotenv";
import express from "express"; import express from "express";
import cors from "cors";
import compression from "compression"; import compression from "compression";
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs";
import crypto from "crypto";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { dirname } from "path"; import { dirname } from "path";
import { createApiRoutes } from "./src/routes/apiRoutes.js"; import { createApiRoutes } from "./src/routes/apiRoutes.js";
@@ -52,6 +52,21 @@ app.use(compression({
threshold: 1024 threshold: 1024
})); }));
// ---- FEATURE: Request body size limits ----
app.use(express.json({ limit: "10kb" }));
app.use(express.urlencoded({ extended: false, limit: "10kb" }));
// ══════════════════════════════════════════════════════════════
// REQUEST ID TRACKING
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Unique request ID for debugging ----
app.use((req, res, next) => {
req.id = crypto.randomUUID();
res.setHeader("X-Request-Id", req.id);
next();
});
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// CORS MIDDLEWARE // CORS MIDDLEWARE
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
@@ -62,8 +77,8 @@ app.use((req, res, next) => {
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-Origin", origin || "*");
} }
res.setHeader("Access-Control-Allow-Methods", "GET"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return res.status(204).end(); return res.status(204).end();
} }
@@ -77,6 +92,9 @@ app.use((req, res, next) => {
res.setHeader("X-XSS-Protection", "1; mode=block"); res.setHeader("X-XSS-Protection", "1; mode=block");
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin"); res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()"); res.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'");
res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
res.setHeader("X-Permitted-Cross-Domain-Policies", "none");
next(); next();
}); });
@@ -135,6 +153,20 @@ const requestCounts = new Map();
const RATE_LIMIT = parseInt(process.env.RATE_LIMIT) || 100; const RATE_LIMIT = parseInt(process.env.RATE_LIMIT) || 100;
const RATE_WINDOW = parseInt(process.env.RATE_WINDOW) || 60000; const RATE_WINDOW = parseInt(process.env.RATE_WINDOW) || 60000;
// ---- FEATURE: Rate limiter cleanup interval (every 5 minutes) ----
const RATE_CLEANUP_INTERVAL = 300000;
setInterval(() => {
const now = Date.now();
for (const [ip, timestamps] of requestCounts.entries()) {
const validTimestamps = timestamps.filter(t => now - t < RATE_WINDOW);
if (validTimestamps.length === 0) {
requestCounts.delete(ip);
} else {
requestCounts.set(ip, validTimestamps);
}
}
}, RATE_CLEANUP_INTERVAL);
app.use((req, res, next) => { app.use((req, res, next) => {
const ip = req.ip || req.connection.remoteAddress; const ip = req.ip || req.connection.remoteAddress;
const now = Date.now(); const now = Date.now();
@@ -164,24 +196,26 @@ app.get("/api/cache/stats", (req, res) => {
// ---- FEATURE: Creator info middleware (injects attribution into all responses) ---- // ---- FEATURE: Creator info middleware (injects attribution into all responses) ----
app.use(addCreatorInfo); app.use(addCreatorInfo);
// ---- FEATURE: Request timeout middleware (30 seconds) ----
app.use((req, res, next) => {
const timeout = parseInt(process.env.REQUEST_TIMEOUT) || 30000;
req.setTimeout(timeout, () => {
if (!res.headersSent) {
res.status(408).json({ success: false, message: "Request timeout" });
}
});
next();
});
createApiRoutes(app, jsonResponse, jsonError); createApiRoutes(app, jsonResponse, jsonError);
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// 404 HANDLER // 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 ---- // ---- FEATURE: Global error handler ----
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
console.error(`[ERROR] ${err.message}`, err.stack); console.error(`[ERROR] ${req.id} ${err.message}`, err.stack);
if (err.type === 'entity.too.large') { if (err.type === 'entity.too.large') {
return res.status(413).json({ success: false, message: "Request entity too large" }); return res.status(413).json({ success: false, message: "Request entity too large" });
} }
@@ -214,8 +248,37 @@ app.use((req, res) => {
// SERVER START // SERVER START
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
app.listen(PORT, () => { const server = app.listen(PORT, () => {
console.info(`AniKotoAPI listening at ${PORT}`); console.info(`AniKotoAPI listening at ${PORT}`);
}); });
// ══════════════════════════════════════════════════════════════ END: server.js // ══════════════════════════════════════════════════════════════
// GRACEFUL SHUTDOWN
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Graceful shutdown handling ----
const gracefulShutdown = (signal) => {
console.info(`\n[SHUTDOWN] Received ${signal}. Starting graceful shutdown...`);
server.close(() => {
console.info("[SHUTDOWN] Server closed. Goodbye.");
process.exit(0);
});
setTimeout(() => {
console.error("[SHUTDOWN] Forced shutdown after timeout.");
process.exit(1);
}, 10000);
};
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
process.on("unhandledRejection", (reason, promise) => {
console.error("[UNHANDLED] Unhandled Rejection:", reason);
});
process.on("uncaughtException", (error) => {
console.error("[UNCAUGHT] Uncaught Exception:", error);
gracefulShutdown("uncaughtException");
});
// ══════════════════════════════════════════════════════════════ END: server.js
+86 -1
View File
@@ -212,5 +212,90 @@ const SORT_IDS = {
"number_of_episodes": "7" "number_of_episodes": "7"
}; };
export { GENRE_IDS, TYPE_IDS, STATUS_IDS, RATING_IDS, SORT_IDS }; // ══════════════════════════════════════════════════════════════
// SOURCE TYPE ID MAPPING
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Source type slug to numeric ID mapping ----
/**
* Maps anime source type slugs to their corresponding numeric IDs.
* Used to filter anime by their original source material.
*
* @type {Object}
* @property {string} manga - ID for manga source
* @property {string} light-novel - ID for light novel source
* @property {string} original - ID for original work
* @property {string} visual-novel - ID for visual novel source
* @property {string} game - ID for game source
* @property {string} 4-koma-manga - ID for 4-koma manga source
*
* @example
* // Get source ID for filtering
* SOURCE_IDS["manga"] // "6"
* SOURCE_IDS["original"] // "10"
*/
const SOURCE_IDS = {
"4-koma-manga": "1",
"book": "2",
"card-game": "3",
"game": "4",
"light-novel": "5",
"manga": "6",
"mixed-media": "7",
"music": "8",
"novel": "9",
"original": "10",
"other": "11",
"picture-book": "12",
"radio": "13",
"unknown": "14",
"video-game": "15",
"visual-novel": "16",
"web-manga": "17",
"web-novel": "18"
};
// ══════════════════════════════════════════════════════════════
// SEASON ID MAPPING
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Season slug to ID mapping ----
/**
* Maps anime season slugs to their corresponding IDs.
* Used to filter anime by their broadcast season.
*
* @type {Object}
* @property {string} spring - ID for spring season
* @property {string} summer - ID for summer season
* @property {string} fall - ID for fall season
* @property {string} winter - ID for winter season
*
* @example
* // Get season ID for filtering
* SEASON_IDS["spring"] // "1"
*/
const SEASON_IDS = {
"spring": "1",
"summer": "2",
"fall": "3",
"winter": "4"
};
// ══════════════════════════════════════════════════════════════
// TV-SPECIFIC TYPE IDS
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extended type slug to numeric ID mapping ----
/**
* Extended type mappings including TV-specific formats.
*
* @type {Object}
*/
const EXTENDED_TYPE_IDS = {
...TYPE_IDS,
"tv-short": "7",
"tv-special": "8"
};
export { GENRE_IDS, TYPE_IDS, STATUS_IDS, RATING_IDS, SORT_IDS, SOURCE_IDS, SEASON_IDS, EXTENDED_TYPE_IDS };
// ══════════════════════════════════════════════════════════════ END: ids.config.js // ══════════════════════════════════════════════════════════════ END: ids.config.js
+6 -5
View File
@@ -41,16 +41,17 @@ import { getCache, setCache, TTL } from "../helper/cache.helper.js";
*/ */
const getAnimeInfo = async (req, res, next) => { const getAnimeInfo = async (req, res, next) => {
try { try {
const { id } = req.query; const { id, slug } = req.query;
if (!id) { const animeSlug = id || slug;
return res.status(400).json({ success: false, message: "Anime slug is required" }); if (!animeSlug) {
return res.status(400).json({ success: false, message: "Anime slug is required (?id= or ?slug=)" });
} }
const cacheKey = `anime_${id}`; const cacheKey = `anime_${animeSlug}`;
const cached = getCache(cacheKey); const cached = getCache(cacheKey);
if (cached) { if (cached) {
return res.json({ success: true, results: cached }); return res.json({ success: true, results: cached });
} }
const data = await extractAnimeInfo(id); const data = await extractAnimeInfo(animeSlug);
setCache(cacheKey, data, TTL.info); setCache(cacheKey, data, TTL.info);
res.json({ success: true, results: data }); res.json({ success: true, results: data });
} catch (error) { } catch (error) {
@@ -0,0 +1,56 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — completedAnime.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for completed anime section. Returns list of anime
* that have finished airing from the homepage.
*
* @exports
* getCompletedAnime - Express route handler for GET /api/completed
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractCompletedAnime } from "../extractors/completedAnime.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: COMPLETED ANIME
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Completed anime endpoint ----
/**
* Handles GET /api/completed requests. Returns list of anime
* that have finished airing from the homepage section.
*
* @param {object} req - Express request object
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with completed anime list
*
* @example
* GET /api/completed
* Response: { success: true, results: [...], ... }
*/
const getCompletedAnime = async (req, res, next) => {
try {
const cacheKey = "completed";
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const data = await extractCompletedAnime();
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getCompletedAnime };
// ══════════════════════════════════════════════════════════════ END: completedAnime.controller.js
@@ -0,0 +1,58 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — recentlyUpdatedTabs.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for recently updated anime with tab filtering.
* Returns recently updated anime filtered by all, dub, or sub.
*
* @exports
* getRecentlyUpdatedTabs - Express route handler for GET /api/recently-updated
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractRecentlyUpdatedTabs } from "../extractors/recentlyUpdatedTabs.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: RECENTLY UPDATED TABS
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Recently updated with tab filtering endpoint ----
/**
* Handles GET /api/recently-updated requests. Returns recently updated
* anime filtered by tab: all, dub, or sub.
*
* @param {object} req - Express request object
* @param {string} [req.query.tab="all"] - Tab filter: "all", "dub", or "sub"
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with recently updated anime list
*
* @example
* GET /api/recently-updated?tab=dub
* Response: { success: true, results: [...], tab: "dub" }
*/
const getRecentlyUpdatedTabs = async (req, res, next) => {
try {
const { tab = "all" } = req.query;
const cacheKey = `recently_updated_${tab}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached, tab });
}
const data = await extractRecentlyUpdatedTabs(tab);
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data, tab });
} catch (error) {
next(error);
}
};
export { getRecentlyUpdatedTabs };
// ══════════════════════════════════════════════════════════════ END: recentlyUpdatedTabs.controller.js
+4 -1
View File
@@ -57,9 +57,12 @@ const getStatus = async (req, res, next) => {
} }
// Map short status names to full slugs // Map short status names to full slugs
const statusMap = { const statusMap = {
ongoing: "currently-airing",
airing: "currently-airing", airing: "currently-airing",
completed: "finished-airing", completed: "finished-airing",
upcoming: "not-yet-aired" finished: "finished-airing",
upcoming: "not-yet-aired",
"not-yet-aired": "not-yet-aired"
}; };
const mappedStatus = statusMap[status] || status; const mappedStatus = statusMap[status] || status;
const data = await extractStatus(mappedStatus, page); const data = await extractStatus(mappedStatus, page);
@@ -0,0 +1,129 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — streamResolver.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for stream URL resolution and quality detection.
* Resolves actual video URLs (m3u8/mp4) from embed player URLs
* and parses available quality options.
*
* @exports
* getResolvedStream - Express route handler for GET /api/stream/resolve
* getStreamQualities - Express route handler for GET /api/stream/qualities
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { resolveStreamUrl, parseM3u8Qualities } from "../extractors/streamResolver.extractor.js";
import { extractStreamInfo } from "../extractors/streamInfo.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: RESOLVE STREAM
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Resolve actual video stream URL from link ID ----
/**
* Handles GET /api/stream/resolve requests. Resolves the actual
* video stream URL (m3u8/mp4) from a server link ID.
*
* @param {object} req - Express request object
* @param {string} req.query.id - Server link ID
* @param {string} req.query.slug - Anime slug (used to establish session)
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with resolved stream URL
*
* @example
* GET /api/stream/resolve?id=abc123&slug=one-piece-odmau
* Response: { success: true, results: { url, qualities, type } }
*
* @throws {400} If 'id' query parameter is missing
*/
const getResolvedStream = async (req, res, next) => {
try {
const { id, slug } = req.query;
if (!id) {
return res.status(400).json({ success: false, message: "Link ID is required" });
}
const cacheKey = `resolved_${id}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
// NOTE: First get the embed URL from the link ID (with session establishment)
const streamInfo = await extractStreamInfo(id, slug);
if (!streamInfo.url) {
return res.status(404).json({ success: false, message: "Stream URL not found for this link ID" });
}
// NOTE: Resolve the actual video URL from the embed page
const resolved = await resolveStreamUrl(streamInfo.url);
const result = {
linkId: id,
embedUrl: streamInfo.url,
...resolved,
skipData: streamInfo.skipData || resolved.skipData,
};
setCache(cacheKey, result, TTL.stream);
res.json({ success: true, results: result });
} catch (error) {
next(error);
}
};
// ══════════════════════════════════════════════════════════════
// CONTROLLER: STREAM QUALITIES
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Available quality options for a stream URL ----
/**
* Handles GET /api/stream/qualities requests. Parses an M3U8
* playlist URL to return available quality options.
*
* @param {object} req - Express request object
* @param {string} req.query.url - M3U8 playlist URL
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with quality options
*
* @example
* GET /api/stream/qualities?url=https://example.com/master.m3u8
* Response: { success: true, results: [{ label: "720p", url: "..." }] }
*
* @throws {400} If 'url' query parameter is missing
*/
const getStreamQualities = async (req, res, next) => {
try {
const { url } = req.query;
if (!url) {
return res.status(400).json({ success: false, message: "M3U8 URL is required" });
}
const cacheKey = `qualities_${url}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const qualities = await parseM3u8Qualities(url);
const result = {
url,
totalQualities: qualities.length,
qualities,
};
setCache(cacheKey, result, TTL.stream);
res.json({ success: true, results: result });
} catch (error) {
next(error);
}
};
export { getResolvedStream, getStreamQualities };
// ══════════════════════════════════════════════════════════════ END: streamResolver.controller.js
@@ -0,0 +1,58 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — topAnimeRankings.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for top anime rankings. Returns ranked anime list
* with support for top (all-time) and newest sort modes.
*
* @exports
* getTopAnimeRankings - Express route handler for GET /api/top-rankings
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractTopAnimeRankings } from "../extractors/topAnimeRankings.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: TOP ANIME RANKINGS
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Top anime rankings endpoint ----
/**
* Handles GET /api/top-rankings requests. Returns ranked anime list
* with support for top (all-time) and newest sort modes.
*
* @param {object} req - Express request object
* @param {string} [req.query.sort="top"] - Sort mode: "top" or "newest"
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with ranked anime list
*
* @example
* GET /api/top-rankings?sort=top
* Response: { success: true, results: [{ rank: 1, title: "...", ... }] }
*/
const getTopAnimeRankings = async (req, res, next) => {
try {
const { sort = "top" } = req.query;
const cacheKey = `top_rankings_${sort}`;
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const data = await extractTopAnimeRankings(sort);
setCache(cacheKey, data, TTL.trending);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getTopAnimeRankings };
// ══════════════════════════════════════════════════════════════ END: topAnimeRankings.controller.js
@@ -0,0 +1,56 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — upcomingAnime.controller.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Controller for upcoming anime section. Returns list of anime
* scheduled for future release from the homepage.
*
* @exports
* getUpcomingAnime - Express route handler for GET /api/upcoming
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import { extractUpcomingAnime } from "../extractors/upcomingAnime.extractor.js";
import { getCache, setCache, TTL } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════
// CONTROLLER: UPCOMING ANIME
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Upcoming anime endpoint ----
/**
* Handles GET /api/upcoming requests. Returns list of anime
* scheduled for future release from the homepage section.
*
* @param {object} req - Express request object
* @param {object} res - Express response object
* @param {Function} next - Express next middleware function
* @returns {void} Sends JSON response with upcoming anime list
*
* @example
* GET /api/upcoming
* Response: { success: true, results: [...], ... }
*/
const getUpcomingAnime = async (req, res, next) => {
try {
const cacheKey = "upcoming";
const cached = getCache(cacheKey);
if (cached) {
return res.json({ success: true, results: cached });
}
const data = await extractUpcomingAnime();
setCache(cacheKey, data, TTL.default);
res.json({ success: true, results: data });
} catch (error) {
next(error);
}
};
export { getUpcomingAnime };
// ══════════════════════════════════════════════════════════════ END: upcomingAnime.controller.js
+3 -23
View File
@@ -17,9 +17,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// ANIME INFO EXTRACTOR // ANIME INFO EXTRACTOR
@@ -41,64 +40,45 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractAnimeInfo = async (slug) => { const extractAnimeInfo = async (slug) => {
try { try {
const url = URLS.watch(slug); const path = `/watch/${slug}`;
const { data } = await axios.get(url, { headers }); const { data } = await fetchWithMirror(path);
const $ = cheerio.load(data); const $ = cheerio.load(data);
// ---- FEATURE: Extract title and identification fields ----
// NOTE: itemprop='name' is used for schema.org microdata on the site
const title = $("h1[itemprop='name'].title.d-title").text().trim() || ""; const title = $("h1[itemprop='name'].title.d-title").text().trim() || "";
// NOTE: data-jp attribute holds the Japanese title variant
const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || ""; const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || "";
const altNames = $(".names.font-italic").text().trim() || ""; const altNames = $(".names.font-italic").text().trim() || "";
const poster = $("img[itemprop='image']").attr("src") || ""; const poster = $("img[itemprop='image']").attr("src") || "";
const synopsis = $(".synopsis .content").text().trim() || ""; const synopsis = $(".synopsis .content").text().trim() || "";
// ---- FEATURE: Extract rating and review metadata ----
// NOTE: Multiple rating selectors are checked — .score .value is the display score,
// itemprop='ratingValue' is the microdata fallback
const rating = $("#w-rating .score .value").text().trim() || ""; const rating = $("#w-rating .score .value").text().trim() || "";
const ratingValue = $("#w-rating span[itemprop='ratingValue']").text().trim() || ""; const ratingValue = $("#w-rating span[itemprop='ratingValue']").text().trim() || "";
const reviewCount = $("#w-rating span[itemprop='reviewCount']").text().trim() || ""; const reviewCount = $("#w-rating span[itemprop='reviewCount']").text().trim() || "";
// NOTE: data-id on #watch-main is the internal anime ID used for AJAX calls
const animeId = parseInt($("#watch-main").attr("data-id")) || 0; const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
// ---- FEATURE: Extract anime metadata (type, premiere, aired, status) ----
// NOTE: .bmeta contains the structured metadata block — first child holds basic info
const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || ""; const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || "";
const premiered = $(".bmeta .meta:first-child > div:nth-child(2) span").text().trim() || ""; const premiered = $(".bmeta .meta:first-child > div:nth-child(2) span").text().trim() || "";
const aired = $(".bmeta .meta:first-child > div:nth-child(3) span").text().trim() || ""; const aired = $(".bmeta .meta:first-child > div:nth-child(3) span").text().trim() || "";
const status = $(".bmeta .meta:first-child > div:nth-child(4) span a").text().trim() || ""; const status = $(".bmeta .meta:first-child > div:nth-child(4) span a").text().trim() || "";
// ---- FEATURE: Extract secondary metadata (MAL score, duration, episodes) ----
// NOTE: Second .meta child holds MAL-linked and production metadata
const malScore = $(".bmeta .meta:nth-child(2) > div:nth-child(1) span").text().trim() || ""; const malScore = $(".bmeta .meta:nth-child(2) > div:nth-child(1) span").text().trim() || "";
const duration = $(".bmeta .meta:nth-child(2) > div:nth-child(2) span").text().trim() || ""; const duration = $(".bmeta .meta:nth-child(2) > div:nth-child(2) span").text().trim() || "";
const episodes = $(".bmeta .meta:nth-child(2) > div:nth-child(3) span").text().trim() || ""; const episodes = $(".bmeta .meta:nth-child(2) > div:nth-child(3) span").text().trim() || "";
// ---- FEATURE: Extract studios list ----
// NOTE: itemprop='director' links on studio spans — itemprop='name' inside holds the name
const studios = []; const studios = [];
$(".bmeta .meta:nth-child(2) > div:nth-child(4) span a[itemprop='director'] span[itemprop='name']").each((i, el) => { $(".bmeta .meta:nth-child(2) > div:nth-child(4) span a[itemprop='director'] span[itemprop='name']").each((i, el) => {
studios.push($(el).text().trim()); studios.push($(el).text().trim());
}); });
// ---- FEATURE: Extract producers list ----
// NOTE: Same selector pattern as studios but from the 5th child (producers row)
const producers = []; const producers = [];
$(".bmeta .meta:nth-child(2) > div:nth-child(5) span a[itemprop='director'] span[itemprop='name']").each((i, el) => { $(".bmeta .meta:nth-child(2) > div:nth-child(5) span a[itemprop='director'] span[itemprop='name']").each((i, el) => {
producers.push($(el).text().trim()); producers.push($(el).text().trim());
}); });
// ---- FEATURE: Extract genres ----
// NOTE: Genre links contain '/genre/' in their href — filters out non-genre links
const genres = []; const genres = [];
$(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => { $(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => {
genres.push($(el).text().trim()); genres.push($(el).text().trim());
}); });
// ---- FEATURE: Extract background artwork from player element ----
// NOTE: The #player div has a CSS background-image set via inline style
const backgroundImage = $("#player").css("background-image")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || ""; const backgroundImage = $("#player").css("background-image")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || "";
return { return {
+2 -34
View File
@@ -15,12 +15,10 @@
* ======= • ======= • ======= • ======= • =======• ======= * ======= • ======= • ======= • ======= • =======• =======
*/ */
import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// A-Z LIST EXTRACTION // A-Z LIST EXTRACTION
@@ -54,40 +52,10 @@ import { countPages } from "../helper/countPages.helper.js";
*/ */
const extractAzList = async (letter = "all", page = 1) => { const extractAzList = async (letter = "all", page = 1) => {
try { try {
// NOTE: URLS.azList generates the correct endpoint for the given letter
const url = URLS.azList(letter); const url = URLS.azList(letter);
const $ = await extractPages(url, page); const $ = await extractPages(url, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($);
const results = [];
// NOTE: Multiple selectors to handle different page layouts
$(".film_list-wrap .flw-item, .film-detail, .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() || "";
const japaneseTitle = $(el).find(".name.d-title").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(".meta .inner .right, .fdi-item:nth-child(2)").text().trim() || "";
const rating = $(el).find(".rating, .fdi-item:nth-child(3)").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, letter, data: results }; return { totalPages, letter, data: results };
} catch (error) { } catch (error) {
+13 -35
View File
@@ -18,6 +18,7 @@
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// CATEGORY FILTER EXTRACTION // CATEGORY FILTER EXTRACTION
@@ -53,53 +54,30 @@ import { extractPages } from "../helper/extractPages.helper.js";
*/ */
const extractCategory = async (category, page = 1) => { const extractCategory = async (category, page = 1) => {
try { try {
// NOTE: Category type is determined by prefix in the category string
let url; let url;
if (category.startsWith("genre/")) { if (category.startsWith("genre/")) {
url = URLS.genre(category.replace("genre/", "")); url = URLS.genre(category.replace("genre/", ""));
} else if (category.startsWith("type/")) { } else if (category.startsWith("type/")) {
url = URLS.type(category.replace("type/", "")); url = URLS.type(category.replace("type/", ""));
} else if (category.startsWith("status/")) { } else if (category.startsWith("status/")) {
url = URLS.status(category.replace("status/", "")); // NOTE: Map short status names to full slugs used by the site
const statusSlug = category.replace("status/", "");
const statusMap = {
ongoing: "currently-airing",
airing: "currently-airing",
completed: "finished-airing",
finished: "finished-airing",
upcoming: "not-yet-aired"
};
const mapped = statusMap[statusSlug] || statusSlug;
url = URLS.status(mapped);
} else { } else {
// NOTE: Fallback to direct URL construction for unknown category types
url = `${URLS.home}/${category}`; url = `${URLS.home}/${category}`;
} }
const $ = await extractPages(url, page); const $ = await extractPages(url, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($, "#list-items > .item", { includeAnimeId: true });
const results = [];
// NOTE: The list items are contained in #list-items container
$("#list-items > .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || "";
const title = $(el).find(".info .b1 a.name.d-title").text().trim() || "";
const japaneseTitle = $(el).find(".info .b1 a.name.d-title").attr("data-jp") || "";
const animeId = $(el).find(".ani.poster.tip").attr("data-tip") || "";
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(".info .meta .m-item:nth-child(2) label").text().trim() || "";
const rating = $(el).find(".info .meta .m-item.rated span").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
animeId,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, data: results }; return { totalPages, data: results };
} catch (error) { } catch (error) {
@@ -0,0 +1,77 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — completedAnime.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts completed anime from the homepage section.
* Scrapes the completed tab/section for finished anime series.
*
* @exports
* extractCompletedAnime
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// COMPLETED ANIME EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract completed anime from homepage section ----
/**
* Fetches and parses the completed anime section from the homepage.
* Returns a list of anime that have finished airing.
*
* @returns {Promise<Array<Object>>} Array of completed anime objects
* @returns {string} return[].slug - URL slug for the anime
* @returns {string} return[].poster - Poster image URL
* @returns {string} return[].title - English title
* @returns {string} return[].japaneseTitle - Japanese title
* @returns {number} return[].sub - Subbed episode count
* @returns {number} return[].dub - Dubbed episode count
* @returns {number} return[].total - Total episode count
* @returns {string} return[].type - Anime type
*
* @example
* const completed = await extractCompletedAnime();
* console.log(completed.length); // number of completed anime
* console.log(completed[0].title); // first completed anime title
*/
const extractCompletedAnime = async () => {
try {
const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data);
const results = [];
// NOTE: completed section is inside .top-tables with data-name="completed"
// Items are <a class="item"> inside .scaff.items
$("section.top-table[data-name='completed'] .scaff.items a.item, .top-table[data-name='completed'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || "";
if (!slug) return;
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".name").text().trim() || "";
const japaneseTitle = $(el).find(".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(".meta .dot:last-child").text().trim() || "";
results.push({ slug, poster, title, japaneseTitle, sub, dub, total, type });
});
return results;
} catch (error) {
throw error;
}
};
export { extractCompletedAnime };
// ══════════════════════════════════════════════════════════════ END: completedAnime.extractor.js
+7 -19
View File
@@ -17,9 +17,9 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js"; import { headers } from "../configs/header.config.js";
import { URLS, BASE_URL } from "../configs/dataUrl.js"; import { URLS, BASE_URL } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// EPISODE LIST EXTRACTOR // EPISODE LIST EXTRACTOR
@@ -31,7 +31,7 @@ import { URLS, BASE_URL } from "../configs/dataUrl.js";
* queries the AJAX episode list endpoint to get all episodes with their * queries the AJAX episode list endpoint to get all episodes with their
* metadata (ID, number, slug, title, active state, href). * metadata (ID, number, slug, title, active state, href).
* *
* @param {string} slug - The anime slug identifier (e.g. "naruto-shippuden") * @param {string} slugOrId - The anime slug or numeric ID (e.g. "naruto-shippuden" or "12345")
* @returns {Promise<Object>} Object with animeId, slug, totalEpisodes, and episodes array * @returns {Promise<Object>} Object with animeId, slug, totalEpisodes, and episodes array
* *
* @example * @example
@@ -44,13 +44,11 @@ const extractEpisodeList = async (slugOrId) => {
let animeId = 0; let animeId = 0;
let resolvedSlug = slugOrId; let resolvedSlug = slugOrId;
// NOTE: Accept either numeric anime ID or slug — if numeric, skip watch page fetch
if (/^\d+$/.test(slugOrId)) { if (/^\d+$/.test(slugOrId)) {
animeId = parseInt(slugOrId); animeId = parseInt(slugOrId);
} else { } else {
// NOTE: Fetch the watch page to extract the internal anime ID from the slug const path = `/watch/${slugOrId}`;
const infoUrl = URLS.watch(slugOrId); const { data: infoData } = await fetchWithMirror(path);
const { data: infoData } = await axios.get(infoUrl, { headers });
const $ = cheerio.load(infoData); const $ = cheerio.load(infoData);
animeId = parseInt($("#watch-main").attr("data-id")) || 0; animeId = parseInt($("#watch-main").attr("data-id")) || 0;
} }
@@ -60,21 +58,14 @@ const extractEpisodeList = async (slugOrId) => {
} }
try { try {
// NOTE: AJAX endpoint requires X-Requested-With header to return HTML fragment const ajaxPath = `/ajax/episode/list/${animeId}`;
const ajaxUrl = `${BASE_URL}/ajax/episode/list/${animeId}`; const { data: ajaxRaw } = await fetchWithMirror(ajaxPath, {
const { data: ajaxRaw } = await axios.get(ajaxUrl, { headers: { "X-Requested-With": "XMLHttpRequest" }
headers: {
...headers,
"X-Requested-With": "XMLHttpRequest"
}
}); });
// NOTE: AJAX response is JSON {status, result} where result is HTML
const ajaxHtml = typeof ajaxRaw === "string" ? ajaxRaw : (ajaxRaw?.result || ""); const ajaxHtml = typeof ajaxRaw === "string" ? ajaxRaw : (ajaxRaw?.result || "");
const $ep = cheerio.load(ajaxHtml); const $ep = cheerio.load(ajaxHtml);
// ---- FEATURE: Parse episode list from AJAX response HTML ----
// NOTE: Episode links have either data-num or data-ep-id attributes
const episodes = []; const episodes = [];
$ep("a[data-num], a[data-ep-id], a[data-id]").each((i, el) => { $ep("a[data-num], a[data-ep-id], a[data-id]").each((i, el) => {
const epId = $ep(el).attr("data-ep-id") || $ep(el).attr("data-id") || ""; const epId = $ep(el).attr("data-ep-id") || $ep(el).attr("data-id") || "";
@@ -83,9 +74,7 @@ const extractEpisodeList = async (slugOrId) => {
const href = $ep(el).attr("href") || ""; const href = $ep(el).attr("href") || "";
const epTitle = $ep(el).find(".ep-title, .ep-name").text().trim() || ""; const epTitle = $ep(el).find(".ep-title, .ep-name").text().trim() || "";
const isActive = $ep(el).hasClass("active") || false; const isActive = $ep(el).hasClass("active") || false;
// NOTE: data-ids is the base64-encoded server ID string needed for /api/servers
const serverIds = $ep(el).attr("data-ids") || ""; const serverIds = $ep(el).attr("data-ids") || "";
// NOTE: data-timestamp used for mapper API
const timestamp = $ep(el).attr("data-timestamp") || ""; const timestamp = $ep(el).attr("data-timestamp") || "";
const malId = $ep(el).attr("data-mal") || ""; const malId = $ep(el).attr("data-mal") || "";
@@ -109,7 +98,6 @@ const extractEpisodeList = async (slugOrId) => {
episodes episodes
}; };
} catch (ajaxError) { } catch (ajaxError) {
// NOTE: Gracefully return empty list if AJAX call fails (e.g. network issue)
return { return {
animeId, animeId,
slug: slugOrId, slug: slugOrId,
+43 -7
View File
@@ -6,7 +6,7 @@
* @description * @description
* Provides advanced anime filtering on anikototv.to — supports filtering * Provides advanced anime filtering on anikototv.to — supports filtering
* by genre, type, status, language, rating, sort order, season, year, * by genre, type, status, language, rating, sort order, season, year,
* and keyword with full pagination support. * source, episode range, and keyword with full pagination support.
* *
* @exports * @exports
* extractFilter * extractFilter
@@ -16,9 +16,8 @@
* ======= • ======= • ======= • ======= • =======• ======= * ======= • ======= • ======= • ======= • =======• =======
*/ */
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { GENRE_IDS, TYPE_IDS, STATUS_IDS, RATING_IDS, SORT_IDS } from "../configs/ids.config.js"; import { GENRE_IDS, TYPE_IDS, STATUS_IDS, RATING_IDS, SORT_IDS, SOURCE_IDS, SEASON_IDS } from "../configs/ids.config.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
@@ -30,7 +29,7 @@ import { extractPages } from "../helper/extractPages.helper.js";
/** /**
* Builds a filter URL from the given parameters and fetches matching anime * Builds a filter URL from the given parameters and fetches matching anime
* from anikototv.to. Supports keyword, genre, type, status, language, * from anikototv.to. Supports keyword, genre, type, status, language,
* rating, sort, season, and year filters — all combinable. * rating, sort, season, year, source, episode range, and exclude watchlist.
* *
* @param {Object} params - Filter parameters object * @param {Object} params - Filter parameters object
* @param {string} [params.keyword] - Search keyword to filter by name * @param {string} [params.keyword] - Search keyword to filter by name
@@ -39,9 +38,13 @@ import { extractPages } from "../helper/extractPages.helper.js";
* @param {string} [params.status] - Comma-separated statuses (e.g. "airing,completed") * @param {string} [params.status] - Comma-separated statuses (e.g. "airing,completed")
* @param {string} [params.language] - Comma-separated languages (e.g. "sub,dub") * @param {string} [params.language] - Comma-separated languages (e.g. "sub,dub")
* @param {string} [params.rating] - Comma-separated ratings (e.g. "pg-13,r") * @param {string} [params.rating] - Comma-separated ratings (e.g. "pg-13,r")
* @param {string} [params.sort] - Sort order key (e.g. "score", "name") * @param {string} [params.sort] - Sort order key (e.g. "score", "name-az")
* @param {string} [params.season] - Comma-separated seasons (e.g. "winter,spring") * @param {string} [params.season] - Comma-separated seasons (e.g. "winter,spring")
* @param {string} [params.year] - Comma-separated years (e.g. "2024,2025") * @param {string} [params.year] - Comma-separated years (e.g. "2024,2025")
* @param {string} [params.source] - Comma-separated sources (e.g. "manga,light-novel")
* @param {number} [params.epMin] - Minimum episode count filter
* @param {number} [params.epMax] - Maximum episode count filter
* @param {boolean} [params.excludeWatchlist=false] - Exclude watchlisted anime
* @param {number} [params.page=1] - Page number for pagination * @param {number} [params.page=1] - Page number for pagination
* @returns {Promise<Object>} Object with totalPages count and data array of results * @returns {Promise<Object>} Object with totalPages count and data array of results
* *
@@ -49,6 +52,17 @@ import { extractPages } from "../helper/extractPages.helper.js";
* const filtered = await extractFilter({ genre: "action", type: "tv", page: 1 }); * const filtered = await extractFilter({ genre: "action", type: "tv", page: 1 });
* console.log(filtered.totalPages); * console.log(filtered.totalPages);
* console.log(filtered.data[0].title); * console.log(filtered.data[0].title);
*
* @example
* // Advanced filter with episode range
* const filtered = await extractFilter({
* genre: "comedy,slice-of-life",
* type: "tv",
* year: "2024",
* epMin: 12,
* epMax: 24,
* sort: "score"
* });
*/ */
const extractFilter = async (params) => { const extractFilter = async (params) => {
try { try {
@@ -102,8 +116,8 @@ const extractFilter = async (params) => {
// ---- FEATURE: Append season filter ---- // ---- FEATURE: Append season filter ----
if (params.season) { if (params.season) {
const seasons = params.season.split(","); const seasons = params.season.split(",").map(s => SEASON_IDS[s.trim().toLowerCase()] || s.trim());
seasons.forEach(s => queryParams.append("season[]", s.trim())); seasons.forEach(s => queryParams.append("season[]", s));
} }
// ---- FEATURE: Append year filter ---- // ---- FEATURE: Append year filter ----
@@ -112,6 +126,28 @@ const extractFilter = async (params) => {
years.forEach(y => queryParams.append("year[]", y.trim())); years.forEach(y => queryParams.append("year[]", y.trim()));
} }
// ---- FEATURE: Append source filter ----
// NOTE: SOURCE_IDS maps source material types to numeric IDs
if (params.source) {
const sources = params.source.split(",").map(s => SOURCE_IDS[s.trim().toLowerCase()] || s.trim());
sources.forEach(s => queryParams.append("source[]", s));
}
// ---- FEATURE: Append episode range filter ----
// NOTE: epMin and epMax filter by total episode count range
if (params.epMin) {
queryParams.set("ep_min", params.epMin);
}
if (params.epMax) {
queryParams.set("ep_max", params.epMax);
}
// ---- FEATURE: Append exclude watchlist filter ----
// NOTE: Only works for logged-in users — ignores for guests
if (params.excludeWatchlist) {
queryParams.set("exclude_watchlist", "1");
}
// NOTE: The filter URL is built by appending query params to the search base URL // NOTE: The filter URL is built by appending query params to the search base URL
const filterUrl = `${URLS.search}?${queryParams.toString()}`; const filterUrl = `${URLS.search}?${queryParams.toString()}`;
const $ = await extractPages(filterUrl, params.page || 1); const $ = await extractPages(filterUrl, params.page || 1);
-19
View File
@@ -16,10 +16,6 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
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"; import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
@@ -38,27 +34,19 @@ import { fetchWithMirror } from "../helper/mirror.helper.js";
* console.log(home.spotlights.length); // number of spotlight items * console.log(home.spotlights.length); // number of spotlight items
*/ */
const extractHomeInfo = async () => { const extractHomeInfo = async () => {
const cached = getCache("home");
if (cached) return cached;
try { try {
const { data } = await fetchWithMirror("/home"); const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data); const $ = cheerio.load(data);
// ---- FEATURE: Extract spotlight carousel items from #hotest section ----
// NOTE: Swiper slides contain the hero carousel on the homepage
const spotlights = []; const spotlights = [];
$("#hotest .swiper-slide.item").each((i, el) => { $("#hotest .swiper-slide.item").each((i, el) => {
// NOTE: The play button's href contains the /watch/{slug} path
const slug = $(el).find("a.play").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a.play").attr("href")?.split("/watch/").pop() || "";
// NOTE: Poster is set as inline CSS background-image on a div inside .image
const poster = $(el).find(".image div").attr("style")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || ""; const poster = $(el).find(".image div").attr("style")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || "";
const title = $(el).find("h2.title.d-title").text().trim() || ""; const title = $(el).find("h2.title.d-title").text().trim() || "";
// NOTE: data-jp attribute holds the Japanese/romaji title variant
const japaneseTitle = $(el).find("h2.title.d-title").attr("data-jp") || ""; const japaneseTitle = $(el).find("h2.title.d-title").attr("data-jp") || "";
const description = $(el).find(".desc").text().trim() || ""; const description = $(el).find(".desc").text().trim() || "";
const rating = $(el).find("i.rating").text().trim() || ""; const rating = $(el).find("i.rating").text().trim() || "";
const quality = $(el).find("i.quality").text().trim() || ""; const quality = $(el).find("i.quality").text().trim() || "";
// NOTE: sub/dub counts are extracted as integers, defaulting to 0
const sub = parseInt($(el).find("i.sub").text().trim()) || 0; const sub = parseInt($(el).find("i.sub").text().trim()) || 0;
const dub = parseInt($(el).find("i.dub").text().trim()) || 0; const dub = parseInt($(el).find("i.dub").text().trim()) || 0;
const date = $(el).find("i.date").text().trim() || ""; const date = $(el).find("i.date").text().trim() || "";
@@ -79,15 +67,12 @@ const extractHomeInfo = async () => {
} }
}); });
// ---- FEATURE: Extract trending/recently-updated anime list ----
// NOTE: Combines both .section-updated and #recent-update containers for coverage
const trending = []; const trending = [];
$(".section-updated .item, #recent-update .item").each((i, el) => { $(".section-updated .item, #recent-update .item").each((i, el) => {
const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
const title = $(el).find("a.name.d-title").text().trim() || ""; const title = $(el).find("a.name.d-title").text().trim() || "";
const japaneseTitle = $(el).find("a.name.d-title").attr("data-jp") || ""; const japaneseTitle = $(el).find("a.name.d-title").attr("data-jp") || "";
// NOTE: Episode counts are in .ep-status spans — sub, dub, and total
const sub = parseInt($(el).find(".ep-status.sub span").text().trim()) || 0; 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 dub = parseInt($(el).find(".ep-status.dub span").text().trim()) || 0;
const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0; const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0;
@@ -107,8 +92,6 @@ const extractHomeInfo = async () => {
} }
}); });
// ---- FEATURE: Extract top airing anime of the day ----
// NOTE: Only the 'day' tab content is scraped from #top-anime
const topAiring = []; const topAiring = [];
$("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
@@ -123,8 +106,6 @@ const extractHomeInfo = async () => {
} }
}); });
// ---- FEATURE: Extract genre filter list from navigation menu ----
// NOTE: Only links containing /genre/ in href are considered valid genre entries
const genres = []; const genres = [];
$("#menu ul.c4 li a").each((i, el) => { $("#menu ul.c4 li a").each((i, el) => {
const genre = $(el).text().trim(); const genre = $(el).text().trim();
+5 -94
View File
@@ -10,19 +10,17 @@
* @exports * @exports
* extractNewRelease * extractNewRelease
* extractNewlyAdded * extractNewlyAdded
* extractLatestUpdated
* *
* @author Shinei Nouzen * @author Shinei Nouzen
* @license MIT * @license MIT
* ======= • ======= • ======= • ======= • =======• ======= * ======= • ======= • ======= • ======= • =======• =======
*/ */
import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { fetchWithMirror } from "../helper/mirror.helper.js"; import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// NEW RELEASE EXTRACTION // NEW RELEASE EXTRACTION
@@ -54,39 +52,9 @@ import { fetchWithMirror } from "../helper/mirror.helper.js";
*/ */
const extractNewRelease = async (page = 1) => { const extractNewRelease = async (page = 1) => {
try { try {
// NOTE: extractPages handles pagination and returns parsed Cheerio object
const $ = await extractPages(URLS.newRelease, page); const $ = await extractPages(URLS.newRelease, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($);
const results = [];
// NOTE: Multiple selectors to handle different page layouts
$(".film_list-wrap .flw-item, .film-detail, .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() || "";
const japaneseTitle = $(el).find(".name.d-title").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(".meta .inner .right, .fdi-item:nth-child(2)").text().trim() || "";
const rating = $(el).find(".rating, .fdi-item:nth-child(3)").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, data: results }; return { totalPages, data: results };
} catch (error) { } catch (error) {
@@ -123,37 +91,9 @@ const extractNewRelease = async (page = 1) => {
*/ */
const extractNewlyAdded = async (page = 1) => { const extractNewlyAdded = async (page = 1) => {
try { try {
// NOTE: The latestUpdated endpoint with sort=added returns recently added anime
const $ = await extractPages(`${URLS.latestUpdated}?sort=added`, page); const $ = await extractPages(`${URLS.latestUpdated}?sort=added`, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($);
const results = [];
// NOTE: Multiple selectors to handle different page layouts
$(".film_list-wrap .flw-item, .film-detail, .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() || "";
const japaneseTitle = $(el).find(".name.d-title").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(".meta .inner .right, .fdi-item:nth-child(2)").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type
});
}
});
return { totalPages, data: results }; return { totalPages, data: results };
} catch (error) { } catch (error) {
@@ -181,36 +121,7 @@ const extractLatestUpdated = async (page = 1) => {
try { try {
const $ = await extractPages("/latest-updated", page); const $ = await extractPages("/latest-updated", page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($, ".item");
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 }; return { totalPages, data: results };
} catch (error) { } catch (error) {
+2 -35
View File
@@ -15,10 +15,10 @@
* ======= • ======= • ======= • ======= • =======• ======= * ======= • ======= • ======= • ======= • =======• =======
*/ */
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// POPULAR EXTRACTION // POPULAR EXTRACTION
@@ -51,42 +51,9 @@ import { extractPages } from "../helper/extractPages.helper.js";
*/ */
const extractPopular = async (page = 1) => { const extractPopular = async (page = 1) => {
try { try {
// NOTE: extractPages handles pagination and returns parsed Cheerio object
const $ = await extractPages(URLS.mostViewed, page); const $ = await extractPages(URLS.mostViewed, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($, "#list-items > .item", { includeAnimeId: true });
const results = [];
// NOTE: The list items are contained in #list-items container
$("#list-items > .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || "";
const title = $(el).find(".info .b1 a.name.d-title").text().trim() || "";
const japaneseTitle = $(el).find(".info .b1 a.name.d-title").attr("data-jp") || "";
const animeId = $(el).find(".ani.poster.tip").attr("data-tip") || "";
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(".info .meta .m-item:nth-child(2) label").text().trim() || "";
const rating = $(el).find(".info .meta .m-item.rated span").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
animeId,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, data: results }; return { totalPages, data: results };
} catch (error) { } catch (error) {
throw error; throw error;
+1 -8
View File
@@ -20,6 +20,7 @@ import * as cheerio from "cheerio";
import axios from "axios"; import axios from "axios";
import { headers } from "../configs/header.config.js"; import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// RANDOM ANIME EXTRACTOR // RANDOM ANIME EXTRACTOR
@@ -40,34 +41,26 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractRandom = async () => { const extractRandom = async () => {
try { try {
// NOTE: maxRedirects=5 ensures we follow the random redirect chain
// NOTE: validateStatus allows any 2xx/3xx response without throwing
const { data, request } = await axios.get(URLS.random, { const { data, request } = await axios.get(URLS.random, {
headers, headers,
maxRedirects: 5, maxRedirects: 5,
validateStatus: (status) => status < 400 validateStatus: (status) => status < 400
}); });
// NOTE: responseURL on the request object gives us the final resolved URL after redirects
const finalUrl = request?.responseURL || URLS.random; const finalUrl = request?.responseURL || URLS.random;
// NOTE: The slug is extracted from the /watch/{slug} path in the final URL
const slug = finalUrl.split("/watch/").pop() || ""; const slug = finalUrl.split("/watch/").pop() || "";
const $ = cheerio.load(data); const $ = cheerio.load(data);
// ---- FEATURE: Extract anime title and identification ----
const title = $("h1[itemprop='name'].title.d-title").text().trim() || ""; const title = $("h1[itemprop='name'].title.d-title").text().trim() || "";
const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || ""; const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || "";
const poster = $("img[itemprop='image']").attr("src") || ""; const poster = $("img[itemprop='image']").attr("src") || "";
// ---- FEATURE: Extract type, synopsis, rating, and anime ID ----
const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || ""; const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || "";
const synopsis = $(".synopsis .content").text().trim() || ""; const synopsis = $(".synopsis .content").text().trim() || "";
const rating = $("#w-rating .score .value").text().trim() || ""; const rating = $("#w-rating .score .value").text().trim() || "";
const animeId = parseInt($("#watch-main").attr("data-id")) || 0; const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
// ---- FEATURE: Extract genres ----
// NOTE: Genre links are identified by '/genre/' in their href attribute
const genres = []; const genres = [];
$(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => { $(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => {
genres.push($(el).text().trim()); genres.push($(el).text().trim());
@@ -0,0 +1,94 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — recentlyUpdatedTabs.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts recently updated anime from homepage with tab filtering.
* Supports three tabs: all, dub, and sub for different update types.
*
* @exports
* extractRecentlyUpdatedTabs
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// RECENTLY UPDATED TABS EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract recently updated anime with tab filtering ----
/**
* Fetches and parses the recently updated anime section from the homepage.
* Supports filtering by update type: all, dub, or sub.
*
* @param {string} tab - Tab filter: "all", "dub", or "sub" (default: "all")
* @returns {Promise<Array<Object>>} Array of recently updated anime objects
* @returns {string} return[].slug - URL slug for the anime
* @returns {string} return[].poster - Poster image URL
* @returns {string} return[].title - English title
* @returns {string} return[].japaneseTitle - Japanese title
* @returns {number} return[].sub - Subbed episode count
* @returns {number} return[].dub - Dubbed episode count
* @returns {number} return[].total - Total episode count
* @returns {string} return[].type - Anime type
* @returns {string} return[].episodeInfo - Latest episode info
*
* @example
* const all = await extractRecentlyUpdatedTabs("all");
* console.log(all.length); // number of updated anime
*
* const dubOnly = await extractRecentlyUpdatedTabs("dub");
* console.log(dubOnly[0].title); // first dubbed updated anime
*/
const extractRecentlyUpdatedTabs = async (tab = "all") => {
try {
const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data);
const results = [];
// NOTE: #recent-update has tabs (all/dub/sub/trending/random) but filtering is client-side
// Items are <div class="item"> inside #recent-update .ani.items
// Each item has .ani.poster with <a> link and .info .name.d-title
const allItems = $("#recent-update .ani.items .item");
allItems.each((i, el) => {
// NOTE: The item itself is a div, the link is inside .ani.poster a or .info a.name
const link = $(el).find(".ani.poster a").attr("href") || $(el).find(".info a.name").attr("href") || "";
const slug = link.split("/watch/").pop()?.split("/ep-")[0] || "";
if (!slug) return;
// NOTE: Check sub/dub status for tab filtering
const hasSub = $(el).find(".ep-status.sub").length > 0;
const hasDub = $(el).find(".ep-status.dub").length > 0;
// NOTE: Filter by tab if not "all" — since server-side rendering shows all items
if (tab === "dub" && !hasDub) return;
if (tab === "sub" && !hasSub) return;
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".name").text().trim() || "";
const japaneseTitle = $(el).find(".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(".meta .right, .type").text().trim() || "";
results.push({ slug, poster, title, japaneseTitle, sub, dub, total, type });
});
return results;
} catch (error) {
throw error;
}
};
export { extractRecentlyUpdatedTabs };
// ══════════════════════════════════════════════════════════════ END: recentlyUpdatedTabs.extractor.js
+3 -7
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SCHEDULE EXTRACTION // SCHEDULE EXTRACTION
@@ -43,21 +42,18 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractSchedule = async (date) => { const extractSchedule = async (date) => {
try { try {
// NOTE: The schedule is fetched by appending date parameter to homepage const path = `/?date=${date}`;
const url = `${URLS.home}?date=${date}`; const { data } = await fetchWithMirror(path);
const { data } = await axios.get(url, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const schedule = []; const schedule = [];
// NOTE: Schedule items use different selectors depending on page structure
$(".schedule-item, .anime-schedule .item").each((i, el) => { $(".schedule-item, .anime-schedule .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
const title = $(el).find(".film-name a, .name").text().trim() || ""; const title = $(el).find(".film-name a, .name").text().trim() || "";
const time = $(el).find(".time, .schedule-time").text().trim() || ""; const time = $(el).find(".time, .schedule-time").text().trim() || "";
const episodeNo = parseInt($(el).find(".episode-no, .ep-num").text().trim()) || 0; const episodeNo = parseInt($(el).find(".episode-no, .ep-num").text().trim()) || 0;
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
schedule.push({ schedule.push({
slug, slug,
+3 -11
View File
@@ -16,11 +16,10 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SEARCH RESULTS EXTRACTOR // SEARCH RESULTS EXTRACTOR
@@ -42,27 +41,21 @@ import { countPages } from "../helper/countPages.helper.js";
*/ */
const extractSearchResults = async (keyword, page = 1) => { const extractSearchResults = async (keyword, page = 1) => {
try { try {
// WARNING: keyword param is required — omitting it may cause a 500 error from the source
const url = `${URLS.search}?keyword=${encodeURIComponent(keyword)}`; const url = `${URLS.search}?keyword=${encodeURIComponent(keyword)}`;
const $ = await extractPages(url, page); const $ = await extractPages(url, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = []; const results = [];
// NOTE: #list-items > .item is the standard result container on anikototv.to search pages
$("#list-items > .item").each((i, el) => { $("#list-items > .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
// NOTE: .ani.poster.tip is the poster container with tooltip data
const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || ""; const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || "";
const title = $(el).find(".info .b1 a.name.d-title").text().trim() || ""; const title = $(el).find(".info .b1 a.name.d-title").text().trim() || "";
const japaneseTitle = $(el).find(".info .b1 a.name.d-title").attr("data-jp") || ""; const japaneseTitle = $(el).find(".info .b1 a.name.d-title").attr("data-jp") || "";
// NOTE: data-tip attribute on the poster container holds the animeId
const animeId = $(el).find(".ani.poster.tip").attr("data-tip") || ""; const animeId = $(el).find(".ani.poster.tip").attr("data-tip") || "";
const sub = parseInt($(el).find(".ep-status.sub span").text().trim()) || 0; 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 dub = parseInt($(el).find(".ep-status.dub span").text().trim()) || 0;
const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0; const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0;
// NOTE: Type is in the second .m-item label (e.g. TV, Movie, OVA)
const type = $(el).find(".info .meta .m-item:nth-child(2) label").text().trim() || ""; const type = $(el).find(".info .meta .m-item:nth-child(2) label").text().trim() || "";
// NOTE: Rating is in a dedicated .m-item.rated span
const rating = $(el).find(".info .meta .m-item.rated span").text().trim() || ""; const rating = $(el).find(".info .meta .m-item.rated span").text().trim() || "";
const genres = []; const genres = [];
$(el).find(".info .b1 .genre a").each((j, g) => { $(el).find(".info .b1 .genre a").each((j, g) => {
@@ -110,8 +103,8 @@ const extractSearchResults = async (keyword, page = 1) => {
*/ */
const extractSearchSuggestions = async (keyword) => { const extractSearchSuggestions = async (keyword) => {
try { try {
const url = `${URLS.search}?keyword=${encodeURIComponent(keyword)}`; const path = `/search?keyword=${encodeURIComponent(keyword)}`;
const { data } = await axios.get(url, { headers }); const { data } = await fetchWithMirror(path);
const $ = cheerio.load(data); const $ = cheerio.load(data);
const suggestions = []; const suggestions = [];
@@ -126,7 +119,6 @@ const extractSearchSuggestions = async (keyword) => {
} }
}); });
// NOTE: Limit to 10 suggestions to keep autocomplete payloads small
return suggestions.slice(0, 10); return suggestions.slice(0, 10);
} catch (error) { } catch (error) {
throw error; throw error;
+38 -50
View File
@@ -5,8 +5,8 @@
* *
* @description * @description
* Extracts season information for a specific anime from the * Extracts season information for a specific anime from the
* anikototv.to AJAX endpoint. Returns all seasons/OVAs/specials * watch page HTML. Returns available seasons from the page
* for a given anime series. * sidebar and metadata.
* *
* @exports * @exports
* extractSeasons * extractSeasons
@@ -21,73 +21,61 @@ import { fetchWithMirror } from "../helper/mirror.helper.js";
/** /**
* Fetches and parses season information for an anime. * Fetches and parses season information for an anime.
* Scrapes the AJAX endpoint that returns season carousel HTML. * Extracts season data from the watch page sidebar.
* *
* @param {string|number} animeId - The numeric anime ID * @param {string|number} slugOrId - The anime slug or numeric ID
* @returns {Promise<Object>} Object with animeId, totalSeasons, and seasons array * @returns {Promise<Object>} Object with animeId, totalSeasons, and seasons array
* *
* @example * @example
* const seasons = await extractSeasons(7174); * const seasons = await extractSeasons("one-piece-odmau");
* console.log(seasons.totalSeasons); // number of seasons * console.log(seasons.totalSeasons);
* console.log(seasons.seasons[0].title); // first season title
*/ */
const extractSeasons = async (animeId) => { const extractSeasons = async (slugOrId) => {
try { try {
const { data } = await fetchWithMirror(`/api/seasons/${animeId}`, { const path = /^\d+$/.test(slugOrId) ? `/watch/${slugOrId}` : `/watch/${slugOrId}`;
headers: { "X-Requested-With": "XMLHttpRequest" } const { data } = await fetchWithMirror(path);
const html = typeof data === "string" ? data : String(data);
const $ = cheerio.load(html);
const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
const seasons = [];
// NOTE: Extract seasons from #ani-seasons section (if populated)
$("#ani-seasons .swiper-slide, .seasons .item, #w-seasons .item").each((_, el) => {
const link = $(el).find("a").first();
const href = link.attr("href") || "";
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".name, .title").text().trim() || link.text().trim() || "";
const slug = href.split("/watch/").pop() || "";
if (slug || title) {
seasons.push({ title, slug, poster, url: href });
}
}); });
// Handle both string HTML and JSON responses // NOTE: If no dedicated seasons section, extract from episode list sidebar
let raw = ""; if (seasons.length === 0) {
if (typeof data === "string") { $(".w-side-section .item").each((_, el) => {
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 link = $(el).find("a").first();
const href = link.attr("href") || ""; const href = link.attr("href") || "";
const style = link.attr("style") || ""; const poster = $(el).find("img").attr("src") || "";
const poster = style.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || ""; const title = $(el).find(".name").text().trim() || "";
const title = $(el).find(".name").text().trim() ||
link.text().trim() || "";
// Extract slug from href
const slug = href.split("/watch/").pop() || ""; const slug = href.split("/watch/").pop() || "";
const score = $(el).find(".score").text().trim() || "";
const episodes = $(el).find(".meta .dot:last-child").text().trim() || "";
if (slug || title) { if (slug && slug !== slugOrId) {
seasons.push({ title, slug, poster, url: href }); seasons.push({ title, slug, poster, url: href, score, episodes });
} }
}); });
if (seasons.length > 0) break;
} }
return { return {
animeId, animeId,
slug: slugOrId,
totalSeasons: seasons.length, totalSeasons: seasons.length,
seasons seasons,
}; };
} catch (error) { } catch (error) {
throw error; throw error;
+2 -6
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SPOTLIGHT EXTRACTION // SPOTLIGHT EXTRACTION
@@ -48,13 +47,11 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractSpotlight = async () => { const extractSpotlight = async () => {
try { try {
// NOTE: The homepage contains the spotlight carousel in #hotest section const { data } = await fetchWithMirror("/home");
const { data } = await axios.get(URLS.home, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const spotlights = []; const spotlights = [];
// NOTE: Each slide in the swiper carousel represents a featured anime
$("#hotest .swiper-slide.item").each((i, el) => { $("#hotest .swiper-slide.item").each((i, el) => {
const slug = $(el).find("a.play").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a.play").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".image div").attr("style")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || ""; const poster = $(el).find(".image div").attr("style")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || "";
@@ -67,7 +64,6 @@ const extractSpotlight = async () => {
const dub = parseInt($(el).find("i.dub").text().trim()) || 0; const dub = parseInt($(el).find("i.dub").text().trim()) || 0;
const date = $(el).find("i.date").text().trim() || ""; const date = $(el).find("i.date").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
spotlights.push({ spotlights.push({
slug, slug,
+2 -34
View File
@@ -15,12 +15,10 @@
* ======= • ======= • ======= • ======= • =======• ======= * ======= • ======= • ======= • ======= • =======• =======
*/ */
import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { extractPages } from "../helper/extractPages.helper.js"; import { extractPages } from "../helper/extractPages.helper.js";
import { countPages } from "../helper/countPages.helper.js"; import { countPages } from "../helper/countPages.helper.js";
import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// STATUS FILTER EXTRACTION // STATUS FILTER EXTRACTION
@@ -54,40 +52,10 @@ import { countPages } from "../helper/countPages.helper.js";
*/ */
const extractStatus = async (status, page = 1) => { const extractStatus = async (status, page = 1) => {
try { try {
// NOTE: URLS.status generates the correct endpoint for the given status
const url = URLS.status(status); const url = URLS.status(status);
const $ = await extractPages(url, page); const $ = await extractPages(url, page);
const totalPages = countPages($); const totalPages = countPages($);
const results = parseListItems($);
const results = [];
// NOTE: Multiple selectors to handle different page layouts
$(".film_list-wrap .flw-item, .film-detail, .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() || "";
const japaneseTitle = $(el).find(".name.d-title").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(".meta .inner .right, .fdi-item:nth-child(2)").text().trim() || "";
const rating = $(el).find(".rating, .fdi-item:nth-child(3)").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) {
results.push({
slug,
poster,
title,
japaneseTitle,
sub,
dub,
total,
type,
rating
});
}
});
return { totalPages, status, data: results }; return { totalPages, status, data: results };
} catch (error) { } catch (error) {
+63 -44
View File
@@ -17,9 +17,10 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js"; import { headers } from "../configs/header.config.js";
import { BASE_URL } from "../configs/dataUrl.js"; import { BASE_URL } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
import { normalizeServerName } from "./streamResolver.extractor.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// STREAM INFO EXTRACTOR // STREAM INFO EXTRACTOR
@@ -28,37 +29,51 @@ import { BASE_URL } from "../configs/dataUrl.js";
// ---- FEATURE: Resolve a single stream URL from a linkId ---- // ---- FEATURE: Resolve a single stream URL from a linkId ----
/** /**
* Fetches the actual stream URL and skip data for a given server link ID. * Fetches the actual stream URL and skip data for a given server link ID.
* This is the primary method for resolving playable video URLs. * First establishes a session by fetching the watch page, then queries
* the AJAX stream endpoint with proper session context.
* *
* @param {string} linkId - The server link ID to resolve * @param {string} linkId - The server link ID to resolve
* @returns {Promise<Object>} Object with linkId, url, and skipData (intro/outro timestamps) * @param {string} [watchSlug] - Optional watch page slug to establish session
* @returns {Promise<Object>} Object with linkId, url, type, skipData (intro/outro timestamps)
* *
* @example * @example
* const stream = await extractStreamInfo("abc123"); * const stream = await extractStreamInfo("abc123", "one-piece-odmau");
* console.log(stream.url); // direct video URL * console.log(stream.url); // direct video URL
* console.log(stream.skipData); // intro/outro skip ranges * console.log(stream.skipData); // intro/outro skip ranges
*/ */
const extractStreamInfo = async (linkId) => { const extractStreamInfo = async (linkId, watchSlug = null) => {
try { try {
const url = `${BASE_URL}/ajax/server?get=${linkId}`; // NOTE: Establish session by visiting watch page first (required for AJAX endpoints)
const { data } = await axios.get(url, { if (watchSlug) {
headers: { await fetchWithMirror(`/watch/${watchSlug}`);
...headers, }
"X-Requested-With": "XMLHttpRequest"
} const path = `/ajax/server?get=${linkId}`;
const { data: raw } = await fetchWithMirror(path, {
headers: { "X-Requested-With": "XMLHttpRequest" }
}); });
// NOTE: Response is JSON {status, result: {url, skip_data}} // NOTE: Handle both string JSON and parsed object responses
let data = raw;
if (typeof raw === "string") {
try { data = JSON.parse(raw); } catch { data = {}; }
}
if (!data || !data.result) { if (!data || !data.result) {
return { linkId, url: null, skipData: null }; return { linkId, url: null, type: null, skipData: null };
} }
const result = typeof data.result === "string" ? (() => { try { return JSON.parse(data.result); } catch { return {}; } })() : data.result; const result = typeof data.result === "string" ? (() => { try { return JSON.parse(data.result); } catch { return {}; } })() : data.result;
const streamUrl = result.url || null;
const streamType = streamUrl?.includes(".m3u8") ? "hls" : streamUrl ? "mp4" : null;
return { return {
linkId, linkId,
url: result.url || null, url: streamUrl,
skipData: result.skip_data || null type: streamType,
skipData: result.skip_data || null,
backup: result.backup || null,
}; };
} catch (error) { } catch (error) {
throw error; throw error;
@@ -72,44 +87,50 @@ const extractStreamInfo = async (linkId) => {
// ---- FEATURE: Fetch available servers for a set of episode IDs ---- // ---- FEATURE: Fetch available servers for a set of episode IDs ----
/** /**
* Retrieves the server list for the given episode IDs from the AJAX endpoint. * Retrieves the server list for the given episode IDs from the AJAX endpoint.
* Returns raw server data as provided by the source site. * First establishes a session by fetching the watch page, then queries
* the AJAX server list endpoint with proper session context.
* *
* @param {string} episodeIds - Comma-separated or single episode ID string * @param {string} episodeIds - Comma-separated or single episode ID string
* @returns {Promise<Object>} Raw server list data from the AJAX response * @param {string} [watchSlug] - Optional watch page slug to establish session
* @returns {Promise<Array>} Array of server objects with type, link_id, ep_id, etc.
* *
* @example * @example
* const servers = await extractServerList("12345"); * const servers = await extractServerList("12345", "one-piece-odmau");
* // servers contains the server configuration for that episode * console.log(servers[0].link_id); // first server's link ID
*/ */
const extractServerList = async (episodeIds) => { const extractServerList = async (episodeIds, watchSlug = null) => {
try { try {
const url = `${BASE_URL}/ajax/server/list?servers=${episodeIds}`; // NOTE: Establish session by visiting watch page first (required for AJAX endpoints)
const { data: raw } = await axios.get(url, { if (watchSlug) {
headers: { await fetchWithMirror(`/watch/${watchSlug}`);
...headers, }
"X-Requested-With": "XMLHttpRequest"
} const path = `/ajax/server/list?servers=${episodeIds}`;
const { data: raw } = await fetchWithMirror(path, {
headers: { "X-Requested-With": "XMLHttpRequest" }
}); });
// NOTE: Response is JSON {status, result} where result is HTML
const html = typeof raw === "string" ? raw : (raw?.result || ""); const html = typeof raw === "string" ? raw : (raw?.result || "");
const $ = cheerio.load(html); const $ = cheerio.load(html);
const servers = []; const servers = [];
// NOTE: Servers are in .servers div, grouped by type (sub/dub) $(".servers .type").each((_, typeEl) => {
$(".servers .type").each((_, typeEl) => { const type = $(typeEl).attr("data-type") || "sub";
const type = $(typeEl).attr("data-type") || "sub"; const label = $(typeEl).find("label").text().trim() || type.toUpperCase();
$(typeEl).find("li[data-link-id]").each((__, li) => { $(typeEl).find("li[data-link-id]").each((__, li) => {
servers.push({ const rawName = $(li).text().trim() || "";
type, servers.push({
ep_id: $(li).attr("data-ep-id") || "", type,
link_id: $(li).attr("data-link-id") || "", typeLabel: label,
cmid: $(li).attr("data-cmid") || "", ep_id: $(li).attr("data-ep-id") || "",
sv_id: $(li).attr("data-sv-id") || "", link_id: $(li).attr("data-link-id") || "",
name: $(li).text().trim() || "" cmid: $(li).attr("data-cmid") || "",
sv_id: $(li).attr("data-sv-id") || "",
name: rawName,
normalizedName: normalizeServerName(rawName),
});
}); });
}); });
});
return servers; return servers;
} catch (error) { } catch (error) {
@@ -139,18 +160,17 @@ const extractServerList = async (episodeIds) => {
*/ */
const extractMapperServers = async (malId, slug, timestamp) => { const extractMapperServers = async (malId, slug, timestamp) => {
try { try {
// Validate and sanitize input to prevent SSRF
if (!Number.isFinite(Number(malId))) throw new Error("Invalid malId"); if (!Number.isFinite(Number(malId))) throw new Error("Invalid malId");
if (!/^[a-zA-Z0-9-]+$/.test(slug)) throw new Error("Invalid slug"); if (!/^[a-zA-Z0-9-]+$/.test(slug)) throw new Error("Invalid slug");
if (!Number.isFinite(Number(timestamp))) throw new Error("Invalid timestamp"); if (!Number.isFinite(Number(timestamp))) throw new Error("Invalid timestamp");
const url = `https://mapper.nekostream.site/api/mal/${encodeURIComponent(malId)}/${encodeURIComponent(slug)}/${encodeURIComponent(timestamp)}`;
const { data } = await axios.get(url, { headers }); const path = `/ajax/mapper/${encodeURIComponent(malId)}/${encodeURIComponent(slug)}/${encodeURIComponent(timestamp)}`;
const { data } = await fetchWithMirror(path);
const servers = []; const servers = [];
if (data && typeof data === "object") { if (data && typeof data === "object") {
for (const [provider, sources] of Object.entries(data)) { for (const [provider, sources] of Object.entries(data)) {
// NOTE: Each provider may have sub, dub, or both source types
if (sources && sources.sub) { if (sources && sources.sub) {
servers.push({ servers.push({
provider, provider,
@@ -172,7 +192,6 @@ const extractMapperServers = async (malId, slug, timestamp) => {
return servers; return servers;
} catch (error) { } catch (error) {
// NOTE: Returns empty array on failure — mapper API may be unavailable
return []; return [];
} }
}; };
+307
View File
@@ -0,0 +1,307 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — streamResolver.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Resolves actual streaming video URLs (m3u8/mp4) from embed player URLs.
* Follows the chain: vidtube.site embed → megaplay API → m3u8 playlist.
* Supports quality selection and subtitle extraction.
*
* @exports
* resolveStreamUrl, resolveStreamUrls, parseM3u8Qualities
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import axios from "axios";
import { headers } from "../configs/header.config.js";
// ══════════════════════════════════════════════════════════════
// STREAM RESOLVER
// ══════════════════════════════════════════════════════════════
// Server name normalization map
const SERVER_NAME_MAP = {
"VidPlay-1": "vidplay",
"VidPlay-2": "vidplay",
"HD-1": "hd",
"HD-2": "hd",
"Vidstream-1": "vidstream",
"Vidstream-2": "vidstream",
"VidCloud-1": "vidcloud",
"VidCloud-2": "vidcloud",
"StreamTape-1": "streamtape",
"StreamTape-2": "streamtape",
};
// Embed domain to API domain mapping
const EMBED_API_MAP = {
"vidtube.site": "megaplay-1.buzz",
"vidplay.site": "megaplay-1.buzz",
"megaplay.buzz": "megaplay-1.buzz",
"embed.bunkrerrer.com": "megaplay-1.buzz",
};
/**
* Normalizes server display names to clean identifiers
* @param {string} name - Raw server name (e.g., "VidPlay-1")
* @returns {string} Normalized name (e.g., "vidplay")
*/
const normalizeServerName = (name) => {
if (!name) return "unknown";
return SERVER_NAME_MAP[name] || name.toLowerCase().replace(/[-\s]+\d+$/, "").trim();
};
/**
* Resolves the actual video stream URL from an embed player page.
* Extracts data-id from the embed HTML, then queries the megaplay API.
*
* @param {string} embedUrl - The embed player URL (e.g., vidtube.site/stream/...)
* @param {object} [options] - Resolution options
* @param {boolean} [options.followRedirects=true] - Follow HTTP redirects
* @param {number} [options.timeout=10000] - Request timeout in ms
* @returns {Promise<Object>} Object with url, qualities, skipData, type
*
* @example
* const resolved = await resolveStreamUrl("https://vidtube.site/stream/...");
* console.log(resolved.url); // m3u8 URL
* console.log(resolved.qualities); // [{ label: "720p", url: "..." }]
*/
const resolveStreamUrl = async (embedUrl, options = {}) => {
const { followRedirects = true, timeout = 10000 } = options;
try {
// NOTE: Extract the embed page to find data-id and API domain
const embedResponse = await axios.get(embedUrl, {
headers: {
...headers,
"Referer": "https://anikototv.to/",
"Origin": "https://anikototv.to",
},
timeout,
maxRedirects: followRedirects ? 5 : 0,
});
const embedHtml = typeof embedResponse.data === "string"
? embedResponse.data
: String(embedResponse.data);
// NOTE: Extract data attributes from the player div
const dataId = embedHtml.match(/data-id="(\d+)"/)?.[1];
const realId = embedHtml.match(/data-realid="([^"]+)"/)?.[1];
const mediaId = embedHtml.match(/data-mediaid="([^"]+)"/)?.[1];
if (!dataId) {
return {
url: null,
qualities: [],
skipData: null,
type: null,
error: "Could not extract player data-id from embed page",
};
}
// NOTE: Determine API domain from embed URL or extract from page
const embedDomain = new URL(embedUrl).hostname;
const apiDomain = EMBED_API_MAP[embedDomain] || embedDomain;
// NOTE: Query the megaplay API for the actual stream URL
const apiResponse = await axios.get(
`https://${apiDomain}/ajax/sources/${dataId}`,
{
headers: {
...headers,
"Referer": embedUrl,
"Origin": `https://${embedDomain}`,
},
timeout,
}
);
const apiData = typeof apiResponse.data === "string"
? (() => { try { return JSON.parse(apiResponse.data); } catch { return {}; } })()
: apiResponse.data;
// NOTE: Extract stream URL from API response
const streamUrl = apiData?.source || apiData?.url || apiData?.file || null;
const streamType = apiData?.type || (streamUrl?.includes(".m3u8") ? "hls" : "mp4");
// NOTE: Parse m3u8 qualities if it's an HLS stream
let qualities = [];
if (streamUrl && streamType === "hls") {
qualities = await parseM3u8Qualities(streamUrl, {
headers: {
...headers,
"Referer": embedUrl,
},
timeout,
});
}
// NOTE: Extract subtitles if available
const subtitles = extractSubtitles(apiData);
return {
url: streamUrl,
type: streamType,
qualities,
subtitles,
skipData: apiData?.skip_data || null,
dataId,
realId,
mediaId,
backup: apiData?.backup || null,
};
} catch (error) {
return {
url: null,
qualities: [],
skipData: null,
type: null,
error: error.message,
};
}
};
/**
* Resolves stream URLs for multiple episodes in batch
* @param {string} embedUrl - The embed player URL
* @param {object} [options] - Resolution options
* @returns {Promise<Object>} Batch resolution result
*/
const resolveStreamUrls = async (embedUrl, options = {}) => {
try {
const resolved = await resolveStreamUrl(embedUrl, options);
return resolved;
} catch (error) {
return { url: null, error: error.message };
}
};
// ══════════════════════════════════════════════════════════════
// M3U8 PARSER
// ══════════════════════════════════════════════════════════════
/**
* Parses an M3U8 playlist to extract available quality options.
* Supports both master playlists (multiple qualities) and media playlists.
*
* @param {string} m3u8Url - URL of the M3U8 playlist
* @param {object} [options] - Fetch options
* @param {object} [options.headers] - Custom headers
* @param {number} [options.timeout=10000] - Request timeout
* @returns {Promise<Array<Object>>} Array of quality objects
*
* @example
* const qualities = await parseM3u8Qualities("https://example.com/master.m3u8");
* qualities.forEach(q => console.log(`${q.label}: ${q.url}`));
*/
const parseM3u8Qualities = async (m3u8Url, options = {}) => {
const { headers: customHeaders = {}, timeout = 10000 } = options;
try {
const response = await axios.get(m3u8Url, {
headers: { ...headers, ...customHeaders },
timeout,
});
const content = typeof response.data === "string"
? response.data
: String(response.data);
const qualities = [];
const lines = content.split("\n").map((l) => l.trim());
// NOTE: Parse master playlist (contains #EXT-X-STREAM-INF)
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("#EXT-X-STREAM-INF:")) {
const attrs = lines[i].substring("#EXT-X-STREAM-INF:".length);
const bandwidth = parseInt(attrs.match(/BANDWIDTH=(\d+)/)?.[1] || "0");
const resolution = attrs.match(/RESOLUTION=(\d+x\d+)/)?.[1] || "";
const [width, height] = resolution.split("x").map(Number);
const nextLine = lines[i + 1];
if (nextLine && !nextLine.startsWith("#")) {
// NOTE: Resolve relative URLs against base M3U8 URL
const qualityUrl = nextLine.startsWith("http")
? nextLine
: new URL(nextLine, m3u8Url).href;
qualities.push({
label: height ? `${height}p` : `${bandwidth}bps`,
width: width || 0,
height: height || 0,
bandwidth,
url: qualityUrl,
});
}
}
}
// NOTE: If no qualities found, it's likely a single-quality stream
if (qualities.length === 0 && content.includes("#EXTINF")) {
qualities.push({
label: "default",
width: 0,
height: 0,
bandwidth: 0,
url: m3u8Url,
});
}
// NOTE: Sort by resolution/bandwidth descending (highest first)
qualities.sort((a, b) => (b.height || b.bandwidth) - (a.height || a.bandwidth));
return qualities;
} catch (error) {
return [];
}
};
// ══════════════════════════════════════════════════════════════
// SUBTITLE EXTRACTOR
// ══════════════════════════════════════════════════════════════
/**
* Extracts subtitle information from API response data
* @param {object} apiData - The megaplay API response
* @returns {Array<Object>} Array of subtitle objects
*/
const extractSubtitles = (apiData) => {
const subtitles = [];
// NOTE: Subtitles may be in different formats depending on the source
if (apiData?.subtitles && Array.isArray(apiData.subtitles)) {
for (const sub of apiData.subtitles) {
subtitles.push({
label: sub.label || sub.language || "Unknown",
language: sub.code || sub.language || "unknown",
url: sub.url || sub.file || null,
format: sub.format || "srt",
});
}
}
// NOTE: Some sources embed subtitles in tracks array
if (apiData?.tracks && Array.isArray(apiData.tracks)) {
for (const track of apiData.tracks) {
if (track.kind === "subtitles" || track.type === "subtitles") {
subtitles.push({
label: track.label || track.language || "Unknown",
language: track.srclang || track.language || "unknown",
url: track.file || track.src || null,
format: track.format || "srt",
});
}
}
}
return subtitles;
};
export { resolveStreamUrl, resolveStreamUrls, parseM3u8Qualities, normalizeServerName, extractSubtitles };
// ══════════════════════════════════════════════════════════════ END: streamResolver.extractor.js
+3 -8
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SUGGESTION EXTRACTION // SUGGESTION EXTRACTION
@@ -46,14 +45,12 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractSuggestions = async (keyword) => { const extractSuggestions = async (keyword) => {
try { try {
// NOTE: The search endpoint requires the 'keyword' parameter const path = `/search?keyword=${encodeURIComponent(keyword)}`;
const url = `${URLS.search}?keyword=${encodeURIComponent(keyword)}`; const { data } = await fetchWithMirror(path);
const { data } = await axios.get(url, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const suggestions = []; const suggestions = [];
// NOTE: Search results use the same list structure as other pages
$("#list-items > .item").each((i, el) => { $("#list-items > .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || ""; const poster = $(el).find(".ani.poster.tip > a > img").attr("src") || "";
@@ -63,13 +60,11 @@ const extractSuggestions = async (keyword) => {
const sub = parseInt($(el).find(".ep-status.sub span").text().trim()) || 0; 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 dub = parseInt($(el).find(".ep-status.dub span").text().trim()) || 0;
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
suggestions.push({ slug, poster, title, japaneseTitle, type, sub, dub }); suggestions.push({ slug, poster, title, japaneseTitle, type, sub, dub });
} }
}); });
// NOTE: Limit to 10 suggestions for autocomplete-style responses
return suggestions.slice(0, 10); return suggestions.slice(0, 10);
} catch (error) { } catch (error) {
throw error; throw error;
@@ -0,0 +1,92 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — topAnimeRankings.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts top anime rankings from the homepage with sort options.
* Supports both "top" (all-time) and "newest" ranking modes.
* Parses ranked items with position numbers 1-9.
*
* @exports
* extractTopAnimeRankings
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════
// TOP ANIME RANKINGS EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract top anime rankings with sort option ----
/**
* Fetches and parses the top anime rankings from the homepage.
* Supports switching between "top" (all-time) and "newest" rankings.
*
* @param {string} sort - Ranking sort mode: "top" or "newest" (default: "top")
* @returns {Promise<Array<Object>>} Array of ranked anime objects
* @returns {number} return[].rank - Ranking position (1-9)
* @returns {string} return[].slug - URL slug for the anime
* @returns {string} return[].poster - Poster image URL
* @returns {string} return[].title - Anime title
* @returns {string} return[].japaneseTitle - Japanese title
* @returns {number} return[].sub - Subbed episode count
* @returns {number} return[].dub - Dubbed episode count
* @returns {string} return[].type - Anime type
* @returns {string} return[].views - View count
*
* @example
* const topAnime = await extractTopAnimeRankings("top");
* console.log(topAnime[0].rank); // 1
* console.log(topAnime[0].title); // #1 anime
*
* const newest = await extractTopAnimeRankings("newest");
* console.log(newest[0].title); // #1 newest anime
*/
const extractTopAnimeRankings = async (sort = "top") => {
try {
// NOTE: Homepage contains both top and newest rankings in tabbed sections
const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data);
const results = [];
// NOTE: Ranking items live inside #top-anime .tab-content .scaff.side.items
// Each item is an <a class="item rankN"> with rank classes rank1..rank9
// The data-name on .tab-content controls which tab: day/week/month
const tabSelector = sort === "week" ? "[data-name='week']"
: sort === "month" ? "[data-name='month']"
: "[data-name='day']";
$(`#top-anime .tab-content${tabSelector} a.item, #top-anime .scaff.side.items a.item`).each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || "";
if (!slug) return;
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".name").text().trim() || "";
const japaneseTitle = $(el).find(".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 type = $(el).find(".meta .dot:last-child").text().trim() || "";
// NOTE: Rank is extracted from the rankN class on the <a> element
const rankClass = [...$(el).attr("class") || ""].join(" ").match(/rank(\d+)/);
const rank = rankClass ? parseInt(rankClass[1]) : i + 1;
results.push({ rank, slug, poster, title, japaneseTitle, sub, dub, type });
});
return results;
} catch (error) {
throw error;
}
};
export { extractTopAnimeRankings };
// ══════════════════════════════════════════════════════════════ END: topAnimeRankings.extractor.js
+2 -8
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// TOP TEN EXTRACTION // TOP TEN EXTRACTION
@@ -47,15 +46,13 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractTopTen = async () => { const extractTopTen = async () => {
try { try {
// NOTE: The top 10 section uses tabbed content with data-name attributes const { data } = await fetchWithMirror("/home");
const { data } = await axios.get(URLS.home, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const today = []; const today = [];
const week = []; const week = [];
const month = []; const month = [];
// NOTE: Each tab contains a list of anime items with ranking data
$("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -65,13 +62,11 @@ const extractTopTen = async () => {
const type = $(el).find(".type").text().trim() || ""; const type = $(el).find(".type").text().trim() || "";
const rank = i + 1; const rank = i + 1;
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
today.push({ slug, rank, name, poster, sub, dub, type }); today.push({ slug, rank, name, poster, sub, dub, type });
} }
}); });
// NOTE: Weekly rankings follow the same structure as daily
$("#top-anime .tab-content[data-name='week'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='week'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -86,7 +81,6 @@ const extractTopTen = async () => {
} }
}); });
// NOTE: Monthly rankings follow the same structure
$("#top-anime .tab-content[data-name='month'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='month'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
+2 -6
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// TRENDING EXTRACTION // TRENDING EXTRACTION
@@ -45,13 +44,11 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractTrending = async () => { const extractTrending = async () => {
try { try {
// NOTE: Trending data is split across multiple sections on the homepage const { data } = await fetchWithMirror("/home");
const { data } = await axios.get(URLS.home, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const trending = []; const trending = [];
// NOTE: This selector targets both the updated section and recent updates
$(".section-updated .item, #recent-update .item").each((i, el) => { $(".section-updated .item, #recent-update .item").each((i, el) => {
const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -62,7 +59,6 @@ const extractTrending = async () => {
const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0; const total = parseInt($(el).find(".ep-status.total span").text().trim()) || 0;
const type = $(el).find(".meta .inner .right").text().trim() || ""; const type = $(el).find(".meta .inner .right").text().trim() || "";
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
trending.push({ trending.push({
slug, slug,
+2 -9
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS } from "../configs/dataUrl.js"; import { URLS } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// TRENDING SIDEBAR EXTRACTION // TRENDING SIDEBAR EXTRACTION
@@ -49,15 +48,13 @@ import { URLS } from "../configs/dataUrl.js";
*/ */
const extractTrendingSidebar = async () => { const extractTrendingSidebar = async () => {
try { try {
// NOTE: The sidebar content is embedded in the homepage HTML const { data } = await fetchWithMirror("/home");
const { data } = await axios.get(URLS.home, { headers });
const $ = cheerio.load(data); const $ = cheerio.load(data);
const day = []; const day = [];
const week = []; const week = [];
const month = []; const month = [];
// NOTE: Daily rankings use the 'day' tab content
$("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='day'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -67,13 +64,11 @@ const extractTrendingSidebar = async () => {
const type = $(el).find(".type").text().trim() || ""; const type = $(el).find(".type").text().trim() || "";
const rank = i + 1; const rank = i + 1;
// NOTE: Only include items with valid slugs
if (slug) { if (slug) {
day.push({ slug, rank, name, poster, sub, dub, type }); day.push({ slug, rank, name, poster, sub, dub, type });
} }
}); });
// NOTE: Weekly rankings use the 'week' tab content
$("#top-anime .tab-content[data-name='week'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='week'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -88,7 +83,6 @@ const extractTrendingSidebar = async () => {
} }
}); });
// NOTE: Monthly rankings use the 'month' tab content
$("#top-anime .tab-content[data-name='month'] a.item").each((i, el) => { $("#top-anime .tab-content[data-name='month'] a.item").each((i, el) => {
const slug = $(el).attr("href")?.split("/watch/").pop() || ""; const slug = $(el).attr("href")?.split("/watch/").pop() || "";
const poster = $(el).find(".poster img").attr("src") || ""; const poster = $(el).find(".poster img").attr("src") || "";
@@ -103,7 +97,6 @@ const extractTrendingSidebar = async () => {
} }
}); });
// NOTE: Latest episodes section provides recently updated content
const latestEpisodes = []; const latestEpisodes = [];
$("#recent-update .item, .section-updated .item").each((i, el) => { $("#recent-update .item, .section-updated .item").each((i, el) => {
const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || ""; const slug = $(el).find("a.name.d-title").attr("href")?.split("/watch/").pop() || "";
+73
View File
@@ -0,0 +1,73 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — upcomingAnime.extractor.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Extracts upcoming anime from the homepage section.
* Scrapes the #upcoming-anime section for future releases.
*
* @exports
* extractUpcomingAnime
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
import * as cheerio from "cheerio";
import { fetchWithMirror } from "../helper/mirror.helper.js";
import { parseListItems } from "../helper/parseListItem.helper.js";
// ══════════════════════════════════════════════════════════════
// UPCOMING ANIME EXTRACTION
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Extract upcoming anime from homepage section ----
/**
* Fetches and parses the upcoming anime section from the homepage.
* Returns a list of anime that are scheduled for future release.
*
* @returns {Promise<Array<Object>>} Array of upcoming anime objects
* @returns {string} return[].slug - URL slug for the anime
* @returns {string} return[].poster - Poster image URL
* @returns {string} return[].title - English title
* @returns {string} return[].japaneseTitle - Japanese title
* @returns {string} return[].type - Anime type (TV, Movie, etc.)
* @returns {string} return[].releaseDate - Expected release date
*
* @example
* const upcoming = await extractUpcomingAnime();
* console.log(upcoming.length); // number of upcoming anime
* console.log(upcoming[0].title); // first upcoming anime title
*/
const extractUpcomingAnime = async () => {
try {
const { data } = await fetchWithMirror("/home");
const $ = cheerio.load(data);
const results = [];
// NOTE: upcoming-anime section contains future releases
$("#upcoming-anime .item, .upcoming .item").each((i, el) => {
const slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
if (!slug) return;
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".film-name a, .name.d-title, a.name").text().trim() || "";
const japaneseTitle = $(el).find(".name.d-title, a.name").attr("data-jp") || "";
const type = $(el).find(".type, .fdi-item:nth-child(2)").text().trim() || "";
const releaseDate = $(el).find(".date, .release-date").text().trim() || "";
results.push({ slug, poster, title, japaneseTitle, type, releaseDate });
});
return results;
} catch (error) {
throw error;
}
};
export { extractUpcomingAnime };
// ══════════════════════════════════════════════════════════════ END: upcomingAnime.extractor.js
+40 -58
View File
@@ -5,8 +5,8 @@
* *
* @description * @description
* Extracts watch order and related anime information from the * Extracts watch order and related anime information from the
* anikototv.to AJAX endpoint. Returns related anime with their * watch page sidebar. Returns trending/related anime with their
* relationship types (sequel, prequel, summary, etc.). * metadata for continuous viewing.
* *
* @exports * @exports
* extractWatchOrder * extractWatchOrder
@@ -21,81 +21,63 @@ import { fetchWithMirror } from "../helper/mirror.helper.js";
/** /**
* Fetches and parses watch order / related anime for an anime. * Fetches and parses watch order / related anime for an anime.
* Scrapes the AJAX endpoint that returns related anime HTML. * Extracts related anime from the watch page sidebar.
* *
* @param {string|number} animeId - The numeric anime ID * @param {string|number} slugOrId - The anime slug or numeric ID
* @returns {Promise<Object>} Object with animeId, totalRelated, related array * @returns {Promise<Object>} Object with animeId, totalRelated, related array
* *
* @example * @example
* const data = await extractWatchOrder(7174); * const data = await extractWatchOrder("one-piece-odmau");
* console.log(data.totalRelated); // number of related anime * console.log(data.totalRelated);
* console.log(data.related[0].title); // first related anime
*/ */
const extractWatchOrder = async (animeId) => { const extractWatchOrder = async (slugOrId) => {
try { try {
const { data } = await fetchWithMirror(`/api/watch-order/${animeId}`, { const path = /^\d+$/.test(slugOrId) ? `/watch/${slugOrId}` : `/watch/${slugOrId}`;
headers: { "X-Requested-With": "XMLHttpRequest" } const { data } = await fetchWithMirror(path);
const html = typeof data === "string" ? data : String(data);
const $ = cheerio.load(html);
const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
const related = [];
// NOTE: Extract from #w-related section
$("#w-related .item, .w-side-section:has(.title:contains('Related')) .item").each((_, el) => {
const link = $(el).find("a").first();
const href = link.attr("href") || "";
const title = $(el).find(".name").text().trim() || "";
const poster = $(el).find("img").attr("src") || "";
const slug = href.split("/watch/").pop() || "";
const relation = $(el).find(".relation, .serieslabelitem").text().trim() || "related";
if (slug) {
related.push({ title, slug, poster, url: href, relation });
}
}); });
// Handle both string HTML and JSON responses // NOTE: Also extract trending sidebar items as suggested watch order
let raw = ""; if (related.length === 0) {
if (typeof data === "string") { $(".w-side-section:has(.title:contains('Trending')) .item, .w-side-section:first .item").each((_, el) => {
try { const link = $(el).find("a").first();
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 href = link.attr("href") || "";
const title = link.text().trim() || ""; const title = $(el).find(".name").text().trim() || "";
const poster = $(el).find("img").attr("src") || ""; const poster = $(el).find("img").attr("src") || "";
const slug = href.split("/watch/").pop() || ""; const slug = href.split("/watch/").pop() || "";
const score = $(el).find(".score").text().trim() || "";
const type = $(el).find(".meta .dot:last-child").text().trim() || "";
const episodes = $(el).find(".meta .dot:first-child").text().trim() || "";
// Extract relationship type if (slug && slug !== slugOrId) {
const relationEl = $(el).find(".relation, .serieslabelitem").first(); related.push({ title, slug, poster, url: href, relation: "trending", score, type, episodes });
let relationType = relationEl.text().trim().toLowerCase() ||
relationEl.attr("id") || "related";
if (slug || title) {
related.push({
title,
slug,
poster,
url: href,
relation: relationType
});
} }
}); });
if (related.length > 0) break;
} }
return { return {
animeId, animeId,
slug: slugOrId,
totalRelated: related.length, totalRelated: related.length,
related related,
}; };
} catch (error) { } catch (error) {
throw error; throw error;
+3 -23
View File
@@ -16,9 +16,8 @@
*/ */
import * as cheerio from "cheerio"; import * as cheerio from "cheerio";
import axios from "axios";
import { headers } from "../configs/header.config.js";
import { URLS, BASE_URL } from "../configs/dataUrl.js"; import { URLS, BASE_URL } from "../configs/dataUrl.js";
import { fetchWithMirror } from "../helper/mirror.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// WATCH PAGE EXTRACTOR // WATCH PAGE EXTRACTOR
@@ -41,54 +40,40 @@ import { URLS, BASE_URL } from "../configs/dataUrl.js";
*/ */
const extractWatchPage = async (slug, ep) => { const extractWatchPage = async (slug, ep) => {
try { try {
const url = URLS.episode(slug, ep); const path = `/watch/${slug}/ep-${ep}`;
const { data } = await axios.get(url, { headers }); const { data } = await fetchWithMirror(path);
const $ = cheerio.load(data); const $ = cheerio.load(data);
// ---- FEATURE: Extract anime identification and title ----
// NOTE: data-id on #watch-main is the internal anime ID for AJAX calls
const animeId = parseInt($("#watch-main").attr("data-id")) || 0; const animeId = parseInt($("#watch-main").attr("data-id")) || 0;
const animeUrl = $("#watch-main").attr("data-url") || ""; const animeUrl = $("#watch-main").attr("data-url") || "";
const title = $("h1[itemprop='name'].title.d-title").text().trim() || slug; const title = $("h1[itemprop='name'].title.d-title").text().trim() || slug;
const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || ""; const japaneseTitle = $("h1[itemprop='name'].title.d-title").attr("data-jp") || "";
const episodeNumber = parseInt(ep) || 0; const episodeNumber = parseInt(ep) || 0;
// ---- FEATURE: Extract synopsis and rating ----
const synopsis = $(".synopsis .content").text().trim() || ""; const synopsis = $(".synopsis .content").text().trim() || "";
const rating = $("#w-rating .score .value").text().trim() || ""; const rating = $("#w-rating .score .value").text().trim() || "";
const poster = $("img[itemprop='image']").attr("src") || ""; const poster = $("img[itemprop='image']").attr("src") || "";
// NOTE: Background image is extracted from CSS background-image property on #player
const backgroundImage = $("#player").css("background-image")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || ""; const backgroundImage = $("#player").css("background-image")?.match(/url\(['"]?(.+?)['"]?\)/)?.[1] || "";
// ---- FEATURE: Extract anime metadata (type, status, MAL score, duration, episodes) ----
const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || ""; const type = $(".bmeta .meta:first-child > div:nth-child(1) span").text().trim() || "";
const status = $(".bmeta .meta:first-child > div:nth-child(4) span a").text().trim() || ""; const status = $(".bmeta .meta:first-child > div:nth-child(4) span a").text().trim() || "";
const malScore = $(".bmeta .meta:nth-child(2) > div:nth-child(1) span").text().trim() || ""; const malScore = $(".bmeta .meta:nth-child(2) > div:nth-child(1) span").text().trim() || "";
const duration = $(".bmeta .meta:nth-child(2) > div:nth-child(2) span").text().trim() || ""; const duration = $(".bmeta .meta:nth-child(2) > div:nth-child(2) span").text().trim() || "";
const episodes = $(".bmeta .meta:nth-child(2) > div:nth-child(3) span").text().trim() || ""; const episodes = $(".bmeta .meta:nth-child(2) > div:nth-child(3) span").text().trim() || "";
// ---- FEATURE: Extract genres ----
// NOTE: Genre links contain '/genre/' in href to distinguish from other links
const genres = []; const genres = [];
$(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => { $(".bmeta .meta:first-child > div:nth-child(5) span a[href*='/genre/']").each((i, el) => {
genres.push($(el).text().trim()); genres.push($(el).text().trim());
}); });
// ---- FEATURE: Extract studios ----
// NOTE: Uses itemprop='director' links with itemprop='name' spans inside
const studios = []; const studios = [];
$(".bmeta .meta:nth-child(2) > div:nth-child(4) span a[itemprop='director'] span[itemprop='name']").each((i, el) => { $(".bmeta .meta:nth-child(2) > div:nth-child(4) span a[itemprop='director'] span[itemprop='name']").each((i, el) => {
studios.push($(el).text().trim()); studios.push($(el).text().trim());
}); });
// ---- FEATURE: Extract next episode release info ----
// NOTE: .next-episode shows the countdown text, .count-down has data-target timestamp
const nextEpisodeDate = $(".next-episode, .alert.next-episode").text().trim() || ""; const nextEpisodeDate = $(".next-episode, .alert.next-episode").text().trim() || "";
const nextEpisodeTimestamp = parseInt($(".count-down").attr("data-target")) || 0; const nextEpisodeTimestamp = parseInt($(".count-down").attr("data-target")) || 0;
// ---- FEATURE: Extract available streaming servers ----
// NOTE: Each server li has data-link-id (unique), data-ep-id, data-cmid, data-sv-id
// NOTE: Server type (sub/dub) is derived from closest .type container's data-type attribute
const servers = []; const servers = [];
$("#w-servers .servers .type li, #w-servers li[data-link-id]").each((i, el) => { $("#w-servers .servers .type li, #w-servers li[data-link-id]").each((i, el) => {
const linkId = $(el).attr("data-link-id") || ""; const linkId = $(el).attr("data-link-id") || "";
@@ -110,14 +95,11 @@ const extractWatchPage = async (slug, ep) => {
} }
}); });
// ---- FEATURE: Extract trending/watch-order sidebar items ----
// NOTE: Grabs from both the first .w-side-section and #watch-order containers
const trending = []; const trending = [];
$(".w-side-section:first .scaff.side.items a.item, #watch-order a.item").each((i, el) => { $(".w-side-section:first .scaff.side.items a.item, #watch-order a.item").each((i, el) => {
const trendSlug = $(el).attr("href")?.split("/watch/").pop() || ""; const trendSlug = $(el).attr("href")?.split("/watch/").pop() || "";
const trendPoster = $(el).find(".poster img").attr("src") || ""; const trendPoster = $(el).find(".poster img").attr("src") || "";
const trendTitle = $(el).find(".name").text().trim() || ""; const trendTitle = $(el).find(".name").text().trim() || "";
// NOTE: .dot:last-child typically holds the type badge text
const trendType = $(el).find(".dot:last-child").text().trim() || ""; const trendType = $(el).find(".dot:last-child").text().trim() || "";
const trendScore = $(el).find(".score").text().trim() || ""; const trendScore = $(el).find(".score").text().trim() || "";
@@ -132,8 +114,6 @@ const extractWatchPage = async (slug, ep) => {
} }
}); });
// ---- FEATURE: Extract recommended anime sidebar items ----
// NOTE: Targets the section with a title containing "Recommended", or the last sidebar
const recommended = []; const recommended = [];
$(".w-side-section:has(.title:contains('Recommended')) a.item, aside.sidebar:last .w-side-section a.item").each((i, el) => { $(".w-side-section:has(.title:contains('Recommended')) a.item, aside.sidebar:last .w-side-section a.item").each((i, el) => {
const recSlug = $(el).attr("href")?.split("/watch/").pop() || ""; const recSlug = $(el).attr("href")?.split("/watch/").pop() || "";
+14 -3
View File
@@ -199,8 +199,17 @@ async function fetchWithMirror(path, options = {}) {
mirror mirror
}; };
} }
// NOTE: 404 means endpoint doesn't exist, not mirror failure — don't retry
if (response.status === 404) {
throw new Error(`Endpoint not found: ${path}`);
}
} catch (error) { } catch (error) {
lastError = error; lastError = error;
// NOTE: Don't retry on 404 — the endpoint simply doesn't exist on this mirror
if (error.message?.includes("Endpoint not found")) {
break;
}
if (attempt < retries) { if (attempt < retries) {
// Wait before retry // Wait before retry
await new Promise(r => setTimeout(r, 500 * (attempt + 1))); await new Promise(r => setTimeout(r, 500 * (attempt + 1)));
@@ -208,9 +217,11 @@ async function fetchWithMirror(path, options = {}) {
} }
} }
// Mark mirror as failed after all retries // NOTE: Only mark mirror as failed for connection errors, not endpoint 404s
failedMirrors.add(mirror); if (!lastError.message?.includes("Endpoint not found")) {
console.log(`[MIRROR] Marked as failed: ${mirror}`); failedMirrors.add(mirror);
console.log(`[MIRROR] Marked as failed: ${mirror}`);
}
} }
throw new Error(`All mirrors failed. Last error: ${lastError?.message}`); throw new Error(`All mirrors failed. Last error: ${lastError?.message}`);
+111
View File
@@ -0,0 +1,111 @@
/*
* ======= • ======= • ======= • ======= • =======• =======
* AniKotoAPI — parseListItem.helper.js
* Repository: https://github.com/Shineii86/AniKotoAPI
*
* @description
* Shared helper for parsing anime list items from Cheerio DOM.
* Eliminates code duplication across multiple extractors by
* providing a unified parsing function for standard list items.
*
* @exports
* parseListItems, parseListItem
*
* @author Shinei Nouzen
* @license MIT
* ======= • ======= • ======= • ======= • =======• =======
*/
// ══════════════════════════════════════════════════════════════
// SINGLE ITEM PARSER
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Parse a single anime list item from a Cheerio element ----
/**
* Parses a single anime list item from a Cheerio element.
* Handles multiple CSS selector patterns for different page layouts
* by falling through comma-separated selectors until one matches.
*
* @param {CheerioAPI} $ - Cheerio instance with loaded HTML
* @param {CheerioElement} el - DOM element to parse
* @param {object} [options] - Parsing options
* @param {boolean} [options.includeAnimeId=false] - Include animeId field from data-tip attribute
* @param {boolean} [options.includeRating=true] - Include rating field from .rated span
* @returns {object|null} Parsed anime object or null if slug is missing (invalid item)
*
* @example
* const item = parseListItem($, el, { includeAnimeId: true });
* if (item) results.push(item);
*/
const parseListItem = ($, el, options = {}) => {
const { includeAnimeId = false, includeRating = true } = options;
// NOTE: slug is the primary key — skip items without a valid watch link
// NOTE: item may BE the <a> tag itself, so check both self and children
let slug = "";
if ($(el).is("a")) {
slug = $(el).attr("href")?.split("/watch/").pop() || "";
}
if (!slug) {
slug = $(el).find("a").attr("href")?.split("/watch/").pop() || "";
}
if (!slug) return null;
// NOTE: Multiple selectors handle different page layouts (#list-items vs .film_list-wrap vs .item)
const poster = $(el).find("img").attr("src") || "";
const title = $(el).find(".name").text().trim() || $(el).children(".info").find(".name").text().trim() || "";
const japaneseTitle = $(el).find(".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(".meta .dot:last-child, .fdi-item:nth-child(2)").text().trim() || "";
const item = { slug, poster, title, japaneseTitle, sub, dub, total, type };
// NOTE: animeId comes from data-tip on .ani.poster.tip — only present on some page layouts
if (includeAnimeId) {
item.animeId = $(el).find(".ani.poster.tip").attr("data-tip") || "";
}
// NOTE: Rating uses different selectors depending on whether it's a list page or detail page
if (includeRating) {
item.rating = $(el).find(".rated span, .rating, .fdi-item:nth-child(3)").text().trim() || "";
}
return item;
};
// ══════════════════════════════════════════════════════════════
// MULTI-ITEM PARSER
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Parse multiple anime list items from a Cheerio instance ----
/**
* Parses multiple anime list items from a Cheerio instance.
* Uses multiple CSS selectors to handle different page layouts,
* returning only items with valid slugs.
*
* @param {CheerioAPI} $ - Cheerio instance with loaded HTML
* @param {string} [selector] - CSS selector for list items (default: auto-detect all layouts)
* @param {object} [options] - Parsing options (passed to parseListItem)
* @returns {Array<object>} Array of parsed anime objects (empty if none found)
*
* @example
* const $ = await extractPages("/most-popular");
* const items = parseListItems($);
* console.log(items.length); // Number of parsed items
*/
const parseListItems = ($, selector = "#list-items > .item, .film_list-wrap .flw-item, .film-detail, .item", options = {}) => {
const results = [];
$(selector).each((i, el) => {
const item = parseListItem($, el, options);
if (item) results.push(item);
});
return results;
};
export { parseListItems, parseListItem };
// ══════════════════════════════════════════════════════════════ END: parseListItem.helper.js
+173 -1
View File
@@ -26,6 +26,7 @@ import { getSearchResults, getSearchSuggestions } from "../controllers/search.co
import { getEpisodeList } from "../controllers/episodeList.controller.js"; import { getEpisodeList } from "../controllers/episodeList.controller.js";
import { getEpisodeListAjax } from "../controllers/episodeListAjax.controller.js"; import { getEpisodeListAjax } from "../controllers/episodeListAjax.controller.js";
import { getStreamInfo, getServerList, getMapperServers } from "../controllers/streamInfo.controller.js"; import { getStreamInfo, getServerList, getMapperServers } from "../controllers/streamInfo.controller.js";
import { getResolvedStream, getStreamQualities } from "../controllers/streamResolver.controller.js";
import { getSchedule } from "../controllers/schedule.controller.js"; import { getSchedule } from "../controllers/schedule.controller.js";
import { getSpotlight } from "../controllers/spotlight.controller.js"; import { getSpotlight } from "../controllers/spotlight.controller.js";
import { getTrending } from "../controllers/trending.controller.js"; import { getTrending } from "../controllers/trending.controller.js";
@@ -42,8 +43,13 @@ import { getTrendingSidebar } from "../controllers/trendingSidebar.controller.js
import { getSeasons } from "../controllers/seasons.controller.js"; import { getSeasons } from "../controllers/seasons.controller.js";
import { getWatchOrder } from "../controllers/watchOrder.controller.js"; import { getWatchOrder } from "../controllers/watchOrder.controller.js";
import { getDownloadLinks } from "../controllers/download.controller.js"; import { getDownloadLinks } from "../controllers/download.controller.js";
import { getUpcomingAnime } from "../controllers/upcomingAnime.controller.js";
import { getTopAnimeRankings } from "../controllers/topAnimeRankings.controller.js";
import { getRecentlyUpdatedTabs } from "../controllers/recentlyUpdatedTabs.controller.js";
import { getCompletedAnime } from "../controllers/completedAnime.controller.js";
import { categoryRoutes } from "./category.route.js"; import { categoryRoutes } from "./category.route.js";
import { getMirrorStatus, resetMirrorCache } from "../helper/mirror.helper.js"; import { getMirrorStatus, resetMirrorCache } from "../helper/mirror.helper.js";
import { getCacheStats } from "../helper/cache.helper.js";
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// ROUTE REGISTRATION // ROUTE REGISTRATION
@@ -204,6 +210,106 @@ app.use((req, res, next) => {
} }
}); });
// ---- FEATURE: Resolve actual stream URL (m3u8/mp4) from link ID ----
app.get("/api/stream/resolve", async (req, res, next) => {
try {
await getResolvedStream(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ---- FEATURE: Available quality options for a stream URL ----
app.get("/api/stream/qualities", async (req, res, next) => {
try {
await getStreamQualities(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ---- FEATURE: M3U8 proxy — fetch and serve M3U8 playlists through API ----
app.get("/api/stream/proxy", async (req, res, next) => {
try {
const { url } = req.query;
if (!url) {
return res.status(400).json({ success: false, message: "M3U8 URL is required" });
}
// NOTE: Validate URL is from known streaming domains
const allowedDomains = ["vidtube.site", "vidplay.site", "megaplay.buzz", "megaplay-1.buzz", "cdn.anipixcdn.co"];
const urlObj = new URL(url);
const isAllowed = allowedDomains.some(d => urlObj.hostname.includes(d)) || urlObj.hostname.endsWith(".m3u8");
if (!isAllowed) {
return res.status(403).json({ success: false, message: "Domain not allowed for proxy" });
}
const axios = (await import("axios")).default;
const { headers: defaultHeaders } = await import("../configs/header.config.js");
const response = await axios.get(url, {
headers: {
...defaultHeaders,
"Referer": "https://anikototv.to/",
"Origin": "https://anikototv.to",
},
timeout: 15000,
responseType: "text",
});
// NOTE: Rewrite relative URLs in M3U8 to proxy URLs
let content = typeof response.data === "string" ? response.data : String(response.data);
const baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
content = content.replace(/(^(?!#).+\.m3u8.*$)/gm, (match) => {
const absoluteUrl = match.startsWith("http") ? match : new URL(match, baseUrl).href;
return `/api/stream/proxy?url=${encodeURIComponent(absoluteUrl)}`;
});
content = content.replace(/(^(?!#).+\.ts.*$)/gm, (match) => {
const absoluteUrl = match.startsWith("http") ? match : new URL(match, baseUrl).href;
return `/api/stream/ts-proxy?url=${encodeURIComponent(absoluteUrl)}`;
});
res.setHeader("Content-Type", "application/vnd.apple.mpegurl");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "public, max-age=30");
res.send(content);
} catch (error) {
jsonError(res, error.message);
}
});
// ---- FEATURE: TS segment proxy for video segments ----
app.get("/api/stream/ts-proxy", async (req, res, next) => {
try {
const { url } = req.query;
if (!url) {
return res.status(400).json({ success: false, message: "TS URL is required" });
}
const axios = (await import("axios")).default;
const { headers: defaultHeaders } = await import("../configs/header.config.js");
const response = await axios.get(url, {
headers: {
...defaultHeaders,
"Referer": "https://anikototv.to/",
"Origin": "https://anikototv.to",
},
timeout: 30000,
responseType: "arraybuffer",
});
res.setHeader("Content-Type", "video/mp2t");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "public, max-age=3600");
res.send(Buffer.from(response.data));
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SCHEDULE // SCHEDULE
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
@@ -328,6 +434,58 @@ app.use((req, res, next) => {
} }
}); });
// ══════════════════════════════════════════════════════════════
// UPCOMING ANIME
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Upcoming anime releases ----
app.get("/api/upcoming", async (req, res, next) => {
try {
await getUpcomingAnime(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════
// TOP ANIME RANKINGS
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Top anime rankings with sort (top/newest) ----
app.get("/api/top-rankings", async (req, res, next) => {
try {
await getTopAnimeRankings(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════
// RECENTLY UPDATED (TAB FILTERED)
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Recently updated anime with tab filter (all/dub/sub) ----
app.get("/api/recently-updated", async (req, res, next) => {
try {
await getRecentlyUpdatedTabs(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════
// COMPLETED ANIME
// ══════════════════════════════════════════════════════════════
// ---- FEATURE: Completed anime series ----
app.get("/api/completed", async (req, res, next) => {
try {
await getCompletedAnime(req, res, next);
} catch (error) {
jsonError(res, error.message);
}
});
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
// SEASONS & WATCH ORDER // SEASONS & WATCH ORDER
// ══════════════════════════════════════════════════════════════ // ══════════════════════════════════════════════════════════════
@@ -418,7 +576,7 @@ app.get("/api/stats", (req, res) => {
ttl: "5 minutes", ttl: "5 minutes",
description: "Map-based cache with TTL expiration", description: "Map-based cache with TTL expiration",
}, },
endpoints: 30, endpoints: 38,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
}, },
}); });
@@ -434,6 +592,12 @@ app.get("/api/mirrors", async (req, res) => {
} }
}); });
// ---- FEATURE: Cache statistics ----
app.get("/api/cache/stats", (req, res) => {
const stats = getCacheStats();
res.json({ success: true, results: stats });
});
// ---- FEATURE: Reset mirror cache ---- // ---- FEATURE: Reset mirror cache ----
app.post("/api/mirrors/reset", (req, res) => { app.post("/api/mirrors/reset", (req, res) => {
resetMirrorCache(); resetMirrorCache();
@@ -481,6 +645,10 @@ app.get("/api/openapi", (req, res) => {
"/mirrors/reset": { post: { summary: "Reset mirror cache", tags: ["System"] } }, "/mirrors/reset": { post: { summary: "Reset mirror cache", tags: ["System"] } },
"/openapi": { get: { summary: "OpenAPI spec", tags: ["System"] } }, "/openapi": { get: { summary: "OpenAPI spec", tags: ["System"] } },
"/watch": { get: { summary: "Watch page data", tags: ["Streaming"] } }, "/watch": { get: { summary: "Watch page data", tags: ["Streaming"] } },
"/stream/resolve": { get: { summary: "Resolve actual stream URL (m3u8/mp4)", tags: ["Streaming"] } },
"/stream/qualities": { get: { summary: "Available quality options for M3U8 stream", tags: ["Streaming"] } },
"/stream/proxy": { get: { summary: "M3U8 playlist proxy (rewrites URLs)", tags: ["Streaming"] } },
"/stream/ts-proxy": { get: { summary: "TS video segment proxy", tags: ["Streaming"] } },
"/search/suggest": { get: { summary: "Search suggestions", tags: ["Search"] } }, "/search/suggest": { get: { summary: "Search suggestions", tags: ["Search"] } },
"/episodes-ajax/{id}": { get: { summary: "AJAX episode list", tags: ["Episodes"] } }, "/episodes-ajax/{id}": { get: { summary: "AJAX episode list", tags: ["Episodes"] } },
"/mapper-servers": { get: { summary: "Mapper servers", tags: ["Streaming"] } }, "/mapper-servers": { get: { summary: "Mapper servers", tags: ["Streaming"] } },
@@ -491,6 +659,10 @@ app.get("/api/openapi", (req, res) => {
"/watch-order/{id}": { get: { summary: "Watch order", tags: ["Anime"] } }, "/watch-order/{id}": { get: { summary: "Watch order", tags: ["Anime"] } },
"/az-list/{letter}": { get: { summary: "A-Z listing", tags: ["Discovery"] } }, "/az-list/{letter}": { get: { summary: "A-Z listing", tags: ["Discovery"] } },
"/suggestions": { get: { summary: "Anime suggestions", tags: ["Search"] } }, "/suggestions": { get: { summary: "Anime suggestions", tags: ["Search"] } },
"/upcoming": { get: { summary: "Upcoming anime", tags: ["Discovery"] } },
"/top-rankings": { get: { summary: "Top anime rankings (top/newest)", tags: ["Rankings"] } },
"/recently-updated": { get: { summary: "Recently updated (all/dub/sub tabs)", tags: ["Releases"] } },
"/completed": { get: { summary: "Completed anime series", tags: ["Rankings"] } },
}, },
tags: [ tags: [
{ name: "Home", description: "Homepage data" }, { name: "Home", description: "Homepage data" },
+30 -16
View File
@@ -19,11 +19,13 @@ const tests = [
// Core endpoints // Core endpoints
{ name: "Home", url: "/", check: (d) => d.results?.spotlights || d.results?.trending }, { name: "Home", url: "/", check: (d) => d.results?.spotlights || d.results?.trending },
{ name: "Search", url: "/search?keyword=naruto", check: (d) => d.results?.data }, { 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: "Info", url: "/info?id=one-piece-odmau", check: (d) => d.results?.title },
{ name: "Episodes", url: "/episodes/road-of-naruto-ggjw8", check: (d) => d.results?.episodes }, { name: "Episodes", url: "/episodes/one-piece-odmau", check: (d) => d.results?.episodes },
{ name: "Servers", url: "/servers?ids=1", check: (d) => d.results }, { 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 }, // Streaming
{ name: "Stream", url: "/watch?slug=one-piece-odmau&ep=1", check: (d) => d.results?.servers || d.results?.episodeNumber },
{ name: "Stream Resolve", url: "/stream/resolve?id=MTF1dkFtaW9BRTZPbzJJRElFZUZrNHVJWFRVWWRWdU5JYnhuaU95bVRYSzk1Z0lVVjJha2FnSE95U3F4M1RsaXNCSnlnd05rTTlBUldTZGZxZjQzajVxcXVDRVY5bjBocnRCV2tkNnNzaXFnc3c5M1JJWjRnNmt5bDNPdm1TczlvVXdwWGplKzFmQmZJMlp0OTBNTXd3PT0&slug=one-piece-odmau", check: (d) => d.results?.url, optional: true },
// Discovery endpoints // Discovery endpoints
{ name: "Suggestions", url: "/suggestions?keyword=naruto", check: (d) => d.results }, { name: "Suggestions", url: "/suggestions?keyword=naruto", check: (d) => d.results },
{ name: "Spotlight", url: "/spotlight", check: (d) => d.results }, { name: "Spotlight", url: "/spotlight", check: (d) => d.results },
@@ -31,27 +33,39 @@ const tests = [
{ name: "Top 10", url: "/top-ten", check: (d) => d.results }, { name: "Top 10", url: "/top-ten", check: (d) => d.results },
{ name: "Random", url: "/random", check: (d) => d.results }, { name: "Random", url: "/random", check: (d) => d.results },
{ name: "Most Popular", url: "/most-popular", check: (d) => d.results }, { name: "Most Popular", url: "/most-popular", check: (d) => d.results },
{ name: "Upcoming", url: "/upcoming", check: (d) => Array.isArray(d.results) },
{ name: "Top Rankings", url: "/top-rankings", check: (d) => Array.isArray(d.results) },
{ name: "Recently Updated", url: "/recently-updated", check: (d) => Array.isArray(d.results) },
{ name: "Completed", url: "/completed", check: (d) => Array.isArray(d.results) },
// Release lists
{ name: "New Release", url: "/new-release", 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: "Newly Added", url: "/newly-added", check: (d) => d.results },
{ name: "Latest Updated", url: "/latest-updated", check: (d) => d.results, optional: true }, { name: "Latest Updated", url: "/latest-updated", check: (d) => d.results },
// Category endpoints // Category endpoints
{ name: "Genre", url: "/genre/action", check: (d) => d.results }, { name: "Genre", url: "/genre/action", check: (d) => d.results },
{ name: "Type", url: "/type/tv", check: (d) => d.results }, { name: "Type", url: "/type/tv", check: (d) => d.results },
{ name: "Status", url: "/status/airing", check: (d) => d.results },
{ name: "AZ List", url: "/az-list/a", 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 }, { name: "Filter", url: "/filter?keyword=naruto", 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 // Search variants
{ name: "Search Suggest", url: "/search/suggest?keyword=naruto", check: (d) => d.results }, { name: "Search Suggest", url: "/search/suggest?keyword=naruto", check: (d) => d.results },
{ name: "Episodes Ajax", url: "/episodes-ajax/7174", check: (d) => d.results }, { name: "Episodes Ajax", url: "/episodes-ajax/one-piece-odmau", check: (d) => d.results },
{ name: "Trending Sidebar", url: "/trending-sidebar", 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&timestamp=1234567890", check: (d) => d.results },
{ name: "Seasons", url: "/seasons/7174", check: (d) => d.results?.seasons || d.results?.totalSeasons, optional: true }, // Anime detail
{ name: "Watch Order", url: "/watch-order/7174", check: (d) => d.results?.related || d.results?.totalRelated, optional: true }, { name: "Seasons", url: "/seasons/one-piece-odmau", check: (d) => d.results?.seasons || d.results?.totalSeasons, optional: true },
{ name: "Watch Order", url: "/watch-order/one-piece-odmau", check: (d) => d.results?.related || d.results?.totalRelated, optional: true },
{ name: "Download", url: "/download?slug=one-piece-odmau&ep=1", check: (d) => d.results, optional: true },
// Utility endpoints
{ name: "Health", url: "/health", check: (d) => d.results?.status === "healthy" },
{ name: "Stats", url: "/stats", check: (d) => d.results?.endpoints },
{ name: "Cache Stats", url: "/cache/stats", check: (d) => d.results?.hits !== undefined },
{ name: "Mirrors", url: "/mirrors", check: (d) => Array.isArray(d.results) },
{ name: "OpenAPI", url: "/openapi", check: (d) => d.openapi === "3.0.3" },
]; ];
let passed = 0; let passed = 0;