-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_service.py
More file actions
328 lines (301 loc) · 11.7 KB
/
Copy pathbackup_service.py
File metadata and controls
328 lines (301 loc) · 11.7 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
"""Persistence and application services for Xbox backup management."""
from __future__ import annotations
import json
import sqlite3
from contextlib import contextmanager
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from app_paths import DATABASE_PATH, ensure_app_dirs
from database_migrations import ensure_application_schema
from backup_manager import (
BackupItem,
FtpBackupClient,
FtpTarget,
ScanResult,
TransferResult,
export_backup_item,
import_stfs_zip,
install_stfs_package,
scan_local_target,
verify_backup_item,
)
from unityscraper.domains.backups.migrations import ensure_backup_schema
class BackupRepository:
"""Additive SQLite storage for targets, scans, inventory, and operations."""
def __init__(self, db_path: str | Path = DATABASE_PATH):
self.db_path = Path(db_path)
if self.db_path == DATABASE_PATH:
ensure_app_dirs()
else:
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self.ensure_schema()
@contextmanager
def connect(self):
connection = sqlite3.connect(self.db_path)
connection.row_factory = sqlite3.Row
try:
yield connection
connection.commit()
except Exception:
connection.rollback()
raise
finally:
connection.close()
def ensure_schema(self) -> None:
with self.connect() as connection:
ensure_backup_schema(connection)
ensure_application_schema(connection)
def save_local_target(self, name: str, location: str | Path) -> int:
now = datetime.now(timezone.utc).isoformat()
resolved = str(Path(location).expanduser().resolve())
with self.connect() as connection:
connection.execute(
"""
INSERT INTO backup_targets
(name, kind, location, settings_json, created_at, updated_at)
VALUES (?, 'local', ?, '{}', ?, ?)
ON CONFLICT(kind, location) DO UPDATE SET
name = excluded.name,
updated_at = excluded.updated_at
""",
(name, resolved, now, now),
)
row = connection.execute(
"SELECT id FROM backup_targets WHERE kind = 'local' AND location = ?",
(resolved,),
).fetchone()
return int(row["id"])
def save_ftp_target(self, name: str, target: FtpTarget) -> int:
"""Persist non-secret FTP settings. Passwords are deliberately omitted."""
now = datetime.now(timezone.utc).isoformat()
location = f"{target.host}:{target.port}"
settings = {
"username": target.username,
"content_root": target.content_root,
"games_root": target.games_root,
"timeout": target.timeout,
}
with self.connect() as connection:
connection.execute(
"""
INSERT INTO backup_targets
(name, kind, location, settings_json, created_at, updated_at)
VALUES (?, 'ftp', ?, ?, ?, ?)
ON CONFLICT(kind, location) DO UPDATE SET
name = excluded.name,
settings_json = excluded.settings_json,
updated_at = excluded.updated_at
""",
(name, location, json.dumps(settings), now, now),
)
row = connection.execute(
"SELECT id FROM backup_targets WHERE kind = 'ftp' AND location = ?",
(location,),
).fetchone()
return int(row["id"])
def list_targets(self) -> list[dict]:
with self.connect() as connection:
rows = connection.execute(
"SELECT * FROM backup_targets ORDER BY updated_at DESC"
).fetchall()
return [dict(row) for row in rows]
def begin_scan(self, location: str, target_id: Optional[int] = None) -> int:
with self.connect() as connection:
cursor = connection.execute(
"""
INSERT INTO backup_scans
(target_id, location, status, started_at)
VALUES (?, ?, 'running', ?)
""",
(target_id, location, datetime.now(timezone.utc).isoformat()),
)
return int(cursor.lastrowid)
def finish_scan(self, scan_id: int, result: ScanResult) -> None:
with self.connect() as connection:
for item in result.items:
connection.execute(
"""
INSERT INTO backup_inventory (
scan_id, titleid, name, format, content_type, media_id,
path, size, status, notes_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
scan_id,
item.title_id,
item.name,
item.format,
item.content_type,
item.media_id,
str(item.path),
item.size,
item.status,
json.dumps(item.notes),
),
)
connection.execute(
"""
UPDATE backup_scans
SET status = 'completed', item_count = ?, total_size = ?,
warnings_json = ?, finished_at = ?
WHERE id = ?
""",
(
len(result.items),
result.total_size,
json.dumps(result.warnings),
datetime.now(timezone.utc).isoformat(),
scan_id,
),
)
def fail_scan(self, scan_id: int, error: Exception) -> None:
with self.connect() as connection:
connection.execute(
"""
UPDATE backup_scans
SET status = 'failed', error_message = ?, finished_at = ?
WHERE id = ?
""",
(str(error), datetime.now(timezone.utc).isoformat(), scan_id),
)
def record_operation(
self,
operation: str,
source: str,
destination: str = "",
result: Optional[TransferResult] = None,
error: Optional[Exception] = None,
details: Optional[dict] = None,
) -> int:
now = datetime.now(timezone.utc).isoformat()
status = "failed" if error else (result.status if result else "completed")
with self.connect() as connection:
cursor = connection.execute(
"""
INSERT INTO backup_operations (
operation, source, destination, status, bytes_copied,
sha256, details_json, started_at, finished_at, error_message
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
operation,
source,
destination or (result.destination if result else ""),
status,
result.bytes_copied if result else 0,
result.sha256 if result else "",
json.dumps(details or {}),
now,
now,
str(error) if error else None,
),
)
return int(cursor.lastrowid)
class BackupService:
"""Coordinates backup operations with metadata lookup and audit records."""
def __init__(self, db_path: str | Path = DATABASE_PATH):
self.repository = BackupRepository(db_path)
def title_name(self, title_id: str) -> Optional[str]:
if not title_id:
return None
with self.repository.connect() as connection:
row = connection.execute(
"SELECT name FROM titleids WHERE titleid = ?",
(title_id.upper(),),
).fetchone()
return row["name"] if row and row["name"] else None
def scan(self, root: str | Path, target_name: str = "Local target") -> ScanResult:
target_id = self.repository.save_local_target(target_name, root)
scan_id = self.repository.begin_scan(str(Path(root).resolve()), target_id)
try:
result = scan_local_target(root, self.title_name)
self.repository.finish_scan(scan_id, result)
return result
except Exception as exc:
self.repository.fail_scan(scan_id, exc)
raise
def install_package(
self, source: str | Path, target: str | Path, conflict: str = "skip"
) -> TransferResult:
try:
result = install_stfs_package(source, target, conflict)
self.repository.record_operation("install_stfs", str(source), result=result)
return result
except Exception as exc:
self.repository.record_operation(
"install_stfs", str(source), str(target), error=exc
)
raise
def import_archive(
self, source: str | Path, target: str | Path, conflict: str = "skip"
) -> list[TransferResult]:
try:
results = import_stfs_zip(source, target, conflict)
self.repository.record_operation(
"import_stfs_zip",
str(source),
str(target),
details={"results": [asdict(result) for result in results]},
)
return results
except Exception as exc:
self.repository.record_operation(
"import_stfs_zip", str(source), str(target), error=exc
)
raise
def export(
self, item: BackupItem, destination: str | Path, conflict: str = "skip"
) -> Path:
try:
result = export_backup_item(item, destination, conflict)
self.repository.record_operation(
"export_backup",
str(item.path),
str(result),
details={"title_id": item.title_id},
)
return result
except Exception as exc:
self.repository.record_operation(
"export_backup", str(item.path), str(destination), error=exc
)
raise
def verify(self, item: BackupItem) -> list[str]:
issues = verify_backup_item(item)
self.repository.record_operation(
"verify_backup",
str(item.path),
details={"issues": issues},
)
return issues
def verify_many(self, items: list[BackupItem]) -> list[dict]:
"""Structurally verify an inventory batch."""
findings = []
for item in items:
issues = self.verify(item)
if issues:
findings.append({"path": str(item.path), "issues": issues})
return findings
def export_many(
self,
items: list[BackupItem],
destination: str | Path,
conflict: str = "skip",
) -> list[Path]:
"""Export an inventory batch using verified per-item exports."""
return [self.export(item, destination, conflict) for item in items]
def upload_ftp(
self, source: str | Path, target: FtpTarget
) -> TransferResult:
self.repository.save_ftp_target(target.host, target)
try:
result = FtpBackupClient(target).upload_stfs(source)
self.repository.record_operation("ftp_upload", str(source), result=result)
return result
except Exception as exc:
self.repository.record_operation(
"ftp_upload", str(source), f"{target.host}:{target.port}", error=exc
)
raise