chore: initial commit for asepharyana-hub-scraper

This commit is contained in:
asepharyana
2026-07-09 22:07:03 +07:00
commit 80c96eaa42
190 changed files with 28465 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
name: Notify Parent Repo
on:
push:
branches:
- main
jobs:
dispatch:
runs-on: ubuntu-latest
steps:
- name: Trigger root monorepo build
uses: peter-evans/repository-dispatch@v3
with:
token: ${{ secrets.DISPATCH_TOKEN }}
repository: MythEclipse/ultimate-asepharyana.tech
event-type: submodule-updated
client-payload: |
{
"service": "scraper-api",
"ref": "${{ github.ref }}",
"sha": "${{ github.sha }}",
"actor": "${{ github.actor }}"
}
+67
View File
@@ -0,0 +1,67 @@
apps/gmw/
# See https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# compiled output
dist
tmp
out-tsc
error.log
# dependencies
node_modules
.bun/**
.turbo/
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
**/target/**
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
.claude
# Next.js
.next
out
**/.codegraph/**
**/.claude/**
test-output
**/**.env
**/**.env.**
vite.config.*.timestamp*
vitest.config.*.timestamp*
storybook-static
~/.bun/**
docs/dependency-map.md
docs/handoff-log.jsonl
docs/observability.md
docs/quality-gates.json
docs/workflow-state.json
docs/todo.md
**/vendor/
# moonrepo
.moon/cache
.~moon**
+27
View File
@@ -0,0 +1,27 @@
# AGENT.md - Universal AI Entry Point
This document serves as the unified entry point for all AI agents (Gemini, Claude, GPT, etc.) interacting with the **Scraping & CDN Service**.
## 🚀 Mission Statement
To provide a specialized, zero-bloat backend engine for high-concurrency web scraping and image persistent caching.
## 🛑 Global AI Protocols
As an AI agent, you **MUST** adhere to the following when working on this codebase:
1. **Professionalism**: Maintain a factual, technical, and objective tone.
2. **No Hyperbole**: Prohibited from using marketing-speak or exaggerated praise (e.g., "amazing", "powerful").
3. **Minimalism**: Prioritize the **Zero-Bloat Policy**. If a request adds unnecessary complexity or dependencies, challenge the user and suggest a leaner alternative.
4. **Zero Suppression**: Never use suppression flags (`#[allow]`, `@ts-ignore`) to bypass warnings. Fix the underlying logic or types.
5. **Observability**: Ensure critical business flows emit structured logs and request context where needed.
## 🔗 Technical Context
- **Architecture**: [GEMINI.md](file:///mnt/code/bp3/ultimate-asepharyana.tech/apps/scraper/GEMINI.md) (Logic flows, tech stack).
- **Maintenance**: [Development Guide](file:///mnt/code/bp3/ultimate-asepharyana.tech/apps/scraper/docs/development.md) (Coding standards).
- **Observability**: [Metrics Guide](file:///mnt/code/bp3/ultimate-asepharyana.tech/apps/scraper/docs/observability.md) (Standard telemetry).
---
*If you are an AI assistant, start by reading [GEMINI.md](file:///mnt/code/bp3/ultimate-asepharyana.tech/apps/scraper/GEMINI.md) for the full architectural context.*
+177
View File
@@ -0,0 +1,177 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Scraper service — a Rust/Axum backend for web scraping (anime/komik data extraction) and image proxy/CDN caching. Serves as the backend engine consumed by the `apps/solidjs` frontend.
## Commands
```bash
# Development
cargo run # Start server (binds 0.0.0.0:4091)
cargo test # Run all tests
cargo clippy -- -D warnings # Lint (warnings are errors)
cargo fmt # Auto-format all source files
# Release build (full LTO, single CGU, stripped)
cargo build --release
# PM2 production
pm2 start ecosystem.config.cjs --env production # Uses target/release/scraper
```
## Architecture
### Modular MVC + Service + Repository
Setiap module mengikuti arsitektur layered yang identik:
```
Request → Router (route.rs) → Controller → Service → Repository → Parser
├── Redis (L1 cache)
├── SeaORM/MySQL (L2, image_cache)
└── External HTTP (alqanime.si, picser CDN)
```
### Directory Layout
```
src/
├── main.rs # Entry point: builds Application, calls run()
├── lib.rs # Public module declarations
├── app.rs # Router assembly: modules + metrics + swagger + middleware layers
├── bootstrap/mod.rs # Application::build(): tracing, Redis, browser pool, DB, AppState
├── modules/ # Feature modules (vertical slices)
│ ├── anime/ # Otakudesu anime scraper
│ ├── anime2/ # Alqanime.si anime scraper
│ ├── komik/ # Komik scraper
│ └── proxy/ # Image proxy/cache/audit endpoints
└── shared/ # Cross-cutting infrastructure
├── config/ # Lazy-static AppConfig from env vars (fail-fast at startup)
├── state/ # AppState (redis_pool, db, semaphore, event_bus)
├── database/
│ ├── traits/ # ScrapingRepository, ImageCacheRepository (async_trait)
│ ├── repositories/ # SeaOrmImageCacheRepository (impl ImageCacheRepository)
│ └── persistence/ # SeaORM entities (image_cache)
├── services/images/ # ImageCache service + apply_cached_posters helper
├── errors/ # AppError enum → axum IntoResponse (500/404 by variant)
├── observability/ # Utoipa/Swagger OpenAPI doc
├── scheduler/ # Cron jobs (daily cache cleanup at 2 AM)
├── browser/ # Headless Chrome pool for JS-rendered scraping
├── scrapers/ # Site-specific scrapers (otakudesu)
├── utils/ # Cache helper, HTTP client, scraping helpers, retry, conversions
├── middlewares/ # Logging, rate limiting
├── events/ # EventBus for repair state updates
└── types/ # ApiResponse<T>, shared entity types (HasPoster trait, Pagination)
```
### Module Structure (identik untuk setiap module)
Setiap `src/modules/<name>/`:
| File | Peran | Pola |
|---|---|---|
| `route.rs` | Daftar endpoint, mapping URL → controller | `Router<Arc<AppState>>`, tidak ada logic |
| `controller.rs` | Extract State/Path/Query/Body, panggil service | `Result<Json<T>, AppError>` |
| `service.rs` | Business logic, caching, delegasi ke repository + parser | Struct dengan repo di-inject via constructor `new(repo: XRepository)` |
| `repository.rs` | HTTP fetching, URL builders, DB queries | Struct + `impl ScrapingRepository` trait |
| `parser.rs` | HTML parsing dengan `scraper` crate | Free functions → `Result<T, AppError>`, via `spawn_blocking` |
| `schema.rs` | Validasi query/path/body params | Struct `Deserialize` + `ToSchema` |
| `types.rs` | Response structs | `Serialize` + `ToSchema`, `impl HasPoster` jika punya poster |
### Dependency Injection
Semua service menerima dependency via constructor:
```rust
// Controller creates and injects dependencies
let repo = AnimeRepository::new();
let service = AnimeService::new(repo);
service.get_anime_index(app_state).await.map(Json)
// Service stores injected repo
pub struct AnimeService {
repository: AnimeRepository,
}
impl AnimeService {
pub fn new(repository: AnimeRepository) -> Self { Self { repository } }
}
```
### Image Caching Architecture
Single unified image cache system:
1. **Trait**: `ImageCacheRepository` (`shared/database/traits/image_cache.rs`) — Redis ops, DB ops, locks, cache invalidation
2. **Impl**: `SeaOrmImageCacheRepository` (`shared/database/repositories/image_cache.rs`)
3. **Service**: `ImageCache` struct (`shared/services/images/cache.rs`) — download, MIME-verify dengan `infer`, upload ke Picser CDN, verifikasi CDN URL (10 retry dengan backoff)
4. **Concurrency**: `Semaphore` (default 5 concurrent uploads) + request coalescing via `DashMap<broadcast::Sender>`
5. **Lazy batch helper**: `cache_image_urls_batch_lazy()` — Redis batch check → DB batch check → background spawn untuk misses
### HasPoster Trait & apply_cached_posters
`HasPoster` trait di `shared/types/entities/anime.rs` memungkinkan generic poster caching:
```rust
pub trait HasPoster {
fn poster(&self) -> &str;
fn set_poster(&mut self, url: String);
}
```
Semua item type dengan field `poster` mengimplementasikan trait ini (`OngoingAnimeItem`, `KomikItem`, `FilterAnimeItem`, `Recommendation`, dll).
`apply_cached_posters()` di `shared/services/images/cache.rs` menerima `&mut [T]` where `T: HasPoster`, menggantikan pola manual ~15 baris yang sebelumnya berulang di setiap service method.
### ScrapingRepository Trait
```rust
#[async_trait]
pub trait ScrapingRepository: Send + Sync {
async fn fetch_html(&self, url: &str) -> Result<String, AppError>;
}
```
Semua module repository (`AnimeRepository`, `Anime2Repository`, `KomikRepository`, `ProxyRepository`) mengimplementasikan trait ini.
### Error Handling
`AppError` enum di `src/shared/errors/app_error.rs` — derives `thiserror::Error` dan implements `IntoResponse` (404 untuk `NotFound`, 500 untuk lainnya).
**Kontrak error per layer:**
- **Parser** → `Result<T, AppError>`
- **Repository** → `Result<T, AppError>` (via `ScrapingRepository` trait)
- **Service** → `Result<T, AppError>` (tidak ada `Result<T, String>` atau `Box<dyn Error>`)
- **Controller** → `Result<Json<T>, AppError>` (kecuali proxy yang return raw `Response`)
### Configuration
`src/shared/config/mod.rs` — global `CONFIG` lazy-static loaded from:
1. `.env` file (dotenvy)
2. `config/default.toml` / `config/{RUN_MODE}.toml`
3. Environment variables (`APP__` prefix or legacy `DATABASE_URL`/`JWT_SECRET`/`REDIS_URL`)
Panics at startup if required config is missing — intentional fail-fast design.
## Constraints
- **No suppression flags**: `#[allow(...)]`, `#[ignore]`, `@ts-ignore` are prohibited. Fix the underlying issue.
- **Lint strictness**: `unsafe_code = "forbid"`, `panic = "deny"`, `todo = "deny"`, `unimplemented = "deny"`, `unwrap_used = "warn"`, `expect_used = "warn"`
- **Minimal dependencies**: Before adding a crate, evaluate if existing deps or std can handle it.
- **Dead code**: Remove unused functions, types, modules rather than leaving them.
- **Performance**: Use `spawn_blocking` for CPU-heavy work (HTML parsing).
- **No duplicate infrastructure**: Satu trait, satu impl. Jangan membuat trait/repository duplikat seperti `ImageRepository` dan `ImageCacheRepository` yang berbeda.
- **No thin wrappers**: Hindari wrapper tipis seperti `CacheImageUseCase` yang hanya meneruskan panggilan ke service lain.
## Useful Endpoints
- `GET /docs` — Swagger UI
- `GET /api-docs/openapi.json` — OpenAPI spec
- `POST /api/proxy/image-cache` — Cache an image URL
- `POST /api/proxy/image-cache/audit` — Audit/repair cached images
- `GET /api/anime/*` — Otakudesu scraping endpoints
- `GET /api/anime2/*` — Alqanime scraping endpoints
- `GET /api/komik/*` — Komik scraping endpoints
Generated
+5564
View File
File diff suppressed because it is too large Load Diff
+132
View File
@@ -0,0 +1,132 @@
[package]
name = "scraper-service"
version = "0.1.0"
edition = "2021"
description = "A batteries-included, production-ready Rust web framework built on Axum"
authors = ["Asep Haryana"]
license = "MIT"
repository = "https://github.com/MythEclipse/ultimate-asepharyana.tech"
keywords = ["web", "framework", "axum", "api", "rest"]
categories = ["web-programming::http-server", "web-programming::websocket"]
default-run = "scraper"
# Dependensi yang dibutuhkan saat aplikasi berjalan
[dependencies]
axum = { version = "0.8.8", features = ["ws", "multipart", "macros"] }
tokio = { version = "1.49.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
dotenvy = "0.15"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
anyhow = "1.0"
# sqlx removed - SeaORM uses it internally via sqlx-postgres feature
sea-orm = { version = "1.1.19", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros", "with-chrono", "with-uuid"] }
uuid = { version = "1.10.0", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
bytes = "1.11.0"
futures = "0.3"
reqwest = { version = "0.12.28", features = ["json", "stream", "multipart"] }
http = "1.4.0"
sha1 = "0.10.6"
data-url = "0.3.2"
base64 = "0.22.1"
tokio-util = { version = "0.7.18", features = ["codec"] }
async-trait = "0.1.89"
regex = "1.12.2"
infer = "0.19.0"
once_cell = "1.21.3"
urlencoding = "2.1"
url = "2.5.8"
rand = "0.8"
tempfile = "3.24.0"
mime_guess = "2.0.5"
tower-http = { version = "0.6.8", features = ["fs", "cors", "compression-gzip", "compression-br", "compression-zstd"] }
backoff = { version = "0.4", features = ["futures", "tokio"] }
dashmap = "6.1"
deadpool-redis = { version = "0.22.1", features = ["serde"] }
rayon = "1.11"
tl = "0.7.8"
tower = { version = "0.5", features = ["make"] }
scraper = "0.25.0"
flate2 = "1.1"
redis = { version = "0.32.7", features = ["tokio-rustls-comp", "safe_iterators"] }
thiserror = "2.0.18"
itertools = "0.14"
clap = { version = "4.5", features = ["derive"] }
config = { version = "0.15.19", features = ["toml"] }
governor = "0.10.4"
tokio-cron-scheduler = "0.15.1"
hex = "0.4.3"
hmac = "0.12.1"
sha2 = "0.10.9"
log = "0.4"
walkdir = "2.5"
utoipa = { version = "5.0", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0", features = ["axum"] }
utoipa-axum = "0.2.0"
# OpenTelemetry metrics
opentelemetry = { version = "0.27", features = ["metrics"] }
opentelemetry_sdk = { version = "0.27", features = ["metrics", "rt-tokio"] }
opentelemetry-otlp = { version = "0.27", features = ["metrics"] }
opentelemetry-semantic-conventions = "0.27"
# Dependensi yang hanya dibutuhkan untuk build script (build.rs)
# Dependensi yang hanya dibutuhkan untuk tes
[dev-dependencies]
sea-orm = { version = "1.1.19", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros", "with-chrono", "with-uuid", "mock"] }
# Definisi targets secara eksplisit untuk menghindari peringatan cargo-chef (edition/plugin)
[lib]
name = "scraper_service"
path = "src/lib.rs"
[[bin]]
name = "scraper"
path = "src/main.rs"
[lints.rust]
unsafe_code = "forbid"
unused_variables = "deny"
unused_imports = "deny"
unused_must_use = "deny"
[lints.clippy]
unwrap_used = "warn"
expect_used = "warn"
panic = "deny"
todo = "deny"
unimplemented = "deny"
[features]
# default = ["ffmpeg"]
ffmpeg = []
# Profile optimasi untuk production - fokus pada performa runtime maksimal
[profile.release]
opt-level = 3 # Optimasi level maksimal
lto = "fat" # Full LTO untuk inlining maksimal dan binary optimal
codegen-units = 1 # Single codegen unit untuk optimasi maksimal (lebih lambat build, binary lebih cepat)
incremental = false # Disable incremental untuk optimasi penuh
debug = false # No debug info untuk binary lebih kecil
strip = true # Strip symbols untuk binary lebih kecil
panic = "abort" # Abort on panic (binary lebih kecil dan lebih cepat)
overflow-checks = false # Non-overflowing arithmetic for speed (disable in debug)
# Optimize dependencies too
[profile.dev]
opt-level = 0
[profile.bench]
opt-level = 3
lto = "fat"
+69
View File
@@ -0,0 +1,69 @@
# GEMINI.md - Codebase Architecture & Structure
Internal technical overview of the **Scraping & CDN Service** (`apps/scraper`) for automated data extraction and image persistence.
## 🌍 Context
- **`apps/scraper`**: Specialized backend engine (Axum).
- **`apps/solidjs`**: Frontend consumer.
- **`packages/services`**: Shared logic.
## 🤖 AI Assistant Guidelines
AI assistants (like Claude, Gemini, GPT) interacting with this codebase **MUST** adhere to the following protocols defined in **[AGENT.md](file:///mnt/code/bp3/ultimate-asepharyana.tech/apps/scraper/AGENT.md)**:
1. **Professional Tone**: Maintain a cold, technical, and objective tone.
2. **No Hyperbole**: **PROHIBITED** from using marketing-speak or exaggerated praise (e.g., "amazing", "unparalleled", "powerful", "revolutionary").
3. **Technical Accuracy**: Focus purely on implementation facts, data structures, and performance metrics.
4. **Minimalist Adherence**: Always prioritize the **Zero-Bloat Policy**. If a request introduces unnecessary dependencies or logic, challenge the user and suggest a leaner alternative.
5. **Documentation Consistency**: Ensure any generated documentation follows the established professional and objective style of the `docs/` folder.
## 🦀 `apps/scraper` - Backend Service
An asynchronous service for scraping and image proxying. All secondary web framework features (Authentication, Social, GraphQL) have been removed to reduce complexity.
### 📊 Tech Stack
- **Framework**: [Axum](https://github.com/tokio-rs/axum) (0.8.8) - Asynchronous Rust HTTP.
- **ORM**: [SeaORM](https://www.sea-ql.org/SeaORM/) (MySQL) - Database abstraction.
- **Caching**: `deadpool-redis` & `redis` - In-memory cache mapping.
- **Observability**: Request ID tracing and structured logging.
- **Scraping**: `scraper` (CSS Selectors) & remote Chrome via HTTP.
### 📂 Directory Structure (`apps/scraper/src`)
Organized as a hybrid of Vertical Slice and Clean Architecture.
| Directory | Description |
| :--- | :--- |
| **`bin/`** | Binary entry points and CLI tools. |
| **`config/`** | Strongly-typed environment configuration. |
| **`entities/`** | **SeaORM Entities**. Database schema mapping. |
| **`routes/`** | **API Handlers**. Automatic routing system. |
| **`services/`** | Business logic (e.g., `ImageCache` service). |
| **`scraping/`** | Data extraction engines and parsers. |
| **`helpers/`** | Shared utilities and cache helpers. |
| **`middleware/`** | Axum layers (CORS, Compression). |
| **`events/`** | Internal event bus for repair state updates. |
| **`jobs/`** | Background task processing. |
| **`scheduler/`** | Periodic tasks (Daily CDN audit). |
| **`observability/`** | OpenAPI documentation, request ID tracing, and structured logging. |
### 🔑 Logic Flows
1. **Scraping**:
`Request` -> `Router` -> `Handler` -> `Scraper Engine` -> `Redis` -> `Response`.
2. **Image Proxy/CDN**:
`Request` -> `ImageCache` -> `Cache Lookup` -> `Picser Upload (on miss)` -> `CDN URL`.
### 📜 Commands
- **Standard Run**: `cargo run`
- **Optimized Build**: `cargo build --release`
- **External Audit**: `POST /api/proxy/image-cache/audit`
## 🏗 Maintenance Constraints
- **Minimalist Approach**: New dependencies require impact evaluation.
- **Lint Compliance**: Suppression flags (`#[allow]`) are prohibited.
- **Performance-First**: Use `spawn_blocking` for CPU-heavy work (HTML parsing).
+55
View File
@@ -0,0 +1,55 @@
# Scraper API
Backend service berbasis Axum untuk scraping, image proxy/cache, dan endpoint API inti.
## Stack
- Rust + Axum
- SeaORM (MySQL)
- Redis (deadpool-redis)
- Utoipa + Swagger UI
## Quick Start
```bash
cargo run
```
Server bind ke `0.0.0.0:${PORT}` dengan default port `4091`.
## Required Environment Variables
```env
DATABASE_URL=mysql://asephs:hunterz@localhost:3306/sosmed
JWT_SECRET=change-me
REDIS_URL=redis://localhost:6379
```
Optional yang sering dipakai:
```env
RUST_LOG=info
EXTERNAL_BROWSERLESS_WS=
MINIO_ENDPOINT=
MINIO_BUCKET_NAME=
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
```
## Useful Endpoints
- `GET /docs` - Swagger UI
- `GET /api-docs/openapi.json` - OpenAPI JSON
- `GET /api/anime2/*`
- `GET /api/komik/*`
- `POST /api/proxy/image-cache`
- `POST /api/proxy/image-cache/audit`
## Notes
- Database akan dicek/dibuat saat startup jika `DATABASE_URL` bertipe MySQL.
- Service ini juga menginisialisasi browser pool dan scheduler saat boot.
## License
MIT
+73
View File
@@ -0,0 +1,73 @@
#!/bin/bash
# Simple script to check image_cache database content
DATABASE_URL="mysql://asephs:hunterz@127.0.0.1:3306/sosmed"
echo "=== Checking Image Cache Database ==="
echo ""
echo "Attempting to connect via Rust binary..."
echo ""
cd "$(dirname "$0")"
# Create temporary Rust script
cat > /tmp/check_img_cache.rs << 'EOF'
use sea_orm::{Database, ConnectionTrait, Statement};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Database::connect("mysql://asephs:hunterz@127.0.0.1:3306/sosmed").await?;
println!("✓ Connected to database\n");
// Show all tables
println!("=== ALL TABLES ===");
let tables = db.query_all(Statement::from_string(
db.get_database_backend(),
"SHOW TABLES".to_owned()
)).await?;
for table in &tables {
println!(" - {:?}", table);
}
// Count image_cache records
println!("\n=== IMAGE_CACHE TABLE ===");
let count = db.query_one(Statement::from_string(
db.get_database_backend(),
"SELECT COUNT(*) as total FROM ImageCache".to_owned()
)).await?;
println!("Total records: {:?}", count);
// Show recent 10 records
println!("\n=== RECENT RECORDS (Last 10) ===");
let records = db.query_all(Statement::from_string(
db.get_database_backend(),
"SELECT id, originalUrl, cdnUrl, createdAt FROM ImageCache ORDER BY createdAt DESC LIMIT 10".to_owned()
)).await?;
for (i, record) in records.iter().enumerate() {
println!("\n[{}]", i + 1);
println!(" ID: {:?}", record.try_get::<String>("", "id"));
println!(" Original: {:?}", record.try_get::<String>("", "originalUrl"));
println!(" CDN URL: {:?}", record.try_get::<String>("", "cdnUrl"));
println!(" Created: {:?}", record.try_get::<chrono::DateTime<chrono::Utc>>("", "createdAt"));
}
Ok(())
}
EOF
echo "Running database check..."
rustc --edition 2021 /tmp/check_img_cache.rs -o /tmp/check_img_cache \
-L dependency=target/debug/deps \
--extern sea_orm=target/debug/deps/libsea_orm.rlib \
--extern tokio=target/debug/deps/libtokio.rlib \
--extern chrono=target/debug/deps/libchrono.rlib \
2>/dev/null
if [ $? -eq 0 ]; then
/tmp/check_img_cache
else
echo "Rust compilation failed, using cargo script instead..."
cargo script /tmp/check_img_cache.rs
fi
@@ -0,0 +1,167 @@
# Clean-Modular Architecture Refactor Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Refactor the codebase into a rigid Clean-Modular architecture to improve maintainability and strictly enforce separation of concerns.
**Architecture:** A three-tier modular approach consisting of Presentation (API Handlers/DTOs), Core (Domain Models/Traits/Use Cases), and Infrastructure (Adapters/Repositories/Scrapers).
**Tech Stack:** Rust, Axum, SeaORM, Redis, reqwest.
---
### Task 1: Initialize Core Domain Models & Shared Errors
**Files:**
- Create: `src/shared/errors/mod.rs`
- Create: `src/core/models/image.rs`
- Create: `src/core/models/mod.rs`
- Create: `src/shared/mod.rs`
- [ ] **Step 1: Define shared application errors**
- [ ] **Step 2: Define pure domain models for ImageCache**
- [ ] **Step 3: Setup core and shared modules in `lib.rs`**
```rust
// src/shared/errors/mod.rs
use axum::{response::{IntoResponse, Response}, Json, http::StatusCode};
use serde_json::json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("Validation error: {0}")]
Validation(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound(m) => (StatusCode::NOT_FOUND, m),
AppError::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),
AppError::Validation(m) => (StatusCode::BAD_REQUEST, m),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
```
- [ ] **Step 4: Commit changes**
```bash
git add src/shared/errors/mod.rs src/core/models/image.rs
git commit -m "feat: init core models and shared errors"
```
### Task 2: Define Core Repository Traits
**Files:**
- Create: `src/core/repositories/image_repository.rs`
- Create: `src/core/repositories/mod.rs`
- [ ] **Step 1: Define ImageRepository trait in `core`**
```rust
// src/core/repositories/image_repository.rs
use async_trait::async_trait;
use crate::core::models::image::ImageCache;
use crate::shared::errors::AppError;
#[async_trait]
pub trait ImageRepository: Send + Sync {
async fn find_by_original_url(&self, url: &str) -> Result<Option<ImageCache>, AppError>;
async fn save(&self, image: ImageCache) -> Result<(), AppError>;
async fn delete_by_original_url(&self, url: &str) -> Result<(), AppError>;
}
```
- [ ] **Step 2: Commit changes**
```bash
git add src/core/repositories/
git commit -m "feat: define core repository traits"
```
### Task 3: Migrate SeaORM Entities to Infrastructure
**Files:**
- Modify: `src/infra/mod.rs`
- Create: `src/infra/repositories/mysql_image_repository.rs`
- [ ] **Step 1: Implement ImageRepository for MySQL using SeaORM**
- [ ] **Step 2: Move `src/entities/image_cache.rs` logic into the new repository implementation**
- [ ] **Step 3: Update `src/infra/mod.rs` to expose repositories**
- [ ] **Step 4: Commit changes**
```bash
git add src/infra/repositories/
git commit -m "feat: implement mysql image repository in infra"
```
### Task 4: Implement Core Use Cases (Image Caching)
**Files:**
- Create: `src/core/use_cases/cache_image.rs`
- Create: `src/core/use_cases/mod.rs`
- [ ] **Step 1: Implement `CacheImageUseCase`**
- [ ] **Step 2: Orchestrate logic between repository, redis, and scraper/uploader**
- [ ] **Step 3: Commit changes**
```bash
git add src/core/use_cases/
git commit -m "feat: implement image caching use cases"
```
### Task 5: Refactor Scrapers into Infrastructure
**Files:**
- Create: `src/core/repositories/scraping_repository.rs`
- Create: `src/infra/scrapers/otakudesu.rs`
- [ ] **Step 1: Define Scraping traits in `core`**
- [ ] **Step 2: Implement site-specific scrapers in `infra`**
- [ ] **Step 3: Migrate existing logic from `src/scraping/`**
- [ ] **Step 4: Commit changes**
```bash
git add src/infra/scrapers/
git commit -m "feat: migrate scrapers to infra adapters"
```
### Task 6: Refactor Presentation Layer (API Handlers)
**Files:**
- Create: `src/presentation/api/anime_handler.rs`
- Create: `src/presentation/api/mod.rs`
- Create: `src/presentation/mod.rs`
- [ ] **Step 1: Migrate handlers from `src/routes/` to `presentation/api/`**
- [ ] **Step 2: Update handlers to use Use Cases instead of direct service/helper calls**
- [ ] **Step 3: Update global router in `src/main.rs` or `src/lib.rs`**
- [ ] **Step 4: Commit changes**
```bash
git add src/presentation/api/
git commit -m "feat: refactor presentation layer api handlers"
```
### Task 7: Global Cleanup & Verification
**Files:**
- Modify: `src/lib.rs`
- Delete: `src/helpers/` (partially merged into shared/infra)
- Delete: `src/services/` (merged into core/use_cases)
- Delete: `src/routes/` (merged into presentation)
- [ ] **Step 1: Update `lib.rs` to reflect new module structure**
- [ ] **Step 2: Remove old redundant directories**
- [ ] **Step 3: Run full test suite**
- [ ] **Step 4: Verify metrics endpoint**
- [ ] **Step 5: Final Commit**
```bash
git commit -m "refactor: complete clean-modular architecture overhaul"
```
@@ -0,0 +1,49 @@
# Design Spec: Clean-Modular Architecture Refactor
**Date**: 2026-05-08
**Topic**: Refactor `apps/rust` from Hybrid to Clean-Modular Architecture.
## 1. Purpose
Standardize codebase structure for rigidity, maintainability, and clear separation of concerns (SOC) without violating the **Zero-Bloat Policy**.
## 2. Target Architecture
Moving from current structure to a three-tier modular design:
### A. Presentation Layer (`src/presentation/`)
- **API Handlers**: Pure Axum handlers.
- **DTOs**: Request/Response models for external communication.
- **Middleware**: Cross-cutting concerns (CORS, Metrics, Logging).
### B. Core Layer (`src/core/`) - The Domain
- **Models**: Pure data structures (Plain Rust Objects).
- **Repository Traits**: Abstract interfaces for data persistence.
- **Use Cases**: Orchestration of business logic (e.g., `ScrapeAnime`, `ProcessImage`).
- **Dependencies**: None (or minimal shared utils).
### C. Infrastructure Layer (`src/infra/`) - The Adapters
- **Repositories**: SeaORM & Redis implementations of Core traits.
- **Scrapers**: Site-specific parsing logic implementing Core scraping traits.
- **External Clients**: HTTP Client (reqwest), Browser Pool.
### D. Shared Layer (`src/shared/`)
- **Utils**: Low-level helpers (Date, JSON, String).
- **Config**: Application configuration.
- **Errors**: Centralized error handling.
## 3. Implementation Strategy
1. **Phase 1**: Scaffold new directory structure.
2. **Phase 2**: Migrate `models` and `entities` to `core/models` and `infra/repositories`.
3. **Phase 3**: Refactor `scraping` logic into `infra/scrapers` and define traits in `core`.
4. **Phase 4**: Move Axum handlers to `presentation/api` and update routing.
5. **Phase 5**: Cleanup `helpers` into `shared/utils`.
## 4. Constraints
- **Zero-Bloat**: No new heavy dependencies for the sake of abstraction.
- **Performance**: Maintain latency metrics as defined in `docs/development.md`.
- **SeaORM**: Entities stay in `infra/` to keep `core/` pure.
## 5. Success Criteria
- All tests pass.
- `/metrics` show no latency regression.
- Circular dependencies are eliminated.
- Folder structure matches this spec.
+26
View File
@@ -0,0 +1,26 @@
// PM2 Ecosystem Configuration for Rust
module.exports = {
apps: [
{
name: 'ultimate-rust',
script: 'target/release/scraper',
cwd: process.env.VPS_TARGET_DIR
? `${process.env.VPS_TARGET_DIR}/apps/scraper`
: '/home/asephs/ultimate-asepharyana.cloud/apps/scraper',
interpreter: 'none',
exec_mode: 'fork',
autorestart: true,
watch: false,
max_memory_restart: '1G',
env_production: {
NODE_ENV: 'production',
PORT: 4091,
},
// Logging configuration
error_file: './logs/error.log',
out_file: './logs/out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
merge_logs: true,
},
],
};
+8
View File
@@ -0,0 +1,8 @@
{
"name": "scraper",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "./target/release/scraper"
}
}
+15
View File
@@ -0,0 +1,15 @@
# rustfmt configuration (stable features only)
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Unix"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2021"
merge_derives = true
use_try_shorthand = true
use_field_init_shorthand = true
force_explicit_abi = true
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Auto-fix warnings and lint Rust code
set -e
echo "🔧 Auto-fixing Rust warnings and linting..."
# Format code
echo "📝 Running rustfmt..."
cargo fmt
# Fix clippy warnings automatically
echo "🔍 Running clippy auto-fix..."
cargo clippy --fix --allow-dirty --allow-staged --all-targets
# Check for remaining issues
echo "✅ Running final check..."
cargo clippy --all-targets -- -D warnings
echo "✨ Done! Code is formatted and linted."
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Compare OpenAPI specifications for endpoint compatibility."""
import json
import sys
from pathlib import Path
def main():
if len(sys.argv) != 3:
print("Usage: compare-openapi.py <reference-openapi.json> <local-openapi.json>")
sys.exit(1)
ref_path = Path(sys.argv[1])
local_path = Path(sys.argv[2])
# Load reference OpenAPI
try:
ref_data = json.loads(ref_path.read_text())
except FileNotFoundError:
print(f"Error: Reference file not found: {ref_path}")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in reference file: {e}")
sys.exit(1)
# Load local OpenAPI
try:
local_data = json.loads(local_path.read_text())
except FileNotFoundError:
print(f"Error: Local file not found: {local_path}")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in local file: {e}")
sys.exit(1)
ref_paths = ref_data.get("paths", {})
local_paths = local_data.get("paths", {})
http_methods = {"get", "put", "post", "delete", "options", "head", "patch", "trace"}
has_differences = False
# Check for missing paths
missing_paths = set(ref_paths.keys()) - set(local_paths.keys())
if missing_paths:
has_differences = True
for path in sorted(missing_paths):
print(f"Missing path: {path}")
# Check for extra paths
extra_paths = set(local_paths.keys()) - set(ref_paths.keys())
if extra_paths:
has_differences = True
for path in sorted(extra_paths):
print(f"Extra path: {path}")
# Check for method mismatches in common paths
common_paths = set(ref_paths.keys()) & set(local_paths.keys())
for path in sorted(common_paths):
ref_methods = set(method.lower() for method in ref_paths[path].keys() if method.lower() in http_methods)
local_methods = set(method.lower() for method in local_paths[path].keys() if method.lower() in http_methods)
missing_methods = ref_methods - local_methods
if missing_methods:
has_differences = True
for method in sorted(missing_methods):
print(f"Missing method {method.upper()} for path: {path}")
extra_methods = local_methods - ref_methods
if extra_methods:
has_differences = True
for method in sorted(extra_methods):
print(f"Extra method {method.upper()} for path: {path}")
if has_differences:
sys.exit(1)
print(f"OpenAPI paths/methods match: {len(ref_paths)} paths")
sys.exit(0)
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
# Script to run database migrations manually
echo "Running database migrations..."
cd "$(dirname "$0")/.."
# Build and run the migration binary
cargo run --bin migrate
if [ $? -eq 0 ]; then
echo "✅ Migration completed successfully."
else
echo "❌ Migration failed."
exit 1
fi
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Pre-build hook to enforce best practices
set -e
echo "🔍 Running pre-build lint checks..."
# Format check
echo "📝 Checking code formatting..."
if ! cargo fmt -- --check; then
echo "❌ Code not formatted. Run: cargo fmt"
exit 1
fi
# Clippy check with denials
echo "🔧 Running clippy..."
cargo clippy --all-targets -- -D warnings
echo "✅ All lint checks passed!"
+51
View File
@@ -0,0 +1,51 @@
use std::sync::Arc;
use axum::Router;
use sea_orm::DatabaseConnection;
use tower_http::compression::{CompressionLayer, CompressionLevel};
use tower_http::cors::CorsLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
use crate::shared::observability::openapi::ApiDoc;
use crate::shared::state::AppState;
pub async fn build_router(
app_state: Arc<AppState>,
db: Arc<DatabaseConnection>,
) -> anyhow::Result<Router> {
init_scheduler(db).await?;
let mut openapi = ApiDoc::openapi();
openapi.merge(crate::shared::observability::openapi_modules::ModuleApiDoc::openapi());
let app = crate::modules::routes(Router::new())
.merge(SwaggerUi::new("/docs").url("/api-docs/openapi.json", openapi))
.with_state(app_state)
.layer(axum::middleware::from_fn(
crate::shared::observability::metrics::otel_metrics_middleware,
))
.layer(CompressionLayer::new().quality(CompressionLevel::Fastest))
.layer(CorsLayer::permissive());
Ok(app)
}
async fn init_scheduler(db: Arc<DatabaseConnection>) -> anyhow::Result<()> {
let scheduler = crate::shared::scheduler::Scheduler::new()
.await
.map_err(|e| anyhow::anyhow!("Failed to create scheduler: {}", e))?;
let cache_cleanup = crate::shared::scheduler::CleanupOldCache::new(db);
scheduler
.add(cache_cleanup)
.await
.map_err(|e| anyhow::anyhow!("Failed to add cache cleanup: {}", e))?;
scheduler
.start()
.await
.map_err(|e| anyhow::anyhow!("Failed to start scheduler: {}", e))?;
tracing::info!("✓ Scheduler started");
Ok(())
}
+117
View File
@@ -0,0 +1,117 @@
use scraper::Selector;
use scraper_service::shared::utils::parse_html;
/// Capture html5ever tree_builder warning evidence by parsing problematic HTML.
///
/// Build with: cargo build --bin capture_warning
/// Run with: RUST_LOG=warn cargo run --bin capture_warning 2>&1
///
/// Evidence of the warning is captured through:
/// 1. HTML that triggers foster_parenting in html5ever::tree_builder
/// 2. Observable parsing behavior showing tree reconstruction
/// 3. The call path from src/helpers::parse_html () to html5ever
/// 4. Real endpoint context from /api/anime2/latest/{slug} route
use std::fs;
use tracing_subscriber::EnvFilter;
fn main() {
// Initialize logging to capture WARN output from html5ever
let env_filter = EnvFilter::from_default_env()
.add_directive("warn".parse().expect("valid directive"))
.add_directive("html5ever=warn".parse().expect("valid directive"));
tracing_subscriber::fmt()
.with_env_filter(env_filter)
.with_writer(std::io::stderr)
.init();
println!("=== HTML5ever Tree Builder Foster Parenting Evidence ===\n");
println!("Real Endpoint: GET /api/anime2/latest/{{slug}}");
println!("Handler: src/routes/api/anime2/latest/[slug].rs:124");
println!("Helper Path: src/helpers/web/scraping.rs::parse_html() -> Html::parse_document()\n");
// Load HTML fixture from shared test file
let fixture_path = "src/bin/test_fixtures/foster_parenting_minimal.html";
let test_html = fs::read_to_string(fixture_path)
.expect(&format!("Failed to read fixture from {}", fixture_path));
println!("Input Request:");
println!(" GET /api/anime2/latest/some-anime");
println!(" Body: HTML containing misplaced text in <table>");
println!(" Fixture: {}", fixture_path);
println!(" Test HTML: {}\n", test_html);
println!("Parsing through src/helpers::parse_html()...\n");
println!("--- BEGIN STDERR (logging output) ---");
// This parse_html() call routes through:
// src/helpers::parse_html()
// -> scraper crate Html::parse_document()
// -> html5ever::parse() [version 0.36.1]
// -> TreeBuilder::process_token()
// -> TreeBuilder::foster_parent_in_body() which emits:
// warn!("foster parenting not implemented")
let document = parse_html(&test_html);
println!("--- END STDERR (logging output) ---\n");
// Analyze the result
println!("Parse Output Evidence:\n");
// Check table structure
let table_sel = Selector::parse("table").expect("Valid CSS selector");
let tr_sel = Selector::parse("tr").expect("Valid CSS selector");
let td_sel = Selector::parse("td").expect("Valid CSS selector");
let tables: Vec<_> = document.select(&table_sel).collect();
println!(" ✓ Tables parsed: {}", tables.len());
let trs: Vec<_> = document.select(&tr_sel).collect();
println!(" ✓ Table rows found: {}", trs.len());
let tds: Vec<_> = document.select(&td_sel).collect();
println!(" ✓ Table cells found: {}", tds.len());
let body_sel = Selector::parse("body").expect("Valid CSS selector");
if let Some(body) = document.select(&body_sel).next() {
let body_text: String = body.text().collect();
let trimmed = body_text.trim();
println!("\n Body element text content:");
println!(" '{}'", trimmed);
if trimmed.contains("orphaned text") {
println!("\n ✓ EVIDENCE: 'orphaned text' moved OUT of <table>");
println!(" This proves foster_parenting occurred!");
}
if trimmed.contains("more text") {
println!(" ✓ EVIDENCE: 'more text' moved OUT of <table>");
println!(" This confirms the adoption agency algorithm ran!");
}
}
println!("\n=== Proven Call Path ===");
println!("Route: GET /api/anime2/latest/{{slug}}");
println!("Request Handler: src/routes/api/anime2/latest/[slug].rs");
println!(" -> latest() handler");
println!(" -> fetch_latest_anime()");
println!(" -> parse_latest_page(html, page)");
println!(" -> crate::shared::utils::parse_html(html) [line 124]\n");
println!("Helper Function: src/helpers/web/scraping.rs");
println!(" pub fn parse_html(html: &str) -> Html {{");
println!(" Html::parse_document(html) // Line 34");
println!(" }}\n");
println!("Call Stack to Warning:");
println!(" 1. crate::shared::utils::parse_html() [src/helpers/web/scraping.rs:34]");
println!(" 2. Html::parse_document() [scraper crate wrapper]");
println!(" 3. html5ever::parse() [Cargo.toml: version 0.36.1]");
println!(" 4. TreeBuilder::process_token()");
println!(" 5. TreeBuilder::process_chars_in_table()");
println!(" 6. TreeBuilder::foster_parent_in_body() [src/tree_builder/mod.rs:1227]");
println!(" 7. warn!(\"foster parenting not implemented\") ← EMITTED ABOVE\n");
println!("=== Fixture Source ===");
println!("Shared File: {}", fixture_path);
println!("HTML Content: {}", test_html);
println!("Expected Parsing Behavior: Text nodes are fostered out of table");
}
+132
View File
@@ -0,0 +1,132 @@
/// Test: Verify parsed output for foster_parenting_minimal.html fixture
///
/// This binary contains tests and assertions that validate the expected behavior
/// when parsing HTML that triggers the html5ever::tree_builder::foster_parent_in_body() warning.
///
/// Uses shared fixture: src/bin/test_fixtures/foster_parenting_minimal.html
/// Uses shared parser: src/helpers::parse_html()
use scraper::Selector;
use scraper_service::shared::utils::parse_html;
use std::fs;
fn main() {
println!("Running foster parenting regression tests...\n");
// Load HTML fixture from shared test file
let fixture_path = "src/bin/test_fixtures/foster_parenting_minimal.html";
let foster_parenting_html = fs::read_to_string(fixture_path)
.expect(&format!("Failed to read fixture from {}", fixture_path));
test_foster_parenting_text_extraction(&foster_parenting_html);
println!("✓ test_foster_parenting_text_extraction passed");
test_foster_parenting_table_structure(&foster_parenting_html);
println!("✓ test_foster_parenting_table_structure passed");
test_expected_parsed_output_assertion(&foster_parenting_html);
println!("✓ test_expected_parsed_output_assertion passed");
println!("\n✓ All assertions passed (3/3)");
println!("\nFixture source: {}", fixture_path);
println!("Parser source: src/helpers/web/scraping.rs::parse_html()");
}
/// Test: Text nodes in <table> are foster-parented to body
fn test_foster_parenting_text_extraction(html: &str) {
let document = parse_html(html);
let body_sel = Selector::parse("body").expect("Valid CSS selector");
let body_text: String = document
.select(&body_sel)
.next()
.map(|el| el.text().collect())
.unwrap_or_default();
assert!(
body_text.contains("orphaned text"),
"Text 'orphaned text' should be present in body (fostered from table)"
);
assert!(
body_text.contains("more text"),
"Text 'more text' should be present in body (fostered from table)"
);
assert!(
body_text.contains("cell content"),
"Cell content should still be present"
);
}
fn test_foster_parenting_table_structure(html: &str) {
let document = parse_html(html);
let table_sel = Selector::parse("table").expect("Valid CSS selector");
let tr_sel = Selector::parse("tr").expect("Valid CSS selector");
let td_sel = Selector::parse("td").expect("Valid CSS selector");
let tables: Vec<_> = document.select(&table_sel).collect();
assert_eq!(tables.len(), 1, "Should have exactly 1 table");
let rows: Vec<_> = document.select(&tr_sel).collect();
assert_eq!(rows.len(), 1, "Should have exactly 1 row");
let cells: Vec<_> = document.select(&td_sel).collect();
assert_eq!(cells.len(), 1, "Should have exactly 1 cell");
if let Some(cell) = cells.first() {
let cell_text: String = cell.text().collect();
assert_eq!(
cell_text.trim(),
"cell content",
"Cell content should be preserved"
);
}
}
fn test_expected_parsed_output_assertion(html: &str) {
let document = parse_html(html);
let body_sel = Selector::parse("body").expect("Valid CSS selector");
let body = document
.select(&body_sel)
.next()
.expect("body should exist");
let full_text: String = body.text().collect();
let expected_pattern = "orphaned textmore textcell content";
assert!(
full_text.contains(&expected_pattern)
|| (full_text.contains("orphaned text")
&& full_text.contains("more text")
&& full_text.contains("cell content")),
"Parsed output should contain all text content in fostered form. Got: '{}'",
full_text
);
}
#[cfg(test)]
mod tests {
use super::*;
fn load_fixture() -> String {
fs::read_to_string("src/bin/test_fixtures/foster_parenting_minimal.html")
.expect("Failed to load fixture")
}
#[test]
fn test_foster_parenting_text_extraction_test() {
let html = load_fixture();
test_foster_parenting_text_extraction(&html);
}
#[test]
fn test_foster_parenting_table_structure_test() {
let html = load_fixture();
test_foster_parenting_table_structure(&html);
}
#[test]
fn test_expected_parsed_output_assertion_test() {
let html = load_fixture();
test_expected_parsed_output_assertion(&html);
}
}
@@ -0,0 +1,83 @@
//! Complete API generator - combines model, migration, controller, service, repository
use anyhow::Result;
pub fn generate_full_api(name: &str, full: bool) -> Result<()> {
println!("📦 Generating model...");
let model_name = singularize(name);
super::model::generate_model(&model_name, true, true, false)?;
if full {
println!("🔧 Generating service...");
super::service::generate_service(name, Some(&model_name))?;
println!("💾 Generating repository...");
super::repository::generate_repository(name, &model_name)?;
}
println!("🎮 Generating CRUD controller...");
super::controller::generate_controller(name, true, Some(&model_name))?;
println!("\n✅ Complete API generated!");
println!("\n📋 Generated files:");
println!(
" - src/entities/{}.rs (SeaORM model)",
model_name.to_lowercase()
);
println!(
" - migrations/m*_create_{}.rs (migration)",
super::model::pluralize(&model_name)
);
if full {
println!(" - src/services/{}_service.rs (service layer)", name);
println!(" - src/repositories/{}_repository.rs (repository)", name);
}
println!(" - src/routes/api/{}/index.rs (list)", name);
println!(" - src/routes/api/{}/[id].rs (get)", name);
println!(" - src/routes/api/{}/create.rs (create)", name);
println!(" - src/routes/api/{}/[id]/update.rs (update)", name);
println!(" - src/routes/api/{}/[id]/delete.rs (delete)", name);
println!("\n🚀 Next steps:");
println!(" 1. Run 'cargo build' to compile");
println!(" 2. Run migrations: cargo run -- migration up");
println!(" 3. Start server: cargo run");
println!("\n📡 Available endpoints:");
println!(" GET /api/{} - List all", name);
println!(" GET /api/{}/{{id}} - Get one", name);
println!(" POST /api/{} - Create", name);
println!(" PUT /api/{}/{{id}} - Update", name);
println!(" DELETE /api/{}/{{id}} - Delete", name);
Ok(())
}
fn singularize(word: &str) -> String {
let lower = word.to_lowercase();
if lower.ends_with("ies") {
format!("{}y", &lower[..lower.len() - 3])
} else if lower.ends_with("es") {
lower[..lower.len() - 2].to_string()
} else if lower.ends_with('s') {
lower[..lower.len() - 1].to_string()
} else {
lower
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_singularize() {
assert_eq!(singularize("users"), "user");
assert_eq!(singularize("categories"), "category");
assert_eq!(singularize("posts"), "post");
assert_eq!(singularize("boxes"), "box");
}
}
@@ -0,0 +1,287 @@
//! API controller generator with CRUD operations
use anyhow::Result;
use std::fs;
use std::path::Path;
pub fn generate_controller(name: &str, crud: bool, model: Option<&str>) -> Result<()> {
let api_dir = Path::new("src/routes/api").join(name);
fs::create_dir_all(&api_dir)?;
let model_name = model.map(|s| s.to_string()).unwrap_or_else(|| {
// Singularize the resource name
let singular = name.trim_end_matches('s');
format!("{}{}", &singular[..1].to_uppercase(), &singular[1..])
});
if crud {
generate_crud_routes(&api_dir, name, &model_name)?;
} else {
generate_basic_controller(&api_dir, name);
}
Ok(())
}
fn generate_crud_routes(api_dir: &Path, resource: &str, model: &str) -> Result<()> {
// List all
let index_content = generate_list_handler(resource, model);
fs::write(api_dir.join("index.rs"), index_content)?;
// Get by ID
let show_content = generate_show_handler(resource, model);
fs::write(api_dir.join("[id].rs"), show_content)?;
// Create
let create_content = generate_create_handler(resource, model);
fs::write(api_dir.join("create.rs"), create_content)?;
// Update & Delete in [id] subdirectory
fs::create_dir_all(api_dir.join("[id]"))?;
let update_content = generate_update_handler(resource, model);
fs::write(api_dir.join("[id]/update.rs"), update_content)?;
let delete_content = generate_delete_handler(resource, model);
fs::write(api_dir.join("[id]/delete.rs"), delete_content)?;
Ok(())
}
fn generate_list_handler(resource: &str, model: &str) -> String {
format!(
r#"//! List all {resource}
use axum::{{Extension, Json, response::IntoResponse, Router}};
use sea_orm::{{DatabaseConnection, EntityTrait}};
use std::sync::Arc;
use crate::shared::state::AppState;
use crate::entities::{model_low}::{{Entity as {model}, Model}};
pub async fn list(
Extension(db): Extension<DatabaseConnection>,
) -> impl IntoResponse {{
match {model}.find().all(&db).await {{
Ok(items) => Json(items).into_response(),
Err(e) => {{
eprintln!("Error listing {resource}: {{}}", e);
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to list {resource}").into_response()
}}
}}
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
resource = resource,
model_low = model.to_lowercase(),
model = model
)
}
fn generate_show_handler(resource: &str, model: &str) -> String {
let singular = resource.trim_end_matches('s');
format!(
r#"//! Get {singular} by ID
use axum::{{Extension, Json, extract::Path, response::IntoResponse, Router}};
use sea_orm::{{DatabaseConnection, EntityTrait}};
use std::sync::Arc;
use crate::shared::state::AppState;
use crate::entities::{model_low}::{{Entity as {model}, Model}};
pub async fn show(
Path(id): Path<i32>,
Extension(db): Extension<DatabaseConnection>,
) -> impl IntoResponse {{
match {model}.find_by_id(id).one(&db).await {{
Ok(Some(item)) => Json(item).into_response(),
Ok(None) => (axum::http::StatusCode::NOT_FOUND, "{singular} not found").into_response(),
Err(e) => {{
eprintln!("Error getting {singular}: {{}}", e);
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to get {singular}").into_response()
}}
}}
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
singular = singular,
model_low = model.to_lowercase(),
model = model,
resource = resource
)
}
fn generate_create_handler(resource: &str, model: &str) -> String {
let singular = resource.trim_end_matches('s');
format!(
r#"//! Create new {singular}
use axum::{{Extension, Json, response::IntoResponse, Router}};
use sea_orm::{{ActiveModelTrait, DatabaseConnection, Set}};
use serde::{{Deserialize, Serialize}};
use std::sync::Arc;
use crate::shared::state::AppState;
use crate::entities::{model_low}::{{ActiveModel, Model}};
#[derive(Serialize, Deserialize)]
pub struct Create{model}Dto {{
pub name: String,
// Add your fields
}}
pub async fn create(
Extension(db): Extension<DatabaseConnection>,
Json(data): Json<Create{model}Dto>,
) -> impl IntoResponse {{
let new_item = ActiveModel {{
name: Set(data.name),
..Default::default()
}};
match new_item.insert(&db).await {{
Ok(item) => (axum::http::StatusCode::CREATED, Json(item)).into_response(),
Err(e) => {{
eprintln!("Error creating {singular}: {{}}", e);
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to create {singular}").into_response()
}}
}}
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
singular = singular,
model_low = model.to_lowercase(),
model = model,
resource = resource
)
}
fn generate_update_handler(resource: &str, model: &str) -> String {
let singular = resource.trim_end_matches('s');
format!(
r#"//! Update {singular}
use axum::{{Extension, Json, extract::Path, response::IntoResponse, Router}};
use sea_orm::{{ActiveModelTrait, DatabaseConnection, EntityTrait, Set}};
use serde::{{Deserialize, Serialize}};
use std::sync::Arc;
use crate::shared::state::AppState;
use crate::entities::{model_low}::{{ActiveModel, Entity as {model}, Model}};
#[derive(Serialize, Deserialize)]
pub struct Update{model}Dto {{
pub name: Option<String>,
// Add your fields
}}
pub async fn update(
Path(id): Path<i32>,
Extension(db): Extension<DatabaseConnection>,
Json(data): Json<Update{model}Dto>,
) -> impl IntoResponse {{
let item = match {model}.find_by_id(id).one(&db).await {{
Ok(Some(item)) => item,
Ok(None) => return (axum::http::StatusCode::NOT_FOUND, "{singular} not found").into_response(),
Err(e) => {{
eprintln!("Error finding {singular}: {{}}", e);
return (axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to find {singular}").into_response();
}}
}};
let mut active_model: ActiveModel = item.into();
if let Some(name) = data.name {{
active_model.name = Set(name);
}}
match active_model.update(&db).await {{
Ok(updated) => Json(updated).into_response(),
Err(e) => {{
eprintln!("Error updating {singular}: {{}}", e);
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to update {singular}").into_response()
}}
}}
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
singular = singular,
model_low = model.to_lowercase(),
model = model,
resource = resource
)
}
fn generate_delete_handler(resource: &str, model: &str) -> String {
let singular = resource.trim_end_matches('s');
format!(
r#"//! Delete {singular}
use axum::{{Extension, extract::Path, response::IntoResponse, Router}};
use sea_orm::{{ActiveModelTrait, DatabaseConnection, EntityTrait, IntoActiveModel}};
use std::sync::Arc;
use crate::shared::state::AppState;
use crate::entities::{model_low}::{{Entity as {model}}};
pub async fn destroy(
Path(id): Path<i32>,
Extension(db): Extension<DatabaseConnection>,
) -> impl IntoResponse {{
let item = match {model}.find_by_id(id).one(&db).await {{
Ok(Some(item)) => item,
Ok(None) => return (axum::http::StatusCode::NOT_FOUND, "{singular} not found").into_response(),
Err(e) => {{
eprintln!("Error finding {singular}: {{}}", e);
return (axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to find {singular}").into_response();
}}
}};
match item.into_active_model().delete(&db).await {{
Ok(_) => axum::http::StatusCode::NO_CONTENT.into_response(),
Err(e) => {{
eprintln!("Error deleting {singular}: {{}}", e);
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Failed to delete {singular}").into_response()
}}
}}
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
singular = singular,
model_low = model.to_lowercase(),
model = model,
resource = resource
)
}
fn generate_basic_controller(api_dir: &Path, resource: &str) {
let content = format!(
r#"//! {resource} controller
use axum::Router;
use std::sync::Arc;
use crate::shared::state::AppState;
pub async fn index() -> &'static str {{
"{resource} endpoint"
}}
pub fn register_routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {{
router
}}
"#,
resource = resource
);
let _ = fs::write(api_dir.join("index.rs"), content);
}
@@ -0,0 +1,262 @@
//! Database migration generator
use anyhow::{Context, Result};
use chrono::Local;
use std::fs;
use std::path::Path;
pub fn generate_migration(name: &str, table: Option<&str>) -> Result<()> {
let timestamp = Local::now().format("%Y%m%d%H%M%S");
let file_name = format!("m{}_{}.rs", timestamp, name);
let migrations_dir = Path::new("migrations");
fs::create_dir_all(migrations_dir)?;
let content = if let Some(table_name) = table {
generate_create_table_migration(table_name)
} else {
generate_empty_migration()
};
let migration_path = migrations_dir.join(&file_name);
fs::write(&migration_path, content)
.with_context(|| format!("Failed to write migration: {:?}", migration_path))?;
update_migrations_mod(&file_name)?;
Ok(())
}
pub fn generate_model_migration(table: &str, timestamps: bool, soft_delete: bool) -> Result<()> {
let timestamp = Local::now().format("%Y%m%d%H%M%S");
let name = format!("create_{}_table", table);
let file_name = format!("m{}_{}.rs", timestamp, name);
let migrations_dir = Path::new("migrations");
fs::create_dir_all(migrations_dir)?;
let content = generate_model_table_migration(table, timestamps, soft_delete);
let migration_path = migrations_dir.join(&file_name);
fs::write(&migration_path, content)?;
update_migrations_mod(&file_name)?;
Ok(())
}
fn generate_create_table_migration(table: &str) -> String {
let struct_name = table
.split('_')
.map(|s| {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().chain(c).collect(),
}
})
.collect::<String>();
format!(
r#"use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {{
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
manager
.create_table(
Table::create()
.table({table}::Table)
.if_not_exists()
.col(
ColumnDef::new({table}::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new({table}::Name).string().not_null())
.to_owned(),
)
.await
}}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
manager
.drop_table(Table::drop().table({table}::Table).to_owned())
.await
}}
}}
#[derive(DeriveIden)]
enum {table} {{
Table,
Id,
Name,
}}
"#,
table = struct_name
)
}
fn generate_model_table_migration(table: &str, timestamps: bool, soft_delete: bool) -> String {
let table_pascal = table
.split('_')
.map(|s| {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().chain(c).collect(),
}
})
.collect::<String>();
let timestamp_cols = if timestamps {
format!(
r#"
.col(ColumnDef::new({}::CreatedAt).timestamp().null())
.col(ColumnDef::new({}::UpdatedAt).timestamp().null())"#,
table_pascal, table_pascal
)
} else {
String::new()
};
let soft_delete_col = if soft_delete {
format!(
r#"
.col(ColumnDef::new({}::DeletedAt).timestamp().null())"#,
table_pascal
)
} else {
String::new()
};
let enum_fields = if timestamps && soft_delete {
format!(" CreatedAt,\n UpdatedAt,\n DeletedAt,")
} else if timestamps {
format!(" CreatedAt,\n UpdatedAt,")
} else if soft_delete {
format!(" DeletedAt,")
} else {
String::new()
};
format!(
r#"use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {{
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
manager
.create_table(
Table::create()
.table({table}::Table)
.if_not_exists()
.col(
ColumnDef::new({table}::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new({table}::Name).string().not_null()){timestamps}{soft_delete}
.to_owned(),
)
.await
}}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
manager
.drop_table(Table::drop().table({table}::Table).to_owned())
.await
}}
}}
#[derive(DeriveIden)]
enum {table} {{
Table,
Id,
Name,
{enum_fields}
}}
"#,
table = table_pascal,
timestamps = timestamp_cols,
soft_delete = soft_delete_col,
enum_fields = enum_fields
)
}
fn generate_empty_migration() -> String {
format!(
r#"use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {{
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
// Add your migration logic here
Ok(())
}}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
// Add your rollback logic here
Ok(())
}}
}}
"#
)
}
fn update_migrations_mod(file_name: &str) -> Result<()> {
let mod_path = Path::new("migrations/mod.rs");
let module_name = file_name.trim_end_matches(".rs");
let module_line = format!("mod {};", module_name);
if mod_path.exists() {
let content = fs::read_to_string(mod_path)?;
if !content.contains(&module_line) {
// Find the vec![] and add migration
let new_content = if content.contains("vec![") {
content.replace(
"vec![",
&format!("vec![\n Box::new({}::Migration),", module_name),
)
} else {
format!("{}\n{}", content.trim(), module_line)
};
fs::write(mod_path, new_content)?;
}
} else {
let initial_content = format!(
r#"pub use sea_orm_migration::prelude::*;
{}
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {{
fn migrations() -> Vec<Box<dyn MigrationTrait>> {{
vec![
Box::new({}::Migration),
]
}}
}}
"#,
module_line, module_name
);
fs::write(mod_path, initial_content)?;
}
Ok(())
}
@@ -0,0 +1,7 @@
// Module declarations for generators
pub mod api;
pub mod controller;
pub mod migration;
pub mod model;
pub mod repository;
pub mod service;
@@ -0,0 +1,125 @@
//! SeaORM model generator
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
pub fn generate_model(
name: &str,
with_migration: bool,
timestamps: bool,
soft_delete: bool,
) -> Result<()> {
let table_name = pluralize(name);
// Create entities directory
let entities_dir = Path::new("src/entities");
fs::create_dir_all(entities_dir)?;
// Generate model file
let model_content = generate_model_content(name, &table_name, timestamps, soft_delete);
let model_path = entities_dir.join(format!("{}.rs", name.to_lowercase()));
fs::write(&model_path, model_content)
.with_context(|| format!("Failed to write model file: {:?}", model_path))?;
// Update entities/mod.rs
update_entities_mod(name)?;
// Generate migration if requested
if with_migration {
super::migration::generate_model_migration(&table_name, timestamps, soft_delete)?;
}
Ok(())
}
fn generate_model_content(
name: &str,
table_name: &str,
timestamps: bool,
soft_delete: bool,
) -> String {
let timestamp_fields = if timestamps {
r#"
#[sea_orm(nullable)]
pub created_at: Option<DateTimeUtc>,
#[sea_orm(nullable)]
pub updated_at: Option<DateTimeUtc>,"#
} else {
""
};
let soft_delete_field = if soft_delete {
r#"
#[sea_orm(nullable)]
pub deleted_at: Option<DateTimeUtc>,"#
} else {
""
};
format!(
r#"//! {} entity
use sea_orm::entity::prelude::*;
use serde::{{Deserialize, Serialize}};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "{}")]
pub struct Model {{
#[sea_orm(primary_key)]
pub id: i32,
// Add your fields here
pub name: String,{}{}
}}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {{}}
impl ActiveModelBehavior for ActiveModel {{}}
"#,
name, table_name, timestamp_fields, soft_delete_field
)
}
fn update_entities_mod(name: &str) -> Result<()> {
let mod_path = Path::new("src/entities/mod.rs");
let module_line = format!("pub mod {};", name.to_lowercase());
if mod_path.exists() {
let content = fs::read_to_string(mod_path)?;
if !content.contains(&module_line) {
let new_content = format!("{}\n{}", content.trim(), module_line);
fs::write(mod_path, new_content)?;
}
} else {
fs::write(mod_path, format!("{}\n", module_line))?;
}
Ok(())
}
pub fn pluralize(word: &str) -> String {
let lower = word.to_lowercase();
if lower.ends_with('y') {
format!("{}ies", &lower[..lower.len() - 1])
} else if lower.ends_with('s') || lower.ends_with("ch") || lower.ends_with("sh") || lower.ends_with('x') {
format!("{}es", lower)
} else {
format!("{}s", lower)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pluralize() {
assert_eq!(pluralize("User"), "users");
assert_eq!(pluralize("Category"), "categories");
assert_eq!(pluralize("Post"), "posts");
assert_eq!(pluralize("Box"), "boxes");
}
}
@@ -0,0 +1,112 @@
//! Repository pattern generator
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
pub fn generate_repository(name: &str, model: &str) -> Result<()> {
let repos_dir = Path::new("src/repositories");
fs::create_dir_all(repos_dir)?;
let repo_content = generate_repository_content(name, model);
let repo_path = repos_dir.join(format!("{}_repository.rs", name.to_lowercase()));
fs::write(&repo_path, repo_content)
.with_context(|| format!("Failed to write repository: {:?}", repo_path))?;
update_repositories_mod(name)?;
Ok(())
}
fn generate_repository_content(name: &str, model: &str) -> String {
format!(
r#"//! {} repository
use sea_orm::*;
use crate::entities::{}::{{Entity as {}, Model, ActiveModel, Column}};
#[derive(Clone)]
pub struct {}Repository {{
db: DatabaseConnection,
}}
impl {}Repository {{
pub fn new(db: DatabaseConnection) -> Self {{
Self {{ db }}
}}
/// Find all records
pub async fn find_all(&self) -> Result<Vec<Model>, DbErr> {{
{}.find().all(&self.db).await
}}
/// Find by ID
pub async fn find_by_id(&self, id: i32) -> Result<Option<Model>, DbErr> {{
{}.find_by_id(id).one(&self.db).await
}}
/// Find with pagination
pub async fn paginate(&self, page: u64, per_page: u64) -> Result<(Vec<Model>, u64), DbErr> {{
let paginator = {}.find()
.paginate(&self.db, per_page);
let total = paginator.num_items().await?;
let items = paginator.fetch_page(page).await?;
Ok((items, total))
}}
/// Create new record
pub async fn create(&self, data: ActiveModel) -> Result<Model, DbErr> {{
data.insert(&self.db).await
}}
/// Update existing record
pub async fn update(&self, data: ActiveModel) -> Result<Model, DbErr> {{
data.update(&self.db).await
}}
/// Delete by ID
pub async fn delete(&self, id: i32) -> Result<DeleteResult, DbErr> {{
{}.delete_by_id(id).exec(&self.db).await
}}
/// Find by custom condition
pub async fn find_by_name(&self, name: &str) -> Result<Vec<Model>, DbErr> {{
{}.find()
.filter(Column::Name.contains(name))
.all(&self.db)
.await
}}
}}
"#,
name,
model.to_lowercase(),
model,
model,
model,
model,
model,
model,
model,
model
)
}
fn update_repositories_mod(name: &str) -> Result<()> {
let mod_path = Path::new("src/repositories/mod.rs");
let module_line = format!("pub mod {}_repository;", name.to_lowercase());
if mod_path.exists() {
let content = fs::read_to_string(mod_path)?;
if !content.contains(&module_line) {
let new_content = format!("{}\n{}", content.trim(), module_line);
fs::write(mod_path, new_content)?;
}
} else {
fs::write(mod_path, format!("{}\n", module_line))?;
}
Ok(())
}
@@ -0,0 +1,86 @@
//! Service layer generator
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
pub fn generate_service(name: &str, model: Option<&str>) -> Result<()> {
let services_dir = Path::new("src/services");
fs::create_dir_all(services_dir)?;
let model_name = model.unwrap_or(name);
let service_content = generate_service_content(name, model_name);
let service_path = services_dir.join(format!("{}_service.rs", name.to_lowercase()));
fs::write(&service_path, service_content)
.with_context(|| format!("Failed to write service: {:?}", service_path))?;
update_services_mod(name)?;
Ok(())
}
fn generate_service_content(name: &str, model: &str) -> String {
format!(
r#"//! {} service layer
use sea_orm::*;
use crate::entities::{}::{{Entity as {}, Model, ActiveModel}};
pub struct {}Service {{
db: DatabaseConnection,
}}
impl {}Service {{
pub fn new(db: DatabaseConnection) -> Self {{
Self {{ db }}
}}
pub async fn find_all(&self) -> Result<Vec<Model>, DbErr> {{
{}.find().all(&self.db).await
}}
pub async fn find_by_id(&self, id: i32) -> Result<Option<Model>, DbErr> {{
{}.find_by_id(id).one(&self.db).await
}}
pub async fn create(&self, data: ActiveModel) -> Result<Model, DbErr> {{
data.insert(&self.db).await
}}
pub async fn update(&self, id: i32, data: ActiveModel) -> Result<Model, DbErr> {{
data.update(&self.db).await
}}
pub async fn delete(&self, id: i32) -> Result<DeleteResult, DbErr> {{
{}.delete_by_id(id).exec(&self.db).await
}}
}}
"#,
name,
model.to_lowercase(),
model,
model,
model,
model,
model,
model
)
}
fn update_services_mod(name: &str) -> Result<()> {
let mod_path = Path::new("src/services/mod.rs");
let module_line = format!("pub mod {}_service;", name.to_lowercase());
if mod_path.exists() {
let content = fs::read_to_string(mod_path)?;
if !content.contains(&module_line) {
let new_content = format!("{}\n{}", content.trim(), module_line);
fs::write(mod_path, new_content)?;
}
} else {
fs::write(mod_path, format!("{}\n", module_line))?;
}
Ok(())
}
@@ -0,0 +1 @@
<table>orphaned text<tr><td>cell content</td></tr>more text</table>
+118
View File
@@ -0,0 +1,118 @@
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use axum::Router;
use sea_orm::Database;
use tracing_subscriber::EnvFilter;
use crate::shared::config::CONFIG;
use crate::shared::database::get_redis_conn;
use crate::shared::state::AppState;
pub struct Application {
pub port: u16,
router: Router,
listener: TcpListener,
}
impl Application {
pub async fn build() -> anyhow::Result<Self> {
// Initialize tracing. Default to warn/error globally unless RUST_LOG is explicitly set.
let env_filter = match std::env::var("RUST_LOG") {
Ok(filter) => EnvFilter::new(filter).add_directive("html5ever=error".parse()?),
Err(_) => EnvFilter::new("warn,html5ever=error"),
};
tracing_subscriber::fmt().with_env_filter(env_filter).init();
// Initialize OpenTelemetry metrics
crate::shared::observability::metrics::init_otel_metrics();
tracing::info!("🚀 Scraper starting up...");
tracing::info!(" Environment: {}", CONFIG.environment);
// Log thread configuration
let worker_threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
tracing::info!(
" Tokio Worker Threads: (Defaulting to CPU cores: {})",
worker_threads
);
// Redis
let _ = get_redis_conn().await;
// Browser Pool
tracing::info!("Initializing browser pool...");
let browser_config = crate::shared::browser::BrowserPoolConfig::default();
match crate::shared::browser::pool::init_browser_pool(browser_config).await {
Ok(_) => tracing::info!("✓ Browser pool initialized"),
Err(e) => tracing::error!("⚠️ Failed to initialize browser pool: {}", e),
}
// Database
let mut opt = sea_orm::ConnectOptions::new(CONFIG.database_url.clone());
opt.max_connections(20)
.min_connections(1)
.connect_timeout(std::time::Duration::from_secs(
CONFIG.db.connect_timeout_seconds,
))
.idle_timeout(std::time::Duration::from_secs(
CONFIG.db.idle_timeout_seconds,
))
.acquire_timeout(std::time::Duration::from_secs(
CONFIG.db.acquire_timeout_seconds,
))
.max_lifetime(std::time::Duration::from_secs(
CONFIG.db.max_lifetime_seconds,
))
.sqlx_logging(CONFIG.log_level == "debug");
let db = Database::connect(opt)
.await
.map_err(|e| anyhow::anyhow!("Failed to connect to database: {}", e))?;
tracing::info!("✓ SeaORM database connection established");
// Schema & Seeding
if let Err(e) = crate::shared::database::setup::init(&db).await {
tracing::error!("Failed to init DB schema: {}", e);
}
// App State components
let db_arc = Arc::new(db);
let image_processing_semaphore = Arc::new(tokio::sync::Semaphore::new(
CONFIG.image_processing_concurrency,
));
let event_bus = Arc::new(crate::shared::events::bus::EventBus::new());
let redis_pool = crate::shared::database::redis_pool()
.map_err(|e| anyhow::anyhow!("Failed to init Redis pool: {}", e))?;
let app_state = Arc::new(AppState {
redis_pool,
db: db_arc.clone(),
image_processing_semaphore,
event_bus: event_bus.clone(),
});
let app = crate::app::build_router(app_state, db_arc.clone()).await?;
// Listener
let port = CONFIG.server_port;
let addr = SocketAddr::from(([0, 0, 0, 0], port));
let listener = TcpListener::bind(&addr).await?;
tracing::info!("Server listening on {}", listener.local_addr()?);
Ok(Self {
port,
router: app,
listener,
})
}
pub async fn run(self) -> std::io::Result<()> {
axum::serve(self.listener, self.router.into_make_service()).await
}
}
+10
View File
@@ -0,0 +1,10 @@
// Library root - clean organized module structure
// All modules organized into logical folders
// ============================================================================
// Core Framework
// ============================================================================
pub mod app;
pub mod bootstrap;
pub mod modules;
pub mod shared;
+12
View File
@@ -0,0 +1,12 @@
#![doc = "Logging Setup"]
use scraper_service::bootstrap::Application;
#[tokio::main(flavor = "multi_thread")]
async fn main() -> anyhow::Result<()> {
// Application setup and server logic is now encapsulated in `startup.rs`
// This makes the main function clean and the app easier to integration test.
let app = Application::build().await?;
app.run().await?;
Ok(())
}
+236
View File
@@ -0,0 +1,236 @@
use crate::modules::anime::repository::AnimeRepository;
use crate::modules::anime::service::AnimeService;
use crate::shared::errors::AppError;
use crate::shared::state::AppState;
use axum::extract::{Path, State};
use axum::Json;
use std::sync::Arc;
use tracing::info;
#[utoipa::path(
get,
path = "/api/anime",
tag = "anime",
operation_id = "anime_index",
responses(
(status = 200, description = "Handles GET requests for the /api/anime endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn anime_index(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<crate::modules::anime::types::AnimeData>, AppError> {
info!("Handling request for anime index");
let service = AnimeService::new(AnimeRepository::new());
service.get_anime_index(app_state).await.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/genre_list",
tag = "anime",
operation_id = "anime_genre_list",
responses(
(status = 200, description = "Handles GET requests for the /api/anime/genre_list endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genres(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<crate::modules::anime::types::GenresResponse>, AppError> {
info!("Handling request for anime genres");
let service = AnimeService::new(AnimeRepository::new());
service.get_genres(app_state).await.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/detail/{slug}",
tag = "anime",
operation_id = "anime_detail_slug",
responses(
(status = 200, description = "Retrieves details for a specific detail by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn detail_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::DetailResponse>, AppError> {
info!("Starting request for detail slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service.get_anime_detail(app_state, slug).await.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/complete_anime/{slug}",
tag = "anime",
operation_id = "anime_complete_anime_slug",
responses(
(status = 200, description = "Retrieves details for a specific complete_anime by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn complete_anime_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::ListResponse>, AppError> {
info!("Starting request for complete_anime slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service
.get_complete_anime_page(app_state, slug)
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/full/{slug}",
tag = "anime",
operation_id = "anime_full_slug",
responses(
(status = 200, description = "Retrieves full episode details for a specific episode by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn full_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::FullResponse>, AppError> {
info!("Starting request for full slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service.get_anime_full(app_state, slug).await.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/ongoing_anime/{slug}",
tag = "anime",
operation_id = "anime_ongoing_anime_slug",
responses(
(status = 200, description = "Retrieves details for a specific ongoing_anime by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn ongoing_anime_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::OngoingAnimeResponse>, AppError> {
info!("Starting request for ongoing_anime slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service
.get_ongoing_anime_page(app_state, slug)
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/latest/{slug}",
tag = "anime",
operation_id = "anime_latest_slug",
responses(
(status = 200, description = "Retrieves details for a specific latest by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn latest_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::LatestAnimeResponse>, AppError> {
info!("Starting request for latest slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service
.get_latest_anime_page(app_state, slug)
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/search/{slug}",
tag = "anime",
operation_id = "anime_search_slug_index",
responses(
(status = 200, description = "Retrieves details for a specific search by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn search_slug_index(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::SearchResponse>, AppError> {
info!("Starting request for search slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service
.get_search_anime_page(app_state, slug, "1".to_string())
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/search/{slug}/{page}",
tag = "anime",
operation_id = "anime_search_slug_page",
responses(
(status = 200, description = "Retrieves details for a specific search by slug and page.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn search_slug_page(
State(app_state): State<Arc<AppState>>,
Path((slug, page)): Path<(String, String)>,
) -> Result<Json<crate::modules::anime::types::SearchResponse>, AppError> {
info!("Starting request for search slug: {} page: {}", slug, page);
let service = AnimeService::new(AnimeRepository::new());
service
.get_search_anime_page(app_state, slug, page)
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/genre/{slug}",
tag = "anime",
operation_id = "anime_genre_slug_index",
responses(
(status = 200, description = "Retrieves details for a specific genre by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genre_slug_index(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime::types::GenreListResponse>, AppError> {
info!("Starting request for genre slug: {}", slug);
let service = AnimeService::new(AnimeRepository::new());
service
.get_genre_anime_page(app_state, slug, "1".to_string())
.await
.map(Json)
}
#[utoipa::path(
get,
path = "/api/anime/genre/{slug}/{page}",
tag = "anime",
operation_id = "anime_genre_slug_page",
responses(
(status = 200, description = "Retrieves details for a specific genre by slug and page.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genre_slug_page(
State(app_state): State<Arc<AppState>>,
Path((slug, page)): Path<(String, String)>,
) -> Result<Json<crate::modules::anime::types::GenreListResponse>, AppError> {
info!("Starting request for genre slug: {} page: {}", slug, page);
let service = AnimeService::new(AnimeRepository::new());
service
.get_genre_anime_page(app_state, slug, page)
.await
.map(Json)
}
+7
View File
@@ -0,0 +1,7 @@
pub mod controller;
pub mod parser;
pub mod repository;
pub mod route;
pub mod schema;
pub mod service;
pub mod types;
+632
View File
@@ -0,0 +1,632 @@
use crate::modules::anime::types::*;
use crate::shared::errors::AppError;
use crate::shared::utils::parse_html;
use crate::shared::utils::scraping::{
attr, attr_from, attr_from_or, extract_slug, selector, text, text_from_or,
};
pub fn parse_ongoing_anime(html: &str) -> Result<Vec<OngoingAnimeItem>, AppError> {
let document = parse_html(html);
let mut ongoing_anime = Vec::new();
let venz_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
for element in document.select(&venz_selector) {
let title = text_from_or(&element, &title_selector, "");
let href = attr_from(&element, &link_selector, "href").unwrap_or_default();
let slug = extract_slug(&href);
let poster = attr_from_or(&element, &img_selector, "src", "");
let current_episode = text_from_or(&element, &episode_selector, "N/A");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
if !title.is_empty() {
ongoing_anime.push(OngoingAnimeItem {
title,
slug,
poster,
current_episode,
anime_url,
});
}
}
Ok(ongoing_anime)
}
pub fn parse_complete_anime(html: &str) -> Result<Vec<CompleteAnimeItem>, AppError> {
let document = parse_html(html);
let mut complete_anime = Vec::new();
let venz_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
for element in document.select(&venz_selector) {
let title = text_from_or(&element, &title_selector, "");
let href = attr_from(&element, &link_selector, "href").unwrap_or_default();
let slug = extract_slug(&href);
let poster = attr_from_or(&element, &img_selector, "src", "");
let episode_count = text_from_or(&element, &episode_selector, "N/A");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
if !title.is_empty() {
complete_anime.push(CompleteAnimeItem {
title,
slug,
poster,
episode_count,
anime_url,
});
}
}
Ok(complete_anime)
}
pub fn parse_genres(html: &str) -> Result<Vec<Genre>, AppError> {
let document = parse_html(html);
let mut genres = Vec::new();
let genre_selector = selector(".genres li a, .genre-list a").unwrap();
for element in document.select(&genre_selector) {
let name = text(&element);
let url = attr(&element, "href").unwrap_or_default();
let slug = extract_slug(&url);
if !name.is_empty() && !slug.is_empty() {
genres.push(Genre { name, slug, url });
}
}
Ok(genres)
}
pub fn parse_anime_detail_document(html: &str) -> Result<AnimeDetailData, AppError> {
let document = parse_html(html);
let info_selector = selector(".infozingle p").unwrap();
let poster_selector = selector(".fotoanime img").unwrap();
let synopsis_selector = selector(".sinopc").unwrap();
let genre_link_selector = selector("a").unwrap();
let episode_list_selector = selector(".episodelist ul li a").unwrap();
let recommendation_selector = selector("#recommend-anime-series .isi-anime").unwrap();
let recommendation_title_selector = selector(".judul-anime a").unwrap();
let recommendation_img_selector = selector("img").unwrap();
let mut title = String::new();
let mut alternative_title = String::new();
let mut r#type: Option<String> = None;
let mut status: Option<String> = None;
let mut release_date = String::new();
let mut studio = String::new();
let producers = Vec::new();
for element in document.select(&info_selector) {
let text = text(&element);
if text.contains("Judul:") {
title = text.replace("Judul:", "").trim().to_string();
} else if text.contains("Japanese:") {
alternative_title = text.replace("Japanese:", "").trim().to_string();
} else if text.contains("Type:") {
let type_str = text.replace("Type:", "").trim().to_string();
if !type_str.is_empty() {
r#type = Some(type_str);
}
} else if text.contains("Status:") {
let status_str = text.replace("Status:", "").trim().to_string();
if !status_str.is_empty() {
status = Some(status_str);
}
} else if text.contains("Tanggal Rilis:") {
release_date = text.replace("Tanggal Rilis:", "").trim().to_string();
} else if text.contains("Studio:") {
studio = text.replace("Studio:", "").trim().to_string();
}
}
let poster = document
.select(&poster_selector)
.next()
.and_then(|e| e.value().attr("src"))
.unwrap_or("")
.to_string();
let synopsis = text_from_or(&document.root_element(), &synopsis_selector, "");
let mut genres = Vec::new();
if let Some(genres_element) = document
.select(&info_selector)
.find(|e| text(&e).contains("Genres:"))
{
for genre_link in genres_element.select(&genre_link_selector) {
let name = text(&genre_link);
let anime_url = attr(&genre_link, "href").unwrap_or_default();
let genre_slug = extract_slug(&anime_url);
genres.push(DetailGenre {
name,
slug: genre_slug,
anime_url,
});
}
}
let mut episode_lists = Vec::new();
for element in document.select(&episode_list_selector) {
let episode = text(&element);
let href = attr(&element, "href").unwrap_or_default();
let slug = extract_slug(&href);
episode_lists.push(EpisodeList { episode, slug });
}
let mut recommendations = Vec::new();
for element in document.select(&recommendation_selector) {
let title = text_from_or(&element, &recommendation_title_selector, "");
let poster = attr_from_or(&element, &recommendation_img_selector, "src", "");
let href = element
.select(&genre_link_selector)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("");
let slug = extract_slug(href);
recommendations.push(Recommendation {
title,
slug,
poster,
status: None,
r#type: None,
});
}
Ok(AnimeDetailData {
title,
alternative_title,
poster,
r#type,
status,
release_date,
studio,
genres,
synopsis,
episode_lists,
batch: vec![],
producers,
recommendations,
})
}
pub fn parse_anime_page(
html: &str,
slug: &str,
) -> Result<(Vec<CompleteAnimeListItem>, Pagination), AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
let item_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
let pagination_selector = selector(".pagenavix .page-numbers:not(.next)").unwrap();
let next_selector = selector(".pagenavix .next.page-numbers").unwrap();
for element in document.select(&item_selector) {
let title = text_from_or(&element, &title_selector, "");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
let slug = extract_slug(&anime_url);
let poster = attr_from_or(&element, &img_selector, "src", "");
let episode_count = text_from_or(&element, &episode_selector, "N/A");
if !title.is_empty() {
anime_list.push(CompleteAnimeListItem {
title,
slug,
poster,
episode_count,
anime_url,
});
}
}
let current_page = slug.parse::<u32>().unwrap_or(1);
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| e.text().collect::<String>().trim().parse::<u32>().ok())
.unwrap_or(1);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
let pagination = Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
};
Ok((anime_list, pagination))
}
pub fn parse_ongoing_anime_document(
html: &str,
slug: &str,
) -> Result<(Vec<OngoingAnimeListItem>, Pagination), AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
let item_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let score_selector = selector(".epz").unwrap();
let pagination_selector = selector(".pagenavix .page-numbers:not(.next)").unwrap();
let next_selector = selector(".pagenavix .next.page-numbers").unwrap();
for element in document.select(&item_selector) {
let title = text_from_or(&element, &title_selector, "");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
let slug = extract_slug(&anime_url);
let poster = attr_from_or(&element, &img_selector, "src", "");
let score = text_from_or(&element, &score_selector, "N/A");
if !title.is_empty() {
anime_list.push(OngoingAnimeListItem {
title,
slug,
poster,
score,
anime_url,
});
}
}
let current_page = slug.parse::<u32>().unwrap_or(1);
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| e.text().collect::<String>().trim().parse::<u32>().ok())
.unwrap_or(1);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
let pagination = Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
};
Ok((anime_list, pagination))
}
pub fn parse_latest_anime_document(
html: &str,
slug: &str,
) -> Result<(Vec<LatestAnimeItem>, Pagination), AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
let item_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
let pagination_selector = selector(".pagenavix .page-numbers:not(.next)").unwrap();
let next_selector = selector(".pagenavix .next.page-numbers").unwrap();
for element in document.select(&item_selector) {
let title = text_from_or(&element, &title_selector, "");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
let slug = extract_slug(&anime_url);
let poster = attr_from_or(&element, &img_selector, "src", "");
let episode = text_from_or(&element, &episode_selector, "N/A");
if !title.is_empty() {
anime_list.push(LatestAnimeItem {
title,
slug,
poster,
episode,
anime_url,
});
}
}
let current_page = slug.parse::<u32>().unwrap_or(1);
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| e.text().collect::<String>().trim().parse::<u32>().ok())
.unwrap_or(1);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
let pagination = Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
};
Ok((anime_list, pagination))
}
pub fn parse_search_anime_document(
html: &str,
slug: &str,
) -> Result<(Vec<SearchAnimeItem>, Pagination), AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
let item_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
let genre_selector = selector(".genre-tag").unwrap();
let status_selector = selector(".status").unwrap();
let rating_selector = selector(".rating").unwrap();
let pagination_selector = selector(".pagenavix .page-numbers:not(.next)").unwrap();
let next_selector = selector(".pagenavix .next.page-numbers").unwrap();
for element in document.select(&item_selector) {
let title = text_from_or(&element, &title_selector, "");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
let slug = extract_slug(&anime_url);
let poster = attr_from_or(&element, &img_selector, "src", "");
let episode = text_from_or(&element, &episode_selector, "N/A");
let mut genres = Vec::new();
for genre_elem in element.select(&genre_selector) {
genres.push(text(&genre_elem));
}
let status = text_from_or(&element, &status_selector, "");
let rating = text_from_or(&element, &rating_selector, "");
if !title.is_empty() {
anime_list.push(SearchAnimeItem {
title,
slug,
poster,
episode,
anime_url,
genres,
status,
rating,
});
}
}
let current_page = slug.parse::<u32>().unwrap_or(1);
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| e.text().collect::<String>().trim().parse::<u32>().ok())
.unwrap_or(1);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
let pagination = Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
};
Ok((anime_list, pagination))
}
pub fn parse_genre_anime_document(
html: &str,
slug: &str,
) -> Result<(Vec<GenreAnimeItem>, Pagination), AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
let item_selector = selector(".venz ul li").unwrap();
let title_selector = selector(".thumbz h2.jdlflm").unwrap();
let link_selector = selector("a").unwrap();
let img_selector = selector("img").unwrap();
let episode_selector = selector(".epz").unwrap();
let pagination_selector = selector(".pagenavix .page-numbers:not(.next)").unwrap();
let next_selector = selector(".pagenavix .next.page-numbers").unwrap();
for element in document.select(&item_selector) {
let title = text_from_or(&element, &title_selector, "");
let anime_url = attr_from_or(&element, &link_selector, "href", "");
let slug = extract_slug(&anime_url);
let poster = attr_from_or(&element, &img_selector, "src", "");
let episode = text_from_or(&element, &episode_selector, "N/A");
if !title.is_empty() {
anime_list.push(GenreAnimeItem {
title,
slug,
poster,
episode,
anime_url,
});
}
}
let current_page = slug.parse::<u32>().unwrap_or(1);
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| e.text().collect::<String>().trim().parse::<u32>().ok())
.unwrap_or(1);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
let pagination = Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
};
Ok((anime_list, pagination))
}
pub fn parse_anime_full_document(html: &str, slug: &str) -> Result<AnimeFullData, AppError> {
let document = parse_html(html);
let episode_title_selector = selector("h1.posttl").unwrap();
let image_selector = selector(".cukder img").unwrap();
let stream_selector = selector("#embed_holder iframe").unwrap();
let download_item_selector = selector(".download ul li").unwrap();
let resolution_selector = selector("strong").unwrap();
let link_selector = selector("a").unwrap();
let next_episode_selector = selector(".flir a[title*='Episode Selanjutnya']").unwrap();
let previous_episode_selector = selector(".flir a[title*='Episode Sebelumnya']").unwrap();
let episode = document
.select(&episode_title_selector)
.next()
.map(|e| text(&e))
.unwrap_or_default();
let episode_number = episode
.split("Episode")
.nth(1)
.map(|s| s.trim().to_string())
.unwrap_or_default();
let image_url = document
.select(&image_selector)
.next()
.and_then(|e| attr(&e, "src"))
.unwrap_or_default();
let stream_url = document
.select(&stream_selector)
.next()
.and_then(|e| attr(&e, "src"))
.unwrap_or_default();
let mut download_urls = std::collections::HashMap::new();
for element in document.select(&download_item_selector) {
let resolution = element
.select(&resolution_selector)
.next()
.map(|e| text(&e))
.unwrap_or_default();
let mut links = Vec::new();
for link_element in element.select(&link_selector) {
let server = text(&link_element);
let url = attr(&link_element, "href").unwrap_or_default();
links.push(DownloadLink { server, url });
}
if !resolution.is_empty() && !links.is_empty() {
download_urls.insert(resolution, links);
}
}
let next_episode_element = document.select(&next_episode_selector).next();
let previous_episode_element = document.select(&previous_episode_selector).next();
let next_episode_slug = next_episode_element
.and_then(|e| attr(&e, "href"))
.and_then(|href| {
href.split('/')
.nth(href.split('/').count().saturating_sub(2))
.map(|s| s.to_string() + "/")
});
let previous_episode_slug = previous_episode_element
.and_then(|e| attr(&e, "href"))
.and_then(|href| {
href.split('/')
.nth(href.split('/').count().saturating_sub(2))
.map(|s| s.to_string() + "/")
});
Ok(AnimeFullData {
episode,
episode_number,
anime: AnimeInfo {
slug: slug.to_string(),
},
has_next_episode: next_episode_slug.is_some(),
next_episode: next_episode_slug.map(|s| EpisodeInfo { slug: s }),
has_previous_episode: previous_episode_slug.is_some(),
previous_episode: previous_episode_slug.map(|s| EpisodeInfo { slug: s }),
stream_url,
download_urls,
image_url,
})
}
+199
View File
@@ -0,0 +1,199 @@
use crate::modules::anime::parser;
use crate::modules::anime::types::*;
use crate::shared::database::traits::scraping_repository::ScrapingRepository;
use crate::shared::errors::AppError;
use crate::shared::utils::web::proxy_fetch::fetch_with_proxy;
use crate::shared::utils::web::scraping_urls::{get_otakudesu_url, OTAKUDESU_BASE_URL};
use crate::shared::utils::{default_backoff, fetch_html_with_retry, transient};
use async_trait::async_trait;
use backoff::future::retry;
use tracing::{info, warn};
pub struct AnimeRepository;
impl Default for AnimeRepository {
fn default() -> Self {
Self::new()
}
}
impl AnimeRepository {
pub fn new() -> Self {
Self
}
}
#[async_trait]
impl ScrapingRepository for AnimeRepository {
async fn fetch_html(&self, url: &str) -> Result<String, AppError> {
fetch_html_with_retry(url).await
}
}
impl AnimeRepository {
pub fn base_url(&self) -> String {
get_otakudesu_url()
}
pub fn index_urls(&self) -> (String, String) {
let base = self.base_url();
(
format!("{}/ongoing-anime/", base),
format!("{}/complete-anime/", base),
)
}
pub fn genres_url(&self) -> String {
format!("{}/genre-list/", self.base_url())
}
pub fn detail_url(&self, slug: &str) -> String {
format!("{}/anime/{}", OTAKUDESU_BASE_URL, slug)
}
pub fn page_url(&self, category: &str, page: &str) -> String {
format!("{}/{}/page/{}/", OTAKUDESU_BASE_URL, category, page)
}
pub fn search_url(&self, query: &str, page: &str) -> String {
if page == "1" {
format!("{}/search/{}/", self.base_url(), query)
} else {
format!("{}/search/{}/page/{}/", self.base_url(), query, page)
}
}
pub fn genre_page_url(&self, genre_slug: &str, page: &str) -> String {
format!("{}/genre/{}/page/{}/", self.base_url(), genre_slug, page)
}
pub fn full_episode_url(&self, slug: &str) -> String {
format!("{}/episode/{}", OTAKUDESU_BASE_URL, slug)
}
pub async fn fetch_anime_index(&self) -> Result<AnimeData, AppError> {
let (ongoing_url, complete_url) = self.index_urls();
let (ongoing_html, complete_html) = tokio::join!(
self.fetch_html(&ongoing_url),
self.fetch_html(&complete_url)
);
let ongoing_html = ongoing_html?;
let complete_html = complete_html?;
let ongoing_anime =
tokio::task::spawn_blocking(move || parser::parse_ongoing_anime(&ongoing_html))
.await??;
let complete_anime =
tokio::task::spawn_blocking(move || parser::parse_complete_anime(&complete_html))
.await??;
Ok(AnimeData {
ongoing_anime,
complete_anime,
})
}
pub async fn fetch_genres(&self) -> Result<Vec<Genre>, AppError> {
let html = self.fetch_html(&self.genres_url()).await?;
tokio::task::spawn_blocking(move || parser::parse_genres(&html)).await?
}
pub async fn fetch_anime_detail(&self, slug: &str) -> Result<AnimeDetailData, AppError> {
let url = self.detail_url(slug);
let html = self
.fetch_with_proxy_retry(&url)
.await
.map_err(|e| AppError::ScraperError(e.to_string()))?;
tokio::task::spawn_blocking(move || parser::parse_anime_detail_document(&html)).await?
}
pub async fn fetch_complete_anime_page(
&self,
slug: &str,
) -> Result<(Vec<CompleteAnimeListItem>, Pagination), AppError> {
let url = self.page_url("complete-anime", slug);
let html = self.fetch_html(&url).await?;
let slug_owned = slug.to_string();
tokio::task::spawn_blocking(move || parser::parse_anime_page(&html, &slug_owned)).await?
}
pub async fn fetch_ongoing_anime_page(
&self,
slug: &str,
) -> Result<(Vec<OngoingAnimeListItem>, Pagination), AppError> {
let url = self.page_url("ongoing-anime", slug);
let html = self.fetch_html(&url).await?;
let slug_owned = slug.to_string();
tokio::task::spawn_blocking(move || {
parser::parse_ongoing_anime_document(&html, &slug_owned)
})
.await?
}
pub async fn fetch_latest_anime_page(
&self,
slug: &str,
) -> Result<(Vec<LatestAnimeItem>, Pagination), AppError> {
let url = self.page_url("latest-anime", slug);
let html = self.fetch_html(&url).await?;
let slug_owned = slug.to_string();
tokio::task::spawn_blocking(move || parser::parse_latest_anime_document(&html, &slug_owned))
.await?
}
pub async fn fetch_search_anime_page(
&self,
slug: &str,
page: &str,
) -> Result<(Vec<SearchAnimeItem>, Pagination), AppError> {
let url = self.search_url(slug, page);
let html = self.fetch_html(&url).await?;
let page_owned = page.to_string();
tokio::task::spawn_blocking(move || parser::parse_search_anime_document(&html, &page_owned))
.await?
}
pub async fn fetch_genre_anime_page(
&self,
genre_slug: &str,
page: &str,
) -> Result<(Vec<GenreAnimeItem>, Pagination), AppError> {
let url = self.genre_page_url(genre_slug, page);
let html = self.fetch_html(&url).await?;
let page_owned = page.to_string();
tokio::task::spawn_blocking(move || parser::parse_genre_anime_document(&html, &page_owned))
.await?
}
pub async fn fetch_anime_full(&self, slug: &str) -> Result<AnimeFullData, AppError> {
let url = self.full_episode_url(slug);
let html = self.fetch_html(&url).await?;
let slug_owned = slug.to_string();
tokio::task::spawn_blocking(move || parser::parse_anime_full_document(&html, &slug_owned))
.await?
}
async fn fetch_with_proxy_retry(&self, url: &str) -> Result<String, AppError> {
let backoff = default_backoff();
let url_owned = url.to_string();
let fetch_op = || async {
info!("Fetching URL: {}", url_owned);
match fetch_with_proxy(&url_owned).await {
Ok(response) => {
info!("Successfully fetched URL: {}", url_owned);
Ok(response.data)
}
Err(e) => {
warn!("Failed to fetch URL: {}, error: {:?}", url_owned, e);
Err(transient(e))
}
}
};
retry(backoff, fetch_op)
.await
.map_err(|e| AppError::ScraperError(e.to_string()))
}
}
+49
View File
@@ -0,0 +1,49 @@
use crate::modules::anime::controller;
use crate::shared::state::AppState;
use axum::Router;
use std::sync::Arc;
pub fn routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {
router
.route("/api/anime", axum::routing::get(controller::anime_index))
.route(
"/api/anime/genre_list",
axum::routing::get(controller::genres),
)
.route(
"/api/anime/detail/{slug}",
axum::routing::get(controller::detail_slug),
)
.route(
"/api/anime/complete_anime/{slug}",
axum::routing::get(controller::complete_anime_slug),
)
.route(
"/api/anime/full/{slug}",
axum::routing::get(controller::full_slug),
)
.route(
"/api/anime/ongoing_anime/{slug}",
axum::routing::get(controller::ongoing_anime_slug),
)
.route(
"/api/anime/latest/{slug}",
axum::routing::get(controller::latest_slug),
)
.route(
"/api/anime/search/{slug}",
axum::routing::get(controller::search_slug_index),
)
.route(
"/api/anime/search/{slug}/{page}",
axum::routing::get(controller::search_slug_page),
)
.route(
"/api/anime/genre/{slug}",
axum::routing::get(controller::genre_slug_index),
)
.route(
"/api/anime/genre/{slug}/{page}",
axum::routing::get(controller::genre_slug_page),
)
}
+18
View File
@@ -0,0 +1,18 @@
use serde::Deserialize;
use utoipa::ToSchema;
#[derive(Deserialize, ToSchema)]
pub struct SearchQuery {
pub q: Option<String>,
}
#[derive(Deserialize, ToSchema)]
pub struct SlugPath {
pub slug: String,
}
#[derive(Deserialize, ToSchema)]
pub struct SlugPagePath {
pub slug: String,
pub page: String,
}
+81
View File
@@ -0,0 +1,81 @@
use crate::shared::types::entities::anime::HasPoster;
use crate::shared::state::AppState;
use std::sync::Arc;
/// Cache poster URLs for a collection of anime items
/// This is a fire-and-forget operation that triggers lazy background caching
pub async fn cache_posters<T: HasPoster>(app_state: &Arc<AppState>, items: &[T]) {
let posters: Vec<String> = items.iter().map(|item| item.poster().to_string()).collect();
if posters.is_empty() {
return;
}
let db = app_state.db.clone();
let redis = app_state.redis_pool.clone();
crate::shared::services::images::cache::cache_image_urls_batch_lazy(
db,
&redis,
posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
}
/// Cache poster URLs and update items with cached URLs
/// Returns the updated items with CDN URLs
pub async fn cache_and_update_posters<T: HasPoster + Clone>(
app_state: &Arc<AppState>,
mut items: Vec<T>,
) -> Vec<T> {
let posters: Vec<String> = items.iter().map(|item| item.poster().to_string()).collect();
if posters.is_empty() {
return items;
}
let db = app_state.db.clone();
let redis = app_state.redis_pool.clone();
let cached_posters = crate::shared::services::images::cache::cache_image_urls_batch_lazy(
db,
&redis,
posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
// Update items with cached URLs
for (i, item) in items.iter_mut().enumerate() {
if let Some(url) = cached_posters.get(i) {
item.set_poster(url.clone());
}
}
items
}
/// Cache multiple collections of posters and update them
/// Useful when you have different types of items (e.g., ongoing and complete anime)
pub async fn cache_multiple_collections(
app_state: &Arc<AppState>,
collections: Vec<Vec<String>>,
) -> Vec<String> {
let all_posters: Vec<String> = collections.into_iter().flatten().collect();
if all_posters.is_empty() {
return Vec::new();
}
let db = app_state.db.clone();
let redis = app_state.redis_pool.clone();
crate::shared::services::images::cache::cache_image_urls_batch_lazy(
db,
&redis,
all_posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await
}
+295
View File
@@ -0,0 +1,295 @@
use std::sync::Arc;
use crate::modules::anime::repository::AnimeRepository;
use crate::modules::anime::types::*;
use crate::shared::errors::AppError;
use crate::shared::state::AppState;
use crate::shared::utils::Cache;
const INDEX_CACHE_TTL: u64 = 10;
const GENRE_LIST_CACHE_TTL: u64 = 3600;
const DEFAULT_CACHE_TTL: u64 = 300;
pub struct AnimeService {
repository: AnimeRepository,
}
impl AnimeService {
pub fn new(repository: AnimeRepository) -> Self {
Self { repository }
}
pub async fn get_anime_index(&self, app_state: Arc<AppState>) -> Result<AnimeData, AppError> {
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set("anime:index:v2", INDEX_CACHE_TTL, || async {
let mut data = self
.repository
.fetch_anime_index()
.await
.map_err(|e| e.to_string())?;
if data.ongoing_anime.is_empty() && data.complete_anime.is_empty() {
return Err("Empty anime index — refusing to cache".to_string());
}
let mut posters: Vec<String> = data
.ongoing_anime
.iter()
.map(|item| item.poster.clone())
.collect();
posters.extend(data.complete_anime.iter().map(|item| item.poster.clone()));
let cached_posters =
crate::shared::services::images::cache::cache_image_urls_batch_lazy(
app_state.db.clone(),
&app_state.redis_pool,
posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
let ongoing_len = data.ongoing_anime.len();
for (i, item) in data.ongoing_anime.iter_mut().enumerate() {
if let Some(url) = cached_posters.get(i) {
item.poster = url.clone();
}
}
for (i, item) in data.complete_anime.iter_mut().enumerate() {
if let Some(url) = cached_posters.get(ongoing_len + i) {
item.poster = url.clone();
}
}
Ok(data)
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_genres(&self, app_state: Arc<AppState>) -> Result<GenresResponse, AppError> {
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set("anime:genres:list", GENRE_LIST_CACHE_TTL, || async {
let genres = self
.repository
.fetch_genres()
.await
.map_err(|e| e.to_string())?;
Ok(GenresResponse {
status: "Ok".to_string(),
data: genres,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_anime_detail(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<DetailResponse, AppError> {
let cache_key = format!("anime:detail:{}", slug);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let mut data = self
.repository
.fetch_anime_detail(&slug)
.await
.map_err(|e| e.to_string())?;
data.poster = crate::shared::services::images::cache::get_cached_or_original(
app_state.db.clone(),
&app_state.redis_pool,
&data.poster,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
let rec_posters: Vec<String> = data
.recommendations
.iter()
.map(|r| r.poster.clone())
.collect();
let cached_rec_posters =
crate::shared::services::images::cache::cache_image_urls_batch_lazy(
app_state.db.clone(),
&app_state.redis_pool,
rec_posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
for (i, rec) in data.recommendations.iter_mut().enumerate() {
if let Some(url) = cached_rec_posters.get(i) {
rec.poster = url.clone();
}
}
Ok(DetailResponse {
status: Some("Ok".to_string()),
data,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_complete_anime_page(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<ListResponse, AppError> {
let cache_key = format!("anime:complete:{}", slug);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let (anime_list, pagination) = self
.repository
.fetch_complete_anime_page(&slug)
.await
.map_err(|e| e.to_string())?;
let total = anime_list.len() as i64;
Ok(ListResponse {
message: "Success".to_string(),
data: anime_list,
total: Some(total),
pagination: Some(pagination),
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_ongoing_anime_page(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<OngoingAnimeResponse, AppError> {
let cache_key = format!("anime:ongoing:{}", slug);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let (anime_list, pagination) = self
.repository
.fetch_ongoing_anime_page(&slug)
.await
.map_err(|e| e.to_string())?;
Ok(OngoingAnimeResponse {
status: "Ok".to_string(),
data: anime_list,
pagination,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_latest_anime_page(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<LatestAnimeResponse, AppError> {
let cache_key = format!("anime:latest:{}", slug);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let (anime_list, pagination) = self
.repository
.fetch_latest_anime_page(&slug)
.await
.map_err(|e| e.to_string())?;
Ok(LatestAnimeResponse {
status: "Ok".to_string(),
data: anime_list,
pagination,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_search_anime_page(
&self,
app_state: Arc<AppState>,
slug: String,
page: String,
) -> Result<SearchResponse, AppError> {
let cache_key = format!("anime:search:{}:{}", slug, page);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let (anime_list, pagination) = self
.repository
.fetch_search_anime_page(&slug, &page)
.await
.map_err(|e| e.to_string())?;
Ok(SearchResponse {
status: "Ok".to_string(),
data: anime_list,
pagination,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_genre_anime_page(
&self,
app_state: Arc<AppState>,
genre_slug: String,
page: String,
) -> Result<GenreListResponse, AppError> {
let cache_key = format!("anime:genre:{}:{}", genre_slug, page);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let (anime_list, pagination) = self
.repository
.fetch_genre_anime_page(&genre_slug, &page)
.await
.map_err(|e| e.to_string())?;
Ok(GenreListResponse {
status: "Ok".to_string(),
data: anime_list,
pagination,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
pub async fn get_anime_full(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<FullResponse, AppError> {
let cache_key = format!("anime:full:{}", slug);
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set(&cache_key, DEFAULT_CACHE_TTL, || async {
let data = self
.repository
.fetch_anime_full(&slug)
.await
.map_err(|e| e.to_string())?;
Ok(FullResponse {
status: "Ok".to_string(),
data,
})
})
.await
.map_err(|e| AppError::ScraperError(e))
}
}
+231
View File
@@ -0,0 +1,231 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
// Index endpoint types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct OngoingAnimeItem {
pub title: String,
pub slug: String,
pub poster: String,
pub current_episode: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct CompleteAnimeItem {
pub title: String,
pub slug: String,
pub poster: String,
pub episode_count: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct AnimeData {
pub ongoing_anime: Vec<OngoingAnimeItem>,
pub complete_anime: Vec<CompleteAnimeItem>,
}
// Genre list types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct Genre {
pub name: String,
pub slug: String,
pub url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct GenresResponse {
pub status: String,
pub data: Vec<Genre>,
}
// Detail endpoint types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct DetailGenre {
pub name: String,
pub slug: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct EpisodeList {
pub episode: String,
pub slug: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct Recommendation {
pub title: String,
pub slug: String,
pub poster: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct AnimeDetailData {
pub title: String,
pub alternative_title: String,
pub poster: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub r#type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
pub release_date: String,
pub studio: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub genres: Vec<DetailGenre>,
pub synopsis: String,
pub episode_lists: Vec<EpisodeList>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub batch: Vec<EpisodeList>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub producers: Vec<String>,
pub recommendations: Vec<Recommendation>,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct DetailResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
pub data: AnimeDetailData,
}
// Complete anime list types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct CompleteAnimeListItem {
pub title: String,
pub slug: String,
pub poster: String,
pub episode_count: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct Pagination {
pub current_page: u32,
pub last_visible_page: u32,
pub has_next_page: bool,
pub next_page: Option<u32>,
pub has_previous_page: bool,
pub previous_page: Option<u32>,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct ListResponse {
pub message: String,
pub data: Vec<CompleteAnimeListItem>,
pub total: Option<i64>,
pub pagination: Option<Pagination>,
}
// Full episode types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct AnimeInfo {
pub slug: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct EpisodeInfo {
pub slug: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct DownloadLink {
pub server: String,
pub url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct AnimeFullData {
pub episode: String,
pub episode_number: String,
pub anime: AnimeInfo,
pub has_next_episode: bool,
pub next_episode: Option<EpisodeInfo>,
pub has_previous_episode: bool,
pub previous_episode: Option<EpisodeInfo>,
pub stream_url: String,
pub download_urls: std::collections::HashMap<String, Vec<DownloadLink>>,
pub image_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct FullResponse {
pub status: String,
pub data: AnimeFullData,
}
// Ongoing anime list types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct OngoingAnimeListItem {
pub title: String,
pub slug: String,
pub poster: String,
pub score: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct OngoingAnimeResponse {
pub status: String,
pub data: Vec<OngoingAnimeListItem>,
pub pagination: Pagination,
}
// Latest anime types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct LatestAnimeItem {
pub title: String,
pub slug: String,
pub poster: String,
pub episode: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct LatestAnimeResponse {
pub status: String,
pub data: Vec<LatestAnimeItem>,
pub pagination: Pagination,
}
// Search types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct SearchAnimeItem {
pub title: String,
pub slug: String,
pub poster: String,
pub episode: String,
pub anime_url: String,
pub genres: Vec<String>,
pub status: String,
pub rating: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct SearchResponse {
pub status: String,
pub data: Vec<SearchAnimeItem>,
pub pagination: Pagination,
}
// Genre list by slug types
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct GenreAnimeItem {
pub title: String,
pub slug: String,
pub poster: String,
pub episode: String,
pub anime_url: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct GenreListResponse {
pub status: String,
pub data: Vec<GenreAnimeItem>,
pub pagination: Pagination,
}
+276
View File
@@ -0,0 +1,276 @@
use std::sync::Arc;
use axum::{
extract::{Path, Query, State},
Json,
};
use crate::modules::anime2::repository::Anime2Repository;
use crate::modules::anime2::schema::FilterQuery;
use crate::modules::anime2::service::Anime2Service;
use crate::shared::errors::AppError;
use crate::shared::state::AppState;
#[utoipa::path(
get,
path = "/api/anime2",
tag = "anime2",
operation_id = "anime2_index",
responses(
(status = 200, description = "Handles GET requests for the /api/anime2 endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn index(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<crate::modules::anime2::types::Anime2Response>, AppError> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.index(app_state).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/genre_list",
tag = "anime2",
operation_id = "anime2_genre_list",
responses(
(status = 200, description = "Handles GET requests for the /api/anime2/genre_list endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genre_list(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<crate::modules::anime2::types::GenresResponse>, AppError> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.genre_list(app_state).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/filter",
tag = "anime2",
operation_id = "anime2_filter",
responses(
(status = 200, description = "Handles GET requests for the /api/anime2/filter endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn filter(
State(app_state): State<Arc<AppState>>,
Query(params): Query<FilterQuery>,
) -> Result<Json<crate::modules::anime2::types::FilterResponse>, AppError> {
let page = params.page.unwrap_or(1);
let genre = params.genre.clone();
let status = params.status.clone();
let anime_type = params.r#type.clone();
let order = params.order.clone().unwrap_or("update".to_string());
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(
service
.filter(app_state, page, genre, status, anime_type, order)
.await?,
))
}
#[utoipa::path(
get,
path = "/api/anime2/detail/{slug}",
tag = "anime2",
operation_id = "anime2_detail_slug",
responses(
(status = 200, description = "Retrieves details for a specific detail by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn detail_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<crate::modules::anime2::types::DetailResponse>, AppError> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.detail(app_state, slug).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/genre/{slug}",
tag = "anime2",
operation_id = "anime2_genre_slug_index",
responses(
(status = 200, description = "Retrieves details for a specific genre by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genre_slug_index(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::GenreAnimeItem>,
>,
>,
AppError,
> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.genre_slug(app_state, slug, 1).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/genre/{slug}/{page}",
tag = "anime2",
operation_id = "anime2_genre_slug_page",
responses(
(status = 200, description = "Handles GET requests for the /api/anime2/genre/{slug}/{page} endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn genre_slug_page(
State(app_state): State<Arc<AppState>>,
Path((slug, page)): Path<(String, u32)>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::GenreAnimeItem>,
>,
>,
AppError,
> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.genre_slug(app_state, slug, page).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/search/{slug}",
tag = "anime2",
operation_id = "anime2_search_slug_index",
responses(
(status = 200, description = "Retrieves details for a specific search by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn search_slug_index(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::SearchAnimeItem>,
>,
>,
AppError,
> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.search(app_state, slug, 1).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/search/{slug}/{page}",
tag = "anime2",
operation_id = "anime2_search_slug_page",
responses(
(status = 200, description = "Handles GET requests for the /api/anime2/search/{slug}/{page} endpoint.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn search_slug_page(
State(app_state): State<Arc<AppState>>,
Path((slug, page)): Path<(String, u32)>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::SearchAnimeItem>,
>,
>,
AppError,
> {
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.search(app_state, slug, page).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/latest/{slug}",
tag = "anime2",
operation_id = "anime2_latest_slug",
responses(
(status = 200, description = "Retrieves details for a specific latest by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn latest_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::LatestAnimeItem>,
>,
>,
AppError,
> {
let page = slug
.parse::<u32>()
.map_err(|_| AppError::ScraperError(format!("Invalid page number: {}", slug)))?;
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.latest(app_state, page).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/ongoing_anime/{slug}",
tag = "anime2",
operation_id = "anime2_ongoing_anime_slug",
responses(
(status = 200, description = "Retrieves details for a specific ongoing_anime by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn ongoing_anime_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::OngoingAnimeItemWithScore>,
>,
>,
AppError,
> {
let page = slug
.parse::<u32>()
.map_err(|_| AppError::ScraperError(format!("Invalid page number: {}", slug)))?;
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.ongoing_anime(app_state, page).await?))
}
#[utoipa::path(
get,
path = "/api/anime2/complete_anime/{slug}",
tag = "anime2",
operation_id = "anime2_complete_anime_slug",
responses(
(status = 200, description = "Retrieves details for a specific complete_anime by slug.", body = serde_json::Value),
(status = 500, description = "Internal Server Error", body = String)
)
)]
pub async fn complete_anime_slug(
State(app_state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<
Json<
crate::shared::types::ApiResponse<
Vec<crate::shared::types::entities::anime::CompleteAnimeItem>,
>,
>,
AppError,
> {
let page = slug
.parse::<u32>()
.map_err(|_| AppError::ScraperError(format!("Invalid page number: {}", slug)))?;
let service = Anime2Service::new(Anime2Repository::new());
Ok(Json(service.complete_anime(app_state, page).await?))
}
+7
View File
@@ -0,0 +1,7 @@
pub mod controller;
pub mod parser;
pub mod repository;
pub mod route;
pub mod schema;
pub mod service;
pub mod types;
+804
View File
@@ -0,0 +1,804 @@
use crate::shared::errors::AppError;
use crate::shared::utils::parse_html;
use crate::shared::utils::scraping::{attr, extract_slug, selector, text, text_from_or};
use once_cell::sync::Lazy;
use regex::Regex;
use scraper::Selector;
static ITEM_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse("article.bs").unwrap());
static TITLE_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse(".tt h2").unwrap());
static IMG_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse("img").unwrap());
static SCORE_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse(".numscore").unwrap());
static STATUS_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse(".status").unwrap());
static TYPE_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse(".type").unwrap());
static LINK_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse("a").unwrap());
static PAGINATION_SELECTOR: Lazy<Selector> =
Lazy::new(|| Selector::parse(".pagination .page-numbers:not(.next)").unwrap());
static NEXT_SELECTOR: Lazy<Selector> = Lazy::new(|| Selector::parse(".pagination .next").unwrap());
static SLUG_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"/([^/]+)/?$").unwrap());
static GENRE_SLUG_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"genre-(.+)$").unwrap());
pub fn parse_ongoing_anime(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::OngoingAnimeItem>, AppError> {
let items = parse_ongoing_anime_with_score(html)?;
Ok(items
.into_iter()
.map(
|item| crate::shared::types::entities::anime::OngoingAnimeItem {
title: item.title,
slug: item.slug,
poster: item.poster,
current_episode: item.score,
anime_url: item.anime_url,
},
)
.collect())
}
pub fn parse_complete_anime(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::CompleteAnimeItem>, AppError> {
let document = parse_html(html);
let mut complete_anime = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
let episode_count = text_from_or(&element, &STATUS_SELECTOR, "N/A");
if !title.is_empty() {
complete_anime.push(crate::shared::types::entities::anime::CompleteAnimeItem {
title,
slug,
poster,
episode_count,
anime_url,
});
}
}
Ok(complete_anime)
}
pub fn parse_genres(html: &str) -> Result<Vec<crate::modules::anime2::types::Genre>, AppError> {
let document = parse_html(html);
let mut genres = Vec::new();
let genre_label_selector = selector("label[for^=\"genre-\"]").ok_or_else(|| {
AppError::ScraperError("Invalid selector: label[for^=\"genre-\"]".to_string())
})?;
for element in document.select(&genre_label_selector) {
let name = text(&element).trim().to_string();
let for_attr = attr(&element, "for").unwrap_or_default();
let slug = GENRE_SLUG_REGEX
.captures(&for_attr)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !name.is_empty() && !slug.is_empty() {
genres.push(crate::modules::anime2::types::Genre { name, slug });
}
}
Ok(genres)
}
pub fn parse_filter_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::FilterAnimeItem>,
crate::shared::types::entities::anime::Pagination,
),
AppError,
> {
let document = parse_html(html);
let mut anime_list = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let score = element
.select(&SCORE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("N/A".to_string());
let status = element
.select(&STATUS_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("Unknown".to_string());
let anime_type = element
.select(&TYPE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("Unknown".to_string());
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !title.is_empty() {
anime_list.push(crate::shared::types::entities::anime::FilterAnimeItem {
title,
slug,
poster,
score,
status,
r#type: anime_type,
anime_url,
});
}
}
let last_visible_page = document
.select(&PAGINATION_SELECTOR)
.next_back()
.map(|e| {
e.text()
.collect::<String>()
.trim()
.parse::<u32>()
.unwrap_or(1)
})
.unwrap_or(1);
let has_next_page = document.select(&NEXT_SELECTOR).next().is_some();
let pagination = crate::shared::types::entities::anime::Pagination {
current_page,
last_visible_page,
has_next_page,
next_page: if has_next_page {
Some(current_page + 1)
} else {
None
},
has_previous_page: current_page > 1,
previous_page: if current_page > 1 {
Some(current_page - 1)
} else {
None
},
};
Ok((anime_list, pagination))
}
pub fn parse_genre_anime(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::GenreAnimeItem>, AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let score = element
.select(&SCORE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("N/A".to_string());
let status = element
.select(&STATUS_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("Unknown".to_string());
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !title.is_empty() {
anime_list.push(crate::shared::types::entities::anime::GenreAnimeItem {
title,
slug,
poster,
score,
status,
anime_url,
});
}
}
Ok(anime_list)
}
pub fn parse_search_anime(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::SearchAnimeItem>, AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !title.is_empty() {
anime_list.push(crate::shared::types::entities::anime::SearchAnimeItem {
title,
slug,
poster,
description: String::new(),
anime_url,
genres: Vec::new(),
rating: "N/A".to_string(),
r#type: "Unknown".to_string(),
season: "Unknown".to_string(),
});
}
}
Ok(anime_list)
}
pub fn parse_latest_anime(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::LatestAnimeItem>, AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let score = element
.select(&SCORE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("N/A".to_string());
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !title.is_empty() {
anime_list.push(crate::shared::types::entities::anime::LatestAnimeItem {
title,
slug,
poster,
current_episode: "N/A".to_string(),
score,
anime_url,
});
}
}
Ok(anime_list)
}
pub fn parse_ongoing_anime_with_score(
html: &str,
) -> Result<Vec<crate::shared::types::entities::anime::OngoingAnimeItemWithScore>, AppError> {
let document = parse_html(html);
let mut anime_list = Vec::new();
for element in document.select(&ITEM_SELECTOR) {
let title = element
.select(&TITLE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or_default();
let poster = element
.select(&IMG_SELECTOR)
.next()
.and_then(|e| e.value().attr("src").or(e.value().attr("data-src")))
.unwrap_or("")
.to_string();
let score = element
.select(&SCORE_SELECTOR)
.next()
.map(|e| e.text().collect::<String>().trim().to_string())
.unwrap_or("N/A".to_string());
let anime_url = element
.select(&LINK_SELECTOR)
.next()
.and_then(|e| e.value().attr("href"))
.unwrap_or("")
.to_string();
let slug = SLUG_REGEX
.captures(&anime_url)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str())
.unwrap_or("")
.to_string();
if !title.is_empty() {
anime_list.push(
crate::shared::types::entities::anime::OngoingAnimeItemWithScore {
title,
slug,
poster,
score,
anime_url,
},
);
}
}
Ok(anime_list)
}
pub fn parse_pagination(
document: &scraper::Html,
current_page: u32,
) -> Result<crate::shared::types::entities::anime::Pagination, String> {
let last_visible_page = document
.select(&PAGINATION_SELECTOR)
.next_back()
.map(|e| {
e.text()
.collect::<String>()
.trim()
.parse::<u32>()
.unwrap_or(1)
})
.unwrap_or(1);
let has_next_page = document.select(&NEXT_SELECTOR).next().is_some();
let pagination = crate::shared::types::entities::anime::Pagination {
current_page,
last_visible_page,
has_next_page,
next_page: if has_next_page {
Some(current_page + 1)
} else {
None
},
has_previous_page: current_page > 1,
previous_page: if current_page > 1 {
Some(current_page - 1)
} else {
None
},
};
Ok(pagination)
}
pub fn parse_pagination_with_string(
document: &scraper::Html,
current_page: u32,
) -> Result<crate::shared::types::entities::anime::PaginationWithStringPages, String> {
let last_visible_page = document
.select(&PAGINATION_SELECTOR)
.next_back()
.map(|e| {
e.text()
.collect::<String>()
.trim()
.parse::<u32>()
.unwrap_or(1)
})
.unwrap_or(1);
let has_next_page = document.select(&NEXT_SELECTOR).next().is_some();
let pagination = crate::shared::types::entities::anime::PaginationWithStringPages {
current_page,
last_visible_page,
has_next_page,
next_page: if has_next_page {
Some((current_page + 1).to_string())
} else {
None
},
has_previous_page: current_page > 1,
previous_page: if current_page > 1 {
Some((current_page - 1).to_string())
} else {
None
},
};
Ok(pagination)
}
pub fn parse_anime_detail(
html: &str,
) -> Result<crate::modules::anime2::types::AnimeDetailData, AppError> {
let document = parse_html(html);
let title_selector = selector(".entry-title")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .entry-title".to_string()))?;
let alt_title_selector = selector(".alter")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .alter".to_string()))?;
let poster_selector = selector(".thumb img, .thumbook img, .wp-post-image, .ts-post-image")
.ok_or_else(|| {
AppError::ScraperError(
"Invalid selector: .thumb img, .thumbook img, .wp-post-image, .ts-post-image"
.to_string(),
)
})?;
let poster2_selector = selector(".bigcover img, .bixbox.animefull .bigcover .ime img")
.ok_or_else(|| {
AppError::ScraperError(
"Invalid selector: .bigcover img, .bixbox.animefull .bigcover .ime img".to_string(),
)
})?;
let spe_span_selector = selector(".info-content .spe span").ok_or_else(|| {
AppError::ScraperError("Invalid selector: .info-content .spe span".to_string())
})?;
let a_selector =
selector("a").ok_or_else(|| AppError::ScraperError("Invalid selector: a".to_string()))?;
let synopsis_selector = selector(".entry-content p")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .entry-content p".to_string()))?;
let genre_selector = selector(".genxed a")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .genxed a".to_string()))?;
let download_container_selector = selector(".soraddl.dlone")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .soraddl.dlone".to_string()))?;
let resolution_selector = selector(".res")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .res".to_string()))?;
let link_selector = selector(".slink a")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .slink a".to_string()))?;
let h3_selector =
selector("h3").ok_or_else(|| AppError::ScraperError("Invalid selector: h3".to_string()))?;
let recommendation_selector = selector(".listupd .bs")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .listupd .bs".to_string()))?;
let rec_title_selector = selector(".ntitle")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .ntitle".to_string()))?;
let rec_img_selector = selector("img")
.ok_or_else(|| AppError::ScraperError("Invalid selector: img".to_string()))?;
let status_selector = selector(".status")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .status".to_string()))?;
let type_selector = selector(".typez")
.ok_or_else(|| AppError::ScraperError("Invalid selector: .typez".to_string()))?;
let title = text_from_or(&document.root_element(), &title_selector, "");
let alternative_title = text_from_or(&document.root_element(), &alt_title_selector, "");
let poster = document
.select(&poster_selector)
.next()
.and_then(|e| {
attr(&e, "src")
.or_else(|| attr(&e, "data-src"))
.or_else(|| attr(&e, "data-lazy-src"))
})
.unwrap_or_default();
let poster2 = document
.select(&poster2_selector)
.next()
.and_then(|e| {
attr(&e, "src")
.or_else(|| attr(&e, "data-src"))
.or_else(|| attr(&e, "data-lazy-src"))
})
.unwrap_or_default();
let r#type = document
.select(&spe_span_selector)
.find(|e| text(&e).contains("Tipe:"))
.and_then(|span| span.select(&a_selector).next())
.map(|e| text(&e))
.unwrap_or_default();
let release_date = document
.select(&spe_span_selector)
.find(|e| text(&e).contains("Dirilis:"))
.map(|e| text(&e))
.unwrap_or_default();
let status = document
.select(&spe_span_selector)
.find(|e| text(&e).contains("Status:"))
.map(|e| text(&e))
.unwrap_or_default();
let synopsis = text_from_or(&document.root_element(), &synopsis_selector, "");
let studio = document
.select(&spe_span_selector)
.find(|e| text(&e).contains("Studio:"))
.and_then(|span| span.select(&a_selector).next())
.map(|e| text(&e))
.unwrap_or_default();
let mut genres = Vec::new();
for element in document.select(&genre_selector) {
let name = text(&element);
let anime_url = attr(&element, "href").unwrap_or_default();
let genre_slug = extract_slug(&anime_url);
genres.push(crate::modules::anime2::types::DetailGenre {
name,
slug: genre_slug,
anime_url,
});
}
let mut batch = Vec::new();
let mut ova = Vec::new();
let mut downloads = Vec::new();
for element in document.select(&download_container_selector) {
let title = element
.select(&h3_selector)
.next()
.map(|e| text(&e))
.unwrap_or_else(|| "Unknown".to_string());
let category = title.to_lowercase();
let is_batch = category.contains("batch");
let is_ova = category.contains("ova");
let mut all_links = Vec::new();
let row_selector = selector("table tr")
.ok_or_else(|| AppError::ScraperError("Invalid selector: table tr".to_string()))?;
for row in element.select(&row_selector) {
let resolution = text_from_or(&row, &resolution_selector, "");
for link_element in row.select(&link_selector) {
let provider = text(&link_element);
let url = attr(&link_element, "href").unwrap_or_default();
let name = if !resolution.is_empty() {
format!("{} - {}", resolution, provider)
} else {
provider
};
all_links.push(crate::modules::anime2::types::Link { name, url });
}
}
let download_item = crate::modules::anime2::types::DownloadItem {
resolution: title,
links: all_links,
};
if is_batch {
batch.push(download_item);
} else if is_ova {
ova.push(download_item);
} else {
downloads.push(download_item);
}
}
let mut recommendations = Vec::new();
for element in document.select(&recommendation_selector) {
let title = text_from_or(&element, &rec_title_selector, "");
let anime_url = element
.select(&a_selector)
.next()
.and_then(|e| attr(&e, "href"))
.unwrap_or_default();
let rec_slug = extract_slug(&anime_url);
let poster = element
.select(&rec_img_selector)
.next()
.and_then(|e| attr(&e, "data-src").or_else(|| attr(&e, "src")))
.unwrap_or_default();
let status = text_from_or(&element, &status_selector, "");
let r#type = text_from_or(&element, &type_selector, "");
recommendations.push(crate::modules::anime2::types::Recommendation {
title,
slug: rec_slug,
poster,
status,
r#type,
});
}
Ok(crate::modules::anime2::types::AnimeDetailData {
title,
alternative_title,
poster,
poster2,
r#type,
release_date,
status,
synopsis,
studio,
genres,
producers: vec![],
recommendations,
batch,
ova,
downloads,
})
}
pub fn parse_genre_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::GenreAnimeItem>,
crate::shared::types::entities::anime::Pagination,
),
AppError,
> {
let document = parse_html(html);
let anime_list = parse_genre_anime(html)?;
let pagination = parse_pagination(&document, current_page)?;
Ok((anime_list, pagination))
}
pub fn parse_search_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::SearchAnimeItem>,
crate::shared::types::entities::anime::PaginationWithStringPages,
),
AppError,
> {
let document = parse_html(html);
let data = parse_search_anime(html)?;
let pagination = parse_pagination_with_string(&document, current_page)?;
Ok((data, pagination))
}
pub fn parse_latest_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::LatestAnimeItem>,
crate::shared::types::entities::anime::Pagination,
),
AppError,
> {
let document = parse_html(html);
let anime_list = parse_latest_anime(html)?;
let pagination = parse_pagination(&document, current_page)?;
Ok((anime_list, pagination))
}
pub fn parse_ongoing_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::OngoingAnimeItemWithScore>,
crate::shared::types::entities::anime::Pagination,
),
AppError,
> {
let document = parse_html(html);
let anime_list = parse_ongoing_anime_with_score(html)?;
let pagination = parse_pagination(&document, current_page)?;
Ok((anime_list, pagination))
}
pub fn parse_complete_page(
html: &str,
current_page: u32,
) -> Result<
(
Vec<crate::shared::types::entities::anime::CompleteAnimeItem>,
crate::shared::types::entities::anime::Pagination,
),
AppError,
> {
let document = parse_html(html);
let anime_list = parse_complete_anime(html)?;
let pagination = parse_pagination(&document, current_page)?;
Ok((anime_list, pagination))
}
+102
View File
@@ -0,0 +1,102 @@
use crate::shared::database::traits::scraping_repository::ScrapingRepository;
use crate::shared::errors::AppError;
use crate::shared::utils::web::proxy_fetch::fetch_with_proxy_only;
use async_trait::async_trait;
use tracing::warn;
const BASE_URL: &str = "https://alqanime.si";
const BASE_DETAIL_URL: &str = "https://alqanime.net";
pub struct Anime2Repository;
impl Default for Anime2Repository {
fn default() -> Self {
Self::new()
}
}
impl Anime2Repository {
pub fn new() -> Self {
Self
}
pub fn index_ongoing_url(&self) -> String {
format!("{}/anime/?status=ongoing&type=&order=update", BASE_URL)
}
pub fn index_complete_url(&self) -> String {
format!("{}/anime/?status=completed&type=&order=update", BASE_URL)
}
pub fn genre_list_url(&self) -> String {
format!("{}/anime/", BASE_URL)
}
pub fn filter_url(&self, page: u32, order: &str) -> String {
if page > 1 {
format!("{}/anime/page/{}/?order={}", BASE_URL, page, order)
} else {
format!("{}/anime/?order={}", BASE_URL, order)
}
}
pub fn detail_url(&self, slug: &str) -> String {
format!("{}/{}/", BASE_DETAIL_URL, slug)
}
pub fn detail_image_url(&self, slug: &str) -> String {
format!("{}/anime/{}/", BASE_URL, slug)
}
pub fn genre_page_url(&self, genre_slug: &str, page: u32) -> String {
if page > 1 {
format!(
"{}/anime/page/{}/?genre[]={}&order=update",
BASE_URL, page, genre_slug
)
} else {
format!("{}/anime/?genre[]={}&order=update", BASE_URL, genre_slug)
}
}
pub fn search_url(&self, query: &str, page: u32) -> String {
let encoded = urlencoding::encode(query);
if page == 1 {
format!("{}/?s={}", BASE_URL, encoded)
} else {
format!("{}/page/{}/?s={}", BASE_URL, page, encoded)
}
}
pub fn latest_url(&self, page: u32) -> String {
format!(
"{}/anime/page/{}/?status=&type=&order=latest",
BASE_URL, page
)
}
pub fn ongoing_url(&self, page: u32) -> String {
format!(
"{}/anime/page/{}/?status=ongoing&type=&order=update",
BASE_URL, page
)
}
pub fn complete_url(&self, page: u32) -> String {
format!(
"{}/anime/page/{}/?status=completed&order=update",
BASE_URL, page
)
}
}
#[async_trait]
impl ScrapingRepository for Anime2Repository {
async fn fetch_html(&self, url: &str) -> Result<String, AppError> {
let response = fetch_with_proxy_only(url).await?;
if response.data.trim().is_empty() {
warn!("Anime2 browserless fetch returned empty body for {}", url);
}
Ok(response.data)
}
}
+39
View File
@@ -0,0 +1,39 @@
use std::sync::Arc;
use axum::{routing::get, Router};
use crate::modules::anime2::controller;
use crate::shared::state::AppState;
pub fn routes(router: Router<Arc<AppState>>) -> Router<Arc<AppState>> {
router
.route("/api/anime2", get(controller::index))
.route(
"/api/anime2/complete_anime/{slug}",
get(controller::complete_anime_slug),
)
.route("/api/anime2/detail/{slug}", get(controller::detail_slug))
.route("/api/anime2/filter", get(controller::filter))
.route("/api/anime2/genre_list", get(controller::genre_list))
.route(
"/api/anime2/genre/{slug}",
get(controller::genre_slug_index),
)
.route(
"/api/anime2/genre/{slug}/{page}",
get(controller::genre_slug_page),
)
.route("/api/anime2/latest/{slug}", get(controller::latest_slug))
.route(
"/api/anime2/ongoing_anime/{slug}",
get(controller::ongoing_anime_slug),
)
.route(
"/api/anime2/search/{slug}",
get(controller::search_slug_index),
)
.route(
"/api/anime2/search/{slug}/{page}",
get(controller::search_slug_page),
)
}
+34
View File
@@ -0,0 +1,34 @@
use serde::Deserialize;
use utoipa::ToSchema;
#[derive(Debug, Clone, Deserialize, ToSchema)]
pub struct SlugPath {
pub slug: String,
}
#[derive(Debug, Clone, Deserialize, ToSchema)]
pub struct SlugPagePath {
pub slug: String,
pub page: u32,
}
#[derive(Deserialize, ToSchema)]
pub struct FilterQuery {
pub page: Option<u32>,
pub genre: Option<String>,
pub status: Option<String>,
pub r#type: Option<String>,
pub order: Option<String>,
}
#[derive(Deserialize, ToSchema)]
pub struct GenreQuery {
pub page: Option<u32>,
pub status: Option<String>,
pub order: Option<String>,
}
#[derive(Deserialize, ToSchema)]
pub struct SearchQuery {
pub q: Option<String>,
}
+359
View File
@@ -0,0 +1,359 @@
use crate::shared::types::entities::anime::*;
use crate::shared::utils::parse_html;
use crate::shared::utils::scraping::{
attr, attr_from, attr_from_or, extract_slug, selector, text, text_from_or,
};
use scraper::{Html, Selector};
// ============================================================================
// SELECTORS
// ============================================================================
/// Common selectors used across anime parsing
pub struct AnimeSelectors {
pub item: Selector,
pub title: Selector,
pub link: Selector,
pub img: Selector,
pub episode: Selector,
pub score: Selector,
pub status: Selector,
pub genre: Selector,
pub rating: Selector,
pub type_sel: Selector,
pub season: Selector,
pub desc: Selector,
}
impl AnimeSelectors {
pub fn new() -> Result<Self, String> {
Ok(Self {
item: selector("article.bs").ok_or("Invalid selector: article.bs")?,
title: selector(".tt h2").ok_or("Invalid selector: .tt h2")?,
link: selector("a").ok_or("Invalid selector: a")?,
img: selector("img").ok_or("Invalid selector: img")?,
episode: selector(".epx").ok_or("Invalid selector: .epx")?,
score: selector(".numscore").ok_or("Invalid selector: .numscore")?,
status: selector(".status").ok_or("Invalid selector: .status")?,
genre: selector(".genres a").ok_or("Invalid selector: .genres a")?,
rating: selector(".score").ok_or("Invalid selector: .score")?,
type_sel: selector(".typez").ok_or("Invalid selector: .typez")?,
season: selector(".season").ok_or("Invalid selector: .season")?,
desc: selector(".data .typez").ok_or("Invalid selector: .data .typez")?,
})
}
}
impl Default for AnimeSelectors {
fn default() -> Self {
Self::new().expect("Valid CSS selectors")
}
}
// Global lazy static instance for selectors to avoid reallocation per parse
use once_cell::sync::Lazy;
static ANIME_SELECTORS: Lazy<Result<AnimeSelectors, String>> =
Lazy::new(|| AnimeSelectors::new().map_err(|e| format!("Failed to create selectors: {}", e)));
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/// Extract poster URL from an element, checking both src and data-src attributes
pub fn extract_poster(element: &scraper::ElementRef, img_selector: &Selector) -> String {
element
.select(img_selector)
.next()
.and_then(|e| attr(&e, "src").or(attr(&e, "data-src")))
.unwrap_or_default()
}
// ============================================================================
// ANIME PARSERS
// ============================================================================
/// Parse ongoing anime items from HTML
pub fn parse_ongoing_anime(
html: &str,
) -> Result<Vec<OngoingAnimeItem>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let href = attr_from_or(&element, &selectors.link, "href", "");
let slug = extract_slug(&href);
let poster = extract_poster(&element, &selectors.img);
let current_episode = text_from_or(&element, &selectors.episode, "N/A");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
items.push(OngoingAnimeItem {
title,
slug,
poster,
current_episode,
anime_url,
});
}
Ok(items)
}
/// Parse ongoing anime items with score from HTML
pub fn parse_ongoing_anime_with_score(
html: &str,
) -> Result<Vec<OngoingAnimeItemWithScore>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let poster = extract_poster(&element, &selectors.img);
let score = text_from_or(&element, &selectors.score, "N/A");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
let slug = extract_slug(&anime_url);
items.push(OngoingAnimeItemWithScore {
title,
slug,
poster,
score,
anime_url,
});
}
Ok(items)
}
/// Parse complete anime items from HTML
pub fn parse_complete_anime(
html: &str,
) -> Result<Vec<CompleteAnimeItem>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let href = attr_from_or(&element, &selectors.link, "href", "");
let slug = extract_slug(&href);
let poster = extract_poster(&element, &selectors.img);
let episode_count = text_from_or(&element, &selectors.episode, "N/A");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
items.push(CompleteAnimeItem {
title,
slug,
poster,
episode_count,
anime_url,
});
}
Ok(items)
}
/// Parse latest anime items from HTML
pub fn parse_latest_anime(
html: &str,
) -> Result<Vec<LatestAnimeItem>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let poster = extract_poster(&element, &selectors.img);
let current_episode = text_from_or(&element, &selectors.episode, "N/A");
let score = text_from_or(&element, &selectors.score, "N/A");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
let slug = extract_slug(&anime_url);
items.push(LatestAnimeItem {
title,
slug,
poster,
current_episode,
score,
anime_url,
});
}
Ok(items)
}
/// Parse search results from HTML
pub fn parse_search_anime(
html: &str,
) -> Result<Vec<SearchAnimeItem>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let href = attr_from(&element, &selectors.link, "href").unwrap_or_default();
let slug = extract_slug(&href);
let poster = extract_poster(&element, &selectors.img);
let description = text_from_or(&element, &selectors.desc, "");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
let genres = element.select(&selectors.genre).map(|e| text(&e)).collect();
let rating = text_from_or(&element, &selectors.rating, "");
let r#type = text_from_or(&element, &selectors.type_sel, "");
let season = text_from_or(&element, &selectors.season, "");
items.push(SearchAnimeItem {
title,
slug,
poster,
description,
anime_url,
genres,
rating,
r#type,
season,
});
}
Ok(items)
}
/// Parse genre-filtered anime items from HTML
pub fn parse_genre_anime(
html: &str,
) -> Result<Vec<GenreAnimeItem>, Box<dyn std::error::Error + Send + Sync>> {
let document = parse_html(html);
let selectors = ANIME_SELECTORS.as_ref().map_err(|e| e.clone())?;
let mut items = Vec::new();
for element in document.select(&selectors.item) {
let title = text_from_or(&element, &selectors.title, "");
if title.is_empty() {
continue;
}
let poster = extract_poster(&element, &selectors.img);
let score = text_from_or(&element, &selectors.score, "N/A");
let status = text_from_or(&element, &selectors.status, "Unknown");
let anime_url = attr_from_or(&element, &selectors.link, "href", "");
let slug = extract_slug(&anime_url);
items.push(GenreAnimeItem {
title,
slug,
poster,
score,
status,
anime_url,
});
}
Ok(items)
}
// ============================================================================
// PAGINATION PARSERS
// ============================================================================
/// Parse pagination from HTML document
pub fn parse_pagination(document: &Html, current_page: u32) -> Result<Pagination, String> {
let pagination_selector =
selector(".pagination .page-numbers:not(.next)").ok_or("Invalid selector")?;
let next_selector = selector(".pagination .next").ok_or("Invalid selector")?;
let last_visible_page = document
.select(&pagination_selector)
.next_back()
.and_then(|e| text(&e).trim().parse::<u32>().ok())
.unwrap_or(current_page);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
Some(current_page + 1)
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some(current_page - 1)
} else {
None
};
Ok(Pagination {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
})
}
/// Parse pagination with string-based page numbers (for search results)
pub fn parse_pagination_with_string(
document: &Html,
current_page: u32,
) -> Result<PaginationWithStringPages, String> {
let pagination_selector =
selector(".pagination .page-numbers:not(.next)").ok_or("Invalid selector")?;
let next_selector = selector(".pagination .next").ok_or("Invalid selector")?;
let last_visible_page = document
.select(&pagination_selector)
.last()
.and_then(|e| text(&e).trim().parse::<u32>().ok())
.unwrap_or(current_page);
let has_next_page = document.select(&next_selector).next().is_some();
let next_page = if has_next_page {
document
.select(&next_selector)
.next()
.and_then(|e| attr(&e, "href"))
.and_then(|href| href.split("/page/").nth(1).map(|s| s.to_string()))
.and_then(|s| s.split('/').next().map(|s| s.to_string()))
} else {
None
};
let has_previous_page = current_page > 1;
let previous_page = if has_previous_page {
Some((current_page - 1).to_string())
} else {
None
};
Ok(PaginationWithStringPages {
current_page,
last_visible_page,
has_next_page,
next_page,
has_previous_page,
previous_page,
})
}
+453
View File
@@ -0,0 +1,453 @@
use std::sync::Arc;
use crate::modules::anime2::parser;
use crate::modules::anime2::repository::Anime2Repository;
use crate::modules::anime2::types::{DetailResponse, GenresResponse};
use crate::shared::database::traits::scraping_repository::ScrapingRepository;
use crate::shared::errors::AppError;
use crate::shared::services::images::cache::{
apply_cached_posters, cache_image_urls_batch_lazy, get_cached_or_original,
};
use crate::shared::state::AppState;
use crate::shared::types::ApiResponse;
use crate::shared::utils::Cache;
const INDEX_CACHE_TTL: u64 = 300;
const GENRE_LIST_CACHE_TTL: u64 = 3600;
const FILTER_CACHE_TTL: u64 = 300;
const DETAIL_CACHE_TTL: u64 = 300;
const GENRE_CACHE_TTL: u64 = 300;
const SEARCH_CACHE_TTL: u64 = 300;
const LATEST_CACHE_TTL: u64 = 120;
const ONGOING_CACHE_TTL: u64 = 300;
const COMPLETE_CACHE_TTL: u64 = 300;
pub struct Anime2Service {
repository: Anime2Repository,
}
impl Anime2Service {
pub fn new(repository: Anime2Repository) -> Self {
Self { repository }
}
pub async fn index(
&self,
app_state: Arc<AppState>,
) -> Result<crate::modules::anime2::types::Anime2Response, AppError> {
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set("anime2:index", INDEX_CACHE_TTL, || async {
let ongoing_html = self
.repository
.fetch_html(&self.repository.index_ongoing_url())
.await
.map_err(|e| e.to_string())?;
let complete_html = self
.repository
.fetch_html(&self.repository.index_complete_url())
.await
.map_err(|e| e.to_string())?;
let mut data = tokio::task::spawn_blocking(move || {
Ok::<_, String>((
parser::parse_ongoing_anime(&ongoing_html).map_err(|e| e.to_string())?,
parser::parse_complete_anime(&complete_html).map_err(|e| e.to_string())?,
))
})
.await
.map_err(|e| e.to_string())??;
let mut posters: Vec<String> =
data.0.iter().map(|item| item.poster.clone()).collect();
posters.extend(data.1.iter().map(|item| item.poster.clone()));
let cached_posters = cache_image_urls_batch_lazy(
app_state.db.clone(),
&app_state.redis_pool,
posters,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
let ongoing_len = data.0.len();
for (i, item) in data.0.iter_mut().enumerate() {
if let Some(url) = cached_posters.get(i) {
item.poster = url.clone();
}
}
for (i, item) in data.1.iter_mut().enumerate() {
if let Some(url) = cached_posters.get(ongoing_len + i) {
item.poster = url.clone();
}
}
Ok(crate::modules::anime2::types::Anime2Response {
status: "Ok".to_string(),
data: crate::modules::anime2::types::Anime2Data {
ongoing_anime: data.0,
complete_anime: data.1,
},
})
})
.await
.map_err(AppError::ScraperError)
}
pub async fn genre_list(&self, app_state: Arc<AppState>) -> Result<GenresResponse, AppError> {
let cache = Cache::new(&app_state.redis_pool);
cache
.get_or_set("anime2:genres:list:v3", GENRE_LIST_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.genre_list_url())
.await
.map_err(|e| e.to_string())?;
let genres = tokio::task::spawn_blocking(move || {
parser::parse_genres(&html).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
Ok(GenresResponse {
status: "Ok".to_string(),
data: genres,
})
})
.await
.map_err(AppError::ScraperError)
}
pub async fn filter(
&self,
app_state: Arc<AppState>,
page: u32,
genre: Option<String>,
status: Option<String>,
anime_type: Option<String>,
order: String,
) -> Result<crate::modules::anime2::types::FilterResponse, AppError> {
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!(
"anime2:filter:{}:{:?}:{:?}:{:?}:{}",
page, genre, status, anime_type, order
);
let genre_clone = genre.clone();
let status_clone = status.clone();
let anime_type_clone = anime_type.clone();
cache
.get_or_set(&cache_key, FILTER_CACHE_TTL, || async {
let mut url = self.repository.filter_url(page, &order);
if let Some(g) = &genre {
for genre_item in g.split(',') {
url.push_str(&format!("&genre[]={}", genre_item.trim()));
}
}
if let Some(s) = &status {
url.push_str(&format!("&status={}", s));
}
if let Some(t) = &anime_type {
url.push_str(&format!("&type={}", t));
}
let html = self
.repository
.fetch_html(&url)
.await
.map_err(|e| e.to_string())?;
let (data, pagination) = tokio::task::spawn_blocking(move || {
parser::parse_filter_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(crate::modules::anime2::types::FilterResponse {
success: true,
data: final_data,
pagination,
filters_applied: crate::modules::anime2::types::FiltersApplied {
genre: genre_clone,
status: status_clone,
r#type: anime_type_clone,
order: order.clone(),
},
status: "Ok".to_string(),
})
})
.await
.map_err(AppError::ScraperError)
}
pub async fn detail(
&self,
app_state: Arc<AppState>,
slug: String,
) -> Result<DetailResponse, AppError> {
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:detail:{}", slug);
cache
.get_or_set(&cache_key, DETAIL_CACHE_TTL, || async {
let detail_url = self.repository.detail_url(&slug);
let image_url = self.repository.detail_image_url(&slug);
let (detail_html, image_html) = tokio::join!(
self.repository.fetch_html(&detail_url),
self.repository.fetch_html(&image_url)
);
let detail_html = detail_html.map_err(|e| e.to_string())?;
let image_html = image_html.ok();
let mut data = tokio::task::spawn_blocking(move || {
let mut data =
parser::parse_anime_detail(&detail_html).map_err(|e| e.to_string())?;
if let Some(image_html) = image_html {
if let Ok(image_data) = parser::parse_anime_detail(&image_html) {
if !image_data.poster.is_empty() {
data.poster = image_data.poster;
}
if !image_data.poster2.is_empty() {
data.poster2 = image_data.poster2;
}
data.recommendations = image_data.recommendations;
}
}
Ok::<_, String>(data)
})
.await
.map_err(|e| e.to_string())??;
data.poster = get_cached_or_original(
app_state.db.clone(),
&app_state.redis_pool,
&data.poster,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
data.poster2 = get_cached_or_original(
app_state.db.clone(),
&app_state.redis_pool,
&data.poster2,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
apply_cached_posters(
&mut data.recommendations,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(DetailResponse {
status: "Ok".to_string(),
data,
})
})
.await
.map_err(AppError::ScraperError)
}
pub async fn genre_slug(
&self,
app_state: Arc<AppState>,
genre_slug: String,
page: u32,
) -> Result<ApiResponse<Vec<crate::shared::types::entities::anime::GenreAnimeItem>>, AppError>
{
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:genre:{}:{}", genre_slug, page);
cache
.get_or_set(&cache_key, GENRE_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.genre_page_url(&genre_slug, page))
.await
.map_err(|e| e.to_string())?;
let (data, _pagination) = tokio::task::spawn_blocking(move || {
parser::parse_genre_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(ApiResponse::success(final_data))
})
.await
.map_err(AppError::ScraperError)
}
pub async fn search(
&self,
app_state: Arc<AppState>,
query: String,
page: u32,
) -> Result<ApiResponse<Vec<crate::shared::types::entities::anime::SearchAnimeItem>>, AppError>
{
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:search:{}:{}", query, page);
cache
.get_or_set(&cache_key, SEARCH_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.search_url(&query, page))
.await
.map_err(|e| e.to_string())?;
let (data, _pagination) = tokio::task::spawn_blocking(move || {
parser::parse_search_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(ApiResponse::success(final_data))
})
.await
.map_err(AppError::ScraperError)
}
pub async fn latest(
&self,
app_state: Arc<AppState>,
page: u32,
) -> Result<ApiResponse<Vec<crate::shared::types::entities::anime::LatestAnimeItem>>, AppError>
{
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:latest:{}", page);
cache
.get_or_set(&cache_key, LATEST_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.latest_url(page))
.await
.map_err(|e| e.to_string())?;
let (data, _pagination) = tokio::task::spawn_blocking(move || {
parser::parse_latest_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(ApiResponse::success(final_data))
})
.await
.map_err(AppError::ScraperError)
}
pub async fn ongoing_anime(
&self,
app_state: Arc<AppState>,
page: u32,
) -> Result<
ApiResponse<Vec<crate::shared::types::entities::anime::OngoingAnimeItemWithScore>>,
AppError,
> {
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:ongoing:{}", page);
cache
.get_or_set(&cache_key, ONGOING_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.ongoing_url(page))
.await
.map_err(|e| e.to_string())?;
let (data, _pagination) = tokio::task::spawn_blocking(move || {
parser::parse_ongoing_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(ApiResponse::success(final_data))
})
.await
.map_err(AppError::ScraperError)
}
pub async fn complete_anime(
&self,
app_state: Arc<AppState>,
page: u32,
) -> Result<ApiResponse<Vec<crate::shared::types::entities::anime::CompleteAnimeItem>>, AppError>
{
let cache = Cache::new(&app_state.redis_pool);
let cache_key = format!("anime2:complete:{}", page);
cache
.get_or_set(&cache_key, COMPLETE_CACHE_TTL, || async {
let html = self
.repository
.fetch_html(&self.repository.complete_url(page))
.await
.map_err(|e| e.to_string())?;
let (data, _pagination) = tokio::task::spawn_blocking(move || {
parser::parse_complete_page(&html, page).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())??;
let mut final_data = data;
apply_cached_posters(
&mut final_data,
app_state.db.clone(),
&app_state.redis_pool,
Some(app_state.image_processing_semaphore.clone()),
)
.await;
Ok(ApiResponse::success(final_data))
})
.await
.map_err(AppError::ScraperError)
}
}

Some files were not shown because too many files have changed in this diff Show More