Karan Adhikari commited on
fix multipart delete
Browse files- Backend/helper/database.py +32 -102
Backend/helper/database.py
CHANGED
|
@@ -82,7 +82,6 @@ class Database:
|
|
| 82 |
|
| 83 |
|
| 84 |
async def get_settings(self) -> dict:
|
| 85 |
-
"""Return the full runtime settings document, or {} if none exists yet."""
|
| 86 |
try:
|
| 87 |
doc = await self.dbs["tracking"]["settings"].find_one({"_id": "app_settings"})
|
| 88 |
return doc or {}
|
|
@@ -91,10 +90,6 @@ class Database:
|
|
| 91 |
return {}
|
| 92 |
|
| 93 |
async def save_settings(self, settings: dict) -> bool:
|
| 94 |
-
"""
|
| 95 |
-
Persist *settings* to the tracking database.
|
| 96 |
-
Uses upsert so the first call creates the document automatically.
|
| 97 |
-
"""
|
| 98 |
try:
|
| 99 |
clean = {k: v for k, v in settings.items() if k != "_id"}
|
| 100 |
await self.dbs["tracking"]["settings"].update_one(
|
|
@@ -110,9 +105,6 @@ class Database:
|
|
| 110 |
|
| 111 |
|
| 112 |
async def connect_storage_db(self, uri: str, index: int) -> bool:
|
| 113 |
-
"""Connect and register a single database at `index`. Verifies the
|
| 114 |
-
connection actually works (via a ping) before registering it, so a
|
| 115 |
-
bad URI never leaves stale half-registered state behind."""
|
| 116 |
try:
|
| 117 |
client = motor.motor_asyncio.AsyncIOMotorClient(uri)
|
| 118 |
await client.admin.command("ping")
|
|
@@ -130,8 +122,6 @@ class Database:
|
|
| 130 |
return False
|
| 131 |
|
| 132 |
async def disconnect_storage_db(self, index: int) -> None:
|
| 133 |
-
"""Close and unregister the storage database at `index`. Never call
|
| 134 |
-
this with index 0 or 1 — those are the locked essential databases."""
|
| 135 |
db_key = f"storage_{index}"
|
| 136 |
client = self.clients.pop(db_key, None)
|
| 137 |
self.dbs.pop(db_key, None)
|
|
@@ -140,14 +130,6 @@ class Database:
|
|
| 140 |
LOGGER.info(f"Disconnected {db_key}.")
|
| 141 |
|
| 142 |
def get_database_list(self) -> List[Dict[str, Any]]:
|
| 143 |
-
"""
|
| 144 |
-
Return every configured database for the admin Settings page.
|
| 145 |
-
|
| 146 |
-
Locked entries (tracking + storage_1) only expose a masked URI since
|
| 147 |
-
they're never editable. Unlocked "extra" entries also include the
|
| 148 |
-
full, unmasked URI (`full_uri`) so the admin can actually edit it in
|
| 149 |
-
the Settings panel — they're already authenticated, so this is safe.
|
| 150 |
-
"""
|
| 151 |
result = []
|
| 152 |
for index, uri in enumerate(self.db_uris):
|
| 153 |
masked = re.sub(r"://(.*?):.*?@", r"://\1:*****@", uri).split('?')[0]
|
|
@@ -165,15 +147,6 @@ class Database:
|
|
| 165 |
return result
|
| 166 |
|
| 167 |
async def reload_extra_databases(self, new_extra_uris: List[str]) -> Dict[str, Any]:
|
| 168 |
-
"""
|
| 169 |
-
Hot-reload additional storage databases (index >= 2) without touching
|
| 170 |
-
the locked tracking (0) and storage_1 (1) databases.
|
| 171 |
-
|
| 172 |
-
Raises ValueError (caught by SettingsManager / the API layer and
|
| 173 |
-
reported to the admin) if the requested change would alter or remove
|
| 174 |
-
a database that isn't at the end of the list, or if a new database
|
| 175 |
-
URI fails to connect.
|
| 176 |
-
"""
|
| 177 |
old_extra = self.db_uris[2:]
|
| 178 |
new_extra = [u.strip() for u in (new_extra_uris or []) if u and u.strip()]
|
| 179 |
|
|
@@ -211,10 +184,6 @@ class Database:
|
|
| 211 |
LOGGER.info(f"reload_extra_databases: {message}")
|
| 212 |
return {"added": added, "removed": removed, "message": message}
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
# -------------------------------
|
| 219 |
# User Subscription Management
|
| 220 |
# -------------------------------
|
|
@@ -426,9 +395,6 @@ class Database:
|
|
| 426 |
"days_assigned": days,
|
| 427 |
}
|
| 428 |
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
# -------------------------------
|
| 433 |
# Custom Catalog Management
|
| 434 |
# -------------------------------
|
|
@@ -693,9 +659,6 @@ class Database:
|
|
| 693 |
# -------------------------------
|
| 694 |
|
| 695 |
async def _build_part_id_and_size(self, parts: List[dict]) -> Tuple[str, str]:
|
| 696 |
-
"""Given a list of part dicts (chat_id, msg_id, part_number, size_bytes),
|
| 697 |
-
produce the aggregate opaque stream `id` (encoding all parts, ordered)
|
| 698 |
-
and the human-readable total size string."""
|
| 699 |
sorted_parts = sorted(parts, key=lambda p: p.get("part_number", 0))
|
| 700 |
payload = {"parts": [{"chat_id": p["chat_id"], "msg_id": p["msg_id"]} for p in sorted_parts]}
|
| 701 |
encoded = await encode_string(payload)
|
|
@@ -705,10 +668,6 @@ class Database:
|
|
| 705 |
return encoded, size_str
|
| 706 |
|
| 707 |
async def remove_media_part(self, channel: int, msg_id: int) -> bool:
|
| 708 |
-
"""Remove a single Telegram message from the database, whether it was
|
| 709 |
-
stored as a standalone quality entry (legacy single-file) or as one
|
| 710 |
-
part of a multi-part split-file quality entry. Mirrors
|
| 711 |
-
delete_media_by_stream_id's cleanup-cascading behaviour."""
|
| 712 |
try:
|
| 713 |
legacy_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
|
| 714 |
if await self.delete_media_by_stream_id(legacy_hash):
|
|
@@ -857,9 +816,6 @@ class Database:
|
|
| 857 |
return await self.update_tv_show(tv_show)
|
| 858 |
|
| 859 |
async def _merge_split_part(self, qualities: List[dict], quality_to_update: dict) -> List[dict]:
|
| 860 |
-
"""Merge an incoming split-part QualityDetail into the matching
|
| 861 |
-
group (by group_key) within `qualities`, or append it as the first
|
| 862 |
-
part of a new group. Returns the updated qualities list."""
|
| 863 |
group_key = quality_to_update.get("group_key")
|
| 864 |
incoming_parts = quality_to_update.get("parts") or []
|
| 865 |
if not incoming_parts:
|
|
@@ -1368,6 +1324,32 @@ class Database:
|
|
| 1368 |
return False
|
| 1369 |
raise
|
| 1370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1371 |
async def delete_document(self, media_type: str, tmdb_id: int, db_index: int) -> bool:
|
| 1372 |
db_key = f"storage_{db_index}"
|
| 1373 |
|
|
@@ -1375,15 +1357,7 @@ class Database:
|
|
| 1375 |
doc = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
|
| 1376 |
if doc and "telegram" in doc:
|
| 1377 |
for quality in doc["telegram"]:
|
| 1378 |
-
|
| 1379 |
-
old_id = quality.get("id")
|
| 1380 |
-
if old_id:
|
| 1381 |
-
decoded_data = await decode_string(old_id)
|
| 1382 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1383 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1384 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1385 |
-
except Exception as e:
|
| 1386 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1387 |
|
| 1388 |
result = await self.dbs[db_key]["movie"].delete_one({"tmdb_id": tmdb_id})
|
| 1389 |
else:
|
|
@@ -1392,15 +1366,7 @@ class Database:
|
|
| 1392 |
for season in doc["seasons"]:
|
| 1393 |
for episode in season.get("episodes", []):
|
| 1394 |
for quality in episode.get("telegram", []):
|
| 1395 |
-
|
| 1396 |
-
old_id = quality.get("id")
|
| 1397 |
-
if old_id:
|
| 1398 |
-
decoded_data = await decode_string(old_id)
|
| 1399 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1400 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1401 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1402 |
-
except Exception as e:
|
| 1403 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1404 |
|
| 1405 |
result = await self.dbs[db_key]["tv"].delete_one({"tmdb_id": tmdb_id})
|
| 1406 |
|
|
@@ -1411,8 +1377,6 @@ class Database:
|
|
| 1411 |
return False
|
| 1412 |
|
| 1413 |
async def get_title_by_stream_id(self, stream_id_hash: str) -> Optional[str]:
|
| 1414 |
-
"""Look up the original media title across all storage DBs using the telegram file ID hash.
|
| 1415 |
-
For TV shows, it includes the Season and Episode number in the title."""
|
| 1416 |
for i in range(1, self.current_db_index + 1):
|
| 1417 |
db = self.dbs[f"storage_{i}"]
|
| 1418 |
|
|
@@ -1438,8 +1402,6 @@ class Database:
|
|
| 1438 |
return None
|
| 1439 |
|
| 1440 |
async def delete_media_by_stream_id(self, stream_id_hash: str) -> bool:
|
| 1441 |
-
"""Finds and removes a specific stream quality by its hash across all DBs.
|
| 1442 |
-
If it's the last quality, it cleans up the movie or episode/season/show."""
|
| 1443 |
for i in range(1, self.current_db_index + 1):
|
| 1444 |
db = self.dbs[f"storage_{i}"]
|
| 1445 |
|
|
@@ -1483,15 +1445,7 @@ class Database:
|
|
| 1483 |
|
| 1484 |
for q in movie["telegram"]:
|
| 1485 |
if q.get("id") == id:
|
| 1486 |
-
|
| 1487 |
-
old_id = q.get("id")
|
| 1488 |
-
if old_id:
|
| 1489 |
-
decoded_data = await decode_string(old_id)
|
| 1490 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1491 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1492 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1493 |
-
except Exception as e:
|
| 1494 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1495 |
break
|
| 1496 |
|
| 1497 |
original_len = len(movie["telegram"])
|
|
@@ -1517,15 +1471,7 @@ class Database:
|
|
| 1517 |
for ep in season["episodes"]:
|
| 1518 |
if ep.get("episode_number") == episode_number:
|
| 1519 |
for quality in ep.get("telegram", []):
|
| 1520 |
-
|
| 1521 |
-
old_id = quality.get("id")
|
| 1522 |
-
if old_id:
|
| 1523 |
-
decoded_data = await decode_string(old_id)
|
| 1524 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1525 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1526 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1527 |
-
except Exception as e:
|
| 1528 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1529 |
break
|
| 1530 |
|
| 1531 |
original_len = len(season["episodes"])
|
|
@@ -1551,15 +1497,7 @@ class Database:
|
|
| 1551 |
if season.get("season_number") == season_number:
|
| 1552 |
for episode in season.get("episodes", []):
|
| 1553 |
for quality in episode.get("telegram", []):
|
| 1554 |
-
|
| 1555 |
-
old_id = quality.get("id")
|
| 1556 |
-
if old_id:
|
| 1557 |
-
decoded_data = await decode_string(old_id)
|
| 1558 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1559 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1560 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1561 |
-
except Exception as e:
|
| 1562 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1563 |
break
|
| 1564 |
|
| 1565 |
original_len = len(tv["seasons"])
|
|
@@ -1586,15 +1524,7 @@ class Database:
|
|
| 1586 |
if episode.get("episode_number") == episode_number and "telegram" in episode:
|
| 1587 |
for q in episode["telegram"]:
|
| 1588 |
if q.get("id") == id:
|
| 1589 |
-
|
| 1590 |
-
old_id = q.get("id")
|
| 1591 |
-
if old_id:
|
| 1592 |
-
decoded_data = await decode_string(old_id)
|
| 1593 |
-
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1594 |
-
msg_id = int(decoded_data['msg_id'])
|
| 1595 |
-
create_task(delete_message(chat_id, msg_id))
|
| 1596 |
-
except Exception as e:
|
| 1597 |
-
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1598 |
break
|
| 1599 |
|
| 1600 |
original_len = len(episode["telegram"])
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
async def get_settings(self) -> dict:
|
|
|
|
| 85 |
try:
|
| 86 |
doc = await self.dbs["tracking"]["settings"].find_one({"_id": "app_settings"})
|
| 87 |
return doc or {}
|
|
|
|
| 90 |
return {}
|
| 91 |
|
| 92 |
async def save_settings(self, settings: dict) -> bool:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
try:
|
| 94 |
clean = {k: v for k, v in settings.items() if k != "_id"}
|
| 95 |
await self.dbs["tracking"]["settings"].update_one(
|
|
|
|
| 105 |
|
| 106 |
|
| 107 |
async def connect_storage_db(self, uri: str, index: int) -> bool:
|
|
|
|
|
|
|
|
|
|
| 108 |
try:
|
| 109 |
client = motor.motor_asyncio.AsyncIOMotorClient(uri)
|
| 110 |
await client.admin.command("ping")
|
|
|
|
| 122 |
return False
|
| 123 |
|
| 124 |
async def disconnect_storage_db(self, index: int) -> None:
|
|
|
|
|
|
|
| 125 |
db_key = f"storage_{index}"
|
| 126 |
client = self.clients.pop(db_key, None)
|
| 127 |
self.dbs.pop(db_key, None)
|
|
|
|
| 130 |
LOGGER.info(f"Disconnected {db_key}.")
|
| 131 |
|
| 132 |
def get_database_list(self) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
result = []
|
| 134 |
for index, uri in enumerate(self.db_uris):
|
| 135 |
masked = re.sub(r"://(.*?):.*?@", r"://\1:*****@", uri).split('?')[0]
|
|
|
|
| 147 |
return result
|
| 148 |
|
| 149 |
async def reload_extra_databases(self, new_extra_uris: List[str]) -> Dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
old_extra = self.db_uris[2:]
|
| 151 |
new_extra = [u.strip() for u in (new_extra_uris or []) if u and u.strip()]
|
| 152 |
|
|
|
|
| 184 |
LOGGER.info(f"reload_extra_databases: {message}")
|
| 185 |
return {"added": added, "removed": removed, "message": message}
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
# -------------------------------
|
| 188 |
# User Subscription Management
|
| 189 |
# -------------------------------
|
|
|
|
| 395 |
"days_assigned": days,
|
| 396 |
}
|
| 397 |
|
|
|
|
|
|
|
|
|
|
| 398 |
# -------------------------------
|
| 399 |
# Custom Catalog Management
|
| 400 |
# -------------------------------
|
|
|
|
| 659 |
# -------------------------------
|
| 660 |
|
| 661 |
async def _build_part_id_and_size(self, parts: List[dict]) -> Tuple[str, str]:
|
|
|
|
|
|
|
|
|
|
| 662 |
sorted_parts = sorted(parts, key=lambda p: p.get("part_number", 0))
|
| 663 |
payload = {"parts": [{"chat_id": p["chat_id"], "msg_id": p["msg_id"]} for p in sorted_parts]}
|
| 664 |
encoded = await encode_string(payload)
|
|
|
|
| 668 |
return encoded, size_str
|
| 669 |
|
| 670 |
async def remove_media_part(self, channel: int, msg_id: int) -> bool:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
try:
|
| 672 |
legacy_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
|
| 673 |
if await self.delete_media_by_stream_id(legacy_hash):
|
|
|
|
| 816 |
return await self.update_tv_show(tv_show)
|
| 817 |
|
| 818 |
async def _merge_split_part(self, qualities: List[dict], quality_to_update: dict) -> List[dict]:
|
|
|
|
|
|
|
|
|
|
| 819 |
group_key = quality_to_update.get("group_key")
|
| 820 |
incoming_parts = quality_to_update.get("parts") or []
|
| 821 |
if not incoming_parts:
|
|
|
|
| 1324 |
return False
|
| 1325 |
raise
|
| 1326 |
|
| 1327 |
+
async def _queue_quality_deletion(self, quality: dict) -> None:
|
| 1328 |
+
try:
|
| 1329 |
+
old_id = quality.get("id")
|
| 1330 |
+
if not old_id:
|
| 1331 |
+
return
|
| 1332 |
+
|
| 1333 |
+
decoded_data = await decode_string(old_id)
|
| 1334 |
+
|
| 1335 |
+
# Split-file: a list of parts, each its own Telegram message.
|
| 1336 |
+
if isinstance(decoded_data, dict) and decoded_data.get("parts"):
|
| 1337 |
+
for part in decoded_data["parts"]:
|
| 1338 |
+
try:
|
| 1339 |
+
chat_id = int(f"-100{part['chat_id']}")
|
| 1340 |
+
msg_id = int(part["msg_id"])
|
| 1341 |
+
create_task(delete_message(chat_id, msg_id))
|
| 1342 |
+
except Exception as e:
|
| 1343 |
+
LOGGER.error(f"Failed to queue split-file part for deletion: {e}")
|
| 1344 |
+
return
|
| 1345 |
+
|
| 1346 |
+
|
| 1347 |
+
chat_id = int(f"-100{decoded_data['chat_id']}")
|
| 1348 |
+
msg_id = int(decoded_data["msg_id"])
|
| 1349 |
+
create_task(delete_message(chat_id, msg_id))
|
| 1350 |
+
except Exception as e:
|
| 1351 |
+
LOGGER.error(f"Failed to queue file for deletion: {e}")
|
| 1352 |
+
|
| 1353 |
async def delete_document(self, media_type: str, tmdb_id: int, db_index: int) -> bool:
|
| 1354 |
db_key = f"storage_{db_index}"
|
| 1355 |
|
|
|
|
| 1357 |
doc = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
|
| 1358 |
if doc and "telegram" in doc:
|
| 1359 |
for quality in doc["telegram"]:
|
| 1360 |
+
await self._queue_quality_deletion(quality)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1361 |
|
| 1362 |
result = await self.dbs[db_key]["movie"].delete_one({"tmdb_id": tmdb_id})
|
| 1363 |
else:
|
|
|
|
| 1366 |
for season in doc["seasons"]:
|
| 1367 |
for episode in season.get("episodes", []):
|
| 1368 |
for quality in episode.get("telegram", []):
|
| 1369 |
+
await self._queue_quality_deletion(quality)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1370 |
|
| 1371 |
result = await self.dbs[db_key]["tv"].delete_one({"tmdb_id": tmdb_id})
|
| 1372 |
|
|
|
|
| 1377 |
return False
|
| 1378 |
|
| 1379 |
async def get_title_by_stream_id(self, stream_id_hash: str) -> Optional[str]:
|
|
|
|
|
|
|
| 1380 |
for i in range(1, self.current_db_index + 1):
|
| 1381 |
db = self.dbs[f"storage_{i}"]
|
| 1382 |
|
|
|
|
| 1402 |
return None
|
| 1403 |
|
| 1404 |
async def delete_media_by_stream_id(self, stream_id_hash: str) -> bool:
|
|
|
|
|
|
|
| 1405 |
for i in range(1, self.current_db_index + 1):
|
| 1406 |
db = self.dbs[f"storage_{i}"]
|
| 1407 |
|
|
|
|
| 1445 |
|
| 1446 |
for q in movie["telegram"]:
|
| 1447 |
if q.get("id") == id:
|
| 1448 |
+
await self._queue_quality_deletion(q)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1449 |
break
|
| 1450 |
|
| 1451 |
original_len = len(movie["telegram"])
|
|
|
|
| 1471 |
for ep in season["episodes"]:
|
| 1472 |
if ep.get("episode_number") == episode_number:
|
| 1473 |
for quality in ep.get("telegram", []):
|
| 1474 |
+
await self._queue_quality_deletion(quality)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1475 |
break
|
| 1476 |
|
| 1477 |
original_len = len(season["episodes"])
|
|
|
|
| 1497 |
if season.get("season_number") == season_number:
|
| 1498 |
for episode in season.get("episodes", []):
|
| 1499 |
for quality in episode.get("telegram", []):
|
| 1500 |
+
await self._queue_quality_deletion(quality)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1501 |
break
|
| 1502 |
|
| 1503 |
original_len = len(tv["seasons"])
|
|
|
|
| 1524 |
if episode.get("episode_number") == episode_number and "telegram" in episode:
|
| 1525 |
for q in episode["telegram"]:
|
| 1526 |
if q.get("id") == id:
|
| 1527 |
+
await self._queue_quality_deletion(q)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1528 |
break
|
| 1529 |
|
| 1530 |
original_len = len(episode["telegram"])
|