mirror of
https://github.com/pacnpal/Pac-cogs.git
synced 2025-12-20 10:51:05 -05:00
Fixed Exception Structure:
Added FileCleanupError to utils/exceptions.py Created root exceptions.py for better organization Fixed circular imports in utils/init.py Updated imports in video_archiver.py and update_checker.py Fixed FFmpeg Management: Updated extraction logic for BtbN's new archive structure Added fallback for backward compatibility Better binary verification and permissions handling Improved Error Handling: Proper exception hierarchy Better error propagation More detailed error messages Enhanced cleanup on errors
This commit is contained in:
@@ -1,64 +1,26 @@
|
|||||||
"""Custom exceptions for the VideoArchiver cog"""
|
"""Base exceptions for VideoArchiver"""
|
||||||
|
|
||||||
class ProcessingError(Exception):
|
from .utils.exceptions import (
|
||||||
"""Base exception for video processing errors"""
|
VideoArchiverError,
|
||||||
def __init__(self, message: str, details: str = None):
|
ConfigurationError,
|
||||||
self.message = message
|
VideoVerificationError,
|
||||||
self.details = details
|
QueueError,
|
||||||
super().__init__(self.message)
|
FileCleanupError,
|
||||||
|
)
|
||||||
|
|
||||||
class DiscordAPIError(ProcessingError):
|
# Re-export base exceptions
|
||||||
"""Raised when Discord API operations fail"""
|
__all__ = [
|
||||||
pass
|
'VideoArchiverError',
|
||||||
|
'ConfigurationError',
|
||||||
|
'VideoVerificationError',
|
||||||
|
'QueueError',
|
||||||
|
'FileCleanupError',
|
||||||
|
'UpdateError',
|
||||||
|
'ProcessingError',
|
||||||
|
'ConfigError',
|
||||||
|
]
|
||||||
|
|
||||||
class UpdateError(ProcessingError):
|
# Alias exceptions for backward compatibility
|
||||||
"""Raised when update operations fail"""
|
ProcessingError = VideoArchiverError
|
||||||
pass
|
ConfigError = ConfigurationError
|
||||||
|
UpdateError = VideoVerificationError
|
||||||
class DownloadError(ProcessingError):
|
|
||||||
"""Raised when video download operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class QueueError(ProcessingError):
|
|
||||||
"""Raised when queue operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class ConfigError(ProcessingError):
|
|
||||||
"""Raised when configuration operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class FileOperationError(ProcessingError):
|
|
||||||
"""Raised when file operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class VideoValidationError(ProcessingError):
|
|
||||||
"""Raised when video validation fails"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class PermissionError(ProcessingError):
|
|
||||||
"""Raised when permission checks fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class ResourceExhaustedError(ProcessingError):
|
|
||||||
"""Raised when system resources are exhausted"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class NetworkError(ProcessingError):
|
|
||||||
"""Raised when network operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class FFmpegError(ProcessingError):
|
|
||||||
"""Raised when FFmpeg operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class CleanupError(ProcessingError):
|
|
||||||
"""Raised when cleanup operations fail"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class URLExtractionError(ProcessingError):
|
|
||||||
"""Raised when URL extraction fails"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
class MessageFormatError(ProcessingError):
|
|
||||||
"""Raised when message formatting fails"""
|
|
||||||
pass
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
|||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
from .exceptions import UpdateError
|
from .exceptions import UpdateError
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,11 @@
|
|||||||
from .exceptions import FileCleanupError, VideoVerificationError
|
from .exceptions import FileCleanupError, VideoVerificationError
|
||||||
from .file_ops import secure_delete_file, cleanup_downloads
|
from .file_ops import secure_delete_file, cleanup_downloads
|
||||||
from .path_manager import temp_path_context
|
from .path_manager import temp_path_context
|
||||||
from .video_downloader import VideoDownloader
|
|
||||||
from .message_manager import MessageManager
|
from .message_manager import MessageManager
|
||||||
|
|
||||||
|
# Import VideoDownloader last to avoid circular imports
|
||||||
|
from .video_downloader import VideoDownloader
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'FileCleanupError',
|
'FileCleanupError',
|
||||||
'VideoVerificationError',
|
'VideoVerificationError',
|
||||||
|
|||||||
@@ -17,11 +17,12 @@ from videoarchiver.ffmpeg.ffmpeg_manager import FFmpegManager
|
|||||||
from videoarchiver.ffmpeg.exceptions import (
|
from videoarchiver.ffmpeg.exceptions import (
|
||||||
FFmpegError,
|
FFmpegError,
|
||||||
CompressionError,
|
CompressionError,
|
||||||
VideoVerificationError,
|
VerificationError,
|
||||||
FFprobeError,
|
FFprobeError,
|
||||||
TimeoutError,
|
TimeoutError,
|
||||||
handle_ffmpeg_error
|
handle_ffmpeg_error
|
||||||
)
|
)
|
||||||
|
from videoarchiver.utils.exceptions import VideoVerificationError
|
||||||
from videoarchiver.utils.file_ops import secure_delete_file
|
from videoarchiver.utils.file_ops import secure_delete_file
|
||||||
from videoarchiver.utils.path_manager import temp_path_context
|
from videoarchiver.utils.path_manager import temp_path_context
|
||||||
|
|
||||||
|
|||||||
@@ -18,16 +18,18 @@ from videoarchiver.utils.video_downloader import VideoDownloader
|
|||||||
from videoarchiver.utils.message_manager import MessageManager
|
from videoarchiver.utils.message_manager import MessageManager
|
||||||
from videoarchiver.utils.file_ops import cleanup_downloads
|
from videoarchiver.utils.file_ops import cleanup_downloads
|
||||||
from videoarchiver.enhanced_queue import EnhancedVideoQueueManager
|
from videoarchiver.enhanced_queue import EnhancedVideoQueueManager
|
||||||
from videoarchiver.ffmpeg.ffmpeg_manager import FFmpegManager # Add FFmpeg manager import
|
from videoarchiver.ffmpeg.ffmpeg_manager import FFmpegManager
|
||||||
from videoarchiver.exceptions import (
|
from videoarchiver.utils.exceptions import (
|
||||||
ProcessingError,
|
VideoArchiverError as ProcessingError,
|
||||||
ConfigError,
|
ConfigurationError as ConfigError,
|
||||||
UpdateError,
|
VideoVerificationError as UpdateError,
|
||||||
QueueError,
|
QueueError,
|
||||||
FileOperationError
|
FileCleanupError as FileOperationError
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger('VideoArchiver')
|
|
||||||
|
logger = logging.getLogger("VideoArchiver")
|
||||||
|
|
||||||
|
|
||||||
class VideoArchiver(commands.Cog):
|
class VideoArchiver(commands.Cog):
|
||||||
"""Archive videos from Discord channels"""
|
"""Archive videos from Discord channels"""
|
||||||
@@ -79,7 +81,7 @@ class VideoArchiver(commands.Cog):
|
|||||||
max_queue_size=1000,
|
max_queue_size=1000,
|
||||||
cleanup_interval=1800,
|
cleanup_interval=1800,
|
||||||
max_history_age=86400,
|
max_history_age=86400,
|
||||||
persistence_path=str(queue_path)
|
persistence_path=str(queue_path),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Initialize update checker
|
# Initialize update checker
|
||||||
@@ -90,7 +92,7 @@ class VideoArchiver(commands.Cog):
|
|||||||
self.bot,
|
self.bot,
|
||||||
self.config_manager,
|
self.config_manager,
|
||||||
self.components,
|
self.components,
|
||||||
queue_manager=self.queue_manager
|
queue_manager=self.queue_manager,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Start update checker
|
# Start update checker
|
||||||
@@ -102,7 +104,9 @@ class VideoArchiver(commands.Cog):
|
|||||||
logger.info("VideoArchiver initialization completed successfully")
|
logger.info("VideoArchiver initialization completed successfully")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Critical error during initialization: {traceback.format_exc()}")
|
logger.error(
|
||||||
|
f"Critical error during initialization: {traceback.format_exc()}"
|
||||||
|
)
|
||||||
# Clean up any partially initialized components
|
# Clean up any partially initialized components
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
raise
|
raise
|
||||||
@@ -146,34 +150,34 @@ class VideoArchiver(commands.Cog):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# Stop update checker
|
# Stop update checker
|
||||||
if hasattr(self, 'update_checker'):
|
if hasattr(self, "update_checker"):
|
||||||
await self.update_checker.stop()
|
await self.update_checker.stop()
|
||||||
|
|
||||||
# Clean up processor
|
# Clean up processor
|
||||||
if hasattr(self, 'processor'):
|
if hasattr(self, "processor"):
|
||||||
await self.processor.cleanup()
|
await self.processor.cleanup()
|
||||||
|
|
||||||
# Clean up queue manager
|
# Clean up queue manager
|
||||||
if hasattr(self, 'queue_manager'):
|
if hasattr(self, "queue_manager"):
|
||||||
await self.queue_manager.cleanup()
|
await self.queue_manager.cleanup()
|
||||||
|
|
||||||
# Clean up components for each guild
|
# Clean up components for each guild
|
||||||
if hasattr(self, 'components'):
|
if hasattr(self, "components"):
|
||||||
for guild_id, components in self.components.items():
|
for guild_id, components in self.components.items():
|
||||||
try:
|
try:
|
||||||
if 'message_manager' in components:
|
if "message_manager" in components:
|
||||||
await components['message_manager'].cancel_all_deletions()
|
await components["message_manager"].cancel_all_deletions()
|
||||||
if 'downloader' in components:
|
if "downloader" in components:
|
||||||
components['downloader'] = None
|
components["downloader"] = None
|
||||||
if 'ffmpeg_mgr' in components:
|
if "ffmpeg_mgr" in components:
|
||||||
components['ffmpeg_mgr'] = None
|
components["ffmpeg_mgr"] = None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error cleaning up guild {guild_id}: {str(e)}")
|
logger.error(f"Error cleaning up guild {guild_id}: {str(e)}")
|
||||||
|
|
||||||
self.components.clear()
|
self.components.clear()
|
||||||
|
|
||||||
# Clean up download directory
|
# Clean up download directory
|
||||||
if hasattr(self, 'download_path') and self.download_path.exists():
|
if hasattr(self, "download_path") and self.download_path.exists():
|
||||||
try:
|
try:
|
||||||
cleanup_downloads(str(self.download_path))
|
cleanup_downloads(str(self.download_path))
|
||||||
self.download_path.rmdir()
|
self.download_path.rmdir()
|
||||||
@@ -198,38 +202,39 @@ class VideoArchiver(commands.Cog):
|
|||||||
# Clean up old components if they exist
|
# Clean up old components if they exist
|
||||||
if guild_id in self.components:
|
if guild_id in self.components:
|
||||||
old_components = self.components[guild_id]
|
old_components = self.components[guild_id]
|
||||||
if 'message_manager' in old_components:
|
if "message_manager" in old_components:
|
||||||
await old_components['message_manager'].cancel_all_deletions()
|
await old_components["message_manager"].cancel_all_deletions()
|
||||||
if 'downloader' in old_components:
|
if "downloader" in old_components:
|
||||||
old_components['downloader'] = None
|
old_components["downloader"] = None
|
||||||
if 'ffmpeg_mgr' in old_components:
|
if "ffmpeg_mgr" in old_components:
|
||||||
old_components['ffmpeg_mgr'] = None
|
old_components["ffmpeg_mgr"] = None
|
||||||
|
|
||||||
# Initialize FFmpeg manager first
|
# Initialize FFmpeg manager first
|
||||||
ffmpeg_mgr = FFmpegManager()
|
ffmpeg_mgr = FFmpegManager()
|
||||||
|
|
||||||
# Initialize new components with validated settings
|
# Initialize new components with validated settings
|
||||||
self.components[guild_id] = {
|
self.components[guild_id] = {
|
||||||
'ffmpeg_mgr': ffmpeg_mgr, # Add FFmpeg manager to components
|
"ffmpeg_mgr": ffmpeg_mgr, # Add FFmpeg manager to components
|
||||||
'downloader': VideoDownloader(
|
"downloader": VideoDownloader(
|
||||||
str(self.download_path),
|
str(self.download_path),
|
||||||
settings['video_format'],
|
settings["video_format"],
|
||||||
settings['video_quality'],
|
settings["video_quality"],
|
||||||
settings['max_file_size'],
|
settings["max_file_size"],
|
||||||
settings['enabled_sites'] if settings['enabled_sites'] else None,
|
settings["enabled_sites"] if settings["enabled_sites"] else None,
|
||||||
settings['concurrent_downloads'],
|
settings["concurrent_downloads"],
|
||||||
ffmpeg_mgr=ffmpeg_mgr # Pass FFmpeg manager to VideoDownloader
|
ffmpeg_mgr=ffmpeg_mgr, # Pass FFmpeg manager to VideoDownloader
|
||||||
|
),
|
||||||
|
"message_manager": MessageManager(
|
||||||
|
settings["message_duration"], settings["message_template"]
|
||||||
),
|
),
|
||||||
'message_manager': MessageManager(
|
|
||||||
settings['message_duration'],
|
|
||||||
settings['message_template']
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(f"Successfully initialized components for guild {guild_id}")
|
logger.info(f"Successfully initialized components for guild {guild_id}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to initialize guild {guild_id}: {traceback.format_exc()}")
|
logger.error(
|
||||||
|
f"Failed to initialize guild {guild_id}: {traceback.format_exc()}"
|
||||||
|
)
|
||||||
raise ProcessingError(f"Guild initialization failed: {str(e)}")
|
raise ProcessingError(f"Guild initialization failed: {str(e)}")
|
||||||
|
|
||||||
@commands.Cog.listener()
|
@commands.Cog.listener()
|
||||||
@@ -251,12 +256,12 @@ class VideoArchiver(commands.Cog):
|
|||||||
if guild.id in self.components:
|
if guild.id in self.components:
|
||||||
# Clean up components
|
# Clean up components
|
||||||
components = self.components[guild.id]
|
components = self.components[guild.id]
|
||||||
if 'message_manager' in components:
|
if "message_manager" in components:
|
||||||
await components['message_manager'].cancel_all_deletions()
|
await components["message_manager"].cancel_all_deletions()
|
||||||
if 'downloader' in components:
|
if "downloader" in components:
|
||||||
components['downloader'] = None
|
components["downloader"] = None
|
||||||
if 'ffmpeg_mgr' in components:
|
if "ffmpeg_mgr" in components:
|
||||||
components['ffmpeg_mgr'] = None
|
components["ffmpeg_mgr"] = None
|
||||||
|
|
||||||
# Remove guild components
|
# Remove guild components
|
||||||
self.components.pop(guild.id)
|
self.components.pop(guild.id)
|
||||||
@@ -274,9 +279,13 @@ class VideoArchiver(commands.Cog):
|
|||||||
try:
|
try:
|
||||||
await self.processor.process_message(message)
|
await self.processor.process_message(message)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error processing message {message.id}: {traceback.format_exc()}")
|
logger.error(
|
||||||
|
f"Error processing message {message.id}: {traceback.format_exc()}"
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
log_channel = await self.config_manager.get_channel(message.guild, "log")
|
log_channel = await self.config_manager.get_channel(
|
||||||
|
message.guild, "log"
|
||||||
|
)
|
||||||
if log_channel:
|
if log_channel:
|
||||||
await log_channel.send(
|
await log_channel.send(
|
||||||
f"Error processing message: {str(e)}\n"
|
f"Error processing message: {str(e)}\n"
|
||||||
@@ -303,8 +312,12 @@ class VideoArchiver(commands.Cog):
|
|||||||
elif isinstance(error, ProcessingError):
|
elif isinstance(error, ProcessingError):
|
||||||
error_msg = f"❌ Processing error: {str(error)}"
|
error_msg = f"❌ Processing error: {str(error)}"
|
||||||
else:
|
else:
|
||||||
logger.error(f"Command error in {ctx.command}: {traceback.format_exc()}")
|
logger.error(
|
||||||
error_msg = "❌ An unexpected error occurred. Check the logs for details."
|
f"Command error in {ctx.command}: {traceback.format_exc()}"
|
||||||
|
)
|
||||||
|
error_msg = (
|
||||||
|
"❌ An unexpected error occurred. Check the logs for details."
|
||||||
|
)
|
||||||
|
|
||||||
if error_msg:
|
if error_msg:
|
||||||
await ctx.send(error_msg)
|
await ctx.send(error_msg)
|
||||||
@@ -312,6 +325,8 @@ class VideoArchiver(commands.Cog):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error handling command error: {str(e)}")
|
logger.error(f"Error handling command error: {str(e)}")
|
||||||
try:
|
try:
|
||||||
await ctx.send("❌ An error occurred while handling another error. Please check the logs.")
|
await ctx.send(
|
||||||
|
"❌ An error occurred while handling another error. Please check the logs."
|
||||||
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass # Give up if we can't even send error messages
|
pass # Give up if we can't even send error messages
|
||||||
|
|||||||
Reference in New Issue
Block a user