Update scripts/file_manager.py
Some checks failed
Generate M3U Playlist / build (push) Has been cancelled
Some checks failed
Generate M3U Playlist / build (push) Has been cancelled
This commit is contained in:
parent
e41d8409ee
commit
4cf684e88e
1 changed files with 14 additions and 75 deletions
|
@ -1,5 +1,5 @@
|
||||||
"""
|
"""
|
||||||
File Manager - FIXED to work with correct paths from scripts folder
|
File Manager - Handles file operations, backups, and channel loading
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
@ -11,38 +11,30 @@ from pathlib import Path
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
class FileManager:
|
class FileManager:
|
||||||
"""Manage file operations with backup and rotation - FIXED paths."""
|
"""Manage file operations with backup and rotation."""
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.config = config
|
self.config = config
|
||||||
self.logger = logging.getLogger(__name__)
|
self.logger = logging.getLogger(__name__)
|
||||||
|
self.backup_dir = Path("backups")
|
||||||
# FIXED: Get root directory and create backups there
|
|
||||||
script_dir = Path(__file__).parent
|
|
||||||
root_dir = script_dir.parent
|
|
||||||
self.backup_dir = root_dir / "backups"
|
|
||||||
self.backup_dir.mkdir(exist_ok=True)
|
self.backup_dir.mkdir(exist_ok=True)
|
||||||
|
|
||||||
self.logger.info(f"FileManager initialized - root: {root_dir}")
|
|
||||||
|
|
||||||
def create_backup(self, file_path: str) -> Optional[Path]:
|
def create_backup(self, file_path: str) -> Optional[Path]:
|
||||||
"""Create timestamped backup with rotation."""
|
"""Create timestamped backup with rotation."""
|
||||||
if not self.config.settings.get('create_backup', True):
|
if not self.config.settings.get('create_backup', True):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Use the full path from config
|
file_path = Path(file_path)
|
||||||
full_path = Path(file_path)
|
if not file_path.exists():
|
||||||
if not full_path.exists():
|
|
||||||
self.logger.info(f"No file to backup: {file_path}")
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||||
backup_path = self.backup_dir / f"{full_path.stem}_{timestamp}{full_path.suffix}"
|
backup_path = self.backup_dir / f"{file_path.stem}_{timestamp}{file_path.suffix}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.copy2(full_path, backup_path)
|
shutil.copy2(file_path, backup_path)
|
||||||
self.logger.info(f"Created backup: {backup_path}")
|
self.logger.info(f"Created backup: {backup_path}")
|
||||||
self._cleanup_old_backups(full_path.stem)
|
self._cleanup_old_backups(file_path.stem)
|
||||||
return backup_path
|
return backup_path
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Failed to create backup: {e}")
|
self.logger.error(f"Failed to create backup: {e}")
|
||||||
|
@ -67,22 +59,14 @@ class FileManager:
|
||||||
|
|
||||||
def load_all_channels(self) -> List[Dict]:
|
def load_all_channels(self) -> List[Dict]:
|
||||||
"""Load all channels from the channels file."""
|
"""Load all channels from the channels file."""
|
||||||
channels_file = self.config.channels_file
|
if not os.path.exists(self.config.channels_file):
|
||||||
|
self.logger.info("No channels.txt file found")
|
||||||
self.logger.info(f"Attempting to load channels from: {channels_file}")
|
|
||||||
|
|
||||||
if not os.path.exists(channels_file):
|
|
||||||
self.logger.info(f"No channels file found at: {channels_file}")
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(channels_file, 'r', encoding='utf-8') as f:
|
with open(self.config.channels_file, 'r', encoding='utf-8') as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
if not content.strip():
|
|
||||||
self.logger.info(f"Channels file is empty: {channels_file}")
|
|
||||||
return []
|
|
||||||
|
|
||||||
channel_blocks = re.split(r'\n\s*\n+', content.strip())
|
channel_blocks = re.split(r'\n\s*\n+', content.strip())
|
||||||
channels = []
|
channels = []
|
||||||
|
|
||||||
|
@ -113,68 +97,23 @@ class FileManager:
|
||||||
|
|
||||||
def save_channels(self, channels: List[Dict]) -> bool:
|
def save_channels(self, channels: List[Dict]) -> bool:
|
||||||
"""Save channels to the channels.txt file."""
|
"""Save channels to the channels.txt file."""
|
||||||
channels_file = self.config.channels_file
|
|
||||||
|
|
||||||
self.logger.info(f"Attempting to save {len(channels)} channels to: {channels_file}")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Create backup first
|
# Create backup first
|
||||||
self.create_backup(channels_file)
|
self.create_backup(self.config.channels_file)
|
||||||
|
|
||||||
# Write all channels
|
with open(self.config.channels_file, 'w', encoding='utf-8') as f:
|
||||||
with open(channels_file, 'w', encoding='utf-8') as f:
|
|
||||||
for i, channel in enumerate(channels):
|
for i, channel in enumerate(channels):
|
||||||
if i > 0:
|
if i > 0:
|
||||||
f.write("\n\n")
|
f.write("\n\n")
|
||||||
f.write(self._convert_to_channels_txt_block(channel))
|
f.write(self._convert_to_channels_txt_block(channel))
|
||||||
|
|
||||||
self.logger.info(f"Successfully saved {len(channels)} channels to {channels_file}")
|
self.logger.info(f"Saved {len(channels)} channels to file")
|
||||||
|
|
||||||
# Verify the file was written
|
|
||||||
if os.path.exists(channels_file):
|
|
||||||
size = os.path.getsize(channels_file)
|
|
||||||
self.logger.info(f"Verified: {channels_file} now has {size} bytes")
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Error saving channels: {e}")
|
self.logger.error(f"Error saving channels: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def append_channels(self, new_channels: List[Dict]) -> bool:
|
|
||||||
"""Append new channels to existing channels file."""
|
|
||||||
if not new_channels:
|
|
||||||
self.logger.info("No new channels to append")
|
|
||||||
return True
|
|
||||||
|
|
||||||
channels_file = self.config.channels_file
|
|
||||||
|
|
||||||
self.logger.info(f"Appending {len(new_channels)} channels to: {channels_file}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Check if file exists and has content
|
|
||||||
file_exists = os.path.exists(channels_file) and os.path.getsize(channels_file) > 0
|
|
||||||
|
|
||||||
with open(channels_file, 'a', encoding='utf-8') as f:
|
|
||||||
for i, channel in enumerate(new_channels):
|
|
||||||
# Add separator if file has content or this isn't the first new channel
|
|
||||||
if i > 0 or file_exists:
|
|
||||||
f.write("\n\n")
|
|
||||||
f.write(self._convert_to_channels_txt_block(channel))
|
|
||||||
|
|
||||||
self.logger.info(f"Successfully appended {len(new_channels)} channels")
|
|
||||||
|
|
||||||
# Verify the file was updated
|
|
||||||
if os.path.exists(channels_file):
|
|
||||||
size = os.path.getsize(channels_file)
|
|
||||||
self.logger.info(f"Verified: {channels_file} now has {size} bytes")
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.error(f"Error appending channels: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _convert_to_channels_txt_block(self, channel_data: Dict) -> str:
|
def _convert_to_channels_txt_block(self, channel_data: Dict) -> str:
|
||||||
"""Convert to channels.txt format."""
|
"""Convert to channels.txt format."""
|
||||||
block = []
|
block = []
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue