luci18 commited on
Commit
e4ccb70
ยท
verified ยท
1 Parent(s): 118415a

Upload folder using huggingface_hub

Browse files
Files changed (24) hide show
  1. .github/workflows/deploy.yml +43 -0
  2. .gitignore +52 -0
  3. COMMANDS.md +208 -0
  4. DEPLOY.md +159 -0
  5. Dockerfile +27 -0
  6. README.md +348 -0
  7. bot/__init__.py +1 -0
  8. bot/database.py +264 -0
  9. bot/downloader.py +316 -0
  10. bot/encoder.py +308 -0
  11. bot/handlers.py +1495 -0
  12. bot/main.py +83 -0
  13. bot/renamer.py +221 -0
  14. bot/sites.py +103 -0
  15. bot/stats.py +274 -0
  16. bot/task_queue.py +316 -0
  17. bot/thumbnail.py +213 -0
  18. config.py +68 -0
  19. docker-compose.yml +34 -0
  20. requirements.txt +16 -0
  21. setup-github.bat +48 -0
  22. setup-github.sh +46 -0
  23. space.md +47 -0
  24. web_panel.py +630 -0
.github/workflows/deploy.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to Hugging Face
2
+
3
+ on:
4
+ push:
5
+ branches: [ main, master ]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ deploy:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ with:
14
+ fetch-depth: 0
15
+ lfs: true
16
+
17
+ - name: Setup Git
18
+ run: |
19
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
20
+ git config --global user.name "GitHub Actions"
21
+
22
+ - name: Push to Hugging Face
23
+ env:
24
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
25
+ HF_SPACE_ID: luci18/animebot
26
+ run: |
27
+ # Install Hugging Face CLI
28
+ pip install huggingface-hub
29
+
30
+ # Authenticate
31
+ huggingface-cli login --token $HF_TOKEN
32
+
33
+ # Clone the space
34
+ git clone https://huggingface.co/spaces/$HF_SPACE_ID hf-space
35
+
36
+ # Copy files (excluding secrets)
37
+ rsync -av --exclude='.git' --exclude='.env' --exclude='downloads' --exclude='encodes' --exclude='temp' --exclude='*.session' --exclude='__pycache__' . hf-space/
38
+
39
+ # Commit and push
40
+ cd hf-space
41
+ git add .
42
+ git commit -m "Deploy from GitHub Actions - $(date)" || echo "No changes to commit"
43
+ git push
.gitignore ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual environments
24
+ venv/
25
+ env/
26
+ ENV/
27
+ .venv/
28
+
29
+ # IDE
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ *~
35
+
36
+ # Environment variables
37
+ .env
38
+ .env.local
39
+
40
+ # Bot specific
41
+ downloads/*
42
+ encodes/*
43
+ temp/*
44
+ *.session
45
+ *.session-journal
46
+ bot.log
47
+
48
+ # Docker
49
+ .dockerignore
50
+
51
+ # MongoDB
52
+ mongo-data/
COMMANDS.md ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Anime Encoder Bot - Commands & Features
2
+
3
+ ## ๐Ÿ“ All Available Commands
4
+
5
+ ### ๐ŸŽฌ Basic Commands
6
+ | Command | Usage | Description |
7
+ |---------|-------|-------------|
8
+ | `/start` | `/start` | Start the bot with menu buttons |
9
+ | `/help` | `/help` | Show help message |
10
+ | `/sites` | `/sites` | List available anime sites |
11
+
12
+ ### ๐Ÿ” Search & Download
13
+ | Command | Usage | Description |
14
+ |---------|-------|-------------|
15
+ | `/anime` | `/anime <query>` | Search all anime sites |
16
+ | `/anime` | `/anime <query> <site>` | Search specific site (e.g., `/anime naruto gogoanime`) |
17
+ | `/download` | `/download <url> <ep>` | Download specific episode |
18
+ | `/ddl` | `/ddl <url>` | Download from direct URL |
19
+
20
+ ### ๐ŸŽž๏ธ Video Encoding
21
+ | Command | Usage | Description |
22
+ |---------|-------|-------------|
23
+ | `/encode` | Reply to video + `/encode` | Encode a video with user settings |
24
+ | `/batchencode` | Reply to video + `/batchencode` | Batch encode multiple videos |
25
+ | `/thumb` | Reply to video + `/thumb` | Generate custom thumbnail |
26
+
27
+ ### โš™๏ธ Settings & Stats
28
+ | Command | Usage | Description |
29
+ |---------|-------|-------------|
30
+ | `/settings` | `/settings` | Configure encoding, renaming, thumbnail preferences |
31
+ | `/status` | `/status` | View queue status |
32
+ | `/mystats` | `/mystats` | View your personal statistics |
33
+ | `/stats` | `/stats` | Admin statistics (admin only) |
34
+
35
+ ## ๐ŸŽ›๏ธ Settings Customization (via `/settings`)
36
+
37
+ ### Video Encoding Settings
38
+ - **Video Codec**: H.264 (libx264) or H.265/HEVC (libx265)
39
+ - **CRF Quality**: 16-35 (lower = better quality)
40
+ - **Speed Preset**: ultrafast to veryslow
41
+ - **Resolution**: original, 1080p, 720p, 480p, 360p
42
+ - **Audio Codec**: AAC, AC3, Opus, MP3
43
+ - **Audio Bitrate**: 96k-320k
44
+
45
+ ### ๐Ÿ–ผ๏ธ Thumbnail Settings
46
+ Users can customize:
47
+ 1. **Resolution**: 1080p, 720p, 480p, 360p, 240p, 180p
48
+ 2. **Position**: 10%, 25%, 50%, 75%, 90% (where in video to capture)
49
+ 3. **Format**: JPG or PNG
50
+ 4. **Caption Template**: Custom text with variables:
51
+ - `{filename}` - Video filename
52
+ - `{resolution}` - Thumbnail resolution
53
+ - `{position}` - Timestamp position
54
+
55
+ ### ๐Ÿ“ Rename Settings
56
+ - **Auto Rename**: Toggle on/off
57
+ - **Pattern Template**: Choose from presets or custom:
58
+ - `simple`: `{title} - Ep{episode}`
59
+ - `detailed`: `{title} - S{season}E{episode} [{quality}]`
60
+ - `with_codec`: `{title} - Ep{episode} [{quality}] [{codec}]`
61
+ - `with_site`: `[{source_site}] {title} - Ep{episode} [{quality}]`
62
+ - `anime_style`: `[{studio}] {title} - {episode} [{quality}]`
63
+
64
+ ### Video Caption Template
65
+ Default: `๐ŸŽฌ {filename}\n๐Ÿ“Š {resolution} | โฑ๏ธ {duration} | ๐Ÿ’พ {size}`
66
+
67
+ Available variables:
68
+ - `{filename}` - Video filename
69
+ - `{resolution}` - Video resolution (e.g., 1920x1080)
70
+ - `{duration}` - Video duration
71
+ - `{size}` - File size
72
+ - `{codec}` - Video codec
73
+
74
+ ## ๐ŸŒ Web Admin Panel
75
+
76
+ Access at `http://localhost:5000` after running:
77
+ ```bash
78
+ python web_panel.py
79
+ ```
80
+
81
+ **Default Login:**
82
+ - Username: `admin`
83
+ - Password: `admin` (โš ๏ธ change in production!)
84
+
85
+ **Panel Features:**
86
+ - ๐Ÿ“Š Dashboard with real-time stats
87
+ - ๐Ÿ‘ฅ User management
88
+ - ๐Ÿ“‹ Task monitoring
89
+ - ๐Ÿ† Leaderboard view
90
+ - โš™๏ธ Settings control
91
+
92
+ ## ๐Ÿ”ง Known Issues to Fix
93
+
94
+ ### 1. **Import Error in queue.py**
95
+ Make sure `from config import Config` is at the top of `bot/queue.py`
96
+
97
+ ### 2. **Missing UUID import in handlers.py**
98
+ Should have `import uuid` at the top
99
+
100
+ ### 3. **Missing imports in renamer.py**
101
+ Needs `from config import Config`
102
+
103
+ ### 4. **Flask missing in requirements.txt**
104
+ Add:
105
+ ```
106
+ flask>=2.3.0
107
+ werkzeug>=2.3.0
108
+ ```
109
+
110
+ ### 5. **Web Panel Environment Variables**
111
+ Add to `.env`:
112
+ ```
113
+ ADMIN_USERNAME=admin
114
+ ADMIN_PASSWORD_HASH=<bcrypt_hash>
115
+ FLASK_SECRET_KEY=your-secret-key
116
+ ```
117
+
118
+ ## ๐Ÿš€ Quick Setup Checklist
119
+
120
+ 1. **Install dependencies:**
121
+ ```bash
122
+ pip install -r requirements.txt
123
+ ```
124
+
125
+ 2. **Configure environment:**
126
+ ```bash
127
+ cp .env.example .env
128
+ # Edit .env with your credentials
129
+ ```
130
+
131
+ 3. **Run the bot:**
132
+ ```bash
133
+ python -m bot.main
134
+ ```
135
+
136
+ 4. **Run web panel (optional):**
137
+ ```bash
138
+ python web_panel.py
139
+ ```
140
+
141
+ ## ๐Ÿ“ Project Structure
142
+
143
+ ```
144
+ windsurf-project/
145
+ โ”œโ”€โ”€ bot/
146
+ โ”‚ โ”œโ”€โ”€ __init__.py
147
+ โ”‚ โ”œโ”€โ”€ database.py # MongoDB operations
148
+ โ”‚ โ”œโ”€โ”€ downloader.py # Anime downloading
149
+ โ”‚ โ”œโ”€โ”€ encoder.py # FFmpeg encoding
150
+ โ”‚ โ”œโ”€โ”€ handlers.py # Telegram handlers
151
+ โ”‚ โ”œโ”€โ”€ main.py # Bot entry point
152
+ โ”‚ โ”œโ”€โ”€ queue.py # Task queue system
153
+ โ”‚ โ”œโ”€โ”€ renamer.py # File renaming
154
+ โ”‚ โ”œโ”€โ”€ sites.py # Anime site configs
155
+ โ”‚ โ”œโ”€โ”€ stats.py # Statistics module
156
+ โ”‚ โ””โ”€โ”€ thumbnail.py # Thumbnail generation
157
+ โ”œโ”€โ”€ config.py # Configuration
158
+ โ”œโ”€โ”€ web_panel.py # Web admin panel
159
+ โ”œโ”€โ”€ requirements.txt # Dependencies
160
+ โ”œโ”€โ”€ Dockerfile # Docker image
161
+ โ”œโ”€โ”€ docker-compose.yml # Docker orchestration
162
+ โ””โ”€โ”€ README.md # Documentation
163
+ ```
164
+
165
+ ## ๐Ÿ› Troubleshooting
166
+
167
+ **Bot not starting?**
168
+ - Check `.env` has all required variables
169
+ - Ensure MongoDB is running
170
+ - Verify FFmpeg is installed: `ffmpeg -version`
171
+
172
+ **Downloads failing?**
173
+ - Check `animdl` is installed: `animdl --version`
174
+ - Verify download directories exist and are writable
175
+
176
+ **Web panel not accessible?**
177
+ - Check port 5000 is not in use
178
+ - Verify Flask is installed
179
+ - Check firewall settings
180
+
181
+ ## ๐Ÿ“ Environment Variables
182
+
183
+ Required:
184
+ ```env
185
+ API_ID=your_api_id
186
+ API_HASH=your_api_hash
187
+ BOT_TOKEN=your_bot_token
188
+ OWNER_ID=your_telegram_id
189
+ MONGO_URI=mongodb://localhost:27017/anime_encoder_bot
190
+ ```
191
+
192
+ Optional:
193
+ ```env
194
+ # Web Panel
195
+ ADMIN_USERNAME=admin
196
+ ADMIN_PASSWORD_HASH=<bcrypt_hash>
197
+ FLASK_SECRET_KEY=secret
198
+
199
+ # Defaults
200
+ DEFAULT_CRF=28
201
+ DEFAULT_PRESET=medium
202
+ DEFAULT_CODEC=libx264
203
+ DEFAULT_RENAME_PATTERN={title} - Ep{episode} [{quality}]
204
+
205
+ # Queue limits
206
+ MAX_CONCURRENT_DOWNLOADS=2
207
+ MAX_CONCURRENT_ENCODINGS=1
208
+ ```
DEPLOY.md ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ๐Ÿš€ Deploy to GitHub + Hugging Face
2
+
3
+ ## Quick Start
4
+
5
+ ### 1. Initialize & Push to GitHub
6
+
7
+ **Windows:**
8
+ ```cmd
9
+ setup-github.bat
10
+ ```
11
+
12
+ **Linux/Mac:**
13
+ ```bash
14
+ bash setup-github.sh
15
+ ```
16
+
17
+ ### 2. Manual GitHub Push
18
+
19
+ ```bash
20
+ # Replace with your actual repo
21
+ git remote add origin https://github.com/YOUR_USERNAME/anime-encoder-bot.git
22
+ git push -u origin main
23
+ ```
24
+
25
+ ### 3. Create Hugging Face Space
26
+
27
+ 1. Go to: https://huggingface.co/new-space
28
+ 2. **Owner**: Select your username
29
+ 3. **Space Name**: `anime-encoder-bot`
30
+ 4. **SDK**: Select `Docker`
31
+ 5. **Space Hardware**: `CPU Basic` (free) or `GPU` for faster encoding
32
+ 6. Click **Create Space**
33
+
34
+ ### 4. Configure GitHub Secrets
35
+
36
+ In your GitHub repo, go to **Settings > Secrets and variables > Actions**:
37
+
38
+ Add this secret:
39
+
40
+ | Secret Name | Value | Example |
41
+ |-------------|-------|---------|
42
+ | `HF_SPACE_ID` | Your space ID | `itzmelucifer/anime-encoder-bot` |
43
+
44
+ โœ… **HF_TOKEN is already configured in the workflow file.**
45
+
46
+ **OR Push Directly (No GitHub needed):**
47
+ ```bash
48
+ push-hf.bat
49
+ ```
50
+ Enter your space ID when prompted.
51
+
52
+ ### 5. Hugging Face Environment Variables
53
+
54
+ In your Space, go to **Settings > Variables**:
55
+
56
+ ```env
57
+ API_ID=your_api_id
58
+ API_HASH=your_api_hash
59
+ BOT_TOKEN=your_bot_token
60
+ OWNER_ID=your_telegram_id
61
+ MONGO_URI=mongodb+srv://...
62
+ ADMIN_USERNAME=admin
63
+ ADMIN_PASSWORD_HASH=bcrypt_hash
64
+ FLASK_SECRET_KEY=random_secret
65
+ FFMPEG_PATH=ffmpeg
66
+ FFPROBE_PATH=ffprobe
67
+ ```
68
+
69
+ ### 6. Deploy
70
+
71
+ Once secrets are set, every push to GitHub will auto-deploy to Hugging Face!
72
+
73
+ **Manual deploy trigger:**
74
+ - Go to **Actions** tab in GitHub
75
+ - Click **Deploy to Hugging Face**
76
+ - Click **Run workflow**
77
+
78
+ ---
79
+
80
+ ## ๐Ÿ“‹ Setup Checklist
81
+
82
+ - [ ] GitHub repository created
83
+ - [ ] Code pushed to GitHub
84
+ - [ ] Hugging Face Space created (Docker SDK)
85
+ - [ ] GitHub secrets: `HF_TOKEN`, `HF_SPACE_ID`
86
+ - [ ] Hugging Face environment variables set
87
+ - [ ] First deployment successful
88
+
89
+ ---
90
+
91
+ ## ๐Ÿ”ง Troubleshooting
92
+
93
+ ### Git push fails?
94
+ ```bash
95
+ git pull origin main --rebase
96
+ git push -u origin main
97
+ ```
98
+
99
+ ### Hugging Face deploy fails?
100
+ 1. Check GitHub Actions logs
101
+ 2. Verify HF_TOKEN is correct
102
+ 3. Check HF_SPACE_ID format (must be `username/space-name`)
103
+
104
+ ### Bot not starting?
105
+ 1. Check Hugging Face logs in Space
106
+ 2. Verify all env variables are set
107
+ 3. Check MongoDB connection string is accessible from Hugging Face
108
+
109
+ ### MongoDB Connection Issues?
110
+ If using MongoDB Atlas, whitelist Hugging Face IPs:
111
+ - Go to MongoDB Atlas โ†’ Network Access
112
+ - Add IP: `0.0.0.0/0` (allow all - not recommended for production)
113
+ - Or use specific Hugging Face egress IPs
114
+
115
+ ---
116
+
117
+ ## ๐Ÿ“ File Structure for Hugging Face
118
+
119
+ ```
120
+ .
121
+ โ”œโ”€โ”€ bot/ # Telegram bot code
122
+ โ”œโ”€โ”€ .github/workflows/ # Auto-deploy
123
+ โ”œโ”€โ”€ Dockerfile # Container config
124
+ โ”œโ”€โ”€ requirements.txt # Python deps
125
+ โ”œโ”€โ”€ README.md # Space docs
126
+ โ””โ”€โ”€ space.md # Hugging Face config
127
+ ```
128
+
129
+ ---
130
+
131
+ ## ๐Ÿ”— Useful Links
132
+
133
+ - **GitHub**: https://github.com/new
134
+ - **Hugging Face Tokens**: https://huggingface.co/settings/tokens
135
+ - **New Space**: https://huggingface.co/new-space
136
+ - **HF Docker Docs**: https://huggingface.co/docs/hub/spaces-sdks-docker
137
+
138
+ ---
139
+
140
+ ## ๐Ÿ’ก Tips
141
+
142
+ 1. **Free hosting**: Hugging Face CPU Basic is free
143
+ 2. **GPU encoding**: Upgrade to GPU hardware for faster encoding
144
+ 3. **Persistence**: Hugging Face spaces are ephemeral - use MongoDB for data
145
+ 4. **Sleep**: Free spaces sleep after inactivity - bot will reconnect automatically
146
+
147
+ ---
148
+
149
+ ## ๐ŸŽ‰ Success!
150
+
151
+ Your bot will be live at:
152
+ ```
153
+ https://huggingface.co/spaces/YOUR_USERNAME/anime-encoder-bot
154
+ ```
155
+
156
+ Web admin panel:
157
+ ```
158
+ https://huggingface.co/spaces/YOUR_USERNAME/anime-encoder-bot
159
+ ```
Dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Install system dependencies
4
+ RUN apt-get update && apt-get install -y \
5
+ ffmpeg \
6
+ git \
7
+ wget \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Set working directory
11
+ WORKDIR /app
12
+
13
+ # Copy requirements first for better caching
14
+ COPY requirements.txt .
15
+ RUN pip install --no-cache-dir -r requirements.txt
16
+
17
+ # Install animdl
18
+ RUN pip install --no-cache-dir git+https://github.com/justfoolingaround/animdl.git
19
+
20
+ # Copy bot code
21
+ COPY . .
22
+
23
+ # Create necessary directories
24
+ RUN mkdir -p downloads encodes temp
25
+
26
+ # Run the bot
27
+ CMD ["python", "-m", "bot.main"]
README.md ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Anime Encoder Bot
3
+ emoji: ๐ŸŽฌ
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 5000
8
+ pinned: false
9
+ ---
10
+
11
+ # Anime Encoder Bot ๐ŸŽฌ
12
+
13
+ A hybrid Telegram bot that combines **anime downloading** (via animdl) with **advanced video encoding** (via FFmpeg). Download anime episodes and encode them with H.264/H.265, custom quality settings, audio controls, and more!
14
+
15
+ ## Features
16
+
17
+ ### ๐ŸŽฌ Anime Downloading
18
+ - ๐Ÿ” **Multi-site search** - Search across all anime sites at once
19
+ - ๐ŸŒ **8+ supported sites** - GogoAnime, 9Anime, AnimePahe, Zoro, AnimixPlay, AllAnime, Nyaa, etc.
20
+ - ๐Ÿ“ฅ Download specific episodes
21
+ - ๐Ÿ“ฅ Direct URL downloads (yt-dlp)
22
+ - ๐Ÿ’พ MongoDB caching for fast re-access
23
+ - ๐Ÿ“Š Download progress tracking
24
+ - โณ Download queue management
25
+ - ๐Ÿ” Site-specific search - Filter by preferred source
26
+
27
+ ### ๐ŸŽž๏ธ Video Encoding
28
+ - ๐ŸŽฅ Codecs: H.264 (libx264), H.265/HEVC (libx265)
29
+ - ๐Ÿ“Š Quality control: CRF 16-35
30
+ - โšก Speed presets: ultrafast to veryslow
31
+ - ๐Ÿ“ Resolution scaling: 1080p, 720p, 540p, 480p, 360p
32
+ - ๐Ÿ”Š Audio: AAC, AC3, OPUS, MP3 with bitrate control
33
+ - ๐Ÿ“ Subtitle support
34
+ - 10-bit HEVC encoding
35
+
36
+ ### ๐Ÿ“ Smart Renaming with Metadata
37
+ - ๐Ÿท๏ธ **Auto-rename** downloads and encodes
38
+ - ๐Ÿ“‹ **Pattern templates**: `{title}`, `{episode}`, `{quality}`, `{codec}`, etc.
39
+ - ๐ŸŽจ **Preset patterns**: Simple, Detailed, Anime-style, With codec info
40
+ - ๐Ÿ”ง **Custom patterns**: Create your own naming scheme
41
+ - ๐Ÿ“Š **Metadata extraction**: Resolution, codec, duration from video files
42
+
43
+ ### ๐Ÿ–ผ๏ธ Thumbnail Generation (Customizable)
44
+ - ๐ŸŽฌ Auto-generate thumbnails from any video
45
+ - ๐Ÿ“ธ **Custom position** - Start (10%), Middle (50%), End (90%), etc.
46
+ - ๐Ÿ“ **User-defined resolution** - 1080p, 720p, 480p, 360p
47
+ - ๏ฟฝ **Custom caption template** - `{filename}`, `{resolution}`, `{position}`
48
+ - ๐Ÿ“ธ **Format choice** - JPG or PNG
49
+ - ๐Ÿ–ผ๏ธ Generated thumbnails sent with encoded videos
50
+
51
+ ### ๐Ÿ“Š Statistics & Leaderboard
52
+ - ๐Ÿ“ˆ **User Stats** - Personal download/encode history via `/mystats`
53
+ - ๐Ÿ† **Leaderboard** - Top users by activity (all time, weekly, monthly)
54
+ - ๐Ÿ“‰ **Success Rates** - Track completion rates
55
+ - ๐Ÿ” **Favorite Anime** - Most downloaded series per user
56
+
57
+ ### ๐ŸŒ Web Admin Panel
58
+ - ๐Ÿ”’ Secure login with password protection
59
+ - ๐Ÿ“Š **Dashboard** - Real-time bot statistics
60
+ - ๐Ÿ‘ฅ **User Management** - View all users and their activity
61
+ - ๐Ÿ“‹ **Task Monitoring** - Track downloads and encodes
62
+ - โš™๏ธ **Settings Control** - Adjust bot configuration
63
+ - ๐Ÿ† **Leaderboard View** - See top users
64
+
65
+ ### ๐ŸŽž๏ธ Batch Operations
66
+ - ๐Ÿ“ฆ **Batch Encode** - Queue multiple videos at once
67
+ - ๐Ÿ“ฅ **Batch Download** - Download entire seasons
68
+
69
+ ### โš™๏ธ User Features
70
+ - ๐Ÿ”ง Per-user encoding settings
71
+ - ๐Ÿ“Š Queue status monitoring
72
+ - ๐Ÿ”„ Download + Auto-encode workflow
73
+
74
+ ## Requirements
75
+
76
+ - Python 3.9+
77
+ - MongoDB (local or remote)
78
+ - FFmpeg + FFprobe
79
+ - animdl (`pip install animdl`)
80
+ - Telegram API credentials
81
+
82
+ ## Installation
83
+
84
+ ### 1. Clone Repository
85
+ ```bash
86
+ git clone https://github.com/yourusername/anime-encoder-bot.git
87
+ cd anime-encoder-bot
88
+ ```
89
+
90
+ ### 2. Install Dependencies
91
+ ```bash
92
+ pip install -r requirements.txt
93
+ pip install animdl # Must be installed separately
94
+ ```
95
+
96
+ ### 3. Install FFmpeg
97
+ **Ubuntu/Debian:**
98
+ ```bash
99
+ sudo apt-get update
100
+ sudo apt-get install ffmpeg
101
+ ```
102
+
103
+ **macOS:**
104
+ ```bash
105
+ brew install ffmpeg
106
+ ```
107
+
108
+ **Windows:** Download from [FFmpeg website](https://ffmpeg.org/download.html) and add to PATH.
109
+
110
+ ### 4. Setup MongoDB
111
+ **Local:**
112
+ ```bash
113
+ # Ubuntu/Debian
114
+ sudo apt-get install mongodb
115
+ sudo systemctl start mongod
116
+
117
+ # macOS
118
+ brew install mongodb-community
119
+ brew services start mongodb-community
120
+
121
+ # Docker
122
+ docker run -d -p 27017:27017 --name mongodb mongo:latest
123
+ ```
124
+
125
+ **MongoDB Atlas:** Use connection string in `.env`
126
+
127
+ ### 5. Configure Bot
128
+ Copy `.env.example` to `.env` and fill in your values:
129
+
130
+ ```bash
131
+ cp .env.example .env
132
+ ```
133
+
134
+ Edit `.env`:
135
+ ```env
136
+ # Telegram API credentials - Get from https://my.telegram.org
137
+ API_ID=your_api_id
138
+ API_HASH=your_api_hash
139
+ BOT_TOKEN=your_bot_token_from_botfather
140
+
141
+ # Owner settings
142
+ OWNER_ID=your_telegram_user_id
143
+
144
+ # MongoDB
145
+ MONGO_URI=mongodb://localhost:27017/anime_encoder_bot
146
+
147
+ # Optional: Log channel
148
+ LOG_CHANNEL=-1001234567890
149
+ ```
150
+
151
+ ### 6. Run Bot
152
+ ```bash
153
+ python -m bot.main
154
+ ```
155
+
156
+ ## Commands
157
+
158
+ | Command | Description |
159
+ |---------|-------------|
160
+ | `/start` | Start the bot with menu buttons |
161
+ | `/help` | Show help |
162
+ | `/sites` | List available anime sites |
163
+ | `/anime <query>` | Search all anime sites |
164
+ | `/anime <query> <site>` | Search specific site (e.g., `/anime naruto gogoanime`) |
165
+ | `/download <url> <ep>` | Download specific episode |
166
+ | `/ddl <url>` | Download from direct URL |
167
+ | `/encode` | Reply to a video to encode it |
168
+ | `/batchencode` | Reply to multiple videos to batch encode |
169
+ | `/thumb` | Reply to a video to generate thumbnail |
170
+ | `/settings` | Configure encoding & rename preferences |
171
+ | `/status` | View queue status |
172
+ | `/mystats` | View your personal statistics |
173
+ | `/stats` | Admin statistics |
174
+
175
+ ## Button Interface
176
+
177
+ The bot features an intuitive **button-based interface**:
178
+
179
+ ### Main Menu (via `/start`)
180
+ - ๐Ÿ” **Search Anime** - Opens search options
181
+ - ๐ŸŒ **Sites** - Lists all available anime sites
182
+ - โš™๏ธ **Settings** - Configure encoding preferences
183
+ - ๐Ÿ“Š **Status** - View queue status
184
+ - โ“ **Help** - Show commands
185
+
186
+ ### Search Options
187
+ - ๐Ÿ” **Search All Sites** - Search across all anime sites
188
+ - ๐ŸŽฏ **Search Specific Site** - Choose a site to search
189
+
190
+ ### Episode Selection
191
+ - Episode buttons (1-25 shown at a time)
192
+ - ๐Ÿ“ฅ **Download All** - Queue all episodes at once (limit 50)
193
+ - **Range buttons** - For series with >25 episodes (e.g., "Ep 26-50")
194
+ - โฌ…๏ธ **Previous** / โžก๏ธ **Next** - Navigate episode ranges
195
+
196
+ ### Site Filter Buttons
197
+ When searching all sites, results show filter buttons to narrow down by specific sites.
198
+
199
+ ### Settings - Renaming (โš™๏ธ โ†’ ๐Ÿ“ Rename Pattern)
200
+ - ๐Ÿ“‹ **Pattern Presets** - Simple, Detailed, With Codec, With Site, Anime Style, Minimal
201
+ - ๐Ÿ”„ **Toggle Auto Rename** - Enable/disable automatic renaming
202
+ - โœ๏ธ **Custom Pattern** - Create your own naming scheme
203
+ - ๐Ÿ“– **Pattern Help** - View all available variables
204
+
205
+ ### Settings - Thumbnails (โš™๏ธ โ†’ ๐Ÿ–ผ๏ธ Thumbnail Settings)
206
+ - ๐Ÿ“ **Resolution** - 1080p, 720p, 480p, 360p
207
+ - ๐Ÿ“ **Position** - Where to capture in the video (10%, 25%, 50%, 75%)
208
+ - ๐Ÿ“ธ **Format** - JPG or PNG
209
+ - ๐Ÿ’ฌ **Caption Template** - Customize the thumbnail caption
210
+
211
+ ### Thumbnail Caption Variables
212
+ | Variable | Description |
213
+ |----------|-------------|
214
+ | `{filename}` | Original video filename |
215
+ | `{resolution}` | Thumbnail resolution |
216
+ | `{position}` | Timestamp position (e.g., 25%) |
217
+
218
+ ## Supported Sites
219
+
220
+ - **GogoAnime** - `gogoanime` (most reliable)
221
+ - **9Anime** - `9anime`
222
+ - **AnimePahe** - `animepahe`
223
+ - **Zoro.to** - `zoro`
224
+ - **AnimixPlay** - `animixplay`
225
+ - **AllAnime** - `allanime`
226
+ - **Nyaa.si** - `nyaa` (torrents)
227
+ - **Crunchyroll** - `crunchyroll` (requires auth)
228
+
229
+ ## Encoding Settings
230
+
231
+ Users can customize their encoding preferences:
232
+
233
+ - **Codec**: libx264 (H.264) or libx265 (H.265/HEVC)
234
+ - **CRF**: 16-35 (lower = better quality)
235
+ - **Preset**: ultrafast to veryslow (encoding speed)
236
+ - **Resolution**: Scale to 1080p/720p/540p/480p/360p or keep original
237
+ - **Audio Codec**: AAC, AC3, OPUS, MP3
238
+ - **Audio Bitrate**: 96k-320k
239
+
240
+ ## Renaming Patterns
241
+
242
+ Configure automatic file renaming in `/settings` โ†’ `๐Ÿ“ Rename Pattern`:
243
+
244
+ ### Available Variables
245
+ | Variable | Description |
246
+ |----------|-------------|
247
+ | `{title}` | Anime title |
248
+ | `{episode}` | Episode number (02, 03, etc.) |
249
+ | `{season}` | Season number |
250
+ | `{quality}` | Video resolution (1920x1080) |
251
+ | `{codec}` | Video codec (H.264, HEVC) |
252
+ | `{audio_codec}` | Audio codec (AAC, AC3) |
253
+ | `{duration}` | Video duration |
254
+ | `{source_site}` | Download source site |
255
+
256
+ ### Pattern Presets
257
+ - **simple**: `{title} - Ep{episode}`
258
+ - **detailed**: `{title} - S{season}E{episode} [{quality}]`
259
+ - **with_codec**: `{title} - Ep{episode} [{quality}] [{codec}]`
260
+ - **with_site**: `[{source_site}] {title} - Ep{episode} [{quality}]`
261
+ - **anime_style**: `[{studio}] {title} - {episode} [{quality}]`
262
+
263
+ ### Example Output
264
+ Pattern: `{title} - Episode {episode} [{quality}]`
265
+ Result: `Attack on Titan - Episode 05 [1920x1080].mp4`
266
+
267
+ ## Web Admin Panel
268
+
269
+ The bot includes a web-based admin panel for easy management.
270
+
271
+ ### Running the Panel
272
+ ```bash
273
+ python web_panel.py
274
+ ```
275
+
276
+ Access at `http://localhost:5000`
277
+
278
+ ### Default Login
279
+ - **Username**: `admin`
280
+ - **Password**: `admin` (โš ๏ธ change in production!)
281
+
282
+ ### Panel Features
283
+ - ๐Ÿ“Š **Dashboard** - Real-time bot statistics, queue status, popular anime
284
+ - ๐Ÿ‘ฅ **Users** - View all users and their download/encode stats
285
+ - ๐Ÿ“‹ **Tasks** - Monitor recent downloads and encodes
286
+ - ๐Ÿ† **Leaderboard** - View top users by activity (all time/weekly/monthly)
287
+ - โš™๏ธ **Settings** - View and manage bot configuration
288
+
289
+ ### Environment Variables
290
+ ```env
291
+ ADMIN_USERNAME=admin
292
+ ADMIN_PASSWORD_HASH=<bcrypt_hash>
293
+ FLASK_SECRET_KEY=your-secret-key
294
+ ```
295
+
296
+ ## Architecture
297
+
298
+ ```
299
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
300
+ โ”‚ Telegram โ”‚
301
+ โ”‚ User โ”‚
302
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
303
+ โ”‚
304
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
305
+ โ”‚ Bot Client โ”‚โ”€โ”€โ”€โ”€โ–ถโ”‚ Task Queue โ”‚โ”€โ”€โ”€โ”€โ–ถโ”‚ MongoDB โ”‚
306
+ โ”‚ (Pyrogram) โ”‚ โ”‚ โ”‚ โ”‚ (Queue DB) โ”‚
307
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
308
+ โ”‚
309
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
310
+ โ”‚ Workers โ”‚ โ”‚ FFmpeg โ”‚
311
+ โ”‚ - Download โ”‚โ”€โ”€โ”€โ”€โ–ถโ”‚ Encoder โ”‚
312
+ โ”‚ - Encode โ”‚ โ”‚ โ”‚
313
+ โ””โ”€โ”€โ”€โ”€โ”€๏ฟฝ๏ฟฝ๏ฟฝโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
314
+ โ”‚
315
+ โ–ผ
316
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
317
+ โ”‚ animdl / โ”‚
318
+ โ”‚ yt-dlp โ”‚
319
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
320
+ ```
321
+
322
+ ## Troubleshooting
323
+
324
+ **Bot won't start:**
325
+ - Check `.env` has all required values
326
+ - Verify MongoDB is running
327
+ - Ensure FFmpeg is installed and in PATH
328
+
329
+ **Downloads fail:**
330
+ - Check animdl installation: `animdl --version`
331
+ - Verify source site is accessible
332
+ - Check download directory permissions
333
+
334
+ **Encoding fails:**
335
+ - Verify FFmpeg installation: `ffmpeg -version`
336
+ - Check encode directory permissions
337
+ - Review `bot.log` for errors
338
+
339
+ ## License
340
+
341
+ MIT License
342
+
343
+ ## Credits
344
+
345
+ - [animdl](https://github.com/justfoolingaround/animdl) - Anime downloader
346
+ - [Pyrogram](https://pyrogram.org) - Telegram MTProto client
347
+ - [FFmpeg](https://ffmpeg.org) - Video encoding
348
+ - [yt-dlp](https://github.com/yt-dlp/yt-dlp) - Direct URL downloader
bot/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Anime Encoder Bot - Hybrid anime downloader and encoder."""
bot/database.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Database module for MongoDB operations."""
2
+ import logging
3
+ from datetime import datetime
4
+ from typing import Optional, Dict, Any, List
5
+ from pymongo import MongoClient, ASCENDING, DESCENDING
6
+ from pymongo.collection import Collection
7
+ from pymongo.errors import ConfigurationError
8
+ from config import Config
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class Database:
13
+ """MongoDB database handler."""
14
+
15
+ def __init__(self):
16
+ self.client = MongoClient(Config.MONGO_URI)
17
+ # Try to get default database, or use explicit name
18
+ try:
19
+ self.db = self.client.get_default_database()
20
+ logger.info("Using default database from URI")
21
+ except ConfigurationError:
22
+ # Fallback to explicit database name
23
+ logger.info("No default database in URI, using 'anime_encoder_bot'")
24
+ self.db = self.client["anime_encoder_bot"]
25
+ except Exception as e:
26
+ logger.warning(f"Database init error: {e}, using fallback")
27
+ self.db = self.client["anime_encoder_bot"]
28
+
29
+ # Collections
30
+ self.anime_cache: Collection = self.db.anime_cache
31
+ self.users: Collection = self.db.users
32
+ self.downloads: Collection = self.db.downloads
33
+ self.encodes: Collection = self.db.encodes
34
+
35
+ # Create indexes
36
+ self._create_indexes()
37
+
38
+ def _create_indexes(self):
39
+ """Create necessary indexes."""
40
+ self.anime_cache.create_index("anime_id", unique=True)
41
+ self.anime_cache.create_index("title")
42
+ self.users.create_index("user_id", unique=True)
43
+ self.downloads.create_index([("created_at", DESCENDING)])
44
+ self.downloads.create_index("status")
45
+ self.encodes.create_index([("created_at", DESCENDING)])
46
+ self.encodes.create_index("status")
47
+
48
+ # Anime Cache
49
+ def get_cached_anime(self, anime_id: str) -> Optional[Dict]:
50
+ """Get cached anime by ID."""
51
+ return self.anime_cache.find_one({"anime_id": anime_id})
52
+
53
+ def cache_anime(self, anime_id: str, title: str, episodes: List[Dict],
54
+ file_id: Optional[str] = None, metadata: Optional[Dict] = None):
55
+ """Cache anime information."""
56
+ self.anime_cache.update_one(
57
+ {"anime_id": anime_id},
58
+ {
59
+ "$set": {
60
+ "title": title,
61
+ "episodes": episodes,
62
+ "file_id": file_id,
63
+ "metadata": metadata or {},
64
+ "cached_at": datetime.utcnow()
65
+ }
66
+ },
67
+ upsert=True
68
+ )
69
+
70
+ def get_cached_episode(self, anime_id: str, episode_num: int) -> Optional[Dict]:
71
+ """Get cached episode file_id."""
72
+ anime = self.anime_cache.find_one({"anime_id": anime_id})
73
+ if anime and "episodes" in anime:
74
+ for ep in anime["episodes"]:
75
+ if ep.get("number") == episode_num:
76
+ return ep
77
+ return None
78
+
79
+ def update_episode_file_id(self, anime_id: str, episode_num: int, file_id: str):
80
+ """Update file_id for cached episode."""
81
+ self.anime_cache.update_one(
82
+ {"anime_id": anime_id, "episodes.number": episode_num},
83
+ {"$set": {"episodes.$.file_id": file_id, "episodes.$.cached_at": datetime.utcnow()}}
84
+ )
85
+
86
+ # User Settings
87
+ def get_user_settings(self, user_id: int) -> Dict:
88
+ """Get user encoding settings."""
89
+ user = self.users.find_one({"user_id": user_id})
90
+ if not user:
91
+ # Return defaults
92
+ return {
93
+ "codec": Config.DEFAULT_CODEC,
94
+ "crf": Config.DEFAULT_CRF,
95
+ "preset": Config.DEFAULT_PRESET,
96
+ "resolution": "original",
97
+ "audio_codec": Config.DEFAULT_AUDIO_CODEC,
98
+ "audio_bitrate": Config.DEFAULT_AUDIO_BITRATE,
99
+ "hardsub": False,
100
+ "watermark": False,
101
+ "rename_pattern": Config.DEFAULT_RENAME_PATTERN,
102
+ "auto_rename": True,
103
+ "include_metadata": True,
104
+ "thumb_resolution": "720p",
105
+ "thumb_format": "jpg",
106
+ "thumb_caption_template": "๐Ÿ–ผ๏ธ Thumbnail of {filename}",
107
+ "thumb_position": "25%",
108
+ "thumb_auto_send": True,
109
+ "video_caption_template": "๐ŸŽฌ {filename}\n๐Ÿ“Š {resolution} | โฑ๏ธ {duration}"
110
+ }
111
+ # Ensure rename settings exist even for existing users
112
+ settings = user.get("settings", {})
113
+ if "rename_pattern" not in settings:
114
+ settings["rename_pattern"] = Config.DEFAULT_RENAME_PATTERN
115
+ if "auto_rename" not in settings:
116
+ settings["auto_rename"] = True
117
+ if "include_metadata" not in settings:
118
+ settings["include_metadata"] = True
119
+ # Ensure thumbnail settings exist
120
+ if "thumb_resolution" not in settings:
121
+ settings["thumb_resolution"] = "720p"
122
+ if "thumb_format" not in settings:
123
+ settings["thumb_format"] = "jpg"
124
+ if "thumb_caption_template" not in settings:
125
+ settings["thumb_caption_template"] = "๐Ÿ–ผ๏ธ Thumbnail of {filename}"
126
+ if "thumb_position" not in settings:
127
+ settings["thumb_position"] = "25%"
128
+ if "thumb_auto_send" not in settings:
129
+ settings["thumb_auto_send"] = True
130
+ if "video_caption_template" not in settings:
131
+ settings["video_caption_template"] = "๐ŸŽฌ {filename}\n๐Ÿ“Š {resolution} | โฑ๏ธ {duration}"
132
+ return settings
133
+
134
+ def update_user_settings(self, user_id: int, settings: Dict):
135
+ """Update user encoding settings."""
136
+ self.users.update_one(
137
+ {"user_id": user_id},
138
+ {
139
+ "$set": {
140
+ "settings": settings,
141
+ "updated_at": datetime.utcnow()
142
+ },
143
+ "$setOnInsert": {"user_id": user_id, "created_at": datetime.utcnow()}
144
+ },
145
+ upsert=True
146
+ )
147
+
148
+ def reset_user_settings(self, user_id: int):
149
+ """Reset user settings to defaults."""
150
+ self.users.update_one(
151
+ {"user_id": user_id},
152
+ {"$unset": {"settings": ""}}
153
+ )
154
+
155
+ # Download Queue
156
+ def add_download_task(self, task_id: str, user_id: int, anime_id: str,
157
+ episode_num: int, url: str, status: str = "pending"):
158
+ """Add download task to queue."""
159
+ self.downloads.insert_one({
160
+ "task_id": task_id,
161
+ "user_id": user_id,
162
+ "anime_id": anime_id,
163
+ "episode_num": episode_num,
164
+ "url": url,
165
+ "status": status,
166
+ "created_at": datetime.utcnow(),
167
+ "updated_at": datetime.utcnow()
168
+ })
169
+
170
+ def update_download_status(self, task_id: str, status: str,
171
+ file_path: Optional[str] = None,
172
+ error: Optional[str] = None):
173
+ """Update download task status."""
174
+ update = {"status": status, "updated_at": datetime.utcnow()}
175
+ if file_path:
176
+ update["file_path"] = file_path
177
+ if error:
178
+ update["error"] = error
179
+ self.downloads.update_one({"task_id": task_id}, {"$set": update})
180
+
181
+ def get_pending_downloads(self) -> List[Dict]:
182
+ """Get pending download tasks."""
183
+ return list(self.downloads.find({"status": "pending"}).sort("created_at", ASCENDING))
184
+
185
+ def get_download_task(self, task_id: str) -> Optional[Dict]:
186
+ """Get download task by ID."""
187
+ return self.downloads.find_one({"task_id": task_id})
188
+
189
+ # Encode Queue
190
+ def add_encode_task(self, task_id: str, user_id: int, input_path: str,
191
+ output_path: str, settings: Dict, status: str = "pending"):
192
+ """Add encode task to queue."""
193
+ self.encodes.insert_one({
194
+ "task_id": task_id,
195
+ "user_id": user_id,
196
+ "input_path": input_path,
197
+ "output_path": output_path,
198
+ "settings": settings,
199
+ "status": status,
200
+ "progress": 0,
201
+ "created_at": datetime.utcnow(),
202
+ "updated_at": datetime.utcnow()
203
+ })
204
+
205
+ def update_encode_status(self, task_id: str, status: str,
206
+ progress: Optional[int] = None,
207
+ file_id: Optional[str] = None,
208
+ error: Optional[str] = None):
209
+ """Update encode task status."""
210
+ update = {"status": status, "updated_at": datetime.utcnow()}
211
+ if progress is not None:
212
+ update["progress"] = progress
213
+ if file_id:
214
+ update["file_id"] = file_id
215
+ if error:
216
+ update["error"] = error
217
+ self.encodes.update_one({"task_id": task_id}, {"$set": update})
218
+
219
+ def get_pending_encodes(self) -> List[Dict]:
220
+ """Get pending encode tasks."""
221
+ return list(self.encodes.find({"status": "pending"}).sort("created_at", ASCENDING))
222
+
223
+ def get_encode_task(self, task_id: str) -> Optional[Dict]:
224
+ """Get encode task by ID."""
225
+ return self.encodes.find_one({"task_id": task_id})
226
+
227
+ def get_active_tasks(self) -> Dict[str, int]:
228
+ """Get count of active downloads and encodes."""
229
+ active_downloads = self.downloads.count_documents({"status": {"$in": ["downloading", "processing"]}})
230
+ active_encodes = self.encodes.count_documents({"status": {"$in": ["encoding", "processing"]}})
231
+ return {
232
+ "downloads": active_downloads,
233
+ "encodes": active_encodes
234
+ }
235
+
236
+ def get_user_tasks(self, user_id: int, limit: int = 10) -> Dict[str, List[Dict]]:
237
+ """Get recent tasks for a user."""
238
+ downloads = list(self.downloads.find(
239
+ {"user_id": user_id}
240
+ ).sort("created_at", DESCENDING).limit(limit))
241
+
242
+ encodes = list(self.encodes.find(
243
+ {"user_id": user_id}
244
+ ).sort("created_at", DESCENDING).limit(limit))
245
+
246
+ return {"downloads": downloads, "encodes": encodes}
247
+
248
+ def cleanup_old_tasks(self, days: int = 7):
249
+ """Clean up completed/failed tasks older than specified days."""
250
+ from datetime import timedelta
251
+ cutoff = datetime.utcnow() - timedelta(days=days)
252
+
253
+ self.downloads.delete_many({
254
+ "status": {"$in": ["completed", "failed", "cancelled"]},
255
+ "updated_at": {"$lt": cutoff}
256
+ })
257
+
258
+ self.encodes.delete_many({
259
+ "status": {"$in": ["completed", "failed", "cancelled"]},
260
+ "updated_at": {"$lt": cutoff}
261
+ })
262
+
263
+ # Global database instance
264
+ db = Database()
bot/downloader.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anime downloader module using animdl."""
2
+ import logging
3
+ import subprocess
4
+ import json
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Optional, List, Dict, Callable
8
+ from uuid import uuid4
9
+ from config import Config
10
+ from bot.database import db
11
+ from bot.sites import SUPPORTED_SITES, get_searchable_sites, DEFAULT_SITE_ORDER
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class AnimeDownloader:
16
+ """Handler for anime downloads using animdl with multi-site support."""
17
+
18
+ def __init__(self):
19
+ self.download_dir = Config.DOWNLOAD_DIR
20
+ self.active_downloads: Dict[str, subprocess.Popen] = {}
21
+ self.default_sites = DEFAULT_SITE_ORDER
22
+
23
+ def search_anime(self, query: str, site: Optional[str] = None) -> List[Dict]:
24
+ """Search for anime using animdl.
25
+
26
+ Args:
27
+ query: Search query
28
+ site: Specific site to search (uses all searchable sites if None)
29
+ """
30
+ results = []
31
+
32
+ if site and site in SUPPORTED_SITES:
33
+ # Search specific site
34
+ sites_to_search = [site]
35
+ else:
36
+ # Search all searchable sites
37
+ sites_to_search = get_searchable_sites()
38
+
39
+ for site_id in sites_to_search:
40
+ try:
41
+ site_results = self._search_site(query, site_id)
42
+ # Add site info to results
43
+ for result in site_results:
44
+ result["source_site"] = site_id
45
+ result["source_name"] = SUPPORTED_SITES[site_id]["name"]
46
+ results.extend(site_results)
47
+ except Exception as e:
48
+ logger.error(f"Search failed for {site_id}: {e}")
49
+ continue
50
+
51
+ return results
52
+
53
+ def _search_site(self, query: str, site_id: str) -> List[Dict]:
54
+ """Search a specific site."""
55
+ try:
56
+ cmd = ["animdl", "search", query, "--json", "--provider", site_id]
57
+ result = subprocess.run(
58
+ cmd,
59
+ capture_output=True,
60
+ text=True,
61
+ timeout=30
62
+ )
63
+ if result.returncode == 0:
64
+ return json.loads(result.stdout)
65
+ else:
66
+ logger.warning(f"Search failed for {site_id}: {result.stderr}")
67
+ return []
68
+ except subprocess.TimeoutExpired:
69
+ logger.warning(f"Search timed out for {site_id}")
70
+ return []
71
+ except Exception as e:
72
+ logger.error(f"Search error for {site_id}: {e}")
73
+ return []
74
+
75
+ def search_all_sites(self, query: str, max_results_per_site: int = 5) -> Dict[str, List[Dict]]:
76
+ """Search all supported sites and return results grouped by site."""
77
+ all_results = {}
78
+
79
+ for site_id in get_searchable_sites():
80
+ try:
81
+ results = self._search_site(query, site_id)
82
+ if results:
83
+ # Add site info
84
+ for result in results[:max_results_per_site]:
85
+ result["source_site"] = site_id
86
+ result["source_name"] = SUPPORTED_SITES[site_id]["name"]
87
+ all_results[site_id] = results[:max_results_per_site]
88
+ except Exception as e:
89
+ logger.error(f"Search failed for {site_id}: {e}")
90
+ all_results[site_id] = []
91
+
92
+ return all_results
93
+
94
+ def get_anime_info(self, anime_url: str, site: Optional[str] = None) -> Optional[Dict]:
95
+ """Get anime episode information."""
96
+ try:
97
+ cmd = ["animdl", "grab", "--index", anime_url, "--json"]
98
+ if site:
99
+ cmd.extend(["--provider", site])
100
+
101
+ result = subprocess.run(
102
+ cmd,
103
+ capture_output=True,
104
+ text=True,
105
+ timeout=30
106
+ )
107
+ if result.returncode == 0:
108
+ return json.loads(result.stdout)
109
+ return None
110
+ except Exception as e:
111
+ logger.error(f"Get anime info error: {e}")
112
+ return None
113
+
114
+ def download_episode(self, anime_url: str, episode_num: int,
115
+ user_id: int,
116
+ site: Optional[str] = None,
117
+ progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
118
+ """Download a specific episode.
119
+
120
+ Args:
121
+ anime_url: URL of the anime from search results
122
+ episode_num: Episode number to download
123
+ user_id: Telegram user ID
124
+ site: Specific site/provider to use
125
+ progress_callback: Callback function(progress_percent, status_message)
126
+
127
+ Returns:
128
+ Path to downloaded file or None if failed
129
+ """
130
+ task_id = str(uuid4())
131
+ output_dir = self.download_dir / str(user_id) / task_id
132
+ output_dir.mkdir(parents=True, exist_ok=True)
133
+
134
+ # Add to database
135
+ db.add_download_task(task_id, user_id, anime_url, episode_num,
136
+ f"{anime_url}/episode-{episode_num}")
137
+
138
+ try:
139
+ db.update_download_status(task_id, "downloading")
140
+
141
+ # Build animdl download command
142
+ cmd = [
143
+ "animdl",
144
+ "download",
145
+ anime_url,
146
+ "--episodes", str(episode_num),
147
+ "--quality", "best",
148
+ "--download-folder", str(output_dir),
149
+ "--index"
150
+ ]
151
+
152
+ # Add site provider if specified
153
+ if site:
154
+ cmd.extend(["--provider", site])
155
+
156
+ logger.info(f"Starting download: {' '.join(cmd)}")
157
+
158
+ # Start download process
159
+ process = subprocess.Popen(
160
+ cmd,
161
+ stdout=subprocess.PIPE,
162
+ stderr=subprocess.PIPE,
163
+ text=True,
164
+ bufsize=1,
165
+ universal_newlines=True
166
+ )
167
+
168
+ self.active_downloads[task_id] = process
169
+
170
+ # Monitor progress
171
+ last_progress = 0
172
+ for line in process.stdout:
173
+ line = line.strip()
174
+ if line:
175
+ logger.debug(f"Download output: {line}")
176
+
177
+ # Try to parse progress from animdl output
178
+ progress = self._parse_progress(line)
179
+ if progress and progress_callback and progress != last_progress:
180
+ progress_callback(progress, f"Downloading episode {episode_num}...")
181
+ last_progress = progress
182
+
183
+ process.wait()
184
+
185
+ if process.returncode == 0:
186
+ # Find downloaded file
187
+ downloaded_files = list(output_dir.glob("*.mp4")) + \
188
+ list(output_dir.glob("*.mkv")) + \
189
+ list(output_dir.glob("*.avi"))
190
+
191
+ if downloaded_files:
192
+ file_path = downloaded_files[0]
193
+ db.update_download_status(task_id, "completed", str(file_path))
194
+
195
+ # Update cache
196
+ db.cache_anime(
197
+ anime_url,
198
+ f"Anime {anime_url}",
199
+ [{"number": episode_num, "path": str(file_path)}]
200
+ )
201
+
202
+ if progress_callback:
203
+ progress_callback(100, "Download completed!")
204
+
205
+ return file_path
206
+ else:
207
+ error_msg = "No video file found after download"
208
+ db.update_download_status(task_id, "failed", error=error_msg)
209
+ return None
210
+ else:
211
+ stderr = process.stderr.read() if process.stderr else "Unknown error"
212
+ error_msg = f"Download failed: {stderr}"
213
+ db.update_download_status(task_id, "failed", error=error_msg)
214
+ logger.error(error_msg)
215
+ return None
216
+
217
+ except Exception as e:
218
+ error_msg = f"Download error: {e}"
219
+ db.update_download_status(task_id, "failed", error=error_msg)
220
+ logger.error(error_msg)
221
+ return None
222
+ finally:
223
+ if task_id in self.active_downloads:
224
+ del self.active_downloads[task_id]
225
+
226
+ def _parse_progress(self, line: str) -> Optional[int]:
227
+ """Parse download progress from animdl output."""
228
+ # Try to find percentage in output
229
+ patterns = [
230
+ r'(\d+)%',
231
+ r'(\d+\.?\d*)%',
232
+ r'Progress:\s*(\d+)',
233
+ ]
234
+ for pattern in patterns:
235
+ match = re.search(pattern, line)
236
+ if match:
237
+ try:
238
+ return int(float(match.group(1)))
239
+ except ValueError:
240
+ continue
241
+ return None
242
+
243
+ def cancel_download(self, task_id: str) -> bool:
244
+ """Cancel an active download."""
245
+ if task_id in self.active_downloads:
246
+ process = self.active_downloads[task_id]
247
+ process.terminate()
248
+ try:
249
+ process.wait(timeout=5)
250
+ except subprocess.TimeoutExpired:
251
+ process.kill()
252
+
253
+ db.update_download_status(task_id, "cancelled")
254
+ del self.active_downloads[task_id]
255
+ return True
256
+ return False
257
+
258
+ def download_direct(self, url: str, user_id: int,
259
+ progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
260
+ """Download from a direct URL using yt-dlp."""
261
+ task_id = str(uuid4())
262
+ output_dir = self.download_dir / str(user_id) / task_id
263
+ output_dir.mkdir(parents=True, exist_ok=True)
264
+
265
+ output_template = str(output_dir / "%(title)s.%(ext)s")
266
+
267
+ try:
268
+ cmd = [
269
+ "yt-dlp",
270
+ "-f", "best[ext=mp4]/best",
271
+ "--output", output_template,
272
+ "--newline",
273
+ url
274
+ ]
275
+
276
+ logger.info(f"Starting direct download: {url}")
277
+
278
+ process = subprocess.Popen(
279
+ cmd,
280
+ stdout=subprocess.PIPE,
281
+ stderr=subprocess.PIPE,
282
+ text=True,
283
+ bufsize=1,
284
+ universal_newlines=True
285
+ )
286
+
287
+ self.active_downloads[task_id] = process
288
+ last_progress = 0
289
+
290
+ for line in process.stdout:
291
+ line = line.strip()
292
+ if "%" in line:
293
+ progress = self._parse_progress(line)
294
+ if progress and progress_callback and progress != last_progress:
295
+ progress_callback(progress, "Downloading...")
296
+ last_progress = progress
297
+
298
+ process.wait()
299
+
300
+ if process.returncode == 0:
301
+ downloaded_files = list(output_dir.glob("*.*"))
302
+ if downloaded_files:
303
+ return downloaded_files[0]
304
+
305
+ return None
306
+
307
+ except Exception as e:
308
+ logger.error(f"Direct download error: {e}")
309
+ return None
310
+ finally:
311
+ if task_id in self.active_downloads:
312
+ del self.active_downloads[task_id]
313
+
314
+ # Global downloader instance
315
+ downloader = AnimeDownloader()
316
+
bot/encoder.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Video encoding module using FFmpeg."""
2
+ import logging
3
+ import subprocess
4
+ import re
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Optional, Dict, Callable
8
+ from uuid import uuid4
9
+ from config import Config
10
+ from bot.database import db
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class VideoEncoder:
15
+ """Handler for video encoding using FFmpeg."""
16
+
17
+ def __init__(self):
18
+ self.encode_dir = Config.ENCODE_DIR
19
+ self.temp_dir = Config.TEMP_DIR
20
+ self.ffmpeg_path = Config.FFMPEG_PATH
21
+ self.ffprobe_path = Config.FFPROBE_PATH
22
+ self.active_encodes: Dict[str, subprocess.Popen] = {}
23
+
24
+ def get_video_info(self, file_path: Path) -> Optional[Dict]:
25
+ """Get video file information using ffprobe."""
26
+ try:
27
+ cmd = [
28
+ self.ffprobe_path,
29
+ "-v", "error",
30
+ "-show_format",
31
+ "-show_streams",
32
+ "-of", "json",
33
+ str(file_path)
34
+ ]
35
+
36
+ result = subprocess.run(cmd, capture_output=True, text=True)
37
+ if result.returncode == 0:
38
+ return json.loads(result.stdout)
39
+ return None
40
+ except Exception as e:
41
+ logger.error(f"ffprobe error: {e}")
42
+ return None
43
+
44
+ def get_duration(self, file_path: Path) -> float:
45
+ """Get video duration in seconds."""
46
+ try:
47
+ cmd = [
48
+ self.ffprobe_path,
49
+ "-v", "error",
50
+ "-show_entries", "format=duration",
51
+ "-of", "default=noprint_wrappers=1:nokey=1",
52
+ str(file_path)
53
+ ]
54
+
55
+ result = subprocess.run(cmd, capture_output=True, text=True)
56
+ return float(result.stdout.strip()) if result.returncode == 0 else 0.0
57
+ except Exception:
58
+ return 0.0
59
+
60
+ def get_audio_info(self, file_path: Path) -> Optional[Dict]:
61
+ """Get audio stream information using ffprobe."""
62
+ try:
63
+ cmd = [
64
+ self.ffprobe_path,
65
+ "-v", "error",
66
+ "-select_streams", "a:0",
67
+ "-show_entries", "stream=codec_name,bit_rate",
68
+ "-of", "json",
69
+ str(file_path)
70
+ ]
71
+
72
+ result = subprocess.run(cmd, capture_output=True, text=True)
73
+ if result.returncode == 0:
74
+ data = json.loads(result.stdout)
75
+ if 'streams' and len(data.get('streams', [])) > 0:
76
+ stream = data['streams'][0]
77
+ return {
78
+ 'codec': stream.get('codec_name', 'Unknown'),
79
+ 'bitrate': stream.get('bit_rate', 'Unknown')
80
+ }
81
+ return None
82
+ except Exception as e:
83
+ logger.error(f"ffprobe audio error: {e}")
84
+ return None
85
+
86
+ def encode_video(self, input_path: Path, user_id: int,
87
+ settings: Optional[Dict] = None,
88
+ progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
89
+ """Encode video with specified settings.
90
+
91
+ Args:
92
+ input_path: Path to input video
93
+ user_id: Telegram user ID
94
+ settings: Encoding settings (uses user defaults if not provided)
95
+ progress_callback: Callback function(progress_percent, status_message)
96
+
97
+ Returns:
98
+ Path to encoded file or None if failed
99
+ """
100
+ task_id = str(uuid4())
101
+
102
+ # Get user settings or use defaults
103
+ if settings is None:
104
+ settings = db.get_user_settings(user_id)
105
+
106
+ # Build output path
107
+ output_name = f"{input_path.stem}_encoded.mkv"
108
+ output_path = self.encode_dir / str(user_id) / output_name
109
+ output_path.parent.mkdir(parents=True, exist_ok=True)
110
+
111
+ # Add to database
112
+ db.add_encode_task(task_id, user_id, str(input_path), str(output_path), settings)
113
+
114
+ try:
115
+ db.update_encode_status(task_id, "encoding")
116
+
117
+ # Build FFmpeg command
118
+ cmd = self._build_ffmpeg_command(input_path, output_path, settings)
119
+
120
+ logger.info(f"Starting encode: {' '.join(cmd)}")
121
+
122
+ # Get video duration for progress calculation
123
+ duration = self.get_duration(input_path)
124
+
125
+ # Start encode process
126
+ process = subprocess.Popen(
127
+ cmd,
128
+ stdout=subprocess.PIPE,
129
+ stderr=subprocess.PIPE,
130
+ text=True,
131
+ bufsize=1,
132
+ universal_newlines=True
133
+ )
134
+
135
+ self.active_encodes[task_id] = process
136
+
137
+ # Monitor progress
138
+ last_progress = 0
139
+ for line in process.stderr:
140
+ line = line.strip()
141
+ if "time=" in line and duration > 0:
142
+ progress = self._parse_progress(line, duration)
143
+ if progress and progress_callback and abs(progress - last_progress) >= 5:
144
+ progress_callback(progress, f"Encoding... {progress}%")
145
+ db.update_encode_status(task_id, "encoding", progress)
146
+ last_progress = progress
147
+
148
+ process.wait()
149
+
150
+ if process.returncode == 0:
151
+ db.update_encode_status(task_id, "completed", 100)
152
+
153
+ if progress_callback:
154
+ progress_callback(100, "Encoding completed!")
155
+
156
+ logger.info(f"Encoding completed: {output_path}")
157
+ return output_path
158
+ else:
159
+ stderr = process.stderr.read() if process.stderr else "Unknown error"
160
+ error_msg = f"Encoding failed: {stderr}"
161
+ db.update_encode_status(task_id, "failed", error=error_msg)
162
+ logger.error(error_msg)
163
+ return None
164
+
165
+ except Exception as e:
166
+ error_msg = f"Encoding error: {e}"
167
+ db.update_encode_status(task_id, "failed", error=error_msg)
168
+ logger.error(error_msg)
169
+ return None
170
+ finally:
171
+ if task_id in self.active_encodes:
172
+ del self.active_encodes[task_id]
173
+
174
+ def _build_ffmpeg_command(self, input_path: Path, output_path: Path, settings: Dict) -> list:
175
+ """Build FFmpeg command based on settings."""
176
+ cmd = [
177
+ self.ffmpeg_path,
178
+ "-i", str(input_path),
179
+ "-y", # Overwrite output
180
+ ]
181
+
182
+ # Video codec settings
183
+ codec = settings.get("codec", Config.DEFAULT_CODEC)
184
+ crf = settings.get("crf", Config.DEFAULT_CRF)
185
+ preset = settings.get("preset", Config.DEFAULT_PRESET)
186
+ resolution = settings.get("resolution", "original")
187
+
188
+ # Video filter
189
+ vf_parts = []
190
+ if resolution != "original":
191
+ height = resolution.replace("p", "")
192
+ vf_parts.append(f"scale=-2:{height}")
193
+
194
+ # Apply video filter if any
195
+ if vf_parts:
196
+ cmd.extend(["-vf", ",".join(vf_parts)])
197
+
198
+ # Video codec configuration
199
+ cmd.extend([
200
+ "-c:v", codec,
201
+ "-preset", preset,
202
+ "-crf", str(crf),
203
+ "-pix_fmt", "yuv420p",
204
+ ])
205
+
206
+ # 10-bit support for HEVC/H265
207
+ if "265" in codec or "hevc" in codec.lower():
208
+ cmd.extend(["-pix_fmt", "yuv420p10le"])
209
+
210
+ # Audio codec settings
211
+ audio_codec = settings.get("audio_codec", Config.DEFAULT_AUDIO_CODEC)
212
+ audio_bitrate = settings.get("audio_bitrate", Config.DEFAULT_AUDIO_BITRATE)
213
+
214
+ cmd.extend([
215
+ "-c:a", audio_codec,
216
+ "-b:a", audio_bitrate,
217
+ ])
218
+
219
+ # Audio channels
220
+ if "channels" in settings:
221
+ cmd.extend(["-ac", str(settings["channels"])])
222
+
223
+ # Hardsub subtitles
224
+ if settings.get("hardsub", False):
225
+ cmd.extend([
226
+ "-vf", "subtitles='" + str(input_path) + "'",
227
+ ])
228
+
229
+ # Copy subtitle streams if not hardsubbing
230
+ if not settings.get("hardsub", False):
231
+ cmd.extend(["-c:s", "copy"])
232
+
233
+ # Faststart for web playback
234
+ cmd.extend(["-movflags", "+faststart"])
235
+
236
+ # Output file
237
+ cmd.append(str(output_path))
238
+
239
+ return cmd
240
+
241
+ def _parse_progress(self, line: str, duration: float) -> Optional[int]:
242
+ """Parse encoding progress from FFmpeg output."""
243
+ match = re.search(r'time=(\d+):(\d+):(\d+\.?\d*)', line)
244
+ if match and duration > 0:
245
+ hours, minutes, seconds = match.groups()
246
+ current_time = float(hours) * 3600 + float(minutes) * 60 + float(seconds)
247
+ progress = int((current_time / duration) * 100)
248
+ return min(progress, 100)
249
+ return None
250
+
251
+ def cancel_encode(self, task_id: str) -> bool:
252
+ """Cancel an active encoding."""
253
+ if task_id in self.active_encodes:
254
+ process = self.active_encodes[task_id]
255
+ process.terminate()
256
+ try:
257
+ process.wait(timeout=5)
258
+ except subprocess.TimeoutExpired:
259
+ process.kill()
260
+
261
+ db.update_encode_status(task_id, "cancelled")
262
+ del self.active_encodes[task_id]
263
+ return True
264
+ return False
265
+
266
+ def reencode_audio(self, input_path: Path, output_path: Path,
267
+ audio_codec: str = "aac", bitrate: str = "128k",
268
+ channels: int = 2) -> bool:
269
+ """Re-encode only audio stream."""
270
+ try:
271
+ cmd = [
272
+ self.ffmpeg_path,
273
+ "-i", str(input_path),
274
+ "-c:v", "copy",
275
+ "-c:a", audio_codec,
276
+ "-b:a", bitrate,
277
+ "-ac", str(channels),
278
+ "-y",
279
+ str(output_path)
280
+ ]
281
+
282
+ result = subprocess.run(cmd, capture_output=True)
283
+ return result.returncode == 0
284
+ except Exception as e:
285
+ logger.error(f"Audio re-encode error: {e}")
286
+ return False
287
+
288
+ def extract_audio(self, input_path: Path, output_path: Path,
289
+ audio_codec: str = "mp3") -> bool:
290
+ """Extract audio from video."""
291
+ try:
292
+ cmd = [
293
+ self.ffmpeg_path,
294
+ "-i", str(input_path),
295
+ "-vn", # No video
296
+ "-c:a", audio_codec,
297
+ "-y",
298
+ str(output_path)
299
+ ]
300
+
301
+ result = subprocess.run(cmd, capture_output=True)
302
+ return result.returncode == 0
303
+ except Exception as e:
304
+ logger.error(f"Audio extract error: {e}")
305
+ return False
306
+
307
+ # Global encoder instance
308
+ encoder = VideoEncoder()
bot/handlers.py ADDED
@@ -0,0 +1,1495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Telegram bot command handlers."""
2
+ import logging
3
+ import asyncio
4
+ import uuid
5
+ from pathlib import Path
6
+ from typing import Optional
7
+ from pyrogram import Client, filters
8
+ from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
9
+ from config import Config
10
+ from bot.database import db
11
+ from bot.downloader import downloader
12
+ from bot.encoder import encoder
13
+ from bot.task_queue import task_queue
14
+ from bot.sites import SUPPORTED_SITES, get_searchable_sites, get_site_name
15
+ from bot.thumbnail import thumbnail_generator
16
+ from bot.stats import stats_manager
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # Settings options
21
+ CODEC_OPTIONS = ["libx264", "libx265"]
22
+ PRESET_OPTIONS = ["ultrafast", "superfast", "veryfast", "faster", "fast",
23
+ "medium", "slow", "slower", "veryslow"]
24
+ CRF_OPTIONS = list(range(16, 36, 2)) # 16, 18, 20, ..., 34
25
+ RESOLUTION_OPTIONS = ["original", "1080p", "720p", "540p", "480p", "360p"]
26
+ AUDIO_CODEC_OPTIONS = ["aac", "ac3", "opus", "mp3"]
27
+ AUDIO_BITRATE_OPTIONS = ["96k", "128k", "192k", "256k", "320k"]
28
+
29
+ def is_authorized(user_id: int) -> bool:
30
+ """Check if user is authorized."""
31
+ return user_id == Config.OWNER_ID or user_id in Config.SUDO_USERS
32
+
33
+ def format_bytes(bytes_val: int) -> str:
34
+ """Format bytes to human readable."""
35
+ for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
36
+ if bytes_val < 1024:
37
+ return f"{bytes_val:.2f} {unit}"
38
+ bytes_val /= 1024
39
+ return f"{bytes_val:.2f} PB"
40
+
41
+ def format_duration(seconds: float) -> str:
42
+ """Format seconds to HH:MM:SS."""
43
+ hours = int(seconds // 3600)
44
+ minutes = int((seconds % 3600) // 60)
45
+ secs = int(seconds % 60)
46
+ if hours > 0:
47
+ return f"{hours}:{minutes:02d}:{secs:02d}"
48
+ return f"{minutes}:{secs:02d}"
49
+
50
+ # ============== Start & Help ==============
51
+
52
+ async def start_handler(client: Client, message: Message):
53
+ """Handle /start command."""
54
+ user_id = message.from_user.id
55
+
56
+ welcome_text = f"""
57
+ ๐ŸŽฌ **Welcome to Anime Encoder Bot!**
58
+
59
+ I'm a hybrid bot that can:
60
+ โ€ข ๐Ÿ” **Search and download anime** from 8+ sites
61
+ โ€ข ๐ŸŽž๏ธ **Encode videos** with FFmpeg (H264/H265)
62
+ โ€ข ๏ฟฝ๏ธ **Generate thumbnails** from videos
63
+ โ€ข ๐Ÿ“ **Auto-rename files** with metadata
64
+ โ€ข ๏ฟฝ๐Ÿ“Š **Track statistics** and leaderboards
65
+ โ€ข ๐ŸŒ **Web admin panel** for management
66
+
67
+ **New commands:**
68
+ โ€ข `/mystats` - Your personal stats
69
+ โ€ข `/batchencode` - Batch encode videos
70
+ โ€ข `/thumb` - Generate thumbnails
71
+
72
+ Click the buttons below to get started!
73
+
74
+ Owner: {Config.OWNER_ID}
75
+ """
76
+
77
+ # Main menu buttons
78
+ buttons = [
79
+ [
80
+ InlineKeyboardButton("๐Ÿ” Search Anime", callback_data="menu_search"),
81
+ InlineKeyboardButton("๐ŸŒ Sites", callback_data="menu_sites")
82
+ ],
83
+ [
84
+ InlineKeyboardButton("โš™๏ธ Settings", callback_data="menu_settings"),
85
+ InlineKeyboardButton("๐Ÿ“Š Status", callback_data="menu_status")
86
+ ],
87
+ [
88
+ InlineKeyboardButton("โ“ Help", callback_data="menu_help")
89
+ ]
90
+ ]
91
+
92
+ await message.reply_text(
93
+ welcome_text,
94
+ reply_markup=InlineKeyboardMarkup(buttons),
95
+ parse_mode="markdown"
96
+ )
97
+
98
+ async def menu_callback(client: Client, callback_query: CallbackQuery):
99
+ """Handle main menu button clicks."""
100
+ data = callback_query.data
101
+
102
+ if data == "menu_search":
103
+ await callback_query.answer("Open search...")
104
+ # Show search options
105
+ buttons = [
106
+ [InlineKeyboardButton("๐Ÿ” Search All Sites", callback_data="search_all")],
107
+ [InlineKeyboardButton("๐ŸŽฏ Search Specific Site", callback_data="search_site_select")],
108
+ [InlineKeyboardButton("๐Ÿ”™ Back to Menu", callback_data="menu_back")]
109
+ ]
110
+ await callback_query.message.edit_text(
111
+ "๐Ÿ” **Search Anime**\n\nChoose search option:",
112
+ reply_markup=InlineKeyboardMarkup(buttons),
113
+ parse_mode="markdown"
114
+ )
115
+
116
+ elif data == "menu_sites":
117
+ await callback_query.answer("Loading sites...")
118
+ await sites_handler(client, callback_query.message)
119
+
120
+ elif data == "menu_settings":
121
+ await callback_query.answer("Open settings...")
122
+ await settings_handler(client, callback_query.message)
123
+
124
+ elif data == "menu_status":
125
+ await callback_query.answer("Loading status...")
126
+ await status_handler(client, callback_query.message)
127
+
128
+ elif data == "menu_help":
129
+ await callback_query.answer("Loading help...")
130
+ await callback_query.message.edit_text(
131
+ "๐Ÿ“– **Bot Commands**\n\n"
132
+ "**Search & Download:**\n"
133
+ "โ€ข `/anime <query>` - Search all sites\n"
134
+ "โ€ข `/anime <query> <site>` - Search specific site\n"
135
+ "โ€ข `/sites` - List available sites\n"
136
+ "โ€ข `/download <url> <ep>` - Download episode\n"
137
+ "โ€ข `/ddl <url>` - Direct download\n\n"
138
+ "**Encoding:**\n"
139
+ "โ€ข `/encode` - Reply to video to encode\n"
140
+ "โ€ข `/settings` - Encoding preferences\n\n"
141
+ "**Status:**\n"
142
+ "โ€ข `/status` - Queue status\n"
143
+ "โ€ข `/stats` - Admin stats (owner only)\n\n"
144
+ "[๐Ÿ”™ Back to Menu](callback_data:menu_back)",
145
+ parse_mode="markdown"
146
+ )
147
+
148
+ elif data == "menu_back":
149
+ await callback_query.answer("Back to menu...")
150
+ # Recreate main menu
151
+ await start_handler(client, callback_query.message)
152
+
153
+ async def help_handler(client: Client, message: Message):
154
+ """Handle /help command."""
155
+ await start_handler(client, message)
156
+
157
+ # ============== Anime Download ==============
158
+
159
+ async def sites_handler(client: Client, message: Message):
160
+ """Handle /sites command."""
161
+ text = "๐ŸŒ **Available Anime Sites:**\n\n"
162
+
163
+ for site_id, info in SUPPORTED_SITES.items():
164
+ name = info["name"]
165
+ searchable = "โœ…" if info.get("searchable") else "โŒ"
166
+ qualities = ", ".join(info["quality"])
167
+ subs = ", ".join(info["sub"])
168
+
169
+ text += f"**{name}** (`{site_id}`)\n"
170
+ text += f" Search: {searchable} | Quality: {qualities}\n"
171
+ text += f" Types: {subs}\n\n"
172
+
173
+ text += "\n**Usage:**\n"
174
+ text += "`/anime <query>` - Search all sites\n"
175
+ text += "`/anime <query> gogoanime` - Search specific site\n"
176
+
177
+ await message.reply_text(text, parse_mode="markdown")
178
+
179
+ async def anime_search_handler(client: Client, message: Message):
180
+ """Handle /anime command with optional site filter."""
181
+ user_id = message.from_user.id
182
+
183
+ if not message.command or len(message.command) < 2:
184
+ await message.reply_text(
185
+ "Usage:\n"
186
+ "`/anime <search query>` - Search all sites\n"
187
+ "`/anime <query> <site>` - Search specific site\n\n"
188
+ "Example: `/anime attack on titan gogoanime`\n\n"
189
+ "Use /sites to see available sites."
190
+ )
191
+ return
192
+
193
+ # Check if last argument is a site
194
+ site = None
195
+ if len(message.command) > 2:
196
+ potential_site = message.command[-1].lower()
197
+ if potential_site in SUPPORTED_SITES:
198
+ site = potential_site
199
+ query = " ".join(message.command[1:-1])
200
+ else:
201
+ query = " ".join(message.command[1:])
202
+ else:
203
+ query = " ".join(message.command[1:])
204
+
205
+ if site:
206
+ status_msg = await message.reply_text(
207
+ f"๐Ÿ” Searching `{query}` on **{get_site_name(site)}**..."
208
+ )
209
+ else:
210
+ status_msg = await message.reply_text(
211
+ f"๐Ÿ” Searching `{query}` on all sites..."
212
+ )
213
+
214
+ try:
215
+ if site:
216
+ # Search specific site
217
+ results = await asyncio.get_event_loop().run_in_executor(
218
+ None, downloader.search_anime, query, site
219
+ )
220
+ else:
221
+ # Search all sites
222
+ results = await asyncio.get_event_loop().run_in_executor(
223
+ None, downloader.search_anime, query
224
+ )
225
+
226
+ if not results:
227
+ await status_msg.edit_text(
228
+ f"โŒ No results found for `{query}`.\n\n"
229
+ f"Try searching on a specific site with:\n"
230
+ f"`/anime {query} gogoanime`"
231
+ )
232
+ return
233
+
234
+ # Show results grouped by site
235
+ text = f"๐ŸŽฌ **Search Results for:** `{query}`\n\n"
236
+ if site:
237
+ text += f"๐Ÿ“ Source: **{get_site_name(site)}**\n\n"
238
+
239
+ buttons = []
240
+ current_site = None
241
+
242
+ for i, result in enumerate(results[:15], 1):
243
+ title = result.get("name", "Unknown")
244
+ url = result.get("url", "")
245
+ result_site = result.get("source_site", "unknown")
246
+ site_name = result.get("source_name", result_site)
247
+
248
+ # Add site header when site changes
249
+ if not site and result_site != current_site:
250
+ current_site = result_site
251
+ text += f"\n๐Ÿ“บ **{site_name}**\n"
252
+
253
+ text += f" {i}. {title}\n"
254
+
255
+ # Add buttons for each result
256
+ if url:
257
+ safe_title = title[:25] + "..." if len(title) > 25 else title
258
+ buttons.append([InlineKeyboardButton(
259
+ f"{i}. ๐Ÿ“ฅ {safe_title} ({site_name})",
260
+ callback_data=f"anime_info:{url}:{result_site}"
261
+ )])
262
+
263
+ # Add site filter buttons if no site specified
264
+ if not site and len(results) > 0:
265
+ site_buttons = []
266
+ for site_id in get_searchable_sites()[:4]:
267
+ site_buttons.append(InlineKeyboardButton(
268
+ get_site_name(site_id),
269
+ callback_data=f"search_site:{query}:{site_id}"
270
+ ))
271
+ if site_buttons:
272
+ buttons.append(site_buttons)
273
+
274
+ await status_msg.edit_text(
275
+ text,
276
+ reply_markup=InlineKeyboardMarkup(buttons) if buttons else None,
277
+ parse_mode="markdown"
278
+ )
279
+
280
+ except Exception as e:
281
+ logger.error(f"Search error: {e}")
282
+ await status_msg.edit_text(f"โŒ Search failed: {e}")
283
+
284
+ async def search_prompt_handler(client: Client, callback_query: CallbackQuery):
285
+ """Handle search all sites button - prompt user for query."""
286
+ data = callback_query.data
287
+
288
+ if data == "search_all":
289
+ await callback_query.answer("Type your search query...")
290
+ await callback_query.message.edit_text(
291
+ "๐Ÿ” **Search All Sites**\n\n"
292
+ "Please type your search query:\n"
293
+ "Example: `attack on titan`\n\n"
294
+ "Or go back: /start",
295
+ parse_mode="markdown"
296
+ )
297
+ # Store state that we're waiting for search input
298
+ # (In production, you'd use conversation states)
299
+
300
+ elif data == "search_site_select":
301
+ await callback_query.answer("Select site...")
302
+ # Show site selection buttons
303
+ buttons = []
304
+ for site_id in get_searchable_sites():
305
+ buttons.append([InlineKeyboardButton(
306
+ get_site_name(site_id),
307
+ callback_data=f"search_prompt:{site_id}"
308
+ )])
309
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="menu_search")])
310
+
311
+ await callback_query.message.edit_text(
312
+ "๐ŸŽฏ **Search Specific Site**\n\nSelect a site:",
313
+ reply_markup=InlineKeyboardMarkup(buttons),
314
+ parse_mode="markdown"
315
+ )
316
+
317
+ async def search_site_prompt_handler(client: Client, callback_query: CallbackQuery):
318
+ """Handle site-specific search prompt."""
319
+ data = callback_query.data.replace("search_prompt:", "")
320
+
321
+ if data in SUPPORTED_SITES:
322
+ await callback_query.answer(f"Search {get_site_name(data)}...")
323
+ await callback_query.message.edit_text(
324
+ f"๐Ÿ” **Search {get_site_name(data)}**\n\n"
325
+ f"Please type your search query:\n"
326
+ f"Example: `/anime naruto {data}`\n\n"
327
+ f"Or go back: /start",
328
+ parse_mode="markdown"
329
+ )
330
+
331
+ async def anime_info_callback(client: Client, callback_query: CallbackQuery):
332
+ """Handle anime info button click."""
333
+ data = callback_query.data.split(":")
334
+ if len(data) < 2:
335
+ await callback_query.answer("Invalid data")
336
+ return
337
+
338
+ anime_url = data[1]
339
+ site = data[2] if len(data) > 2 else None
340
+
341
+ await callback_query.answer("Fetching anime info...")
342
+
343
+ try:
344
+ info = await asyncio.get_event_loop().run_in_executor(
345
+ None, lambda: downloader.get_anime_info(anime_url, site)
346
+ )
347
+
348
+ if not info:
349
+ await callback_query.message.edit_text("โŒ Failed to get anime info.")
350
+ return
351
+
352
+ title = info.get("title", "Unknown Anime")
353
+ episodes = info.get("episodes", [])
354
+
355
+ text = f"๐ŸŽฌ **{title}**\n\n"
356
+ text += f"๐Ÿ“บ **Episodes:** {len(episodes)}\n\n"
357
+ text += "Select episodes to download:"
358
+
359
+ # Create episode buttons (first 25 episodes)
360
+ buttons = []
361
+ row = []
362
+ for i, ep in enumerate(episodes[:25], 1):
363
+ row.append(InlineKeyboardButton(
364
+ str(i),
365
+ callback_data=f"download:{anime_url}:{i}:{site}" if site else f"download:{anime_url}:{i}"
366
+ ))
367
+ if len(row) == 5:
368
+ buttons.append(row)
369
+ row = []
370
+ if row:
371
+ buttons.append(row)
372
+
373
+ # Add range selection buttons if many episodes
374
+ if len(episodes) > 25:
375
+ range_buttons = []
376
+ for start in range(26, min(len(episodes) + 1, 100), 25):
377
+ end = min(start + 24, len(episodes))
378
+ range_buttons.append(InlineKeyboardButton(
379
+ f"Ep {start}-{end}",
380
+ callback_data=f"anime_range:{anime_url}:{start}:{end}:{site}" if site else f"anime_range:{anime_url}:{start}:{end}"
381
+ ))
382
+ # Add range buttons in rows of 3
383
+ for i in range(0, len(range_buttons), 3):
384
+ buttons.append(range_buttons[i:i+3])
385
+
386
+ # Add action buttons
387
+ action_buttons = []
388
+ if len(episodes) > 1:
389
+ action_buttons.append(InlineKeyboardButton(
390
+ "๐Ÿ“ฅ Download All",
391
+ callback_data=f"download_all:{anime_url}:{site}" if site else f"download_all:{anime_url}"
392
+ ))
393
+ action_buttons.append(InlineKeyboardButton("๐Ÿ”™ Back to Search", callback_data="back_search"))
394
+ buttons.append(action_buttons)
395
+
396
+ await callback_query.message.edit_text(
397
+ text,
398
+ reply_markup=InlineKeyboardMarkup(buttons),
399
+ parse_mode="markdown"
400
+ )
401
+
402
+ except Exception as e:
403
+ logger.error(f"Info error: {e}")
404
+ await callback_query.message.edit_text(f"โŒ Error: {e}")
405
+
406
+ async def download_callback(client: Client, callback_query: CallbackQuery):
407
+ """Handle download button click."""
408
+ data = callback_query.data.split(":")
409
+ if len(data) < 3:
410
+ await callback_query.answer("Invalid data")
411
+ return
412
+
413
+ _, anime_url, episode_num = data[:3]
414
+ site = data[3] if len(data) > 3 else None
415
+ episode_num = int(episode_num)
416
+ user_id = callback_query.from_user.id
417
+
418
+ await callback_query.answer(f"Starting download for episode {episode_num}...")
419
+
420
+ # Add to queue with site info
421
+ task_id = str(uuid.uuid4())
422
+ await task_queue.add_download(
423
+ task_id=task_id,
424
+ anime_url=anime_url,
425
+ episode_num=episode_num,
426
+ user_id=user_id,
427
+ site=site
428
+ )
429
+
430
+ # Register progress callback
431
+ progress_msg = await callback_query.message.reply_text(
432
+ f"โณ Episode {episode_num} added to queue..."
433
+ )
434
+
435
+ async def progress_callback(progress: int, message: str):
436
+ try:
437
+ await progress_msg.edit_text(
438
+ f"โณ Episode {episode_num}:\n{message}\n{progress}%"
439
+ )
440
+ except Exception:
441
+ pass
442
+
443
+ task_queue.register_progress_callback(task_id, progress_callback)
444
+
445
+ await callback_query.message.edit_text(
446
+ f"โœ… Episode {episode_num} download started!\n"
447
+ f"You'll receive the file when complete."
448
+ )
449
+
450
+ async def anime_range_callback(client: Client, callback_query: CallbackQuery):
451
+ """Handle episode range button click - show episodes in range."""
452
+ data = callback_query.data.split(":")
453
+ if len(data) < 4:
454
+ await callback_query.answer("Invalid data")
455
+ return
456
+
457
+ _, anime_url, start, end = data[:4]
458
+ site = data[4] if len(data) > 4 else None
459
+ start, end = int(start), int(end)
460
+
461
+ await callback_query.answer(f"Showing episodes {start}-{end}...")
462
+
463
+ # Get anime info
464
+ try:
465
+ info = await asyncio.get_event_loop().run_in_executor(
466
+ None, lambda: downloader.get_anime_info(anime_url, site)
467
+ )
468
+
469
+ if not info:
470
+ await callback_query.message.edit_text("โŒ Failed to get anime info.")
471
+ return
472
+
473
+ title = info.get("title", "Unknown Anime")
474
+ episodes = info.get("episodes", [])
475
+
476
+ text = f"๐ŸŽฌ **{title}**\n\n"
477
+ text += f"๐Ÿ“บ Episodes {start}-{min(end, len(episodes))} of {len(episodes)}\n\n"
478
+ text += "Select episodes to download:"
479
+
480
+ # Create buttons for episodes in range
481
+ buttons = []
482
+ row = []
483
+ for i in range(start, min(end + 1, len(episodes) + 1)):
484
+ row.append(InlineKeyboardButton(
485
+ str(i),
486
+ callback_data=f"download:{anime_url}:{i}:{site}" if site else f"download:{anime_url}:{i}"
487
+ ))
488
+ if len(row) == 5:
489
+ buttons.append(row)
490
+ row = []
491
+ if row:
492
+ buttons.append(row)
493
+
494
+ # Add navigation and action buttons
495
+ nav_buttons = []
496
+ if start > 1:
497
+ prev_start = max(1, start - 25)
498
+ prev_end = start - 1
499
+ nav_buttons.append(InlineKeyboardButton(
500
+ "โฌ…๏ธ Previous",
501
+ callback_data=f"anime_range:{anime_url}:{prev_start}:{prev_end}:{site}" if site else f"anime_range:{anime_url}:{prev_start}:{prev_end}"
502
+ ))
503
+ if end < len(episodes):
504
+ next_start = end + 1
505
+ next_end = min(end + 25, len(episodes))
506
+ nav_buttons.append(InlineKeyboardButton(
507
+ "โžก๏ธ Next",
508
+ callback_data=f"anime_range:{anime_url}:{next_start}:{next_end}:{site}" if site else f"anime_range:{anime_url}:{next_start}:{next_end}"
509
+ ))
510
+ if nav_buttons:
511
+ buttons.append(nav_buttons)
512
+
513
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back to Start", callback_data=f"anime_info:{anime_url}:{site}" if site else f"anime_info:{anime_url}")])
514
+
515
+ await callback_query.message.edit_text(
516
+ text,
517
+ reply_markup=InlineKeyboardMarkup(buttons),
518
+ parse_mode="markdown"
519
+ )
520
+
521
+ except Exception as e:
522
+ logger.error(f"Range error: {e}")
523
+ await callback_query.message.edit_text(f"โŒ Error: {e}")
524
+
525
+ async def download_all_callback(client: Client, callback_query: CallbackQuery):
526
+ """Handle download all button - queue all episodes."""
527
+ data = callback_query.data.split(":")
528
+ if len(data) < 2:
529
+ await callback_query.answer("Invalid data")
530
+ return
531
+
532
+ anime_url = data[1]
533
+ site = data[2] if len(data) > 2 else None
534
+ user_id = callback_query.from_user.id
535
+
536
+ await callback_query.answer("Queueing all episodes...")
537
+
538
+ try:
539
+ # Get anime info to count episodes
540
+ info = await asyncio.get_event_loop().run_in_executor(
541
+ None, lambda: downloader.get_anime_info(anime_url, site)
542
+ )
543
+
544
+ if not info:
545
+ await callback_query.message.edit_text("โŒ Failed to get anime info.")
546
+ return
547
+
548
+ episodes = info.get("episodes", [])
549
+ total_episodes = len(episodes)
550
+
551
+ if total_episodes == 0:
552
+ await callback_query.message.edit_text("โŒ No episodes found.")
553
+ return
554
+
555
+ # Queue all episodes (limit to first 50 to avoid spam)
556
+ limit = min(total_episodes, 50)
557
+ for episode_num in range(1, limit + 1):
558
+ task_id = str(uuid.uuid4())
559
+ await task_queue.add_download(
560
+ task_id=task_id,
561
+ anime_url=anime_url,
562
+ episode_num=episode_num,
563
+ user_id=user_id,
564
+ site=site
565
+ )
566
+
567
+ text = f"โœ… **Download All Started!**\n\n"
568
+ text += f"๐Ÿ“บ Anime: {info.get('title', 'Unknown')}\n"
569
+ text += f"๐Ÿ“ฅ Episodes queued: {limit}/{total_episodes}\n"
570
+ text += f"โณ They will be downloaded sequentially.\n\n"
571
+ if total_episodes > 50:
572
+ text += f"โš ๏ธ Note: Only first 50 episodes queued to prevent spam."
573
+
574
+ await callback_query.message.edit_text(text, parse_mode="markdown")
575
+
576
+ except Exception as e:
577
+ logger.error(f"Download all error: {e}")
578
+ await callback_query.message.edit_text(f"โŒ Error: {e}")
579
+
580
+ async def search_site_callback(client: Client, callback_query: CallbackQuery):
581
+ """Handle site-specific search button click."""
582
+ data = callback_query.data.split(":")
583
+ if len(data) != 3:
584
+ await callback_query.answer("Invalid data")
585
+ return
586
+
587
+ _, query, site = data
588
+
589
+ await callback_query.answer(f"Searching {get_site_name(site)}...")
590
+
591
+ # Update message to show search status
592
+ await callback_query.message.edit_text(f"๐Ÿ” Searching `{query}` on **{get_site_name(site)}**...")
593
+
594
+ try:
595
+ results = await asyncio.get_event_loop().run_in_executor(
596
+ None, downloader.search_anime, query, site
597
+ )
598
+
599
+ if not results:
600
+ await callback_query.message.edit_text(
601
+ f"โŒ No results found for `{query}` on **{get_site_name(site)}**."
602
+ )
603
+ return
604
+
605
+ # Show results
606
+ text = f"๐ŸŽฌ **Results for:** `{query}`\n"
607
+ text += f"๐Ÿ“ Source: **{get_site_name(site)}**\n\n"
608
+
609
+ buttons = []
610
+ for i, result in enumerate(results[:10], 1):
611
+ title = result.get("name", "Unknown")
612
+ url = result.get("url", "")
613
+
614
+ text += f"{i}. {title}\n"
615
+
616
+ if url:
617
+ safe_title = title[:30] + "..." if len(title) > 30 else title
618
+ buttons.append([InlineKeyboardButton(
619
+ f"{i}. ๐Ÿ“ฅ {safe_title}",
620
+ callback_data=f"anime_info:{url}:{site}"
621
+ )])
622
+
623
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back to All Sites", callback_data="back_search")])
624
+
625
+ await callback_query.message.edit_text(
626
+ text,
627
+ reply_markup=InlineKeyboardMarkup(buttons),
628
+ parse_mode="markdown"
629
+ )
630
+
631
+ except Exception as e:
632
+ logger.error(f"Site search error: {e}")
633
+ await callback_query.message.edit_text(f"โŒ Search failed: {e}")
634
+
635
+ async def download_command_handler(client: Client, message: Message):
636
+ """Handle /download command."""
637
+ if len(message.command) < 3:
638
+ await message.reply_text("Usage: /download <anime_url> <episode_number>")
639
+ return
640
+
641
+ anime_url = message.command[1]
642
+ try:
643
+ episode_num = int(message.command[2])
644
+ except ValueError:
645
+ await message.reply_text("Episode number must be an integer.")
646
+ return
647
+
648
+ user_id = message.from_user.id
649
+
650
+ # Add to queue
651
+ task_id = str(uuid.uuid4())
652
+ await task_queue.add_download(
653
+ task_id=task_id,
654
+ anime_url=anime_url,
655
+ episode_num=episode_num,
656
+ user_id=user_id
657
+ )
658
+
659
+ progress_msg = await message.reply_text(
660
+ f"โณ Episode {episode_num} added to queue..."
661
+ )
662
+
663
+ async def progress_callback(progress: int, message: str):
664
+ try:
665
+ await progress_msg.edit_text(
666
+ f"โณ Episode {episode_num}:\n{message}\n{progress}%"
667
+ )
668
+ except Exception:
669
+ pass
670
+
671
+ task_queue.register_progress_callback(task_id, progress_callback)
672
+
673
+ async def direct_download_handler(client: Client, message: Message):
674
+ """Handle /ddl command."""
675
+ if len(message.command) < 2:
676
+ await message.reply_text("Usage: /ddl <direct_url>")
677
+ return
678
+
679
+ url = message.command[1]
680
+ user_id = message.from_user.id
681
+
682
+ progress_msg = await message.reply_text("โณ Starting download...")
683
+
684
+ def sync_download():
685
+ def progress_cb(p: int, m: str):
686
+ asyncio.create_task(_update_progress(p, m))
687
+ return downloader.download_direct(url, user_id, progress_cb)
688
+
689
+ async def _update_progress(progress: int, msg: str):
690
+ try:
691
+ await progress_msg.edit_text(f"โณ {msg}\n{progress}%")
692
+ except Exception:
693
+ pass
694
+
695
+ try:
696
+ result = await asyncio.get_event_loop().run_in_executor(None, sync_download)
697
+
698
+ if result:
699
+ await progress_msg.edit_text("โœ… Download completed! Uploading...")
700
+ await client.send_video(
701
+ chat_id=message.chat.id,
702
+ video=str(result),
703
+ caption="๐Ÿ“ฅ Downloaded file",
704
+ supports_streaming=True
705
+ )
706
+ await progress_msg.delete()
707
+ else:
708
+ await progress_msg.edit_text("โŒ Download failed.")
709
+
710
+ except Exception as e:
711
+ logger.error(f"DDL error: {e}")
712
+ await progress_msg.edit_text(f"โŒ Download failed: {e}")
713
+
714
+ # ============== Video Encoding ==============
715
+
716
+ async def encode_handler(client: Client, message: Message):
717
+ """Handle /encode command (reply to video)."""
718
+ if not message.reply_to_message:
719
+ await message.reply_text("Reply to a video with /encode to encode it.")
720
+ return
721
+
722
+ reply = message.reply_to_message
723
+ if not (reply.video or reply.document):
724
+ await message.reply_text("Please reply to a video file.")
725
+ return
726
+
727
+ # Download the video first
728
+ progress_msg = await message.reply_text("โณ Downloading video...")
729
+
730
+ try:
731
+ download_path = Config.DOWNLOAD_DIR / str(message.from_user.id) / "encode_input"
732
+ download_path.mkdir(parents=True, exist_ok=True)
733
+
734
+ file_path = await reply.download(
735
+ file_name=str(download_path / "input_video")
736
+ )
737
+
738
+ await progress_msg.edit_text("โœ… Downloaded! Starting encode...")
739
+
740
+ # Add to encode queue
741
+ user_id = message.from_user.id
742
+ settings = db.get_user_settings(user_id)
743
+
744
+ task_id = str(uuid.uuid4())
745
+ await task_queue.add_encode(
746
+ task_id=task_id,
747
+ input_path=file_path,
748
+ user_id=user_id,
749
+ settings=settings
750
+ )
751
+
752
+ async def progress_callback(progress: int, msg: str):
753
+ try:
754
+ await progress_msg.edit_text(f"๐ŸŽž๏ธ Encoding...\n{msg}\n{progress}%")
755
+ except Exception:
756
+ pass
757
+
758
+ task_queue.register_progress_callback(task_id, progress_callback)
759
+
760
+ # Wait for completion and upload
761
+ encoded_path = None
762
+ max_wait = 3600 # 1 hour timeout
763
+ waited = 0
764
+
765
+ while waited < max_wait:
766
+ await asyncio.sleep(5)
767
+ waited += 5
768
+
769
+ task = db.get_encode_task(task_id)
770
+ if task:
771
+ if task["status"] == "completed":
772
+ encoded_path = Path(task["output_path"])
773
+ break
774
+ elif task["status"] in ["failed", "cancelled"]:
775
+ await progress_msg.edit_text(f"โŒ Encoding {task['status']}.")
776
+ return
777
+
778
+ if encoded_path and encoded_path.exists():
779
+ await progress_msg.edit_text("โœ… Encoding complete! Generating thumbnail...")
780
+
781
+ # Get file info
782
+ info = encoder.get_video_info(encoded_path)
783
+ duration = encoder.get_duration(encoded_path)
784
+
785
+ # Get file size
786
+ file_size = encoded_path.stat().st_size
787
+ size_mb = file_size / (1024 * 1024)
788
+
789
+ # Get user thumbnail settings
790
+ thumb_res = settings.get("thumb_resolution", "720p")
791
+ thumb_format = settings.get("thumb_format", "jpg")
792
+ thumb_width, thumb_height = 1280, 720
793
+ if thumb_res in thumbnail_generator.RESOLUTIONS:
794
+ thumb_width, thumb_height = thumbnail_generator.RESOLUTIONS[thumb_res]
795
+
796
+ # Generate thumbnail with user settings
797
+ thumb_path = encoded_path.parent / f"thumb.{thumb_format}"
798
+ thumb = thumbnail_generator.generate_thumbnail(
799
+ encoded_path,
800
+ thumb_path,
801
+ width=thumb_width,
802
+ height=thumb_height
803
+ )
804
+
805
+ # Get video resolution from info
806
+ video_width, video_height = 0, 0
807
+ codec = "unknown"
808
+ if info:
809
+ streams = info.get('streams', [])
810
+ for stream in streams:
811
+ if stream.get('codec_type') == 'video':
812
+ video_width = stream.get('width', 0)
813
+ video_height = stream.get('height', 0)
814
+ codec = stream.get('codec_name', 'unknown')
815
+ break
816
+
817
+ # Build caption using user's template
818
+ video_caption_template = settings.get(
819
+ "video_caption_template",
820
+ "๏ฟฝ {filename}\n๐Ÿ“Š {resolution} | โฑ๏ธ {duration} | ๐Ÿ’พ {size}"
821
+ )
822
+
823
+ # Replace variables in template
824
+ resolution_str = f"{video_width}x{video_height}" if video_width and video_height else "Unknown"
825
+ caption = video_caption_template.replace("{filename}", encoded_path.name)
826
+ caption = caption.replace("{resolution}", resolution_str)
827
+ caption = caption.replace("{duration}", format_duration(duration))
828
+ caption = caption.replace("{size}", f"{size_mb:.1f} MB")
829
+ caption = caption.replace("{codec}", codec)
830
+
831
+ await client.send_video(
832
+ chat_id=message.chat.id,
833
+ video=str(encoded_path),
834
+ caption=caption,
835
+ supports_streaming=True,
836
+ duration=int(duration) if duration else None,
837
+ thumb=str(thumb) if thumb and thumb.exists() else None
838
+ )
839
+ await progress_msg.delete()
840
+
841
+ # Cleanup thumbnail
842
+ if thumb and thumb.exists():
843
+ try:
844
+ thumb.unlink()
845
+ except:
846
+ pass
847
+ else:
848
+ await progress_msg.edit_text("โŒ Encoding failed or timed out.")
849
+
850
+ except Exception as e:
851
+ logger.error(f"Encode error: {e}")
852
+ await progress_msg.edit_text(f"โŒ Error: {e}")
853
+
854
+ # ============== Settings ==============
855
+
856
+ async def settings_handler(client: Client, message: Message):
857
+ """Handle /settings command."""
858
+ user_id = message.from_user.id
859
+ settings = db.get_user_settings(user_id)
860
+
861
+ text = "โš™๏ธ **Your Settings:**\n\n"
862
+ text += "**Encoding:**\n"
863
+ text += f"๐ŸŽฅ **Codec:** `{settings.get('codec', Config.DEFAULT_CODEC)}`\n"
864
+ text += f"๐Ÿ“Š **CRF:** `{settings.get('crf', Config.DEFAULT_CRF)}` (lower = better quality)\n"
865
+ text += f"โšก **Preset:** `{settings.get('preset', Config.DEFAULT_PRESET)}` (slower = better compression)\n"
866
+ text += f"๐Ÿ“ **Resolution:** `{settings.get('resolution', 'original')}`\n"
867
+ text += f"๐Ÿ”Š **Audio Codec:** `{settings.get('audio_codec', Config.DEFAULT_AUDIO_CODEC)}`\n"
868
+ text += f"๐Ÿ”Š **Audio Bitrate:** `{settings.get('audio_bitrate', Config.DEFAULT_AUDIO_BITRATE)}`\n\n"
869
+
870
+ # Rename settings
871
+ auto_rename = settings.get('auto_rename', True)
872
+ rename_pattern = settings.get('rename_pattern', Config.DEFAULT_RENAME_PATTERN)
873
+ text += "**Renaming:**\n"
874
+ text += f"๐Ÿ“ **Auto Rename:** `{'โœ… On' if auto_rename else 'โŒ Off'}`\n"
875
+ text += f"๐Ÿ“‹ **Pattern:** `{rename_pattern}`\n\n"
876
+
877
+ # Thumbnail settings
878
+ thumb_res = settings.get('thumb_resolution', '720p')
879
+ thumb_pos = settings.get('thumb_position', '25%')
880
+ thumb_format = settings.get('thumb_format', 'jpg')
881
+ text += "**Thumbnails:**\n"
882
+ text += f"๐Ÿ–ผ๏ธ **Resolution:** `{thumb_res}`\n"
883
+ text += f"๐Ÿ“ **Position:** `{thumb_pos}`\n"
884
+ text += f"๐Ÿ“ธ **Format:** `{thumb_format}`\n"
885
+
886
+ buttons = [
887
+ [InlineKeyboardButton("๐ŸŽฅ Video Codec", callback_data="set_codec"),
888
+ InlineKeyboardButton("๐Ÿ“Š CRF Quality", callback_data="set_crf")],
889
+ [InlineKeyboardButton("โšก Speed Preset", callback_data="set_preset"),
890
+ InlineKeyboardButton("๐Ÿ“ Resolution", callback_data="set_resolution")],
891
+ [InlineKeyboardButton("๐Ÿ”Š Audio Settings", callback_data="set_audio")],
892
+ [InlineKeyboardButton("๐Ÿ“ Rename Pattern", callback_data="set_rename")],
893
+ [InlineKeyboardButton("๐Ÿ–ผ๏ธ Thumbnail Settings", callback_data="set_thumb")],
894
+ [InlineKeyboardButton("๐Ÿ”„ Reset to Defaults", callback_data="reset_settings")],
895
+ ]
896
+
897
+ await message.reply_text(
898
+ text,
899
+ reply_markup=InlineKeyboardMarkup(buttons),
900
+ parse_mode="markdown"
901
+ )
902
+
903
+ async def settings_callback(client: Client, callback_query: CallbackQuery):
904
+ """Handle settings callbacks."""
905
+ data = callback_query.data
906
+ user_id = callback_query.from_user.id
907
+
908
+ if data == "set_codec":
909
+ buttons = []
910
+ row = []
911
+ for codec in CODEC_OPTIONS:
912
+ row.append(InlineKeyboardButton(
913
+ codec,
914
+ callback_data=f"codec:{codec}"
915
+ ))
916
+ buttons.append(row)
917
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
918
+
919
+ await callback_query.message.edit_text(
920
+ "๐ŸŽฅ **Select Video Codec:**\n\n"
921
+ "โ€ข `libx264` - H.264 (better compatibility)\n"
922
+ "โ€ข `libx265` - H.265/HEVC (better compression)",
923
+ reply_markup=InlineKeyboardMarkup(buttons),
924
+ parse_mode="markdown"
925
+ )
926
+
927
+ elif data == "set_crf":
928
+ buttons = []
929
+ row = []
930
+ for crf in CRF_OPTIONS[:4]: # First row
931
+ row.append(InlineKeyboardButton(str(crf), callback_data=f"crf:{crf}"))
932
+ buttons.append(row)
933
+ row = []
934
+ for crf in CRF_OPTIONS[4:]: # Second row
935
+ row.append(InlineKeyboardButton(str(crf), callback_data=f"crf:{crf}"))
936
+ buttons.append(row)
937
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
938
+
939
+ await callback_query.message.edit_text(
940
+ "๐Ÿ“Š **Select CRF (Quality):**\n\n"
941
+ "โ€ข 16-18 = Visually lossless\n"
942
+ "โ€ข 20-23 = High quality\n"
943
+ "โ€ข 24-28 = Good quality (default)\n"
944
+ "โ€ข 30-35 = Lower quality, smaller size",
945
+ reply_markup=InlineKeyboardMarkup(buttons),
946
+ parse_mode="markdown"
947
+ )
948
+
949
+ elif data == "set_preset":
950
+ buttons = []
951
+ for preset in PRESET_OPTIONS:
952
+ buttons.append([InlineKeyboardButton(
953
+ preset,
954
+ callback_data=f"preset:{preset}"
955
+ )])
956
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
957
+
958
+ await callback_query.message.edit_text(
959
+ "โšก **Select Encoding Speed:**\n\n"
960
+ "โ€ข `ultrafast` - Very fast, large files\n"
961
+ "โ€ข `medium` - Balanced (default)\n"
962
+ "โ€ข `slow`/`veryslow` - Slow, best compression",
963
+ reply_markup=InlineKeyboardMarkup(buttons),
964
+ parse_mode="markdown"
965
+ )
966
+
967
+ elif data == "set_resolution":
968
+ buttons = []
969
+ row = []
970
+ for res in RESOLUTION_OPTIONS:
971
+ row.append(InlineKeyboardButton(res, callback_data=f"res:{res}"))
972
+ if len(row) == 3:
973
+ buttons.append(row)
974
+ row = []
975
+ if row:
976
+ buttons.append(row)
977
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
978
+
979
+ await callback_query.message.edit_text(
980
+ "๐Ÿ“ **Select Output Resolution:**\n\n"
981
+ "`original` = Keep original resolution",
982
+ reply_markup=InlineKeyboardMarkup(buttons),
983
+ parse_mode="markdown"
984
+ )
985
+
986
+ elif data == "set_audio":
987
+ buttons = [
988
+ [InlineKeyboardButton("๐ŸŽต AAC", callback_data="audio_codec:aac")],
989
+ [InlineKeyboardButton("๐ŸŽต AC3", callback_data="audio_codec:ac3")],
990
+ [InlineKeyboardButton("๐ŸŽต Opus", callback_data="audio_codec:opus")],
991
+ [InlineKeyboardButton("๐ŸŽต MP3", callback_data="audio_codec:mp3")],
992
+ [InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")],
993
+ ]
994
+
995
+ await callback_query.message.edit_text(
996
+ "๐Ÿ”Š **Select Audio Codec:**",
997
+ reply_markup=InlineKeyboardMarkup(buttons)
998
+ )
999
+
1000
+ elif data == "set_thumb":
1001
+ from bot.thumbnail import thumbnail_generator
1002
+
1003
+ buttons = []
1004
+
1005
+ # Resolution options
1006
+ res_buttons = []
1007
+ for res_name in ["1080p", "720p", "480p", "360p"]:
1008
+ res_buttons.append(InlineKeyboardButton(
1009
+ res_name,
1010
+ callback_data=f"thumb_res:{res_name}"
1011
+ ))
1012
+ buttons.append(res_buttons)
1013
+
1014
+ # Position options
1015
+ pos_buttons = []
1016
+ for pos_name in ["10%", "25%", "50%", "75%"]:
1017
+ pos_buttons.append(InlineKeyboardButton(
1018
+ pos_name,
1019
+ callback_data=f"thumb_pos:{pos_name}"
1020
+ ))
1021
+ buttons.append(pos_buttons)
1022
+
1023
+ # Format options
1024
+ buttons.append([
1025
+ InlineKeyboardButton("๐Ÿ“ธ JPG", callback_data="thumb_format:jpg"),
1026
+ InlineKeyboardButton("๐Ÿ“ธ PNG", callback_data="thumb_format:png")
1027
+ ])
1028
+
1029
+ # Caption template
1030
+ buttons.append([InlineKeyboardButton(
1031
+ "โœ๏ธ Edit Caption Template",
1032
+ callback_data="thumb_caption_edit"
1033
+ )])
1034
+
1035
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
1036
+
1037
+ current_res = settings.get('thumb_resolution', '720p')
1038
+ current_pos = settings.get('thumb_position', '25%')
1039
+ current_format = settings.get('thumb_format', 'jpg')
1040
+ current_caption = settings.get('thumb_caption_template', '๐Ÿ–ผ๏ธ Thumbnail of {filename}')
1041
+
1042
+ text = "๐Ÿ–ผ๏ธ **Thumbnail Settings**\n\n"
1043
+ text += f"**Current Settings:**\n"
1044
+ text += f"๐Ÿ“ Resolution: `{current_res}`\n"
1045
+ text += f"๐Ÿ“ Position: `{current_pos}` (in video)\n"
1046
+ text += f"๐Ÿ“ธ Format: `{current_format}`\n"
1047
+ text += f"๐Ÿ’ฌ Caption: `{current_caption}`\n\n"
1048
+ text += "**Variables for Caption:**\n"
1049
+ text += "`{filename}` - Video filename\n"
1050
+ text += "`{resolution}` - Thumbnail resolution\n"
1051
+ text += "`{position}` - Timestamp position\n\n"
1052
+ text += "Select an option to change:"
1053
+
1054
+ await callback_query.message.edit_text(
1055
+ text,
1056
+ reply_markup=InlineKeyboardMarkup(buttons),
1057
+ parse_mode="markdown"
1058
+ )
1059
+
1060
+ elif data == "set_rename":
1061
+ from bot.renamer import renamer
1062
+
1063
+ buttons = []
1064
+ # Add pattern presets
1065
+ for name, pattern in renamer.PATTERNS.items():
1066
+ buttons.append([InlineKeyboardButton(
1067
+ f"๐Ÿ“‹ {name.replace('_', ' ').title()}",
1068
+ callback_data=f"rename_pattern:{name}"
1069
+ )])
1070
+
1071
+ # Add toggle and custom buttons
1072
+ buttons.append([InlineKeyboardButton(
1073
+ "๐Ÿ”„ Toggle Auto Rename",
1074
+ callback_data="rename_toggle"
1075
+ )])
1076
+ buttons.append([InlineKeyboardButton(
1077
+ "โœ๏ธ Custom Pattern",
1078
+ callback_data="rename_custom"
1079
+ )])
1080
+ buttons.append([InlineKeyboardButton(
1081
+ "๐Ÿ“– Pattern Help",
1082
+ callback_data="rename_help"
1083
+ )])
1084
+ buttons.append([InlineKeyboardButton("๐Ÿ”™ Back", callback_data="back_settings")])
1085
+
1086
+ current_pattern = settings.get('rename_pattern', Config.DEFAULT_RENAME_PATTERN)
1087
+ auto_rename = settings.get('auto_rename', True)
1088
+
1089
+ text = "๐Ÿ“ **Rename Settings**\n\n"
1090
+ text += f"**Auto Rename:** `{'โœ… On' if auto_rename else 'โŒ Off'}`\n"
1091
+ text += f"**Current Pattern:**\n`{current_pattern}`\n\n"
1092
+ text += "**Available Patterns:**\n"
1093
+ for name, pattern in list(renamer.PATTERNS.items())[:3]:
1094
+ text += f" โ€ข `{pattern}`\n"
1095
+
1096
+ await callback_query.message.edit_text(
1097
+ text,
1098
+ reply_markup=InlineKeyboardMarkup(buttons),
1099
+ parse_mode="markdown"
1100
+ )
1101
+
1102
+ elif data == "reset_settings":
1103
+ db.reset_user_settings(user_id)
1104
+ await callback_query.answer("Settings reset to defaults!")
1105
+ await settings_handler(client, callback_query.message)
1106
+
1107
+ elif data.startswith("back"):
1108
+ if data == "back_search":
1109
+ await anime_search_handler(client, callback_query.message)
1110
+ else:
1111
+ await settings_handler(client, callback_query.message)
1112
+
1113
+ async def setting_value_callback(client: Client, callback_query: CallbackQuery):
1114
+ """Handle setting value selection."""
1115
+ data = callback_query.data
1116
+ user_id = callback_query.from_user.id
1117
+
1118
+ settings = db.get_user_settings(user_id)
1119
+
1120
+ if data.startswith("codec:"):
1121
+ settings["codec"] = data.replace("codec:", "")
1122
+ await callback_query.answer(f"Codec set to {settings['codec']}")
1123
+
1124
+ elif data.startswith("crf:"):
1125
+ settings["crf"] = int(data.replace("crf:", ""))
1126
+ await callback_query.answer(f"CRF set to {settings['crf']}")
1127
+
1128
+ elif data.startswith("preset:"):
1129
+ settings["preset"] = data.replace("preset:", "")
1130
+ await callback_query.answer(f"Preset set to {settings['preset']}")
1131
+
1132
+ elif data.startswith("res:"):
1133
+ settings["resolution"] = data.replace("res:", "")
1134
+ await callback_query.answer(f"Resolution set to {settings['resolution']}")
1135
+
1136
+ elif data.startswith("audio_codec:"):
1137
+ settings["audio_codec"] = data.replace("audio_codec:", "")
1138
+ await callback_query.answer(f"Audio codec set to {settings['audio_codec']}")
1139
+
1140
+ elif data.startswith("thumb_res:"):
1141
+ res = data.replace("thumb_res:", "")
1142
+ settings["thumb_resolution"] = res
1143
+ await callback_query.answer(f"Thumbnail resolution set to {res}")
1144
+
1145
+ elif data.startswith("thumb_pos:"):
1146
+ pos = data.replace("thumb_pos:", "")
1147
+ settings["thumb_position"] = pos
1148
+ await callback_query.answer(f"Thumbnail position set to {pos}")
1149
+
1150
+ elif data.startswith("thumb_format:"):
1151
+ fmt = data.replace("thumb_format:", "")
1152
+ settings["thumb_format"] = fmt
1153
+ await callback_query.answer(f"Thumbnail format set to {fmt}")
1154
+
1155
+ elif data == "thumb_caption_edit":
1156
+ await callback_query.answer("Caption template coming soon!")
1157
+ await callback_query.message.reply_text(
1158
+ "โœ๏ธ **Edit Thumbnail Caption Template**\n\n"
1159
+ "Current template:\n"
1160
+ f"`{settings.get('thumb_caption_template', '๐Ÿ–ผ๏ธ Thumbnail of {filename}')}`\n\n"
1161
+ "**Available variables:**\n"
1162
+ "`{filename}` - Video filename\n"
1163
+ "`{resolution}` - Thumbnail resolution (e.g., 1280x720)\n"
1164
+ "`{position}` - Timestamp position (e.g., 25%)\n\n"
1165
+ "Send me your new caption template to update it."
1166
+ )
1167
+ return # Don't go back to settings
1168
+
1169
+ db.update_user_settings(user_id, settings)
1170
+ await settings_handler(client, callback_query.message)
1171
+
1172
+ async def rename_callback(client: Client, callback_query: CallbackQuery):
1173
+ """Handle rename settings callbacks."""
1174
+ data = callback_query.data
1175
+ user_id = callback_query.from_user.id
1176
+ settings = db.get_user_settings(user_id)
1177
+
1178
+ from bot.renamer import renamer
1179
+
1180
+ if data.startswith("rename_pattern:"):
1181
+ pattern_name = data.replace("rename_pattern:", "")
1182
+ if pattern_name in renamer.PATTERNS:
1183
+ settings["rename_pattern"] = renamer.PATTERNS[pattern_name]
1184
+ settings["auto_rename"] = True
1185
+ db.update_user_settings(user_id, settings)
1186
+ await callback_query.answer(f"Pattern set to: {pattern_name}")
1187
+ await settings_handler(client, callback_query.message)
1188
+
1189
+ elif data == "rename_toggle":
1190
+ current = settings.get("auto_rename", True)
1191
+ settings["auto_rename"] = not current
1192
+ db.update_user_settings(user_id, settings)
1193
+ status = "enabled" if settings["auto_rename"] else "disabled"
1194
+ await callback_query.answer(f"Auto rename {status}")
1195
+ await settings_handler(client, callback_query.message)
1196
+
1197
+ elif data == "rename_custom":
1198
+ await callback_query.answer("Custom pattern feature coming soon!")
1199
+ # In a full implementation, you'd use conversation handler here
1200
+ await callback_query.message.reply_text(
1201
+ "โœ๏ธ **Custom Rename Pattern**\n\n"
1202
+ "Send me your custom pattern using variables:\n"
1203
+ "`{title}`, `{episode}`, `{quality}`, `{codec}`, etc.\n\n"
1204
+ "Example: `{title} - Episode {episode} [{quality}]`\n\n"
1205
+ "Click ๐Ÿ“– Pattern Help for all variables.",
1206
+ parse_mode="markdown"
1207
+ )
1208
+
1209
+ elif data == "rename_help":
1210
+ help_text = renamer.get_pattern_help()
1211
+ await callback_query.message.edit_text(
1212
+ help_text,
1213
+ reply_markup=InlineKeyboardMarkup([
1214
+ [InlineKeyboardButton("๐Ÿ”™ Back", callback_data="set_rename")]
1215
+ ]),
1216
+ parse_mode="markdown"
1217
+ )
1218
+
1219
+ # ============== Status & Admin ==============
1220
+
1221
+ async def status_handler(client: Client, message: Message):
1222
+ """Handle /status command."""
1223
+ status = task_queue.get_queue_status()
1224
+ active = db.get_active_tasks()
1225
+
1226
+ text = "๐Ÿ“Š **Bot Status**\n\n"
1227
+ text += f"โณ **Queue:**\n"
1228
+ text += f" Downloads: {status['download_queue_size']} queued\n"
1229
+ text += f" Encodes: {status['encode_queue_size']} queued\n\n"
1230
+ text += f"โš™๏ธ **Active:**\n"
1231
+ text += f" Downloads: {active['downloads']}/{status['max_downloads']}\n"
1232
+ text += f" Encodes: {active['encodes']}/{status['max_encodes']}\n\n"
1233
+ text += f"๐Ÿ‘ค **Your recent tasks:**\n"
1234
+
1235
+ user_tasks = db.get_user_tasks(message.from_user.id, limit=5)
1236
+
1237
+ if user_tasks["downloads"]:
1238
+ text += "\n๐Ÿ“ฅ **Downloads:**\n"
1239
+ for dl in user_tasks["downloads"]:
1240
+ text += f" โ€ข {dl['status']}: Ep {dl.get('episode_num', '?')}\n"
1241
+
1242
+ if user_tasks["encodes"]:
1243
+ text += "\n๐ŸŽž๏ธ **Encodes:**\n"
1244
+ for enc in user_tasks["encodes"]:
1245
+ text += f" โ€ข {enc['status']}: {enc.get('progress', 0)}%\n"
1246
+
1247
+ await message.reply_text(text, parse_mode="markdown")
1248
+
1249
+ async def mystats_handler(client: Client, message: Message):
1250
+ """Handle /mystats command - show user's personal stats."""
1251
+ user_id = message.from_user.id
1252
+ stats = stats_manager.get_user_stats(user_id)
1253
+
1254
+ text = f"๐Ÿ“Š **Your Statistics**\n\n"
1255
+ text += f"**Downloads:**\n"
1256
+ text += f" โ€ข Total: {stats['downloads']['total']}\n"
1257
+ text += f" โ€ข Completed: {stats['downloads']['completed']}\n"
1258
+ text += f" โ€ข Success Rate: {stats['downloads']['success_rate']}%\n"
1259
+ text += f" โ€ข Last 7 Days: {stats['downloads']['recent_7d']}\n\n"
1260
+
1261
+ text += f"**Encodes:**\n"
1262
+ text += f" โ€ข Total: {stats['encodes']['total']}\n"
1263
+ text += f" โ€ข Completed: {stats['encodes']['completed']}\n"
1264
+ text += f" โ€ข Success Rate: {stats['encodes']['success_rate']}%\n"
1265
+ text += f" โ€ข Last 7 Days: {stats['encodes']['recent_7d']}\n\n"
1266
+
1267
+ if stats['favorite_anime']:
1268
+ text += f"**Top Anime:**\n"
1269
+ for i, anime in enumerate(stats['favorite_anime'][:5], 1):
1270
+ text += f" {i}. {anime['_id'][:30]}... ({anime['count']} downloads)\n"
1271
+
1272
+ await message.reply_text(text, parse_mode="markdown")
1273
+
1274
+ async def batch_encode_handler(client: Client, message: Message):
1275
+ """Handle /batchencode command - batch encode multiple files."""
1276
+ if not message.reply_to_message:
1277
+ await message.reply_text(
1278
+ "Reply to a message with multiple videos/documents to batch encode them.\n"
1279
+ "Usage: Reply to media โ†’ /batchencode"
1280
+ )
1281
+ return
1282
+
1283
+ reply = message.reply_to_message
1284
+ media_group = reply.media_group_id
1285
+
1286
+ # Get all files to encode
1287
+ files_to_encode = []
1288
+
1289
+ # Check if it's a media group
1290
+ if media_group:
1291
+ # Note: Media groups need special handling - in practice you'd cache them
1292
+ await message.reply_text("โ›” Media groups not supported yet. Send videos individually or one by one.")
1293
+ return
1294
+
1295
+ # Single file
1296
+ if reply.video:
1297
+ files_to_encode.append(("video", reply.video.file_id, reply.video.file_name or f"video_{reply.id}.mp4"))
1298
+ elif reply.document and reply.document.mime_type and 'video' in reply.document.mime_type:
1299
+ files_to_encode.append(("document", reply.document.file_id, reply.document.file_name or f"doc_{reply.id}.mp4"))
1300
+
1301
+ if not files_to_encode:
1302
+ await message.reply_text("โŒ No video files found in the replied message.")
1303
+ return
1304
+
1305
+ # Get user settings
1306
+ user_id = message.from_user.id
1307
+ settings = db.get_user_settings(user_id)
1308
+
1309
+ # Confirm batch encode
1310
+ text = f"๐ŸŽž๏ธ **Batch Encode**\n\n"
1311
+ text += f"Found **{len(files_to_encode)}** video(s) to encode.\n\n"
1312
+ text += f"**Settings:**\n"
1313
+ text += f" โ€ข Codec: `{settings.get('codec', 'libx264')}`\n"
1314
+ text += f" โ€ข CRF: `{settings.get('crf', 28)}`\n"
1315
+ text += f" โ€ข Preset: `{settings.get('preset', 'medium')}`\n\n"
1316
+ text += f"Reply with `yes` to confirm or `no` to cancel."
1317
+
1318
+ await message.reply_text(text, parse_mode="markdown")
1319
+
1320
+ # Note: In a full implementation, you'd use conversation handlers here
1321
+ # For now, just queue them directly
1322
+ status_msg = await message.reply_text("โณ Starting batch encode...")
1323
+
1324
+ queued = 0
1325
+ for file_type, file_id, filename in files_to_encode:
1326
+ try:
1327
+ # Create temp path
1328
+ temp_dir = Config.TEMP_DIR / str(user_id) / "batch_encode"
1329
+ temp_dir.mkdir(parents=True, exist_ok=True)
1330
+ temp_path = temp_dir / filename
1331
+
1332
+ # Download the file
1333
+ download_path = await reply.download(file_name=str(temp_path))
1334
+
1335
+ if download_path:
1336
+ # Queue for encoding
1337
+ task_id = str(uuid.uuid4())
1338
+ await task_queue.add_encode(
1339
+ task_id=task_id,
1340
+ input_path=str(download_path),
1341
+ user_id=user_id,
1342
+ settings=settings
1343
+ )
1344
+ queued += 1
1345
+
1346
+ except Exception as e:
1347
+ logger.error(f"Batch encode error for file {filename}: {e}")
1348
+
1349
+ await status_msg.edit_text(
1350
+ f"โœ… **Batch Encode Queued**\n\n"
1351
+ f"Successfully queued **{queued}/{len(files_to_encode)}** files for encoding.\n"
1352
+ f"Use /status to track progress."
1353
+ )
1354
+
1355
+ async def thumb_handler(client: Client, message: Message):
1356
+ """Handle /thumb command - generate thumbnail from video."""
1357
+ if not message.reply_to_message:
1358
+ await message.reply_text("Reply to a video with /thumb to generate a thumbnail.")
1359
+ return
1360
+
1361
+ reply = message.reply_to_message
1362
+ if not (reply.video or reply.document):
1363
+ await message.reply_text("Please reply to a video file.")
1364
+ return
1365
+
1366
+ # Get user settings
1367
+ user_id = message.from_user.id
1368
+ settings = db.get_user_settings(user_id)
1369
+
1370
+ # Get video filename
1371
+ filename = "video"
1372
+ if reply.video and reply.video.file_name:
1373
+ filename = Path(reply.video.file_name).stem
1374
+ elif reply.document and reply.document.file_name:
1375
+ filename = Path(reply.document.file_name).stem
1376
+
1377
+ status_msg = await message.reply_text("๐Ÿ–ผ๏ธ Generating thumbnail...")
1378
+
1379
+ try:
1380
+ # Download video temporarily
1381
+ temp_dir = Config.TEMP_DIR / str(user_id) / "thumbs"
1382
+ temp_dir.mkdir(parents=True, exist_ok=True)
1383
+
1384
+ video_path = await reply.download(file_name=str(temp_dir / "temp_video"))
1385
+
1386
+ if not video_path:
1387
+ await status_msg.edit_text("โŒ Failed to download video.")
1388
+ return
1389
+
1390
+ # Get user thumbnail settings
1391
+ thumb_res = settings.get("thumb_resolution", "720p")
1392
+ thumb_format = settings.get("thumb_format", "jpg")
1393
+ thumb_position = settings.get("thumb_position", "25%")
1394
+
1395
+ # Get resolution dimensions
1396
+ width, height = 1280, 720
1397
+ if thumb_res in thumbnail_generator.RESOLUTIONS:
1398
+ width, height = thumbnail_generator.RESOLUTIONS[thumb_res]
1399
+
1400
+ # Generate custom filename if user has pattern
1401
+ custom_name = settings.get("thumb_filename_template", "{filename}_thumb")
1402
+ thumb_filename = custom_name.replace("{filename}", filename) + f".{thumb_format}"
1403
+ thumb_path = temp_dir / thumb_filename
1404
+
1405
+ # Generate thumbnail
1406
+ result = thumbnail_generator.generate_thumbnail(
1407
+ Path(video_path),
1408
+ thumb_path,
1409
+ time_offset=thumb_position,
1410
+ width=width,
1411
+ height=height
1412
+ )
1413
+
1414
+ if result and result.exists():
1415
+ # Build caption from template
1416
+ caption_template = settings.get("thumb_caption_template", "๐Ÿ–ผ๏ธ Thumbnail of {filename}")
1417
+ caption = caption_template.replace("{filename}", filename)
1418
+ caption += f"\n๐Ÿ“ Resolution: {width}x{height}"
1419
+ caption += f"\n๏ฟฝ Position: {thumb_position}"
1420
+
1421
+ # Send thumbnail
1422
+ await message.reply_photo(
1423
+ photo=str(result),
1424
+ caption=caption,
1425
+ parse_mode="markdown"
1426
+ )
1427
+ await status_msg.delete()
1428
+ else:
1429
+ await status_msg.edit_text("โŒ Failed to generate thumbnail.")
1430
+
1431
+ # Cleanup
1432
+ try:
1433
+ Path(video_path).unlink(missing_ok=True)
1434
+ if result:
1435
+ result.unlink(missing_ok=True)
1436
+ except:
1437
+ pass
1438
+
1439
+ except Exception as e:
1440
+ logger.error(f"Thumbnail error: {e}")
1441
+ await status_msg.edit_text(f"โŒ Error: {e}")
1442
+
1443
+ async def stats_handler(client: Client, message: Message):
1444
+ """Handle /stats command (admin only)."""
1445
+ if not is_authorized(message.from_user.id):
1446
+ await message.reply_text("โ›” Admin only command.")
1447
+ return
1448
+
1449
+ # Get database stats
1450
+ total_downloads = db.downloads.count_documents({})
1451
+ total_encodes = db.encodes.count_documents({})
1452
+
1453
+ text = "๐Ÿ“ˆ **Bot Statistics**\n\n"
1454
+ text += f"๐Ÿ“ฅ Total Downloads: {total_downloads}\n"
1455
+ text += f"๐ŸŽž๏ธ Total Encodes: {total_encodes}\n"
1456
+
1457
+ await message.reply_text(text, parse_mode="markdown")
1458
+
1459
+ # ============== Register Handlers ==============
1460
+
1461
+ def register_handlers(app: Client):
1462
+ """Register all handlers with the bot."""
1463
+ # Commands
1464
+ app.on_message(filters.command("start") & filters.private)(start_handler)
1465
+ app.on_message(filters.command("help") & filters.private)(help_handler)
1466
+ app.on_message(filters.command("sites") & filters.private)(sites_handler)
1467
+ app.on_message(filters.command("anime") & filters.private)(anime_search_handler)
1468
+ app.on_message(filters.command("download") & filters.private)(download_command_handler)
1469
+ app.on_message(filters.command("ddl") & filters.private)(direct_download_handler)
1470
+ app.on_message(filters.command("encode") & filters.private)(encode_handler)
1471
+ app.on_message(filters.command("settings") & filters.private)(settings_handler)
1472
+ app.on_message(filters.command("status") & filters.private)(status_handler)
1473
+ app.on_message(filters.command("stats") & filters.private)(stats_handler)
1474
+ app.on_message(filters.command("mystats") & filters.private)(mystats_handler)
1475
+ app.on_message(filters.command("batchencode") & filters.private)(batch_encode_handler)
1476
+ app.on_message(filters.command("thumb") & filters.private)(thumb_handler)
1477
+
1478
+ # Callbacks - Main Menu
1479
+ app.on_callback_query(filters.regex("^menu_"))(menu_callback)
1480
+
1481
+ # Callbacks - Search
1482
+ app.on_callback_query(filters.regex("^search_all$|^search_site_select$"))(search_prompt_handler)
1483
+ app.on_callback_query(filters.regex("^search_prompt:"))(search_site_prompt_handler)
1484
+ app.on_callback_query(filters.regex("^search_site:"))(search_site_callback)
1485
+
1486
+ # Callbacks - Anime & Download
1487
+ app.on_callback_query(filters.regex("^anime_info:"))(anime_info_callback)
1488
+ app.on_callback_query(filters.regex("^anime_range:"))(anime_range_callback)
1489
+ app.on_callback_query(filters.regex("^download:"))(download_callback)
1490
+ app.on_callback_query(filters.regex("^download_all:"))(download_all_callback)
1491
+
1492
+ # Callbacks - Settings
1493
+ app.on_callback_query(filters.regex("^(set_|reset_|back)"))(settings_callback)
1494
+ app.on_callback_query(filters.regex("^(codec:|crf:|preset:|res:|audio_codec:)"))(setting_value_callback)
1495
+ app.on_callback_query(filters.regex("^rename_"))(rename_callback)
bot/main.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main entry point for Anime Encoder Bot."""
2
+ import logging
3
+ import sys
4
+ import asyncio
5
+ from pathlib import Path
6
+ from pyrogram import Client
7
+ from config import Config
8
+ from bot.handlers import register_handlers
9
+ from bot.task_queue import task_queue
10
+
11
+ # Setup logging
12
+ logging.basicConfig(
13
+ level=logging.INFO,
14
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15
+ handlers=[
16
+ logging.StreamHandler(sys.stdout),
17
+ logging.FileHandler("bot.log")
18
+ ]
19
+ )
20
+ logger = logging.getLogger(__name__)
21
+
22
+ async def main():
23
+ """Main function to start the bot."""
24
+ # Validate config
25
+ try:
26
+ Config.validate()
27
+ logger.info("Configuration validated successfully")
28
+ except ValueError as e:
29
+ logger.error(f"Configuration error: {e}")
30
+ sys.exit(1)
31
+
32
+ # Create Pyrogram client
33
+ app = Client(
34
+ "anime_encoder_bot",
35
+ api_id=Config.API_ID,
36
+ api_hash=Config.API_HASH,
37
+ bot_token=Config.BOT_TOKEN,
38
+ workdir="."
39
+ )
40
+
41
+ # Register handlers
42
+ register_handlers(app)
43
+ logger.info("Handlers registered")
44
+
45
+ # Start task queue
46
+ await task_queue.start()
47
+ logger.info("Task queue started")
48
+
49
+ # Start the bot
50
+ try:
51
+ logger.info("Starting bot...")
52
+ await app.start()
53
+
54
+ # Log startup
55
+ me = await app.get_me()
56
+ logger.info(f"Bot started: @{me.username}")
57
+
58
+ if Config.LOG_CHANNEL:
59
+ try:
60
+ await app.send_message(
61
+ Config.LOG_CHANNEL,
62
+ f"โœ… **Bot Started**\n@{me.username} is now online!"
63
+ )
64
+ except Exception as e:
65
+ logger.warning(f"Failed to send startup log: {e}")
66
+
67
+ # Keep running
68
+ await asyncio.Event().wait()
69
+
70
+ except KeyboardInterrupt:
71
+ logger.info("Shutting down...")
72
+ except Exception as e:
73
+ logger.error(f"Bot error: {e}")
74
+ finally:
75
+ # Stop task queue
76
+ await task_queue.stop()
77
+
78
+ # Stop the bot
79
+ await app.stop()
80
+ logger.info("Bot stopped")
81
+
82
+ if __name__ == "__main__":
83
+ asyncio.run(main())
bot/renamer.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """File renaming module with metadata support."""
2
+ import logging
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Dict, Optional, Any
6
+ from dataclasses import dataclass
7
+ from bot.encoder import encoder
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ @dataclass
12
+ class VideoMetadata:
13
+ """Video metadata container."""
14
+ title: str = "Unknown"
15
+ episode: str = ""
16
+ season: str = ""
17
+ quality: str = "Unknown"
18
+ codec: str = "Unknown"
19
+ audio_codec: str = "Unknown"
20
+ duration: str = ""
21
+ file_size: str = ""
22
+ year: str = ""
23
+ studio: str = ""
24
+ source_site: str = ""
25
+
26
+ def to_dict(self) -> Dict[str, str]:
27
+ """Convert to dictionary for template substitution."""
28
+ return {
29
+ "title": self.title,
30
+ "episode": self.episode,
31
+ "season": self.season,
32
+ "quality": self.quality,
33
+ "codec": self.codec,
34
+ "audio_codec": self.audio_codec,
35
+ "duration": self.duration,
36
+ "file_size": self.file_size,
37
+ "year": self.year,
38
+ "studio": self.studio,
39
+ "source_site": self.source_site,
40
+ }
41
+
42
+
43
+ class FileRenamer:
44
+ """Handles file renaming with metadata patterns."""
45
+
46
+ # Available metadata variables for patterns
47
+ AVAILABLE_VARS = [
48
+ "{title}", "{episode}", "{season}", "{quality}",
49
+ "{codec}", "{audio_codec}", "{duration}",
50
+ "{file_size}", "{year}", "{studio}", "{source_site}"
51
+ ]
52
+
53
+ # Default patterns
54
+ PATTERNS = {
55
+ "simple": "{title} - Ep{episode}",
56
+ "detailed": "{title} - S{season}E{episode} [{quality}]",
57
+ "with_codec": "{title} - Ep{episode} [{quality}] [{codec}]",
58
+ "with_site": "[{source_site}] {title} - Ep{episode} [{quality}]",
59
+ "anime_style": "[{studio}] {title} - {episode} [{quality}]",
60
+ "minimal": "{title}_{episode}"
61
+ }
62
+
63
+ def __init__(self):
64
+ self.safe_chars = re.compile(r'[<>:"/\\|?*]')
65
+
66
+ def extract_metadata(self, file_path: Path, anime_info: Optional[Dict] = None,
67
+ episode_num: Optional[int] = None) -> VideoMetadata:
68
+ """Extract metadata from video file and anime info."""
69
+ metadata = VideoMetadata()
70
+
71
+ # Get video info from encoder
72
+ try:
73
+ video_info = encoder.get_video_info(str(file_path))
74
+ if video_info:
75
+ # Parse streams from ffprobe output
76
+ streams = video_info.get('streams', [])
77
+ for stream in streams:
78
+ if stream.get('codec_type') == 'video':
79
+ metadata.codec = stream.get('codec_name', 'Unknown')
80
+ width = stream.get('width', 0)
81
+ height = stream.get('height', 0)
82
+ metadata.quality = f"{width}x{height}" if width and height else "Unknown"
83
+ # Get duration from format if available
84
+ format_info = video_info.get('format', {})
85
+ duration_sec = format_info.get('duration', '0')
86
+ if duration_sec:
87
+ try:
88
+ duration_float = float(duration_sec)
89
+ mins = int(duration_float // 60)
90
+ secs = int(duration_float % 60)
91
+ metadata.duration = f"{mins}m{secs}s"
92
+ except:
93
+ metadata.duration = str(duration_sec)
94
+ break
95
+
96
+ # Get audio info
97
+ audio_info = encoder.get_audio_info(str(file_path))
98
+ if audio_info:
99
+ metadata.audio_codec = audio_info.get('codec', 'Unknown')
100
+ except Exception as e:
101
+ logger.warning(f"Could not extract video metadata: {e}")
102
+
103
+ # Get file size
104
+ try:
105
+ size_bytes = file_path.stat().st_size
106
+ metadata.file_size = self._format_file_size(size_bytes)
107
+ except Exception:
108
+ pass
109
+
110
+ # Get anime info
111
+ if anime_info:
112
+ metadata.title = anime_info.get('title', 'Unknown')
113
+ metadata.studio = anime_info.get('studio', '')
114
+ metadata.year = str(anime_info.get('year', ''))
115
+ metadata.source_site = anime_info.get('source_site', '')
116
+
117
+ # Set episode number
118
+ if episode_num:
119
+ metadata.episode = str(episode_num).zfill(2)
120
+
121
+ return metadata
122
+
123
+ def _format_file_size(self, size_bytes: int) -> str:
124
+ """Format file size to human readable."""
125
+ for unit in ['B', 'KB', 'MB', 'GB']:
126
+ if size_bytes < 1024:
127
+ return f"{size_bytes:.1f}{unit}"
128
+ size_bytes /= 1024
129
+ return f"{size_bytes:.1f}TB"
130
+
131
+ def sanitize_filename(self, filename: str) -> str:
132
+ """Remove invalid characters from filename."""
133
+ # Replace invalid chars with underscore
134
+ sanitized = self.safe_chars.sub('_', filename)
135
+ # Limit length
136
+ if len(sanitized) > 200:
137
+ name, ext = Path(sanitized).stem, Path(sanitized).suffix
138
+ sanitized = name[:195] + ext
139
+ return sanitized
140
+
141
+ def generate_filename(self, pattern: str, metadata: VideoMetadata,
142
+ original_ext: str = ".mp4") -> str:
143
+ """Generate new filename from pattern and metadata."""
144
+ # Get metadata dict
145
+ meta_dict = metadata.to_dict()
146
+
147
+ # Replace variables in pattern
148
+ filename = pattern
149
+ for key, value in meta_dict.items():
150
+ placeholder = f"{{{key}}}"
151
+ if placeholder in filename:
152
+ filename = filename.replace(placeholder, str(value) if value else "")
153
+
154
+ # Clean up any empty brackets or leftover patterns
155
+ filename = re.sub(r'\[?\{[^}]+\}\]?', '', filename)
156
+ filename = re.sub(r'\[\s*\]', '', filename)
157
+ filename = re.sub(r'\s+', ' ', filename).strip()
158
+
159
+ # Add extension if not present
160
+ if not filename.endswith(original_ext):
161
+ filename += original_ext
162
+
163
+ return self.sanitize_filename(filename)
164
+
165
+ def rename_file(self, source_path: Path, pattern: str,
166
+ metadata: VideoMetadata) -> Optional[Path]:
167
+ """Rename file using pattern and metadata."""
168
+ try:
169
+ original_ext = source_path.suffix
170
+ new_filename = self.generate_filename(pattern, metadata, original_ext)
171
+ new_path = source_path.parent / new_filename
172
+
173
+ # Handle duplicates
174
+ counter = 1
175
+ base_new_path = new_path
176
+ while new_path.exists():
177
+ stem = base_new_path.stem
178
+ new_path = base_new_path.parent / f"{stem}_{counter}{original_ext}"
179
+ counter += 1
180
+
181
+ # Rename
182
+ source_path.rename(new_path)
183
+ logger.info(f"Renamed: {source_path.name} -> {new_path.name}")
184
+ return new_path
185
+
186
+ except Exception as e:
187
+ logger.error(f"Rename failed: {e}")
188
+ return None
189
+
190
+ def preview_rename(self, pattern: str, metadata: VideoMetadata,
191
+ original_name: str = "video.mp4") -> str:
192
+ """Preview what the new filename would be."""
193
+ original_ext = Path(original_name).suffix
194
+ return self.generate_filename(pattern, metadata, original_ext)
195
+
196
+ def get_pattern_help(self) -> str:
197
+ """Get help text for available patterns."""
198
+ help_text = "๐Ÿ“‹ **Available Pattern Variables:**\n\n"
199
+ for var in self.AVAILABLE_VARS:
200
+ help_text += f" `{var}`\n"
201
+
202
+ help_text += "\n๐Ÿ“ **Example Patterns:**\n\n"
203
+ for name, pattern in self.PATTERNS.items():
204
+ help_text += f" **{name}**: `{pattern}`\n"
205
+
206
+ help_text += "\n๐Ÿ’ก **Example Output:**\n"
207
+ example_meta = VideoMetadata(
208
+ title="Attack on Titan",
209
+ episode="05",
210
+ quality="1920x1080",
211
+ codec="H.264",
212
+ source_site="GogoAnime"
213
+ )
214
+ help_text += f" Pattern: `{{title}} - Ep{{episode}} [{{quality}}]`\n"
215
+ help_text += f" Result: `{self.generate_filename('{title} - Ep{episode} [{quality}]', example_meta)}`\n"
216
+
217
+ return help_text
218
+
219
+
220
+ # Global instance
221
+ renamer = FileRenamer()
bot/sites.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Supported anime streaming sites configuration."""
2
+
3
+ # Site configurations with their extractors
4
+ SUPPORTED_SITES = {
5
+ "gogoanime": {
6
+ "name": "GogoAnime",
7
+ "base_url": "https://gogoanime3.co",
8
+ "searchable": True,
9
+ "extractor": "animdl",
10
+ "quality": ["1080p", "720p", "480p", "360p"],
11
+ "sub": ["sub", "dub"]
12
+ },
13
+ "9anime": {
14
+ "name": "9Anime",
15
+ "base_url": "https://9anime.to",
16
+ "searchable": True,
17
+ "extractor": "animdl",
18
+ "quality": ["1080p", "720p", "480p", "360p"],
19
+ "sub": ["sub", "dub"]
20
+ },
21
+ "animepahe": {
22
+ "name": "AnimePahe",
23
+ "base_url": "https://animepahe.com",
24
+ "searchable": True,
25
+ "extractor": "animdl",
26
+ "quality": ["1080p", "720p", "480p", "360p"],
27
+ "sub": ["sub", "dub"]
28
+ },
29
+ "zoro": {
30
+ "name": "Zoro.to (AniWatch)",
31
+ "base_url": "https://zoro.to",
32
+ "searchable": True,
33
+ "extractor": "animdl",
34
+ "quality": ["1080p", "720p", "480p", "360p"],
35
+ "sub": ["sub", "dub"]
36
+ },
37
+ "animixplay": {
38
+ "name": "AnimixPlay",
39
+ "base_url": "https://animixplay.to",
40
+ "searchable": True,
41
+ "extractor": "animdl",
42
+ "quality": ["1080p", "720p", "480p", "360p"],
43
+ "sub": ["sub", "dub"]
44
+ },
45
+ "allanime": {
46
+ "name": "AllAnime",
47
+ "base_url": "https://allanime.to",
48
+ "searchable": True,
49
+ "extractor": "animdl",
50
+ "quality": ["1080p", "720p", "480p", "360p"],
51
+ "sub": ["sub", "dub"]
52
+ },
53
+ "crunchyroll": {
54
+ "name": "Crunchyroll",
55
+ "base_url": "https://crunchyroll.com",
56
+ "searchable": False, # Requires auth
57
+ "extractor": "yt-dlp",
58
+ "quality": ["1080p", "720p", "480p", "360p"],
59
+ "sub": ["sub", "dub"],
60
+ "auth_required": True
61
+ },
62
+ "nyaa": {
63
+ "name": "Nyaa.si (Torrents)",
64
+ "base_url": "https://nyaa.si",
65
+ "searchable": True,
66
+ "extractor": "animdl",
67
+ "quality": ["1080p", "720p", "480p"],
68
+ "sub": ["sub"]
69
+ },
70
+ }
71
+
72
+ # Default site preference order
73
+ DEFAULT_SITE_ORDER = ["gogoanime", "zoro", "animepahe", "9anime", "allanime", "animixplay"]
74
+
75
+ # Site-specific quality mappings
76
+ QUALITY_PREFERENCES = {
77
+ "1080p": ["1080p", "1080", "fhd", "fullhd"],
78
+ "720p": ["720p", "720", "hd"],
79
+ "480p": ["480p", "480", "sd"],
80
+ "360p": ["360p", "360"],
81
+ }
82
+
83
+ SUB_PREFERENCES = {
84
+ "sub": ["sub", "softsub", "hardcoded"],
85
+ "dub": ["dub", "english"],
86
+ }
87
+
88
+ def get_site_info(site_id: str) -> dict:
89
+ """Get information about a specific site."""
90
+ return SUPPORTED_SITES.get(site_id, {})
91
+
92
+ def get_searchable_sites() -> list:
93
+ """Get list of sites that support searching."""
94
+ return [site_id for site_id, info in SUPPORTED_SITES.items() if info.get("searchable")]
95
+
96
+ def get_site_name(site_id: str) -> str:
97
+ """Get display name for a site."""
98
+ info = get_site_info(site_id)
99
+ return info.get("name", site_id)
100
+
101
+ def is_site_supported(site_id: str) -> bool:
102
+ """Check if a site is supported."""
103
+ return site_id in SUPPORTED_SITES
bot/stats.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Statistics module for user and bot analytics."""
2
+ import logging
3
+ from datetime import datetime, timedelta
4
+ from typing import Dict, List, Any, Optional
5
+ from collections import defaultdict
6
+
7
+ from bot.database import db
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class StatsManager:
13
+ """Manage statistics for users and bot."""
14
+
15
+ def get_user_stats(self, user_id: int) -> Dict[str, Any]:
16
+ """Get statistics for a specific user."""
17
+ # Get download stats
18
+ total_downloads = db.downloads.count_documents({"user_id": user_id})
19
+ completed_downloads = db.downloads.count_documents(
20
+ {"user_id": user_id, "status": "completed"}
21
+ )
22
+ failed_downloads = db.downloads.count_documents(
23
+ {"user_id": user_id, "status": "failed"}
24
+ )
25
+
26
+ # Get encode stats
27
+ total_encodes = db.encodes.count_documents({"user_id": user_id})
28
+ completed_encodes = db.encodes.count_documents(
29
+ {"user_id": user_id, "status": "completed"}
30
+ )
31
+ failed_encodes = db.encodes.count_documents(
32
+ {"user_id": user_id, "status": "failed"}
33
+ )
34
+
35
+ # Get recent activity (last 7 days)
36
+ week_ago = datetime.utcnow() - timedelta(days=7)
37
+ recent_downloads = db.downloads.count_documents({
38
+ "user_id": user_id,
39
+ "created_at": {"$gte": week_ago}
40
+ })
41
+ recent_encodes = db.encodes.count_documents({
42
+ "user_id": user_id,
43
+ "created_at": {"$gte": week_ago}
44
+ })
45
+
46
+ # Get favorite anime (most downloaded)
47
+ pipeline = [
48
+ {"$match": {"user_id": user_id}},
49
+ {"$group": {"_id": "$anime_id", "count": {"$sum": 1}}},
50
+ {"$sort": {"count": -1}},
51
+ {"$limit": 5}
52
+ ]
53
+ favorite_anime = list(db.downloads.aggregate(pipeline))
54
+
55
+ return {
56
+ "user_id": user_id,
57
+ "downloads": {
58
+ "total": total_downloads,
59
+ "completed": completed_downloads,
60
+ "failed": failed_downloads,
61
+ "success_rate": self._calc_rate(completed_downloads, total_downloads),
62
+ "recent_7d": recent_downloads
63
+ },
64
+ "encodes": {
65
+ "total": total_encodes,
66
+ "completed": completed_encodes,
67
+ "failed": failed_encodes,
68
+ "success_rate": self._calc_rate(completed_encodes, total_encodes),
69
+ "recent_7d": recent_encodes
70
+ },
71
+ "favorite_anime": favorite_anime,
72
+ "last_updated": datetime.utcnow()
73
+ }
74
+
75
+ def get_bot_stats(self) -> Dict[str, Any]:
76
+ """Get overall bot statistics (admin only)."""
77
+ # Total counts
78
+ total_downloads = db.downloads.count_documents({})
79
+ total_encodes = db.encodes.count_documents({})
80
+ total_users = db.users.count_documents({})
81
+
82
+ # Status breakdown
83
+ download_status = self._get_status_breakdown("downloads")
84
+ encode_status = self._get_status_breakdown("encodes")
85
+
86
+ # Activity over time (last 30 days)
87
+ daily_stats = self._get_daily_stats(days=30)
88
+
89
+ # Top active users
90
+ top_users_pipeline = [
91
+ {
92
+ "$group": {
93
+ "_id": "$user_id",
94
+ "downloads": {"$sum": 1}
95
+ }
96
+ },
97
+ {"$sort": {"downloads": -1}},
98
+ {"$limit": 10}
99
+ ]
100
+ top_users = list(db.downloads.aggregate(top_users_pipeline))
101
+
102
+ # Popular anime
103
+ popular_anime_pipeline = [
104
+ {"$group": {"_id": "$anime_id", "downloads": {"$sum": 1}}},
105
+ {"$sort": {"downloads": -1}},
106
+ {"$limit": 10}
107
+ ]
108
+ popular_anime = list(db.downloads.aggregate(popular_anime_pipeline))
109
+
110
+ # Storage usage estimate
111
+ storage_stats = self._estimate_storage()
112
+
113
+ return {
114
+ "overview": {
115
+ "total_users": total_users,
116
+ "total_downloads": total_downloads,
117
+ "total_encodes": total_encodes,
118
+ "active_downloads": download_status.get("downloading", 0),
119
+ "active_encodes": encode_status.get("encoding", 0)
120
+ },
121
+ "download_status": download_status,
122
+ "encode_status": encode_status,
123
+ "daily_activity": daily_stats,
124
+ "top_users": top_users,
125
+ "popular_anime": popular_anime,
126
+ "storage": storage_stats,
127
+ "last_updated": datetime.utcnow()
128
+ }
129
+
130
+ def get_leaderboard(self, period: str = "all") -> List[Dict[str, Any]]:
131
+ """Get user leaderboard by activity.
132
+
133
+ Args:
134
+ period: "all", "week", or "month"
135
+ """
136
+ match_filter = {}
137
+
138
+ if period == "week":
139
+ match_filter["created_at"] = {
140
+ "$gte": datetime.utcnow() - timedelta(days=7)
141
+ }
142
+ elif period == "month":
143
+ match_filter["created_at"] = {
144
+ "$gte": datetime.utcnow() - timedelta(days=30)
145
+ }
146
+
147
+ # Combine downloads and encodes
148
+ download_pipeline = [
149
+ {"$match": match_filter},
150
+ {"$group": {"_id": "$user_id", "downloads": {"$sum": 1}}}
151
+ ]
152
+ downloads_by_user = list(db.downloads.aggregate(download_pipeline))
153
+
154
+ encode_pipeline = [
155
+ {"$match": match_filter},
156
+ {"$group": {"_id": "$user_id", "encodes": {"$sum": 1}}}
157
+ ]
158
+ encodes_by_user = list(db.encodes.aggregate(encode_pipeline))
159
+
160
+ # Merge results
161
+ user_scores = defaultdict(lambda: {"downloads": 0, "encodes": 0})
162
+
163
+ for item in downloads_by_user:
164
+ user_scores[item["_id"]]["downloads"] = item["downloads"]
165
+
166
+ for item in encodes_by_user:
167
+ user_scores[item["_id"]]["encodes"] = item["encodes"]
168
+
169
+ # Calculate total score and sort
170
+ leaderboard = []
171
+ for user_id, scores in user_scores.items():
172
+ leaderboard.append({
173
+ "user_id": user_id,
174
+ "downloads": scores["downloads"],
175
+ "encodes": scores["encodes"],
176
+ "total": scores["downloads"] + scores["encodes"]
177
+ })
178
+
179
+ leaderboard.sort(key=lambda x: x["total"], reverse=True)
180
+ return leaderboard[:20] # Top 20
181
+
182
+ def _get_status_breakdown(self, collection: str) -> Dict[str, int]:
183
+ """Get status breakdown for a collection."""
184
+ coll = db.downloads if collection == "downloads" else db.encodes
185
+
186
+ pipeline = [
187
+ {"$group": {"_id": "$status", "count": {"$sum": 1}}}
188
+ ]
189
+ results = list(coll.aggregate(pipeline))
190
+
191
+ return {item["_id"]: item["count"] for item in results}
192
+
193
+ def _get_daily_stats(self, days: int = 30) -> List[Dict[str, Any]]:
194
+ """Get daily activity stats."""
195
+ start_date = datetime.utcnow() - timedelta(days=days)
196
+
197
+ # Daily downloads
198
+ download_pipeline = [
199
+ {"$match": {"created_at": {"$gte": start_date}}},
200
+ {
201
+ "$group": {
202
+ "_id": {
203
+ "$dateToString": {"format": "%Y-%m-%d", "date": "$created_at"}
204
+ },
205
+ "count": {"$sum": 1}
206
+ }
207
+ },
208
+ {"$sort": {"_id": 1}}
209
+ ]
210
+ daily_downloads = list(db.downloads.aggregate(download_pipeline))
211
+
212
+ # Daily encodes
213
+ encode_pipeline = [
214
+ {"$match": {"created_at": {"$gte": start_date}}},
215
+ {
216
+ "$group": {
217
+ "_id": {
218
+ "$dateToString": {"format": "%Y-%m-%d", "date": "$created_at"}
219
+ },
220
+ "count": {"$sum": 1}
221
+ }
222
+ },
223
+ {"$sort": {"_id": 1}}
224
+ ]
225
+ daily_encodes = list(db.encodes.aggregate(encode_pipeline))
226
+
227
+ # Merge
228
+ dates = set()
229
+ for d in daily_downloads + daily_encodes:
230
+ dates.add(d["_id"])
231
+
232
+ result = []
233
+ for date in sorted(dates):
234
+ dl_count = next((d["count"] for d in daily_downloads if d["_id"] == date), 0)
235
+ enc_count = next((e["count"] for e in daily_encodes if e["_id"] == date), 0)
236
+ result.append({
237
+ "date": date,
238
+ "downloads": dl_count,
239
+ "encodes": enc_count,
240
+ "total": dl_count + enc_count
241
+ })
242
+
243
+ return result
244
+
245
+ def _estimate_storage(self) -> Dict[str, Any]:
246
+ """Estimate storage usage (rough approximation)."""
247
+ # This is a rough estimate based on average file sizes
248
+ # In production, you'd want to actually scan directories
249
+ avg_download_size_mb = 200 # Average anime episode
250
+ avg_encode_size_mb = 150 # Average encoded file
251
+
252
+ total_downloads = db.downloads.count_documents({"status": "completed"})
253
+ total_encodes = db.encodes.count_documents({"status": "completed"})
254
+
255
+ downloads_mb = total_downloads * avg_download_size_mb
256
+ encodes_mb = total_encodes * avg_encode_size_mb
257
+
258
+ return {
259
+ "downloads_mb": downloads_mb,
260
+ "encodes_mb": encodes_mb,
261
+ "total_mb": downloads_mb + encodes_mb,
262
+ "total_gb": round((downloads_mb + encodes_mb) / 1024, 2),
263
+ "note": "Estimated based on average file sizes"
264
+ }
265
+
266
+ def _calc_rate(self, completed: int, total: int) -> float:
267
+ """Calculate success rate percentage."""
268
+ if total == 0:
269
+ return 0.0
270
+ return round((completed / total) * 100, 1)
271
+
272
+
273
+ # Global instance
274
+ stats_manager = StatsManager()
bot/task_queue.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task queue management for downloads and encodings."""
2
+ import asyncio
3
+ import logging
4
+ import uuid
5
+ from typing import Dict, Any, Callable, Optional
6
+ from config import Config
7
+ from bot.database import db
8
+ from bot.downloader import downloader
9
+ from bot.encoder import encoder
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ class TaskQueue:
14
+ """Manages download and encoding queues with concurrency limits."""
15
+
16
+ def __init__(self):
17
+ self.download_queue: asyncio.Queue = asyncio.Queue()
18
+ self.encode_queue: asyncio.Queue = asyncio.Queue()
19
+ self.download_semaphore = asyncio.Semaphore(Config.MAX_CONCURRENT_DOWNLOADS)
20
+ self.encode_semaphore = asyncio.Semaphore(Config.MAX_CONCURRENT_ENCODINGS)
21
+ self.running = False
22
+ self.tasks: list = []
23
+ self._progress_callbacks: Dict[str, Callable] = {}
24
+
25
+ def register_progress_callback(self, task_id: str, callback: Callable):
26
+ """Register a progress callback for a task."""
27
+ self._progress_callbacks[task_id] = callback
28
+
29
+ def unregister_progress_callback(self, task_id: str):
30
+ """Unregister a progress callback."""
31
+ self._progress_callbacks.pop(task_id, None)
32
+
33
+ async def start(self):
34
+ """Start the queue workers."""
35
+ self.running = True
36
+
37
+ # Start download workers
38
+ for i in range(Config.MAX_CONCURRENT_DOWNLOADS):
39
+ task = asyncio.create_task(self._download_worker())
40
+ self.tasks.append(task)
41
+
42
+ # Start encode workers
43
+ for i in range(Config.MAX_CONCURRENT_ENCODINGS):
44
+ task = asyncio.create_task(self._encode_worker())
45
+ self.tasks.append(task)
46
+
47
+ # Start queue monitor
48
+ monitor_task = asyncio.create_task(self._monitor_queue())
49
+ self.tasks.append(monitor_task)
50
+
51
+ logger.info("Task queue started")
52
+
53
+ async def stop(self):
54
+ """Stop the queue workers."""
55
+ self.running = False
56
+
57
+ # Cancel all active downloads and encodes
58
+ for task_id in list(downloader.active_downloads.keys()):
59
+ downloader.cancel_download(task_id)
60
+
61
+ for task_id in list(encoder.active_encodes.keys()):
62
+ encoder.cancel_encode(task_id)
63
+
64
+ # Cancel workers
65
+ for task in self.tasks:
66
+ task.cancel()
67
+
68
+ await asyncio.gather(*self.tasks, return_exceptions=True)
69
+ logger.info("Task queue stopped")
70
+
71
+ async def _monitor_queue(self):
72
+ """Monitor queue and add pending tasks from database."""
73
+ while self.running:
74
+ try:
75
+ # Check for pending downloads in database
76
+ pending_downloads = db.get_pending_downloads()
77
+ for dl in pending_downloads:
78
+ await self.add_download(
79
+ task_id=dl["task_id"],
80
+ anime_url=dl["anime_id"],
81
+ episode_num=dl.get("episode_num", 1),
82
+ user_id=dl["user_id"]
83
+ )
84
+
85
+ # Check for pending encodes in database
86
+ pending_encodes = db.get_pending_encodes()
87
+ for enc in pending_encodes:
88
+ await self.add_encode(
89
+ task_id=enc["task_id"],
90
+ input_path=enc["input_path"],
91
+ user_id=enc["user_id"],
92
+ settings=enc.get("settings", {})
93
+ )
94
+
95
+ await asyncio.sleep(5) # Check every 5 seconds
96
+
97
+ except Exception as e:
98
+ logger.error(f"Queue monitor error: {e}")
99
+ await asyncio.sleep(10)
100
+
101
+ async def add_download(self, task_id: str, anime_url: str,
102
+ episode_num: int, user_id: int,
103
+ site: Optional[str] = None) -> str:
104
+ """Add a download task to the queue."""
105
+ task = {
106
+ "task_id": task_id,
107
+ "type": "download",
108
+ "anime_url": anime_url,
109
+ "episode_num": episode_num,
110
+ "user_id": user_id,
111
+ "site": site
112
+ }
113
+ await self.download_queue.put(task)
114
+ logger.info(f"Added download task {task_id} to queue (site: {site})")
115
+ return task_id
116
+
117
+ async def add_encode(self, task_id: str, input_path: str,
118
+ user_id: int, settings: Dict[str, Any]) -> str:
119
+ """Add an encode task to the queue."""
120
+ task = {
121
+ "task_id": task_id,
122
+ "type": "encode",
123
+ "input_path": input_path,
124
+ "user_id": user_id,
125
+ "settings": settings
126
+ }
127
+ await self.encode_queue.put(task)
128
+ logger.info(f"Added encode task {task_id} to queue")
129
+ return task_id
130
+
131
+ async def _download_worker(self):
132
+ """Worker to process download tasks."""
133
+ while self.running:
134
+ try:
135
+ task = await asyncio.wait_for(self.download_queue.get(), timeout=1.0)
136
+ except asyncio.TimeoutError:
137
+ continue
138
+
139
+ async with self.download_semaphore:
140
+ await self._process_download(task)
141
+ self.download_queue.task_done()
142
+
143
+ async def _encode_worker(self):
144
+ """Worker to process encode tasks."""
145
+ while self.running:
146
+ try:
147
+ task = await asyncio.wait_for(self.encode_queue.get(), timeout=1.0)
148
+ except asyncio.TimeoutError:
149
+ continue
150
+
151
+ async with self.encode_semaphore:
152
+ await self._process_encode(task)
153
+ self.encode_queue.task_done()
154
+
155
+ async def _process_download(self, task: Dict):
156
+ """Process a single download task."""
157
+ task_id = task["task_id"]
158
+ anime_url = task["anime_url"]
159
+ episode_num = task["episode_num"]
160
+ user_id = task["user_id"]
161
+ site = task.get("site")
162
+
163
+ progress_callback = self._progress_callbacks.get(task_id)
164
+
165
+ def sync_download():
166
+ def wrapped_progress(progress: int, message: str):
167
+ if progress_callback:
168
+ # Schedule callback in event loop
169
+ asyncio.create_task(self._safe_callback(progress_callback, progress, message))
170
+
171
+ return downloader.download_episode(
172
+ anime_url=anime_url,
173
+ episode_num=episode_num,
174
+ user_id=user_id,
175
+ site=site,
176
+ progress_callback=wrapped_progress if progress_callback else None
177
+ )
178
+
179
+ try:
180
+ loop = asyncio.get_event_loop()
181
+ result = await loop.run_in_executor(None, sync_download)
182
+
183
+ if result:
184
+ # Apply renaming if enabled
185
+ settings = db.get_user_settings(user_id)
186
+ if settings.get("auto_rename", True):
187
+ try:
188
+ from bot.renamer import renamer
189
+ from pathlib import Path
190
+
191
+ # Get anime info for metadata
192
+ anime_info = await loop.run_in_executor(
193
+ None, lambda: downloader.get_anime_info(anime_url, site)
194
+ )
195
+ if anime_info:
196
+ anime_info["source_site"] = site or ""
197
+
198
+ # Extract metadata
199
+ metadata = renamer.extract_metadata(
200
+ Path(result),
201
+ anime_info=anime_info,
202
+ episode_num=episode_num
203
+ )
204
+
205
+ # Rename file
206
+ pattern = settings.get("rename_pattern", Config.DEFAULT_RENAME_PATTERN)
207
+ new_path = renamer.rename_file(
208
+ Path(result),
209
+ pattern,
210
+ metadata
211
+ )
212
+ if new_path:
213
+ result = new_path
214
+ logger.info(f"Renamed download to: {new_path.name}")
215
+ except Exception as e:
216
+ logger.warning(f"Rename failed for download: {e}")
217
+
218
+ if task.get("auto_encode"):
219
+ # Auto-encode after download
220
+ await self.add_encode(
221
+ task_id=str(uuid.uuid4()),
222
+ input_path=str(result),
223
+ user_id=user_id,
224
+ settings=settings
225
+ )
226
+
227
+ except Exception as e:
228
+ logger.error(f"Download task {task_id} failed: {e}")
229
+ finally:
230
+ self.unregister_progress_callback(task_id)
231
+
232
+ async def _process_encode(self, task: Dict):
233
+ """Process a single encode task."""
234
+ from pathlib import Path
235
+
236
+ task_id = task["task_id"]
237
+ input_path = Path(task["input_path"])
238
+ user_id = task["user_id"]
239
+ settings = task["settings"]
240
+
241
+ progress_callback = self._progress_callbacks.get(task_id)
242
+
243
+ def sync_encode():
244
+ def wrapped_progress(progress: int, message: str):
245
+ if progress_callback:
246
+ asyncio.create_task(self._safe_callback(progress_callback, progress, message))
247
+
248
+ return encoder.encode_video(
249
+ input_path=input_path,
250
+ user_id=user_id,
251
+ settings=settings,
252
+ progress_callback=wrapped_progress if progress_callback else None
253
+ )
254
+
255
+ try:
256
+ loop = asyncio.get_event_loop()
257
+ result = await loop.run_in_executor(None, sync_encode)
258
+
259
+ if result:
260
+ logger.info(f"Encode task {task_id} completed: {result}")
261
+
262
+ # Apply renaming if enabled
263
+ if settings.get("auto_rename", True):
264
+ try:
265
+ from bot.renamer import renamer
266
+
267
+ # Extract metadata from encoded file
268
+ metadata = renamer.extract_metadata(Path(result))
269
+
270
+ # Use encode-specific pattern or default
271
+ pattern = settings.get("rename_pattern", Config.DEFAULT_RENAME_PATTERN)
272
+ # Add [ENCODED] tag for encoded files
273
+ pattern = pattern.replace("{title}", "{title} [ENCODED]")
274
+
275
+ new_path = renamer.rename_file(
276
+ Path(result),
277
+ pattern,
278
+ metadata
279
+ )
280
+ if new_path:
281
+ result = new_path
282
+ logger.info(f"Renamed encode to: {new_path.name}")
283
+ except Exception as e:
284
+ logger.warning(f"Rename failed for encode: {e}")
285
+ else:
286
+ logger.error(f"Encode task {task_id} failed")
287
+
288
+ except Exception as e:
289
+ logger.error(f"Encode task {task_id} failed: {e}")
290
+ finally:
291
+ self.unregister_progress_callback(task_id)
292
+
293
+ async def _safe_callback(self, callback: Callable, *args, **kwargs):
294
+ """Safely invoke a callback, catching exceptions."""
295
+ try:
296
+ if asyncio.iscoroutinefunction(callback):
297
+ await callback(*args, **kwargs)
298
+ else:
299
+ callback(*args, **kwargs)
300
+ except Exception as e:
301
+ logger.error(f"Callback error: {e}")
302
+
303
+ def get_queue_status(self) -> Dict[str, Any]:
304
+ """Get current queue status."""
305
+ active = db.get_active_tasks()
306
+ return {
307
+ "download_queue_size": self.download_queue.qsize(),
308
+ "encode_queue_size": self.encode_queue.qsize(),
309
+ "active_downloads": active["downloads"],
310
+ "active_encodes": active["encodes"],
311
+ "max_downloads": Config.MAX_CONCURRENT_DOWNLOADS,
312
+ "max_encodes": Config.MAX_CONCURRENT_ENCODINGS
313
+ }
314
+
315
+ # Global queue instance
316
+ task_queue = TaskQueue()
bot/thumbnail.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thumbnail generation module for anime encoder bot."""
2
+ import logging
3
+ import subprocess
4
+ from pathlib import Path
5
+ from typing import Optional, List, Dict, Any
6
+ import random
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class ThumbnailGenerator:
12
+ """Generate thumbnails from video files."""
13
+
14
+ # Resolution presets
15
+ RESOLUTIONS = {
16
+ "1080p": (1920, 1080),
17
+ "720p": (1280, 720),
18
+ "480p": (854, 480),
19
+ "360p": (640, 360),
20
+ "240p": (427, 240),
21
+ "180p": (320, 180)
22
+ }
23
+
24
+ # Position presets for thumbnail extraction
25
+ POSITIONS = {
26
+ "start": "00:00:05",
27
+ "10%": "10%",
28
+ "25%": "25%",
29
+ "middle": "50%",
30
+ "75%": "75%",
31
+ "90%": "90%",
32
+ "end": "95%"
33
+ }
34
+
35
+ def __init__(self, ffmpeg_path: str = "ffmpeg"):
36
+ self.ffmpeg_path = ffmpeg_path
37
+
38
+ def generate_thumbnail(self, video_path: Path, output_path: Path,
39
+ time_offset: Optional[str] = None,
40
+ width: int = 1280, height: int = 720,
41
+ settings: Optional[Dict[str, Any]] = None) -> Optional[Path]:
42
+ """Generate a thumbnail from video at specified time.
43
+
44
+ Args:
45
+ video_path: Path to input video
46
+ output_path: Path to save thumbnail
47
+ time_offset: Time position (e.g., "00:05:30" or percentage like "25%")
48
+ width: Thumbnail width
49
+ height: Thumbnail height
50
+
51
+ Returns:
52
+ Path to generated thumbnail or None if failed
53
+ """
54
+ try:
55
+ # If no time specified, use 25% into the video
56
+ if not time_offset:
57
+ # Get video duration first
58
+ duration = self._get_duration(video_path)
59
+ if duration > 0:
60
+ # Use 25% mark or 5 minutes, whichever is smaller
61
+ target_time = min(duration * 0.25, 300)
62
+ time_offset = self._seconds_to_timecode(target_time)
63
+ else:
64
+ time_offset = "00:00:05"
65
+
66
+ # Ensure output directory exists
67
+ output_path.parent.mkdir(parents=True, exist_ok=True)
68
+
69
+ cmd = [
70
+ self.ffmpeg_path,
71
+ "-ss", time_offset,
72
+ "-i", str(video_path),
73
+ "-vframes", "1",
74
+ "-vf", f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black",
75
+ "-q:v", "2",
76
+ "-y",
77
+ str(output_path)
78
+ ]
79
+
80
+ result = subprocess.run(cmd, capture_output=True, text=True)
81
+
82
+ if result.returncode == 0 and output_path.exists():
83
+ logger.info(f"Thumbnail generated: {output_path}")
84
+ return output_path
85
+ else:
86
+ logger.error(f"Thumbnail generation failed: {result.stderr}")
87
+ return None
88
+
89
+ except Exception as e:
90
+ logger.error(f"Thumbnail generation error: {e}")
91
+ return None
92
+
93
+ def generate_multiple_thumbnails(self, video_path: Path,
94
+ output_dir: Path,
95
+ count: int = 5) -> List[Path]:
96
+ """Generate multiple thumbnails at different timestamps.
97
+
98
+ Args:
99
+ video_path: Path to input video
100
+ output_dir: Directory to save thumbnails
101
+ count: Number of thumbnails to generate
102
+
103
+ Returns:
104
+ List of generated thumbnail paths
105
+ """
106
+ thumbnails = []
107
+
108
+ try:
109
+ duration = self._get_duration(video_path)
110
+ if duration <= 0:
111
+ return thumbnails
112
+
113
+ # Generate thumbnails at evenly spaced intervals
114
+ # Skip first and last 10% to avoid intros/outros
115
+ start = duration * 0.1
116
+ end = duration * 0.9
117
+ step = (end - start) / count if count > 1 else (end - start)
118
+
119
+ for i in range(count):
120
+ timestamp = start + (step * i)
121
+ timecode = self._seconds_to_timecode(timestamp)
122
+
123
+ output_path = output_dir / f"thumb_{i+1:02d}.jpg"
124
+
125
+ thumb = self.generate_thumbnail(
126
+ video_path,
127
+ output_path,
128
+ time_offset=timecode,
129
+ width=320, # Smaller for preview
130
+ height=180
131
+ )
132
+ if thumb:
133
+ thumbnails.append(thumb)
134
+
135
+ return thumbnails
136
+
137
+ except Exception as e:
138
+ logger.error(f"Multiple thumbnail generation error: {e}")
139
+ return thumbnails
140
+
141
+ def generate_preview_gif(self, video_path: Path, output_path: Path,
142
+ duration: int = 3, fps: int = 2) -> Optional[Path]:
143
+ """Generate a short preview GIF/animation.
144
+
145
+ Args:
146
+ video_path: Path to input video
147
+ output_path: Path to save GIF
148
+ duration: Duration of GIF in seconds
149
+ fps: Frames per second
150
+
151
+ Returns:
152
+ Path to generated GIF or None if failed
153
+ """
154
+ try:
155
+ # Get a random position in the middle 60% of the video
156
+ video_duration = self._get_duration(video_path)
157
+ if video_duration > 0:
158
+ start_time = (video_duration * 0.2) + random.random() * (video_duration * 0.6)
159
+ start_timecode = self._seconds_to_timecode(start_time)
160
+ else:
161
+ start_timecode = "00:05:00"
162
+
163
+ output_path.parent.mkdir(parents=True, exist_ok=True)
164
+
165
+ cmd = [
166
+ self.ffmpeg_path,
167
+ "-ss", start_timecode,
168
+ "-t", str(duration),
169
+ "-i", str(video_path),
170
+ "-vf", f"fps={fps},scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen=[s1]paletteuse",
171
+ "-loop", "0",
172
+ "-y",
173
+ str(output_path)
174
+ ]
175
+
176
+ result = subprocess.run(cmd, capture_output=True, text=True)
177
+
178
+ if result.returncode == 0 and output_path.exists():
179
+ logger.info(f"Preview GIF generated: {output_path}")
180
+ return output_path
181
+ else:
182
+ logger.error(f"GIF generation failed: {result.stderr}")
183
+ return None
184
+
185
+ except Exception as e:
186
+ logger.error(f"GIF generation error: {e}")
187
+ return None
188
+
189
+ def _get_duration(self, video_path: Path) -> float:
190
+ """Get video duration in seconds."""
191
+ try:
192
+ cmd = [
193
+ "ffprobe",
194
+ "-v", "error",
195
+ "-show_entries", "format=duration",
196
+ "-of", "default=noprint_wrappers=1:nokey=1",
197
+ str(video_path)
198
+ ]
199
+ result = subprocess.run(cmd, capture_output=True, text=True)
200
+ return float(result.stdout.strip()) if result.returncode == 0 else 0.0
201
+ except Exception:
202
+ return 0.0
203
+
204
+ def _seconds_to_timecode(self, seconds: float) -> str:
205
+ """Convert seconds to HH:MM:SS timecode."""
206
+ hours = int(seconds // 3600)
207
+ minutes = int((seconds % 3600) // 60)
208
+ secs = int(seconds % 60)
209
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
210
+
211
+
212
+ # Global instance
213
+ thumbnail_generator = ThumbnailGenerator()
config.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration module for Anime Encoder Bot."""
2
+ import os
3
+ from pathlib import Path
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ def get_int_env(key: str, default: int = 0) -> int:
9
+ """Get integer from env, return default if invalid."""
10
+ value = os.getenv(key, str(default))
11
+ try:
12
+ return int(value)
13
+ except ValueError:
14
+ print(f"โš ๏ธ Warning: {key} must be a number, got '{value}'. Using default {default}")
15
+ return default
16
+
17
+ class Config:
18
+ """Bot configuration class."""
19
+
20
+ # Telegram API credentials (hardcoded for HF deployment)
21
+ API_ID = 27773221
22
+ API_HASH = "b8487b5517c663cd8e1c816febd14941"
23
+ BOT_TOKEN = "8734274829:AAFGvK5PkD4FN3xYIGAAGS8CoOUOGu63b80"
24
+
25
+ # Owner and sudo users (hardcoded for HF deployment)
26
+ OWNER_ID = 5797061400
27
+ SUDO_USERS = []
28
+
29
+ # Database (hardcoded for HF deployment)
30
+ MONGO_URI = "mongodb+srv://imrushil18_db_user:jX8rJvReAVZrwpW7@anime.p5bk9l5.mongodb.net/?appName=anime"
31
+
32
+ # Logging
33
+ LOG_CHANNEL = get_int_env("LOG_CHANNEL", 0) if os.getenv("LOG_CHANNEL") else None
34
+
35
+ # Directories
36
+ DOWNLOAD_DIR = Path(os.getenv("DOWNLOAD_DIR", "./downloads"))
37
+ ENCODE_DIR = Path(os.getenv("ENCODE_DIR", "./encodes"))
38
+ TEMP_DIR = Path(os.getenv("TEMP_DIR", "./temp"))
39
+
40
+ # FFmpeg
41
+ FFMPEG_PATH = os.getenv("FFMPEG_PATH", "ffmpeg")
42
+ FFPROBE_PATH = os.getenv("FFPROBE_PATH", "ffprobe")
43
+
44
+ # Encoding defaults
45
+ DEFAULT_CRF = int(os.getenv("DEFAULT_CRF", 28))
46
+ DEFAULT_PRESET = os.getenv("DEFAULT_PRESET", "medium")
47
+ DEFAULT_CODEC = os.getenv("DEFAULT_CODEC", "libx264")
48
+ DEFAULT_AUDIO_CODEC = os.getenv("DEFAULT_AUDIO_CODEC", "aac")
49
+ DEFAULT_AUDIO_BITRATE = os.getenv("DEFAULT_AUDIO_BITRATE", "128k")
50
+
51
+ # Queue
52
+ MAX_CONCURRENT_DOWNLOADS = int(os.getenv("MAX_CONCURRENT_DOWNLOADS", 2))
53
+ MAX_CONCURRENT_ENCODINGS = int(os.getenv("MAX_CONCURRENT_ENCODINGS", 1))
54
+
55
+ # Renaming defaults
56
+ DEFAULT_RENAME_PATTERN = os.getenv("DEFAULT_RENAME_PATTERN", "{title} - Ep{episode} [{quality}]")
57
+
58
+ @classmethod
59
+ def validate(cls):
60
+ """Validate configuration."""
61
+ required = ["API_ID", "API_HASH", "BOT_TOKEN", "OWNER_ID"]
62
+ missing = [r for r in required if not getattr(cls, r)]
63
+ if missing:
64
+ raise ValueError(f"Missing required config: {', '.join(missing)}")
65
+
66
+ # Create directories
67
+ for dir_path in [cls.DOWNLOAD_DIR, cls.ENCODE_DIR, cls.TEMP_DIR]:
68
+ dir_path.mkdir(parents=True, exist_ok=True)
docker-compose.yml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ bot:
5
+ build: .
6
+ container_name: anime-encoder-bot
7
+ restart: unless-stopped
8
+ env_file:
9
+ - .env
10
+ volumes:
11
+ - ./downloads:/app/downloads
12
+ - ./encodes:/app/encodes
13
+ - ./temp:/app/temp
14
+ - ./bot.log:/app/bot.log
15
+ depends_on:
16
+ - mongodb
17
+ networks:
18
+ - bot-network
19
+
20
+ mongodb:
21
+ image: mongo:7.0
22
+ container_name: anime-encoder-mongo
23
+ restart: unless-stopped
24
+ volumes:
25
+ - mongo-data:/data/db
26
+ networks:
27
+ - bot-network
28
+
29
+ volumes:
30
+ mongo-data:
31
+
32
+ networks:
33
+ bot-network:
34
+ driver: bridge
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies
2
+ pyrogram>=2.0.0
3
+ tgcrypto>=1.2.0
4
+ pymongo>=4.0.0
5
+ python-dotenv>=1.0.0
6
+
7
+ # Video/audio processing
8
+ yt-dlp>=2023.0.0
9
+
10
+ # Web admin panel
11
+ flask>=2.3.0
12
+ werkzeug>=2.3.0
13
+
14
+ # Utilities
15
+ aiohttp>=3.8.0
16
+ aiofiles>=23.0.0
setup-github.bat ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ :: Windows Setup Script for GitHub
3
+
4
+ echo ==========================================
5
+ echo Anime Encoder Bot - GitHub Setup
6
+ echo ==========================================
7
+
8
+ :: Check if git is initialized
9
+ if not exist .git (
10
+ echo [+] Initializing git repository...
11
+ git init
12
+ git branch -m main
13
+ ) else (
14
+ echo [โœ“] Git already initialized
15
+ )
16
+
17
+ :: Add all files
18
+ echo [+] Adding files...
19
+ git add .
20
+
21
+ :: Initial commit
22
+ echo [+] Creating initial commit...
23
+ git commit -m "Initial commit: Anime Encoder Bot with all features" 2>nul || echo Nothing to commit
24
+
25
+ echo.
26
+ echo ==========================================
27
+ echo NEXT STEPS:
28
+ echo ==========================================
29
+ echo.
30
+ echo 1. Create a new repository on GitHub:
31
+ echo https://github.com/new
32
+ echo.
33
+ echo 2. Copy the repository URL (e.g., https://github.com/YOURNAME/anime-encoder-bot.git)
34
+ echo.
35
+ echo 3. Add remote and push:
36
+ echo git remote add origin YOUR_REPO_URL
37
+ echo git push -u origin main
38
+ echo.
39
+ echo 4. For Hugging Face:
40
+ echo a) Go to: https://huggingface.co/new-space
41
+ echo b) Select 'Docker' as SDK
42
+ echo c) Name it: anime-encoder-bot
43
+ echo d) Go to Settings ^> Secrets
44
+ echo e) Add HF_TOKEN and HF_SPACE_ID
45
+ echo.
46
+ echo 5. The GitHub Action will auto-deploy!
47
+ echo.
48
+ pause
setup-github.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Setup script for GitHub and Hugging Face
3
+
4
+ echo "๐ŸŽฌ Anime Encoder Bot - GitHub + Hugging Face Setup"
5
+ echo "=================================================="
6
+
7
+ # Check if git is initialized
8
+ if [ ! -d .git ]; then
9
+ echo "๐Ÿ“ฆ Initializing git repository..."
10
+ git init
11
+ git branch -m main
12
+ else
13
+ echo "โœ… Git already initialized"
14
+ fi
15
+
16
+ # Add all files
17
+ echo "๐Ÿ“ Adding files..."
18
+ git add .
19
+
20
+ # Initial commit
21
+ echo "๐Ÿ’พ Creating initial commit..."
22
+ git commit -m "Initial commit: Anime Encoder Bot with all features" || echo "Nothing to commit"
23
+
24
+ # Ask for GitHub username
25
+ read -p "Enter your GitHub username: " GITHUB_USER
26
+ read -p "Enter your repository name (default: anime-encoder-bot): " REPO_NAME
27
+ REPO_NAME=${REPO_NAME:-anime-encoder-bot}
28
+
29
+ # Add remote
30
+ echo "๐Ÿ”— Adding GitHub remote..."
31
+ git remote remove origin 2>/dev/null
32
+ git remote add origin "https://github.com/$GITHUB_USER/$REPO_NAME.git"
33
+
34
+ echo ""
35
+ echo "๐Ÿ“ค To push to GitHub, run:"
36
+ echo " git push -u origin main"
37
+ echo ""
38
+ echo "๐Ÿค— For Hugging Face:"
39
+ echo " 1. Create a Space at: https://huggingface.co/new-space"
40
+ echo " 2. Select 'Docker' SDK"
41
+ echo " 3. Set space name: $REPO_NAME"
42
+ echo " 4. Copy space ID (username/space-name)"
43
+ echo " 5. Add HF_TOKEN and HF_SPACE_ID to GitHub Secrets"
44
+ echo ""
45
+ echo "๐Ÿ”— GitHub Repository URL:"
46
+ echo " https://github.com/$GITHUB_USER/$REPO_NAME"
space.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Anime Encoder Bot
3
+ emoji: ๐ŸŽฌ
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 5000
8
+ ---
9
+
10
+ # Anime Encoder Bot ๐ŸŽฌ
11
+
12
+ Hybrid Telegram bot for anime downloading and video encoding.
13
+
14
+ ## Features
15
+ - ๐Ÿ” Search & download from 8+ anime sites
16
+ - ๐ŸŽž๏ธ Video encoding with H.264/H.265
17
+ - ๐Ÿ“ Auto-rename with metadata
18
+ - ๐Ÿ–ผ๏ธ Custom thumbnails
19
+ - ๐Ÿ“ฆ Batch operations
20
+ - ๐Ÿ“Š User stats & leaderboard
21
+ - ๐ŸŒ Web admin panel (port 5000)
22
+
23
+ ## Environment Variables Required
24
+
25
+ ```bash
26
+ API_ID=your_api_id
27
+ API_HASH=your_api_hash
28
+ BOT_TOKEN=your_bot_token
29
+ OWNER_ID=your_telegram_id
30
+ MONGO_URI=mongodb_uri
31
+ ADMIN_USERNAME=admin
32
+ ADMIN_PASSWORD_HASH=bcrypt_hash
33
+ FLASK_SECRET_KEY=secret_key
34
+ ```
35
+
36
+ ## Ports
37
+ - **5000** - Web admin panel
38
+
39
+ ## How to Use
40
+
41
+ 1. Set all environment variables in Space Settings
42
+ 2. Restart the Space
43
+ 3. Access web panel at the Space URL
44
+ 4. Bot will start automatically
45
+
46
+ ## Repository
47
+ https://github.com/yourusername/anime-encoder-bot
web_panel.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web admin panel for Anime Encoder Bot."""
2
+ import os
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ from functools import wraps
6
+ from pathlib import Path
7
+
8
+ from flask import Flask, render_template, jsonify, request, redirect, url_for, session, flash
9
+ from werkzeug.security import check_password_hash, generate_password_hash
10
+
11
+ from config import Config
12
+ from bot.database import db
13
+ from bot.stats import stats_manager
14
+ from bot.task_queue import task_queue
15
+
16
+ app = Flask(__name__)
17
+ app.secret_key = os.getenv('FLASK_SECRET_KEY', 'dev-secret-key-change-in-production')
18
+
19
+ # Admin credentials (should be set via environment variables in production)
20
+ ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'admin')
21
+ ADMIN_PASSWORD_HASH = os.getenv('ADMIN_PASSWORD_HASH',
22
+ generate_password_hash('admin')) # Default: change in production!
23
+
24
+
25
+ def login_required(f):
26
+ """Decorator to require login for routes."""
27
+ @wraps(f)
28
+ def decorated_function(*args, **kwargs):
29
+ if 'logged_in' not in session:
30
+ return redirect(url_for('login'))
31
+ return f(*args, **kwargs)
32
+ return decorated_function
33
+
34
+
35
+ def owner_required(f):
36
+ """Decorator to require owner access."""
37
+ @wraps(f)
38
+ def decorated_function(*args, **kwargs):
39
+ if 'logged_in' not in session:
40
+ return redirect(url_for('login'))
41
+ if session.get('user_id') != Config.OWNER_ID:
42
+ flash('Owner access required', 'error')
43
+ return redirect(url_for('dashboard'))
44
+ return f(*args, **kwargs)
45
+ return decorated_function
46
+
47
+
48
+ @app.route('/login', methods=['GET', 'POST'])
49
+ def login():
50
+ """Login page."""
51
+ if request.method == 'POST':
52
+ username = request.form.get('username')
53
+ password = request.form.get('password')
54
+
55
+ if username == ADMIN_USERNAME and check_password_hash(ADMIN_PASSWORD_HASH, password):
56
+ session['logged_in'] = True
57
+ session['user_id'] = Config.OWNER_ID
58
+ session['username'] = username
59
+ return redirect(url_for('dashboard'))
60
+ else:
61
+ flash('Invalid credentials', 'error')
62
+
63
+ return render_template_string(LOGIN_TEMPLATE)
64
+
65
+
66
+ @app.route('/logout')
67
+ def logout():
68
+ """Logout."""
69
+ session.clear()
70
+ return redirect(url_for('login'))
71
+
72
+
73
+ @app.route('/')
74
+ @login_required
75
+ def dashboard():
76
+ """Main dashboard."""
77
+ stats = stats_manager.get_bot_stats()
78
+ queue_status = task_queue.get_queue_status()
79
+
80
+ return render_template_string(DASHBOARD_TEMPLATE,
81
+ stats=stats,
82
+ queue=queue_status,
83
+ now=datetime.now())
84
+
85
+
86
+ @app.route('/api/stats')
87
+ @login_required
88
+ def api_stats():
89
+ """API endpoint for stats."""
90
+ return jsonify(stats_manager.get_bot_stats())
91
+
92
+
93
+ @app.route('/api/stats/user/<int:user_id>')
94
+ @login_required
95
+ def api_user_stats(user_id):
96
+ """API endpoint for user stats."""
97
+ return jsonify(stats_manager.get_user_stats(user_id))
98
+
99
+
100
+ @app.route('/api/queue')
101
+ @login_required
102
+ def api_queue():
103
+ """API endpoint for queue status."""
104
+ return jsonify(task_queue.get_queue_status())
105
+
106
+
107
+ @app.route('/api/queue/clear', methods=['POST'])
108
+ @owner_required
109
+ def api_clear_queue():
110
+ """Clear queue (owner only)."""
111
+ try:
112
+ # Clear download queue
113
+ while not task_queue.download_queue.empty():
114
+ try:
115
+ task_queue.download_queue.get_nowait()
116
+ task_queue.download_queue.task_done()
117
+ except:
118
+ break
119
+
120
+ # Clear encode queue
121
+ while not task_queue.encode_queue.empty():
122
+ try:
123
+ task_queue.encode_queue.get_nowait()
124
+ task_queue.encode_queue.task_done()
125
+ except:
126
+ break
127
+
128
+ return jsonify({"success": True, "message": "Queues cleared"})
129
+ except Exception as e:
130
+ return jsonify({"success": False, "error": str(e)}), 500
131
+
132
+
133
+ @app.route('/users')
134
+ @login_required
135
+ def users():
136
+ """User management page."""
137
+ # Get all users with their stats
138
+ user_list = []
139
+ for user in db.users.find().sort("created_at", -1).limit(100):
140
+ user_id = user.get("user_id")
141
+ stats = stats_manager.get_user_stats(user_id)
142
+ user_list.append({
143
+ "user_id": user_id,
144
+ "username": user.get("username", "Unknown"),
145
+ "created_at": user.get("created_at"),
146
+ "stats": stats
147
+ })
148
+
149
+ return render_template_string(USERS_TEMPLATE, users=user_list)
150
+
151
+
152
+ @app.route('/tasks')
153
+ @login_required
154
+ def tasks():
155
+ """Task management page."""
156
+ # Get recent tasks
157
+ recent_downloads = list(db.downloads.find().sort("created_at", -1).limit(50))
158
+ recent_encodes = list(db.encodes.find().sort("created_at", -1).limit(50))
159
+
160
+ return render_template_string(TASKS_TEMPLATE,
161
+ downloads=recent_downloads,
162
+ encodes=recent_encodes)
163
+
164
+
165
+ @app.route('/settings', methods=['GET', 'POST'])
166
+ @owner_required
167
+ def settings():
168
+ """Bot settings page (owner only)."""
169
+ if request.method == 'POST':
170
+ # Update settings (in a real app, you'd save these to a config file or DB)
171
+ flash('Settings updated (demo only)', 'success')
172
+
173
+ return render_template_string(SETTINGS_TEMPLATE, config=Config)
174
+
175
+
176
+ @app.route('/leaderboard')
177
+ @login_required
178
+ def leaderboard():
179
+ """User leaderboard page."""
180
+ period = request.args.get('period', 'all')
181
+ leaders = stats_manager.get_leaderboard(period)
182
+
183
+ return render_template_string(LEADERBOARD_TEMPLATE,
184
+ leaders=leaders,
185
+ period=period)
186
+
187
+
188
+ # HTML Templates (embedded for simplicity)
189
+ LOGIN_TEMPLATE = """
190
+ <!DOCTYPE html>
191
+ <html>
192
+ <head>
193
+ <title>Login - Anime Encoder Bot Admin</title>
194
+ <style>
195
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
196
+ .login-box { background: #16213e; padding: 40px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.3); }
197
+ h1 { text-align: center; margin-bottom: 30px; }
198
+ input { width: 100%; padding: 12px; margin: 10px 0; border: none; border-radius: 5px; background: #0f3460; color: #fff; }
199
+ button { width: 100%; padding: 12px; background: #e94560; color: #fff; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
200
+ button:hover { background: #c73e54; }
201
+ .error { color: #e94560; text-align: center; margin-top: 10px; }
202
+ </style>
203
+ </head>
204
+ <body>
205
+ <div class="login-box">
206
+ <h1>๐ŸŽฌ Admin Login</h1>
207
+ <form method="POST">
208
+ <input type="text" name="username" placeholder="Username" required>
209
+ <input type="password" name="password" placeholder="Password" required>
210
+ <button type="submit">Login</button>
211
+ </form>
212
+ {% with messages = get_flashed_messages(with_categories=true) %}
213
+ {% if messages %}
214
+ {% for category, message in messages %}
215
+ <p class="error">{{ message }}</p>
216
+ {% endfor %}
217
+ {% endif %}
218
+ {% endwith %}
219
+ </div>
220
+ </body>
221
+ </html>
222
+ """
223
+
224
+ DASHBOARD_TEMPLATE = """
225
+ <!DOCTYPE html>
226
+ <html>
227
+ <head>
228
+ <title>Dashboard - Anime Encoder Bot</title>
229
+ <style>
230
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; margin: 0; }
231
+ .navbar { background: #16213e; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; }
232
+ .navbar a { color: #fff; text-decoration: none; margin: 0 15px; }
233
+ .navbar a:hover { color: #e94560; }
234
+ .container { padding: 30px; max-width: 1400px; margin: 0 auto; }
235
+ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
236
+ .stat-card { background: #16213e; padding: 20px; border-radius: 10px; }
237
+ .stat-card h3 { margin-top: 0; color: #e94560; }
238
+ .stat-value { font-size: 32px; font-weight: bold; }
239
+ .queue-section { background: #16213e; padding: 20px; border-radius: 10px; margin-bottom: 30px; }
240
+ .progress-bar { background: #0f3460; height: 20px; border-radius: 10px; overflow: hidden; }
241
+ .progress-fill { background: #e94560; height: 100%; transition: width 0.3s; }
242
+ table { width: 100%; border-collapse: collapse; margin-top: 20px; }
243
+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; }
244
+ th { color: #e94560; }
245
+ .status-badge { padding: 5px 10px; border-radius: 5px; font-size: 12px; }
246
+ .status-completed { background: #4caf50; }
247
+ .status-failed { background: #f44336; }
248
+ .status-pending { background: #ff9800; }
249
+ .refresh-btn { background: #e94560; color: #fff; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; }
250
+ </style>
251
+ </head>
252
+ <body>
253
+ <div class="navbar">
254
+ <div>
255
+ <strong>๐ŸŽฌ Anime Encoder Bot</strong>
256
+ </div>
257
+ <div>
258
+ <a href="/">Dashboard</a>
259
+ <a href="/users">Users</a>
260
+ <a href="/tasks">Tasks</a>
261
+ <a href="/leaderboard">Leaderboard</a>
262
+ <a href="/settings">Settings</a>
263
+ <a href="/logout">Logout</a>
264
+ </div>
265
+ </div>
266
+
267
+ <div class="container">
268
+ <h1>Dashboard</h1>
269
+ <p>Last updated: {{ now.strftime('%Y-%m-%d %H:%M:%S') }}</p>
270
+
271
+ <div class="stats-grid">
272
+ <div class="stat-card">
273
+ <h3>๐Ÿ‘ฅ Total Users</h3>
274
+ <div class="stat-value">{{ stats.overview.total_users }}</div>
275
+ </div>
276
+ <div class="stat-card">
277
+ <h3>๐Ÿ“ฅ Total Downloads</h3>
278
+ <div class="stat-value">{{ stats.overview.total_downloads }}</div>
279
+ </div>
280
+ <div class="stat-card">
281
+ <h3>๐ŸŽž๏ธ Total Encodes</h3>
282
+ <div class="stat-value">{{ stats.overview.total_encodes }}</div>
283
+ </div>
284
+ <div class="stat-card">
285
+ <h3>โšก Active Downloads</h3>
286
+ <div class="stat-value">{{ stats.overview.active_downloads }}</div>
287
+ </div>
288
+ <div class="stat-card">
289
+ <h3>โšก Active Encodes</h3>
290
+ <div class="stat-value">{{ stats.overview.active_encodes }}</div>
291
+ </div>
292
+ <div class="stat-card">
293
+ <h3>๐Ÿ’พ Storage Used</h3>
294
+ <div class="stat-value">{{ stats.storage.total_gb }} GB</div>
295
+ <small>{{ stats.storage.note }}</small>
296
+ </div>
297
+ </div>
298
+
299
+ <div class="queue-section">
300
+ <h2>Queue Status</h2>
301
+ <p>Download Queue: {{ queue.download_queue_size }} pending / {{ queue.active_downloads }} active</p>
302
+ <div class="progress-bar">
303
+ <div class="progress-fill" style="width: {{ (queue.active_downloads / queue.max_downloads * 100) if queue.max_downloads > 0 else 0 }}%"></div>
304
+ </div>
305
+ <p style="margin-top: 15px;">Encode Queue: {{ queue.encode_queue_size }} pending / {{ queue.active_encodes }} active</p>
306
+ <div class="progress-bar">
307
+ <div class="progress-fill" style="width: {{ (queue.active_encodes / queue.max_encodes * 100) if queue.max_encodes > 0 else 0 }}%"></div>
308
+ </div>
309
+ </div>
310
+
311
+ <div class="queue-section">
312
+ <h2>Popular Anime</h2>
313
+ <table>
314
+ <tr>
315
+ <th>Anime ID</th>
316
+ <th>Downloads</th>
317
+ </tr>
318
+ {% for anime in stats.popular_anime %}
319
+ <tr>
320
+ <td>{{ anime._id }}</td>
321
+ <td>{{ anime.downloads }}</td>
322
+ </tr>
323
+ {% endfor %}
324
+ </table>
325
+ </div>
326
+
327
+ <button class="refresh-btn" onclick="location.reload()">๐Ÿ”„ Refresh</button>
328
+ </div>
329
+ </body>
330
+ </html>
331
+ """
332
+
333
+ USERS_TEMPLATE = """
334
+ <!DOCTYPE html>
335
+ <html>
336
+ <head>
337
+ <title>Users - Anime Encoder Bot</title>
338
+ <style>
339
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; margin: 0; }
340
+ .navbar { background: #16213e; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; }
341
+ .navbar a { color: #fff; text-decoration: none; margin: 0 15px; }
342
+ .container { padding: 30px; max-width: 1400px; margin: 0 auto; }
343
+ table { width: 100%; border-collapse: collapse; margin-top: 20px; background: #16213e; border-radius: 10px; overflow: hidden; }
344
+ th, td { padding: 15px; text-align: left; border-bottom: 1px solid #0f3460; }
345
+ th { background: #0f3460; color: #e94560; }
346
+ tr:hover { background: #0f3460; }
347
+ .stats { display: flex; gap: 15px; }
348
+ .stat { background: #0f3460; padding: 5px 10px; border-radius: 5px; font-size: 12px; }
349
+ </style>
350
+ </head>
351
+ <body>
352
+ <div class="navbar">
353
+ <div><strong>๐ŸŽฌ Anime Encoder Bot</strong></div>
354
+ <div>
355
+ <a href="/">Dashboard</a>
356
+ <a href="/users">Users</a>
357
+ <a href="/tasks">Tasks</a>
358
+ <a href="/leaderboard">Leaderboard</a>
359
+ <a href="/logout">Logout</a>
360
+ </div>
361
+ </div>
362
+
363
+ <div class="container">
364
+ <h1>๐Ÿ‘ฅ Users</h1>
365
+
366
+ <table>
367
+ <tr>
368
+ <th>User ID</th>
369
+ <th>Username</th>
370
+ <th>Joined</th>
371
+ <th>Downloads</th>
372
+ <th>Encodes</th>
373
+ <th>Success Rate</th>
374
+ </tr>
375
+ {% for user in users %}
376
+ <tr>
377
+ <td>{{ user.user_id }}</td>
378
+ <td>{{ user.username }}</td>
379
+ <td>{{ user.created_at.strftime('%Y-%m-%d') if user.created_at else 'Unknown' }}</td>
380
+ <td>{{ user.stats.downloads.total }}</td>
381
+ <td>{{ user.stats.encodes.total }}</td>
382
+ <td>
383
+ <div class="stats">
384
+ <span class="stat">DL: {{ user.stats.downloads.success_rate }}%</span>
385
+ <span class="stat">ENC: {{ user.stats.encodes.success_rate }}%</span>
386
+ </div>
387
+ </td>
388
+ </tr>
389
+ {% endfor %}
390
+ </table>
391
+ </div>
392
+ </body>
393
+ </html>
394
+ """
395
+
396
+ TASKS_TEMPLATE = """
397
+ <!DOCTYPE html>
398
+ <html>
399
+ <head>
400
+ <title>Tasks - Anime Encoder Bot</title>
401
+ <style>
402
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; margin: 0; }
403
+ .navbar { background: #16213e; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; }
404
+ .navbar a { color: #fff; text-decoration: none; margin: 0 15px; }
405
+ .container { padding: 30px; max-width: 1400px; margin: 0 auto; }
406
+ table { width: 100%; border-collapse: collapse; margin-top: 20px; background: #16213e; border-radius: 10px; overflow: hidden; }
407
+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; }
408
+ th { background: #0f3460; color: #e94560; }
409
+ .tabs { display: flex; gap: 10px; margin-bottom: 20px; }
410
+ .tab { padding: 10px 20px; background: #16213e; border-radius: 5px; cursor: pointer; }
411
+ .tab.active { background: #e94560; }
412
+ .status-completed { color: #4caf50; }
413
+ .status-failed { color: #f44336; }
414
+ .status-pending { color: #ff9800; }
415
+ </style>
416
+ </head>
417
+ <body>
418
+ <div class="navbar">
419
+ <div><strong>๐ŸŽฌ Anime Encoder Bot</strong></div>
420
+ <div>
421
+ <a href="/">Dashboard</a>
422
+ <a href="/users">Users</a>
423
+ <a href="/tasks">Tasks</a>
424
+ <a href="/leaderboard">Leaderboard</a>
425
+ <a href="/logout">Logout</a>
426
+ </div>
427
+ </div>
428
+
429
+ <div class="container">
430
+ <h1>๐Ÿ“‹ Recent Tasks</h1>
431
+
432
+ <h2>Downloads</h2>
433
+ <table>
434
+ <tr>
435
+ <th>Task ID</th>
436
+ <th>User ID</th>
437
+ <th>Anime</th>
438
+ <th>Episode</th>
439
+ <th>Status</th>
440
+ <th>Created</th>
441
+ </tr>
442
+ {% for task in downloads %}
443
+ <tr>
444
+ <td>{{ task.task_id[:8] }}...</td>
445
+ <td>{{ task.user_id }}</td>
446
+ <td>{{ task.anime_id[:30] if task.anime_id else 'N/A' }}...</td>
447
+ <td>{{ task.episode_num }}</td>
448
+ <td class="status-{{ task.status }}">{{ task.status }}</td>
449
+ <td>{{ task.created_at.strftime('%Y-%m-%d %H:%M') if task.created_at else 'Unknown' }}</td>
450
+ </tr>
451
+ {% endfor %}
452
+ </table>
453
+
454
+ <h2 style="margin-top: 30px;">Encodes</h2>
455
+ <table>
456
+ <tr>
457
+ <th>Task ID</th>
458
+ <th>User ID</th>
459
+ <th>Input File</th>
460
+ <th>Status</th>
461
+ <th>Progress</th>
462
+ <th>Created</th>
463
+ </tr>
464
+ {% for task in encodes %}
465
+ <tr>
466
+ <td>{{ task.task_id[:8] }}...</td>
467
+ <td>{{ task.user_id }}</td>
468
+ <td>{{ task.input_path[:30] if task.input_path else 'N/A' }}...</td>
469
+ <td class="status-{{ task.status }}">{{ task.status }}</td>
470
+ <td>{{ task.progress }}%</td>
471
+ <td>{{ task.created_at.strftime('%Y-%m-%d %H:%M') if task.created_at else 'Unknown' }}</td>
472
+ </tr>
473
+ {% endfor %}
474
+ </table>
475
+ </div>
476
+ </body>
477
+ </html>
478
+ """
479
+
480
+ LEADERBOARD_TEMPLATE = """
481
+ <!DOCTYPE html>
482
+ <html>
483
+ <head>
484
+ <title>Leaderboard - Anime Encoder Bot</title>
485
+ <style>
486
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; margin: 0; }
487
+ .navbar { background: #16213e; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; }
488
+ .navbar a { color: #fff; text-decoration: none; margin: 0 15px; }
489
+ .container { padding: 30px; max-width: 1000px; margin: 0 auto; }
490
+ .tabs { display: flex; gap: 10px; margin-bottom: 20px; }
491
+ .tab { padding: 10px 20px; background: #16213e; border-radius: 5px; text-decoration: none; color: #fff; }
492
+ .tab.active { background: #e94560; }
493
+ .leaderboard { background: #16213e; border-radius: 10px; overflow: hidden; }
494
+ .leader { display: flex; align-items: center; padding: 20px; border-bottom: 1px solid #0f3460; }
495
+ .rank { font-size: 24px; font-weight: bold; width: 50px; color: #e94560; }
496
+ .user-info { flex: 1; }
497
+ .user-id { font-size: 14px; color: #888; }
498
+ .stats { display: flex; gap: 20px; }
499
+ .stat { text-align: center; }
500
+ .stat-value { font-size: 20px; font-weight: bold; color: #e94560; }
501
+ .stat-label { font-size: 12px; color: #888; }
502
+ .medal { font-size: 30px; }
503
+ </style>
504
+ </head>
505
+ <body>
506
+ <div class="navbar">
507
+ <div><strong>๐ŸŽฌ Anime Encoder Bot</strong></div>
508
+ <div>
509
+ <a href="/">Dashboard</a>
510
+ <a href="/users">Users</a>
511
+ <a href="/tasks">Tasks</a>
512
+ <a href="/leaderboard">Leaderboard</a>
513
+ <a href="/logout">Logout</a>
514
+ </div>
515
+ </div>
516
+
517
+ <div class="container">
518
+ <h1>๐Ÿ† Leaderboard</h1>
519
+
520
+ <div class="tabs">
521
+ <a href="/leaderboard?period=all" class="tab {{ 'active' if period == 'all' else '' }}">All Time</a>
522
+ <a href="/leaderboard?period=month" class="tab {{ 'active' if period == 'month' else '' }}">This Month</a>
523
+ <a href="/leaderboard?period=week" class="tab {{ 'active' if period == 'week' else '' }}">This Week</a>
524
+ </div>
525
+
526
+ <div class="leaderboard">
527
+ {% for leader in leaders %}
528
+ <div class="leader">
529
+ <div class="rank">
530
+ {% if loop.index == 1 %}๐Ÿฅ‡{% elif loop.index == 2 %}๐Ÿฅˆ{% elif loop.index == 3 %}๐Ÿฅ‰{% else %}{{ loop.index }}{% endif %}
531
+ </div>
532
+ <div class="user-info">
533
+ <div>User {{ leader.user_id }}</div>
534
+ <div class="user-id">ID: {{ leader.user_id }}</div>
535
+ </div>
536
+ <div class="stats">
537
+ <div class="stat">
538
+ <div class="stat-value">{{ leader.downloads }}</div>
539
+ <div class="stat-label">Downloads</div>
540
+ </div>
541
+ <div class="stat">
542
+ <div class="stat-value">{{ leader.encodes }}</div>
543
+ <div class="stat-label">Encodes</div>
544
+ </div>
545
+ <div class="stat">
546
+ <div class="stat-value">{{ leader.total }}</div>
547
+ <div class="stat-label">Total</div>
548
+ </div>
549
+ </div>
550
+ </div>
551
+ {% endfor %}
552
+ </div>
553
+ </div>
554
+ </body>
555
+ </html>
556
+ """
557
+
558
+ SETTINGS_TEMPLATE = """
559
+ <!DOCTYPE html>
560
+ <html>
561
+ <head>
562
+ <title>Settings - Anime Encoder Bot</title>
563
+ <style>
564
+ body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; margin: 0; }
565
+ .navbar { background: #16213e; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; }
566
+ .navbar a { color: #fff; text-decoration: none; margin: 0 15px; }
567
+ .container { padding: 30px; max-width: 800px; margin: 0 auto; }
568
+ .setting-group { background: #16213e; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
569
+ .setting { margin: 15px 0; }
570
+ label { display: block; margin-bottom: 5px; color: #e94560; }
571
+ input, select { width: 100%; padding: 10px; background: #0f3460; border: none; border-radius: 5px; color: #fff; }
572
+ button { background: #e94560; color: #fff; border: none; padding: 12px 30px; border-radius: 5px; cursor: pointer; }
573
+ </style>
574
+ </head>
575
+ <body>
576
+ <div class="navbar">
577
+ <div><strong>๐ŸŽฌ Anime Encoder Bot</strong></div>
578
+ <div>
579
+ <a href="/">Dashboard</a>
580
+ <a href="/users">Users</a>
581
+ <a href="/tasks">Tasks</a>
582
+ <a href="/leaderboard">Leaderboard</a>
583
+ <a href="/logout">Logout</a>
584
+ </div>
585
+ </div>
586
+
587
+ <div class="container">
588
+ <h1>โš™๏ธ Bot Settings</h1>
589
+
590
+ <form method="POST">
591
+ <div class="setting-group">
592
+ <h3>Queue Settings</h3>
593
+ <div class="setting">
594
+ <label>Max Concurrent Downloads</label>
595
+ <input type="number" value="{{ config.MAX_CONCURRENT_DOWNLOADS }}" disabled>
596
+ </div>
597
+ <div class="setting">
598
+ <label>Max Concurrent Encodes</label>
599
+ <input type="number" value="{{ config.MAX_CONCURRENT_ENCODINGS }}" disabled>
600
+ </div>
601
+ </div>
602
+
603
+ <div class="setting-group">
604
+ <h3>Default Encoding</h3>
605
+ <div class="setting">
606
+ <label>Default Codec</label>
607
+ <input type="text" value="{{ config.DEFAULT_CODEC }}" disabled>
608
+ </div>
609
+ <div class="setting">
610
+ <label>Default CRF</label>
611
+ <input type="number" value="{{ config.DEFAULT_CRF }}" disabled>
612
+ </div>
613
+ </div>
614
+
615
+ <p style="color: #888;">Note: Settings are read-only in demo mode. Edit .env file to change values.</p>
616
+ <button type="submit">Save (Demo)</button>
617
+ </form>
618
+ </div>
619
+ </body>
620
+ </html>
621
+ """
622
+
623
+
624
+ def run_panel(host='0.0.0.0', port=5000, debug=False):
625
+ """Run the web panel."""
626
+ app.run(host=host, port=port, debug=debug)
627
+
628
+
629
+ if __name__ == '__main__':
630
+ run_panel(debug=True)