luci18 commited on
Commit
7cb306b
·
verified ·
1 Parent(s): 10a4525

Re-upload fresh bot files

Browse files
Files changed (11) hide show
  1. bot/__init__.py +1 -0
  2. bot/database.py +264 -0
  3. bot/downloader.py +316 -0
  4. bot/encoder.py +308 -0
  5. bot/handlers.py +1495 -0
  6. bot/main.py +83 -0
  7. bot/renamer.py +221 -0
  8. bot/sites.py +103 -0
  9. bot/stats.py +274 -0
  10. bot/task_queue.py +316 -0
  11. bot/thumbnail.py +213 -0
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()