-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCatchStream.py
More file actions
2882 lines (2492 loc) · 120 KB
/
Copy pathCatchStream.py
File metadata and controls
2882 lines (2492 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import time
import json
import logging
import hashlib
import threading
import requests
import shutil
import ffmpeg
import asyncio
import aiohttp
import sqlite3
from datetime import datetime, timedelta
from yt_dlp import YoutubeDL
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich import box
from rich.layout import Layout
from rich.live import Live
from rich.syntax import Syntax
from typing import List, Dict, Optional, Union, Any, Tuple, Callable
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from enum import Enum
from PIL import Image
import ffmpeg
from ffmpeg import Error as FFmpegError
import aiofiles
from functools import lru_cache
from contextlib import contextmanager, suppress
from typing import Generator, Iterator
class DownloadStatus(Enum):
"""Enhanced download status tracking with more descriptive states"""
QUEUED = "queued"
DOWNLOADING = "downloading"
PAUSED = "paused"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
PROCESSING = "processing"
CONVERTING = "converting"
VALIDATING = "validating"
ARCHIVED = "archived"
SCHEDULED = "scheduled"
RETRYING = "retrying"
@dataclass
class DownloadInfo:
"""Enhanced download information with additional metadata"""
url: str
format_id: str
filename: str
status: DownloadStatus
progress: float
speed: str
eta: str
size: int
downloaded_size: int
start_time: datetime
end_time: Optional[datetime] = None
error: Optional[str] = None
thumbnail_path: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
video_quality: Optional[str] = None
subtitles: Optional[Dict[str, str]] = None
retry_count: int = 0
checksum: Optional[str] = None
schedule_time: Optional[datetime] = None
priority: int = 0
tags: List[str] = field(default_factory=list)
class VideoProcessor:
"""Enhanced video processor with better performance and resilience"""
def __init__(self, input_path: str, output_path: str, config: Dict[str, Any]):
self.input_path = Path(input_path)
self.output_path = Path(output_path)
self.config = config
self._temp_files: List[Path] = []
self._progress_callback: Optional[Callable[[float], None]] = None
self._cancel_flag = threading.Event()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.cleanup()
def cleanup(self) -> None:
"""Clean up temporary files safely"""
for temp_file in self._temp_files:
try:
if temp_file.exists():
temp_file.unlink()
except Exception as e:
logging.warning(f"Failed to cleanup temp file {temp_file}: {str(e)}")
def set_progress_callback(self, callback: Callable[[float], None]) -> None:
"""Set callback for progress updates"""
self._progress_callback = callback
def cancel_processing(self) -> None:
"""Cancel ongoing processing"""
self._cancel_flag.set()
@contextmanager
def _processing_context(self) -> Generator[None, None, None]:
"""Context manager for safe processing with cleanup"""
try:
self._cancel_flag.clear()
yield
finally:
self.cleanup()
if self._progress_callback:
self._progress_callback(100.0)
async def process_video(self, options: Dict[str, Any]) -> bool:
"""Improved video processing with better error handling and performance"""
async with self._processing_context():
try:
if not await self._validate_input():
return False
# Process tasks concurrently with proper resource management
tasks = self._create_processing_tasks(options)
if not tasks:
return True # No tasks to process is considered success
return await self._execute_tasks(tasks)
except Exception as e:
logging.error(f"Video processing error: {str(e)}", exc_info=True)
return False
async def _validate_input(self) -> bool:
"""Validate input file and create output directory"""
try:
if not self.input_path.exists():
raise FileNotFoundError(f"Input file not found: {self.input_path}")
# Create output directory with proper permissions
self.output_path.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
return True
except Exception as e:
logging.error(f"Validation error: {str(e)}")
return False
def _create_processing_tasks(self, options: Dict[str, Any]) -> List[asyncio.Task]:
"""Create processing tasks based on options with proper resource limits"""
tasks = []
total_tasks = sum(1 for opt in options.values() if opt)
completed_tasks = 0
# Map of task types to their processing functions
task_map = {
'extract_audio': lambda: self.extract_audio(options.get('audio_format', 'mp3')),
'compress': lambda: self.compress_video(options.get('target_size')),
'watermark': lambda: self.add_watermark(options.get('watermark_text')),
'trim': lambda: self.trim_video(options.get('start_time'), options.get('end_time')),
'convert_format': lambda: self.convert_format(options.get('target_format'))
}
for task_name, task_func in task_map.items():
if options.get(task_name) and not self._cancel_flag.is_set():
task = asyncio.create_task(task_func())
tasks.append(task)
completed_tasks += 1
if self._progress_callback:
self._progress_callback(completed_tasks / total_tasks * 100)
return tasks
async def _execute_tasks(self, tasks: List[asyncio.Task]) -> bool:
"""Execute tasks with proper error handling and resource management"""
try:
results = await asyncio.gather(*tasks, return_exceptions=True)
return all(not isinstance(r, Exception) and r for r in results)
except Exception as e:
logging.error(f"Task execution error: {str(e)}")
return False
async def _run_async_ffmpeg(self, stream) -> None:
"""Enhanced FFmpeg execution with better error handling and resource management"""
try:
process = await asyncio.create_subprocess_exec(
*stream.get_args(),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
limit=1024*1024 # 1MB buffer limit
)
# Use asyncio.wait_for to implement timeout
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=self.config.get('ffmpeg_timeout', 3600) # 1 hour default timeout
)
except asyncio.TimeoutError:
process.kill()
raise FFmpegError("FFmpeg process timed out")
if process.returncode != 0:
raise FFmpegError(f"FFmpeg error: {stderr.decode()}")
except Exception as e:
raise FFmpegError(f"FFmpeg execution error: {str(e)}")
@contextmanager
def _temp_file(self, suffix: str = '') -> Iterator[Path]:
"""Safe temporary file management"""
temp_path = Path(self.config['temp_dir']) / f"temp_{int(time.time())}_{os.urandom(4).hex()}{suffix}"
try:
yield temp_path
self._temp_files.append(temp_path)
except Exception as e:
if temp_path.exists():
temp_path.unlink()
raise e
@lru_cache(maxsize=32)
def _get_audio_codec(self, format: str) -> str:
"""Cached audio codec mapping for better performance"""
codec_map = {
'mp3': 'libmp3lame',
'aac': 'aac',
'opus': 'libopus',
'vorbis': 'libvorbis'
}
return codec_map.get(format, 'libmp3lame')
def _get_format_options(self, format: str) -> Dict[str, str]:
format_presets = {
'mp4': {
'vcodec': 'libx264',
'acodec': 'aac',
'preset': 'medium',
'crf': '23'
},
'webm': {
'vcodec': 'libvpx-vp9',
'acodec': 'libopus',
'deadline': 'good',
'cpu-used': '2'
},
'mkv': {
'vcodec': 'libx265',
'acodec': 'libopus',
'preset': 'medium',
'crf': '28'
}
}
return format_presets.get(format, format_presets['mp4'])
def get_file_hash(self, file_path: str) -> str:
"""Calculate SHA-256 hash of file"""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def validate_output(self, output_path: str) -> bool:
"""Validate processed video file"""
try:
probe = ffmpeg.probe(output_path)
if not probe:
return False
return True
except FFmpegError:
return False
async def extract_audio(self, audio_format: str = 'mp3') -> bool:
"""Extract audio with improved error handling and temp file management"""
with self._temp_file(f'.{audio_format}') as temp_output:
try:
stream = ffmpeg.input(self.input_path)
stream = ffmpeg.output(
stream,
str(temp_output),
acodec=self._get_audio_codec(audio_format),
audio_bitrate=self.config.get('audio_bitrate', '192k'),
loglevel='error'
)
await self._run_async_ffmpeg(stream)
shutil.move(str(temp_output), str(self.output_path))
return True
except FFmpegError as e:
logging.error(f"Audio extraction error: {str(e)}")
return False
async def compress_video(self, target_size: int) -> bool:
"""Compress video with improved bitrate calculation and temp file handling"""
with self._temp_file('.mp4') as temp_output:
try:
# Get video duration and calculate target bitrate
probe = await asyncio.to_thread(ffmpeg.probe, self.input_path)
duration = float(probe['format']['duration'])
target_bitrate = max(int((target_size * 8) / duration), 128) # Minimum 128kbps
# Set up compression with quality preservation
stream = ffmpeg.input(self.input_path)
stream = ffmpeg.output(
stream,
str(temp_output),
video_bitrate=f"{target_bitrate}k",
audio_bitrate=self.config.get('audio_bitrate', '192k'),
preset=self.config.get('compression_preset', 'medium'),
crf=self.config.get('crf', 23),
maxrate=f"{int(target_bitrate * 1.5)}k",
bufsize=f"{target_bitrate * 2}k",
loglevel='error'
)
await self._run_async_ffmpeg(stream)
shutil.move(str(temp_output), str(self.output_path))
return True
except Exception as e:
logging.error(f"Compression error: {str(e)}")
return False
async def add_watermark(self, text: str) -> bool:
"""Add watermark with improved text rendering and positioning"""
with self._temp_file('.mp4') as temp_output:
try:
# Validate watermark text
if not text or len(text) > 100:
raise ValueError("Invalid watermark text length")
# Configure watermark with better defaults
stream = ffmpeg.input(self.input_path)
stream = ffmpeg.drawtext(
stream,
text=text,
x=self.config.get('watermark_x', '(w-text_w)/2'),
y=self.config.get('watermark_y', '(h-text_h)/2'),
fontsize=self.config.get('watermark_fontsize', 24),
fontcolor=self.config.get('watermark_color', 'white'),
alpha=self.config.get('watermark_alpha', 0.5),
font=self.config.get('watermark_font', 'Arial'),
shadowcolor=self.config.get('watermark_shadow', 'black'),
shadowx=2,
shadowy=2
)
stream = ffmpeg.output(stream, str(temp_output), loglevel='error')
await self._run_async_ffmpeg(stream)
shutil.move(str(temp_output), str(self.output_path))
return True
except Exception as e:
logging.error(f"Watermark error: {str(e)}")
return False
async def trim_video(self, start_time: str, end_time: str) -> bool:
"""Trim video with improved timestamp handling and seeking"""
with self._temp_file('.mp4') as temp_output:
try:
# Validate timestamps
if not self._validate_timestamp(start_time) or not self._validate_timestamp(end_time):
raise ValueError("Invalid timestamp format")
stream = ffmpeg.input(
self.input_path,
ss=start_time,
t=end_time,
accurate_seek=True
)
stream = ffmpeg.output(
stream,
str(temp_output),
acodec='copy',
vcodec='copy',
loglevel='error'
)
await self._run_async_ffmpeg(stream)
shutil.move(str(temp_output), str(self.output_path))
return True
except Exception as e:
logging.error(f"Trim error: {str(e)}")
return False
async def convert_format(self, target_format: str) -> bool:
"""Convert video format with optimized settings for each format"""
with self._temp_file(f'.{target_format}') as temp_output:
try:
format_options = self._get_format_options(target_format)
stream = ffmpeg.input(self.input_path)
stream = ffmpeg.output(
stream,
str(temp_output),
**format_options,
loglevel='error'
)
await self._run_async_ffmpeg(stream)
shutil.move(str(temp_output), str(self.output_path))
return True
except Exception as e:
logging.error(f"Format conversion error: {str(e)}")
return False
@lru_cache(maxsize=8)
def _get_format_options(self, format: str) -> Dict[str, str]:
"""Get optimized format options with caching"""
format_presets = {
'mp4': {
'vcodec': 'libx264',
'acodec': 'aac',
'preset': self.config.get('compression_preset', 'medium'),
'crf': str(self.config.get('crf', 23)),
'movflags': '+faststart'
},
'webm': {
'vcodec': 'libvpx-vp9',
'acodec': 'libopus',
'deadline': 'good',
'cpu-used': '2',
'row-mt': '1',
'tile-columns': '2'
},
'mkv': {
'vcodec': 'libx265',
'acodec': 'libopus',
'preset': self.config.get('compression_preset', 'medium'),
'crf': str(self.config.get('crf', 28)),
'x265-params': 'pools=auto:frame-threads=auto'
}
}
return format_presets.get(format, format_presets['mp4'])
def _validate_timestamp(self, timestamp: str) -> bool:
"""Validate timestamp format (HH:MM:SS or MM:SS or SS)"""
try:
parts = timestamp.split(':')
if len(parts) > 3:
return False
return all(0 <= int(part) < 60 for part in parts)
except ValueError:
return False
def get_file_hash(self, file_path: str) -> str:
"""Calculate SHA-256 hash of file with progress updates"""
try:
sha256_hash = hashlib.sha256()
file_size = os.path.getsize(file_path)
processed_size = 0
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
processed_size += len(byte_block)
if self._progress_callback:
self._progress_callback((processed_size / file_size) * 100)
return sha256_hash.hexdigest()
except Exception as e:
logging.error(f"Hash calculation error: {str(e)}")
return ""
async def validate_output(self, output_path: str) -> bool:
"""Validate processed video file with improved checks"""
try:
if not os.path.exists(output_path):
return False
# Check file size
if os.path.getsize(output_path) == 0:
return False
# Verify file integrity
probe = await asyncio.to_thread(ffmpeg.probe, output_path)
if not probe or 'streams' not in probe:
return False
# Check for video stream
has_video = any(s['codec_type'] == 'video' for s in probe['streams'])
if not has_video:
return False
return True
except Exception as e:
logging.error(f"Download validation error: {str(e)}")
return False
class DatabaseManager:
"""Manages database operations with improved security and error handling"""
def __init__(self, db_path: str):
self.db_path = Path(db_path)
self.db_dir = self.db_path.parent
# Secure directory creation
try:
self.db_dir.mkdir(mode=0o755, parents=True, exist_ok=True)
except Exception as e:
raise Exception(f"Failed to create database directory: {str(e)}")
# Set proper permissions
try:
self.db_dir.chmod(0o755)
except Exception as e:
raise Exception(f"Failed to set directory permissions: {str(e)}")
# Initialize database
if not self.db_path.exists():
try:
self.db_path.touch(mode=0o644)
except Exception as e:
raise Exception(f"Failed to create database file: {str(e)}")
# Verify database connection
self._verify_connection()
self.setup_database()
def _verify_connection(self) -> None:
"""Verify database connection with timeout"""
try:
with sqlite3.connect(str(self.db_path), timeout=20) as conn:
conn.execute("SELECT 1")
except sqlite3.Error as e:
raise Exception(f"Failed to connect to database: {str(e)}")
def setup_database(self):
def adapt_datetime(dt):
return dt.isoformat()
def convert_datetime(s):
return datetime.fromisoformat(s)
sqlite3.register_adapter(datetime, adapt_datetime)
sqlite3.register_converter("timestamp", convert_datetime)
try:
with sqlite3.connect(self.db_path, detect_types=sqlite3.PARSE_DECLTYPES, timeout=20) as conn:
conn.execute("PRAGMA journal_mode=WAL") # Enable Write-Ahead Logging for better concurrency
conn.execute("PRAGMA foreign_keys=ON") # Enable foreign key constraints
conn.executescript("""
CREATE TABLE IF NOT EXISTS downloads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
filename TEXT NOT NULL,
status TEXT NOT NULL,
start_time TIMESTAMP,
end_time TIMESTAMP,
file_size INTEGER,
file_hash TEXT,
metadata TEXT,
video_quality TEXT,
thumbnail_path TEXT,
subtitles TEXT,
retry_count INTEGER DEFAULT 0,
checksum TEXT,
tags TEXT,
notes TEXT
);
CREATE TABLE IF NOT EXISTS favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
title TEXT NOT NULL,
added_date TIMESTAMP,
tags TEXT,
notes TEXT,
category TEXT,
rating INTEGER
);
CREATE TABLE IF NOT EXISTS playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
title TEXT NOT NULL,
video_count INTEGER,
last_updated TIMESTAMP,
auto_download BOOLEAN,
download_schedule TEXT,
quality_preset TEXT
);
CREATE TABLE IF NOT EXISTS statistics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date DATE NOT NULL,
downloads_count INTEGER,
success_rate REAL,
total_size BIGINT,
average_speed REAL
);
""")
conn.commit()
except sqlite3.Error as e:
raise Exception(f"Database setup error: {str(e)}")
def add_download(self, download_info: DownloadInfo) -> int:
"""Add download record to database"""
try:
with sqlite3.connect(str(self.db_path), timeout=20) as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO downloads (
url, filename, status, start_time, file_size,
metadata, video_quality, thumbnail_path
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
download_info.url,
download_info.filename,
download_info.status.value,
download_info.start_time,
download_info.size,
json.dumps(download_info.metadata),
download_info.video_quality,
download_info.thumbnail_path
))
conn.commit()
return cursor.lastrowid
except sqlite3.Error as e:
logging.error(f"Database error in add_download: {str(e)}")
return -1
def update_download_status(self, download_id: int, status: DownloadStatus) -> None:
with sqlite3.connect(self.db_path) as conn:
conn.execute(
"UPDATE downloads SET status = ? WHERE id = ?",
(status.value, download_id)
)
def get_download_by_url(self, url: str) -> Optional[Dict]:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
result = cursor.execute(
"SELECT * FROM downloads WHERE url = ?",
(url,)
).fetchone()
return dict(zip([col[0] for col in cursor.description], result)) if result else None
class CatchStream:
# Main application class for video downloading and management
def __init__(self):
# Version info
self.version = "1.0.2"
self.author = "DV64"
self.console = Console()
# Quality presets configuration
self.quality_presets = {
"high": {
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
'video_quality': '1080p'
},
"medium": {
'format': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
'video_quality': '720p'
},
"low": {
'format': 'bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]/best',
'video_quality': '480p'
}
}
# Download management system
self.download_queue = asyncio.Queue()
self.active_downloads = {}
self.download_semaphore = asyncio.Semaphore(3) # Max concurrent downloads
# Core initialization
self.setup_paths()
self.load_config()
# Setup optimized event loop
try:
import uvloop
uvloop.install()
except ImportError:
pass
# Initialize core components
self._setup_logging()
self.db = DatabaseManager(str(Path(self.base_folder) / "catchstream.db"))
self.initialize_components()
# Initialize managers
self.stats_manager = StatisticsManager(self.db)
self.download_scheduler = DownloadScheduler(self)
# Setup caching system
self._cache = {}
self._cache_ttl = 300 # Cache lifetime in seconds
def display_banner(self):
"""Display application banner with enhanced design"""
banner = f"""[bold cyan]
╔══════════════════════════════════════════════════════════════════════╗
║ ______ __ __ _____ __ ║
║ / ____/___ _/ /______/ /_ / ___// /_________ ____ _____ ___ ║
║ / / / __ `/ __/ ___/ __ \\\\__ \\/ __/ ___/ _ \\/ __ `/ __ `__ \\ ║
║/ /___/ /_/ / /_/ /__/ / / /__/ / /_/ / / __/ /_/ / / / / / / ║
║\\____/\\__,_/\\__/\\___/_/ /_/____/\\__/_/ \\___/\\__,_/_/ /_/ /_/ ║
║ ║
║ [yellow]Version: {self.version}[/yellow] • [green]By: {self.author}[/green] • [blue]2025[/blue] ║
╚══════════════════════════════════════════════════════════════════════╝[/bold cyan]"""
self.console.print(banner)
# Display quick statistics
if self.active_downloads:
stats = Table.grid(padding=1)
stats.add_row(
f"[cyan]Active: {len(self.active_downloads)}[/cyan]",
f"[yellow]Queued: {self.download_queue.qsize()}[/yellow]",
f"[green]Completed: {self._get_completed_count()}[/green]"
)
self.console.print(stats)
async def download_video(self, url: str, format_id: str = "best",
filename: Optional[str] = None, quality: str = "medium",
ydl_opts: Optional[dict] = None) -> bool:
"""Async video download method with authentication support"""
try:
# Start with base options
download_opts = {
'format': self._get_quality_options(quality)['format'],
'outtmpl': os.path.join(self.paths['downloads']['video'], '%(title)s.%(ext)s'),
'quiet': True,
'no_warnings': True,
'progress_hooks': [self._update_progress_hook],
}
# Update with any provided options (like authentication)
if ydl_opts:
download_opts.update(ydl_opts)
return await self._async_download_video(url, format_id, filename, quality, download_opts)
except Exception as e:
logging.error(f"Download error: {str(e)}")
self.console.print(f"\n[red]Download error: {str(e)}[/red]")
return False
async def _async_download_video(self, url: str, format_id: str = "best",
filename: Optional[str] = None, quality: str = None,
ydl_opts: Optional[dict] = None) -> bool:
"""Async implementation for video downloading"""
async with self.download_semaphore:
try:
# Check cache for video info
cache_key = f"video_info_{url}"
info = self._cache.get(cache_key)
if not info:
with YoutubeDL({'quiet': True}) as ydl:
info = await asyncio.get_running_loop().run_in_executor(
None,
lambda: ydl.extract_info(url, download=False)
)
self._cache[cache_key] = info
# Setup download configuration
safe_filename = filename or self._generate_safe_filename(url, info)
download_info = self._create_download_info(url, format_id, safe_filename, info)
self.active_downloads[url] = download_info
# Get quality settings from presets
quality_preset = self.quality_presets.get(quality, self.quality_presets['medium'])
# Configure download settings
ydl_opts = {
'format': quality_preset['format'],
'outtmpl': os.path.join(self.paths['downloads']['video'], safe_filename),
'quiet': True,
'no_warnings': True,
'progress_hooks': [self._update_progress_hook],
'merge_output_format': 'mp4',
'writethumbnail': True,
'writesubtitles': True,
'subtitlesformat': 'srt',
'retries': self.config['download_options']['max_retries'],
'fragment_retries': self.config['download_options']['fragment_retries'],
'ratelimit': self.config['download_options']['ratelimit'],
'socket_timeout': self.config['download_options']['socket_timeout'],
'concurrent_fragments': 3,
'file_access_retries': 3,
'extractor_retries': 3,
'buffersize': 1024 * 16
}
# Execute download
result = await self._execute_download(url, ydl_opts)
if result == 0:
await self._handle_download_complete(download_info)
return True
return False
except Exception as e:
logging.error(f"Download error: {str(e)}")
if url in self.active_downloads:
self.active_downloads[url].status = DownloadStatus.FAILED
self.active_downloads[url].error = str(e)
return False
def _update_progress_hook(self, d):
"""Progress hook for yt-dlp"""
try:
url = d.get('info_dict', {}).get('webpage_url', '')
if url in self.active_downloads:
download_info = self.active_downloads[url]
if d['status'] == 'downloading':
total = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
if total > 0:
downloaded = d.get('downloaded_bytes', 0)
download_info.progress = (downloaded / total) * 100
download_info.downloaded_size = downloaded
download_info.size = total
# Update speed
speed = d.get('speed', 0)
if speed:
download_info.speed = self.format_speed(speed)
# Update ETA
eta = d.get('eta', 0)
if eta:
download_info.eta = str(timedelta(seconds=int(eta)))
elif d['status'] == 'finished':
download_info.status = DownloadStatus.COMPLETED
download_info.progress = 100.0
download_info.end_time = datetime.now()
download_info.speed = "0 B/s"
download_info.eta = "0:00"
except Exception as e:
logging.error(f"Progress hook error: {str(e)}")
async def validate_download(self, file_path: str) -> bool:
"""Validate downloaded file integrity"""
try:
if not os.path.exists(file_path):
return False
# Check file size
if os.path.getsize(file_path) == 0:
return False
# Verify file integrity
probe = await asyncio.to_thread(ffmpeg.probe, file_path)
if not probe or 'streams' not in probe:
return False
# Check for video stream
has_video = any(s['codec_type'] == 'video' for s in probe['streams'])
if not has_video:
return False
return True
except Exception as e:
logging.error(f"Download validation error: {str(e)}")
return False
def _download_complete_hook(self, d):
if d['status'] == 'finished':
url = d.get('url', '')
if url in self.active_downloads:
download = self.active_downloads[url]
download.status = DownloadStatus.COMPLETED
download.end_time = datetime.now()
def _download_error_hook(self, d):
if d['status'] == 'error':
url = d.get('url', '')
if url in self.active_downloads:
download = self.active_downloads[url]
download.status = DownloadStatus.FAILED
download.error = str(d.get('error'))
def _postprocess_hook(self, d):
if d['status'] == 'started':
url = d.get('url', '')
if url in self.active_downloads:
download = self.active_downloads[url]
download.status = DownloadStatus.PROCESSING
async def close(self):
await self.session.close()
self.thread_pool.shutdown()
self.download_scheduler.stop()
def _setup_logging(self):
log_file = os.path.join(
self.paths['log'],
f"catchstream_{datetime.now().strftime('%Y%m%d')}.log"
)
logging.basicConfig(
filename=log_file,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def load_config(self):
"""Load configuration with default quality settings"""
config_path = os.path.join(self.base_folder, "config.json")
default_config = {
'theme': 'cyan',
'auto_cleanup': True,
'max_concurrent_downloads': 3,
'download_path': str(Path.home() / 'Downloads' / 'CatchStream'),
'default_quality': {
'format': 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
'video_quality': '720p'
},
'log_retention_days': 30,
'audio_bitrate': '192k',
'compression_preset': 'medium',
'auto_archive': False,
'notifications': True,
'thumbnail_quality': 'high',
'download_options': {
'max_retries': 3,
'fragment_retries': 3,
'ratelimit': 1000000,
'socket_timeout': 30
},
'interface': {
'show_progress_bar': True,
'show_eta': True,
'show_speed': True,
'show_file_size': True
}
}
try:
os.makedirs(os.path.dirname(config_path), exist_ok=True)
if os.path.exists(config_path):
with open(config_path) as f:
saved_config = json.load(f)
# Merge saved config with default config to ensure all keys exist
self.config = {**default_config, **saved_config}
else:
self.config = default_config
with open(config_path, 'w') as f:
json.dump(default_config, f, indent=4)
except Exception as e:
logging.error(f"Failed to load config: {str(e)}")
self.config = default_config
def setup_paths(self):
"""Setup paths in a cross-platform way"""
# Get the Downloads folder path for any operating system
if os.name == 'nt': # Windows
downloads_dir = os.path.join(os.path.expanduser('~'), 'Downloads')
else: # Linux, MacOS, Android
downloads_dir = os.path.join(os.path.expanduser('~'), 'Downloads')
if not os.path.exists(downloads_dir): # Fallback for some Linux/Android systems
downloads_dir = os.path.join(os.path.expanduser('~'), 'Download')
# Create CatchStream folder inside Downloads
self.base_folder = os.path.join(downloads_dir, "CatchStream")
# Create separate folders for video and audio
self.paths = {
'config': os.path.join(self.base_folder, "config.json"),
'log': os.path.join(self.base_folder, "logs"),
'downloads': {
'video': os.path.join(self.base_folder, "downloads", "video"),
'audio': os.path.join(self.base_folder, "downloads", "audio")
},
'temp': os.path.join(self.base_folder, "temp"),
'cache': os.path.join(self.base_folder, "cache"),
'db': os.path.join(self.base_folder, "catchstream.db"),
'thumbnails': os.path.join(self.base_folder, "thumbnails"),
'exports': os.path.join(self.base_folder, "exports"),
'archive': os.path.join(self.base_folder, "archive")
}
# Create all directories
for path in self.paths.values():
if isinstance(path, dict): # For nested paths like downloads
for subpath in path.values():
os.makedirs(subpath, mode=0o755, exist_ok=True)
# Ensure write permissions
if not os.access(subpath, os.W_OK):
os.chmod(subpath, 0o755)
else:
if not path.endswith(('.db', '.json')):
os.makedirs(path, mode=0o755, exist_ok=True)
# Ensure write permissions
if not os.access(path, os.W_OK):
os.chmod(path, 0o755)
async def process_video(self, url: str, options: Dict[str, Any]) -> bool:
try:
download_info = self.active_downloads.get(url)
if not download_info:
return False