-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_manager.py
More file actions
171 lines (144 loc) · 5.98 KB
/
file_manager.py
File metadata and controls
171 lines (144 loc) · 5.98 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
"""File operations, validation, and organization for Zoom recordings."""
import logging
import os
import re
from datetime import date
from pathlib import Path
from typing import Optional
from mutagen.mp4 import MP4
from mutagen import MutagenError
logger = logging.getLogger(__name__)
class FileValidationError(Exception):
"""Raised when a downloaded file fails validation."""
pass
class FileManager:
"""Handles file organization, validation, and cleanup for recordings."""
def __init__(self, base_archive_path: str):
self._base_path = Path(base_archive_path)
def ensure_directory(self, recording_date: date,
account_name: str) -> Path:
"""Create and return the target directory: <base>/<YYYYMMDD>/<account_name>/."""
date_str = recording_date.strftime("%Y%m%d")
target = self._base_path / date_str / account_name
target.mkdir(parents=True, exist_ok=True)
return target
@staticmethod
def sanitize_filename(name: str, max_length: int = 200) -> str:
"""Remove characters illegal in Windows and Unix filenames.
Strips: < > : " / \\ | ? *
Collapses multiple spaces/underscores.
Truncates to max_length.
"""
# Replace illegal characters with underscores
sanitized = re.sub(r'[<>:"/\\|?*]', '_', name)
# Replace control characters
sanitized = re.sub(r'[\x00-\x1f\x7f]', '', sanitized)
# Collapse multiple underscores/spaces
sanitized = re.sub(r'[_\s]+', '_', sanitized)
# Strip leading/trailing underscores and spaces
sanitized = sanitized.strip('_ ')
# Truncate
if len(sanitized) > max_length:
sanitized = sanitized[:max_length]
# Fallback if empty
return sanitized or "recording"
def build_filename(self, recording_date: date,
meeting_topic: str) -> str:
"""Build filename: <YYYYMMDD><SanitizedTopic>.m4a."""
date_str = recording_date.strftime("%Y%m%d")
safe_topic = self.sanitize_filename(meeting_topic)
return f"{date_str}{safe_topic}.m4a"
def get_target_path(self, recording_date: date, account_name: str,
meeting_topic: str) -> Path:
"""Build the full target file path, creating directories as needed."""
target_dir = self.ensure_directory(recording_date, account_name)
filename = self.build_filename(recording_date, meeting_topic)
return target_dir / filename
def file_exists_with_size(self, file_path: Path,
expected_size: Optional[int] = None) -> bool:
"""Check if file exists and optionally matches expected size."""
if not file_path.exists():
return False
if expected_size is not None:
return file_path.stat().st_size == expected_size
return True
def validate_m4a(self, file_path: Path) -> bool:
"""Validate an M4A file using mutagen.
Checks: file exists, size > 0, mutagen can parse it.
Raises FileValidationError with details if invalid.
"""
path = Path(file_path)
if not path.exists():
raise FileValidationError(f"File does not exist: {path}")
size = path.stat().st_size
if size == 0:
raise FileValidationError(f"File is empty: {path}")
try:
MP4(str(path))
except MutagenError as e:
raise FileValidationError(
f"Invalid M4A file ({size} bytes): {path} - {e}"
) from e
return True
def validate_file_size(self, file_path: Path,
expected_size: int) -> bool:
"""Check if file size matches expected size from API.
Raises FileValidationError on mismatch.
"""
actual_size = Path(file_path).stat().st_size
if actual_size != expected_size:
raise FileValidationError(
f"Size mismatch for {file_path}: "
f"expected {expected_size}, got {actual_size}"
)
return True
def delete_file(self, file_path: Path) -> None:
"""Delete a file, logging the action."""
try:
Path(file_path).unlink(missing_ok=True)
logger.info("Deleted file: %s", file_path)
except OSError as e:
logger.error("Failed to delete %s: %s", file_path, e)
def get_archive_stats(self) -> dict:
"""Walk the base archive path and return summary statistics."""
total_files = 0
total_size = 0
dates = []
if not self._base_path.exists():
return {
"total_files": 0,
"total_size_bytes": 0,
"total_size_human": "0 B",
"date_folders": 0,
"oldest_date": None,
"newest_date": None,
}
for item in self._base_path.iterdir():
if item.is_dir() and re.match(r'^\d{8}$', item.name):
dates.append(item.name)
for root, _dirs, files in os.walk(item):
for f in files:
if f.lower().endswith('.m4a'):
total_files += 1
total_size += (Path(root) / f).stat().st_size
dates.sort()
return {
"total_files": total_files,
"total_size_bytes": total_size,
"total_size_human": self.human_readable_size(total_size),
"date_folders": len(dates),
"oldest_date": dates[0] if dates else None,
"newest_date": dates[-1] if dates else None,
}
@staticmethod
def human_readable_size(size_bytes: int) -> str:
"""Convert bytes to human-readable string."""
if size_bytes == 0:
return "0 B"
units = ["B", "KB", "MB", "GB", "TB"]
i = 0
size = float(size_bytes)
while size >= 1024 and i < len(units) - 1:
size /= 1024
i += 1
return f"{size:.1f} {units[i]}"