Karan Adhikari commited on
🚀 Release v3.1.0: Add auto catalog generation
Browse files✨ Added auto catalog feature
🏷️ Added support for multiple catalog tags like Netflix, Prime Video, Anime, Bollywood, Hollywood, K-Drama, Hotstar, and more
⚙️ Added catalog selection from dashboard
🔄 Added Full Rebuild for first-time setup and tag changes
⚡ Added Quick Sync for newly added media
⏱️ Added automatic Quick Sync every 1 hour
🧹 Prevent duplicate catalogs and duplicate media entries
- Backend/__init__.py +1 -1
- Backend/__main__.py +14 -0
- Backend/fastapi/main.py +23 -1
- Backend/fastapi/routes/api_routes.py +41 -0
- Backend/fastapi/templates/custom_catalogs.html +169 -2
- Backend/helper/auto_catalog.py +694 -0
- pyproject.toml +1 -1
Backend/__init__.py
CHANGED
|
@@ -11,4 +11,4 @@ StartTime = time()
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
-
__version__ = "3.
|
|
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
+
__version__ = "3.1.0"
|
Backend/__main__.py
CHANGED
|
@@ -15,6 +15,11 @@ from Backend.pyrofork.plugins.channels import _load_channels_from_db
|
|
| 15 |
from Backend.helper.subscription_checker import subscription_checker_loop
|
| 16 |
from Backend.helper.link_checker import DeadLinkChecker
|
| 17 |
from Backend.fastapi.main import app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
loop = get_event_loop()
|
|
@@ -54,6 +59,15 @@ async def start_services():
|
|
| 54 |
|
| 55 |
link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
|
| 56 |
loop.create_task(link_checker_task.start())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
if Telegram.SUBSCRIPTION:
|
| 59 |
loop.create_task(subscription_checker_loop(StreamBot))
|
|
|
|
| 15 |
from Backend.helper.subscription_checker import subscription_checker_loop
|
| 16 |
from Backend.helper.link_checker import DeadLinkChecker
|
| 17 |
from Backend.fastapi.main import app
|
| 18 |
+
from Backend.helper.auto_catalog import (
|
| 19 |
+
start_auto_catalog_sync_background, start_auto_catalog_interval_loop,
|
| 20 |
+
AUTO_SYNC_DELAY_SECONDS, AUTO_CATALOG_ON_STARTUP,
|
| 21 |
+
AUTO_CATALOG_FULL_REBUILD_ON_STARTUP
|
| 22 |
+
)
|
| 23 |
|
| 24 |
|
| 25 |
loop = get_event_loop()
|
|
|
|
| 59 |
|
| 60 |
link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
|
| 61 |
loop.create_task(link_checker_task.start())
|
| 62 |
+
|
| 63 |
+
if AUTO_CATALOG_ON_STARTUP:
|
| 64 |
+
loop.create_task(start_auto_catalog_sync_background(
|
| 65 |
+
db,
|
| 66 |
+
delay_seconds=AUTO_SYNC_DELAY_SECONDS,
|
| 67 |
+
full_rebuild=AUTO_CATALOG_FULL_REBUILD_ON_STARTUP,
|
| 68 |
+
))
|
| 69 |
+
|
| 70 |
+
loop.create_task(start_auto_catalog_interval_loop(db))
|
| 71 |
|
| 72 |
if Telegram.SUBSCRIPTION:
|
| 73 |
loop.create_task(subscription_checker_loop(StreamBot))
|
Backend/fastapi/main.py
CHANGED
|
@@ -29,7 +29,9 @@ from Backend.fastapi.routes.api_routes import (
|
|
| 29 |
search_media_rescan_api, apply_media_rescan_api,
|
| 30 |
list_custom_catalogs_api, create_custom_catalog_api, update_custom_catalog_api,
|
| 31 |
delete_custom_catalog_api, get_custom_catalog_items_api, search_catalog_media_api,
|
| 32 |
-
add_custom_catalog_item_api, remove_custom_catalog_item_api
|
|
|
|
|
|
|
| 33 |
)
|
| 34 |
|
| 35 |
templates = Jinja2Templates(directory="Backend/fastapi/templates")
|
|
@@ -326,6 +328,26 @@ async def search_catalog_media(
|
|
| 326 |
):
|
| 327 |
return await search_catalog_media_api(query, media_type, page, page_size)
|
| 328 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
@app.get("/api/custom-catalogs/{catalog_id}/items")
|
| 330 |
async def get_custom_catalog_items(
|
| 331 |
catalog_id: str,
|
|
|
|
| 29 |
search_media_rescan_api, apply_media_rescan_api,
|
| 30 |
list_custom_catalogs_api, create_custom_catalog_api, update_custom_catalog_api,
|
| 31 |
delete_custom_catalog_api, get_custom_catalog_items_api, search_catalog_media_api,
|
| 32 |
+
add_custom_catalog_item_api, remove_custom_catalog_item_api,
|
| 33 |
+
auto_sync_custom_catalogs_api, auto_catalog_sync_status_api,
|
| 34 |
+
get_auto_catalog_settings_api, update_auto_catalog_settings_api
|
| 35 |
)
|
| 36 |
|
| 37 |
templates = Jinja2Templates(directory="Backend/fastapi/templates")
|
|
|
|
| 328 |
):
|
| 329 |
return await search_catalog_media_api(query, media_type, page, page_size)
|
| 330 |
|
| 331 |
+
|
| 332 |
+
@app.post("/api/custom-catalogs/auto-sync")
|
| 333 |
+
async def auto_sync_custom_catalogs(
|
| 334 |
+
full_rebuild: bool = Query(False),
|
| 335 |
+
_: bool = Depends(require_auth)
|
| 336 |
+
):
|
| 337 |
+
return await auto_sync_custom_catalogs_api(full_rebuild)
|
| 338 |
+
|
| 339 |
+
@app.get("/api/custom-catalogs/auto-sync/status")
|
| 340 |
+
async def auto_catalog_sync_status(_: bool = Depends(require_auth)):
|
| 341 |
+
return await auto_catalog_sync_status_api()
|
| 342 |
+
|
| 343 |
+
@app.get("/api/custom-catalogs/auto-sync/settings")
|
| 344 |
+
async def get_auto_catalog_settings_route(_: bool = Depends(require_auth)):
|
| 345 |
+
return await get_auto_catalog_settings_api()
|
| 346 |
+
|
| 347 |
+
@app.put("/api/custom-catalogs/auto-sync/settings")
|
| 348 |
+
async def update_auto_catalog_settings_route(payload: dict, _: bool = Depends(require_auth)):
|
| 349 |
+
return await update_auto_catalog_settings_api(payload)
|
| 350 |
+
|
| 351 |
@app.get("/api/custom-catalogs/{catalog_id}/items")
|
| 352 |
async def get_custom_catalog_items(
|
| 353 |
catalog_id: str,
|
Backend/fastapi/routes/api_routes.py
CHANGED
|
@@ -14,6 +14,12 @@ from Backend.helper.metadata import (
|
|
| 14 |
from Backend.pyrofork.bot import multi_clients, StreamBot
|
| 15 |
from Backend.helper.custom_dl import run_speed_test, _speed_test_single_client
|
| 16 |
from time import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
# --- API Routes for System Stats ---
|
|
@@ -924,3 +930,38 @@ async def remove_custom_catalog_item_api(
|
|
| 924 |
if not removed:
|
| 925 |
return {"message": "Item was not in this catalog.", "removed": False}
|
| 926 |
return {"message": "Removed from catalog.", "removed": True}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from Backend.pyrofork.bot import multi_clients, StreamBot
|
| 15 |
from Backend.helper.custom_dl import run_speed_test, _speed_test_single_client
|
| 16 |
from time import time
|
| 17 |
+
from Backend.helper.auto_catalog import (
|
| 18 |
+
start_auto_catalog_sync_background,
|
| 19 |
+
get_auto_catalog_sync_status,
|
| 20 |
+
get_auto_catalog_settings,
|
| 21 |
+
update_auto_catalog_settings,
|
| 22 |
+
)
|
| 23 |
|
| 24 |
|
| 25 |
# --- API Routes for System Stats ---
|
|
|
|
| 930 |
if not removed:
|
| 931 |
return {"message": "Item was not in this catalog.", "removed": False}
|
| 932 |
return {"message": "Removed from catalog.", "removed": True}
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
async def auto_sync_custom_catalogs_api(full_rebuild: bool = False):
|
| 936 |
+
try:
|
| 937 |
+
result = await start_auto_catalog_sync_background(db, force=True, full_rebuild=full_rebuild)
|
| 938 |
+
return {"message": result.get("message", "Auto sync started."), "result": result}
|
| 939 |
+
except Exception as e:
|
| 940 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
async def auto_catalog_sync_status_api():
|
| 944 |
+
try:
|
| 945 |
+
return {"status": await get_auto_catalog_sync_status(db)}
|
| 946 |
+
except Exception as e:
|
| 947 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
async def get_auto_catalog_settings_api():
|
| 951 |
+
try:
|
| 952 |
+
return {"settings": await get_auto_catalog_settings(db)}
|
| 953 |
+
except Exception as e:
|
| 954 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
async def update_auto_catalog_settings_api(payload: dict):
|
| 958 |
+
try:
|
| 959 |
+
enabled_keys = payload.get("enabled_keys", [])
|
| 960 |
+
if not isinstance(enabled_keys, list):
|
| 961 |
+
raise HTTPException(status_code=400, detail="enabled_keys must be a list.")
|
| 962 |
+
settings = await update_auto_catalog_settings(db, enabled_keys)
|
| 963 |
+
return {"message": "Auto catalog settings saved.", "settings": settings}
|
| 964 |
+
except HTTPException:
|
| 965 |
+
raise
|
| 966 |
+
except Exception as e:
|
| 967 |
+
raise HTTPException(status_code=500, detail=str(e))
|
Backend/fastapi/templates/custom_catalogs.html
CHANGED
|
@@ -276,6 +276,42 @@
|
|
| 276 |
</div>
|
| 277 |
</div>
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
<div class="grid grid-cols-1 xl:grid-cols-[0.88fr_1.12fr] gap-6">
|
| 280 |
<div class="space-y-6">
|
| 281 |
<div class="glass-card rounded-3xl p-5 sm:p-6">
|
|
@@ -466,8 +502,9 @@ function renderCatalogs() {
|
|
| 466 |
<div class="flex items-start justify-between gap-3">
|
| 467 |
<button class="text-left min-w-0 flex-1" onclick="selectCatalog('${c._id}')">
|
| 468 |
<div class="flex items-center gap-2 min-w-0">
|
| 469 |
-
<span class="text-xl">${c.visible ? '🌐' : '🔒'}</span>
|
| 470 |
<h3 class="font-black truncate">${escapeHtml(c.name)}</h3>
|
|
|
|
| 471 |
</div>
|
| 472 |
<p class="muted text-xs mt-2">${count} title${count === 1 ? '' : 's'} · ${c.visible ? 'Visible in Stremio' : 'Hidden from Stremio'}</p>
|
| 473 |
</button>
|
|
@@ -622,6 +659,136 @@ async function deleteSelectedCatalog() {
|
|
| 622 |
await loadCatalogs();
|
| 623 |
}
|
| 624 |
|
| 625 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 626 |
</script>
|
| 627 |
{% endblock %}
|
|
|
|
| 276 |
</div>
|
| 277 |
</div>
|
| 278 |
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
<div class="glass-card rounded-3xl p-5 sm:p-6">
|
| 282 |
+
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
|
| 283 |
+
<div>
|
| 284 |
+
<div class="flex flex-wrap gap-2 mb-3">
|
| 285 |
+
<span class="pill">✨ Auto catalogs</span>
|
| 286 |
+
<span id="auto-sync-status" class="pill">Checking status...</span>
|
| 287 |
+
</div>
|
| 288 |
+
<h2 class="section-title text-2xl sm:text-3xl">Auto-create by selected language & OTT</h2>
|
| 289 |
+
<p class="muted text-sm sm:text-base mt-2 leading-7 max-w-3xl">
|
| 290 |
+
On app startup this scans your movie and series library, fetches TMDb original language + watch providers, then creates only the auto catalogs you select below. Genre auto catalogs are removed.
|
| 291 |
+
</p>
|
| 292 |
+
</div>
|
| 293 |
+
<div class="flex flex-col sm:flex-row gap-3">
|
| 294 |
+
<button id="auto-sync-btn" onclick="runAutoSync(false)" class="btn-ui btn-primary lg:w-auto">⚡ Quick Sync</button>
|
| 295 |
+
<button id="auto-rebuild-btn" onclick="runAutoSync(true)" class="btn-ui btn-ghost lg:w-auto">♻️ Full Rebuild</button>
|
| 296 |
+
</div>
|
| 297 |
+
</div>
|
| 298 |
+
|
| 299 |
+
<div class="mt-5 pt-5 border-t" style="border-color: color-mix(in srgb, var(--border) 80%, transparent);">
|
| 300 |
+
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
|
| 301 |
+
<div>
|
| 302 |
+
<h3 class="section-title text-xl">Choose Auto Catalogs</h3>
|
| 303 |
+
<p class="muted text-sm mt-1">Disable anything you do not want to auto-create. Save, then run Full Rebuild once to apply removed catalogs.</p>
|
| 304 |
+
</div>
|
| 305 |
+
<button id="save-auto-settings-btn" onclick="saveAutoCatalogSettings()" class="btn-ui btn-ghost md:w-auto">💾 Save Selection</button>
|
| 306 |
+
</div>
|
| 307 |
+
<div id="auto-settings-list" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
|
| 308 |
+
<div class="skeleton"></div>
|
| 309 |
+
<div class="skeleton"></div>
|
| 310 |
+
<div class="skeleton"></div>
|
| 311 |
+
</div>
|
| 312 |
+
</div>
|
| 313 |
+
</div>
|
| 314 |
+
|
| 315 |
<div class="grid grid-cols-1 xl:grid-cols-[0.88fr_1.12fr] gap-6">
|
| 316 |
<div class="space-y-6">
|
| 317 |
<div class="glass-card rounded-3xl p-5 sm:p-6">
|
|
|
|
| 502 |
<div class="flex items-start justify-between gap-3">
|
| 503 |
<button class="text-left min-w-0 flex-1" onclick="selectCatalog('${c._id}')">
|
| 504 |
<div class="flex items-center gap-2 min-w-0">
|
| 505 |
+
<span class="text-xl">${c.auto ? '✨' : (c.visible ? '🌐' : '🔒')}</span>
|
| 506 |
<h3 class="font-black truncate">${escapeHtml(c.name)}</h3>
|
| 507 |
+
${c.auto ? '<span class="pill text-[0.62rem] px-2 py-0.5">Auto</span>' : ''}
|
| 508 |
</div>
|
| 509 |
<p class="muted text-xs mt-2">${count} title${count === 1 ? '' : 's'} · ${c.visible ? 'Visible in Stremio' : 'Hidden from Stremio'}</p>
|
| 510 |
</button>
|
|
|
|
| 659 |
await loadCatalogs();
|
| 660 |
}
|
| 661 |
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
async function loadAutoCatalogSettings() {
|
| 665 |
+
const box = document.getElementById('auto-settings-list');
|
| 666 |
+
if (!box) return;
|
| 667 |
+
try {
|
| 668 |
+
const res = await fetch('/api/custom-catalogs/auto-sync/settings');
|
| 669 |
+
const data = await res.json().catch(() => ({}));
|
| 670 |
+
if (!res.ok) throw new Error(data.detail || 'Failed to load auto catalog settings');
|
| 671 |
+
const defs = (data.settings && data.settings.definitions) || [];
|
| 672 |
+
if (!defs.length) {
|
| 673 |
+
box.innerHTML = `<div class="empty-state p-4 muted">No auto catalog options found.</div>`;
|
| 674 |
+
return;
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
const groups = {};
|
| 678 |
+
defs.forEach(def => {
|
| 679 |
+
if (!groups[def.group]) groups[def.group] = [];
|
| 680 |
+
groups[def.group].push(def);
|
| 681 |
+
});
|
| 682 |
+
|
| 683 |
+
box.innerHTML = Object.entries(groups).map(([group, items]) => `
|
| 684 |
+
<div class="catalog-card p-4 space-y-3">
|
| 685 |
+
<div class="flex items-center justify-between gap-2">
|
| 686 |
+
<h4 class="section-title text-base">${escapeHtml(group)}</h4>
|
| 687 |
+
<span class="pill text-[0.65rem] px-2 py-0.5">${items.length}</span>
|
| 688 |
+
</div>
|
| 689 |
+
<div class="space-y-2">
|
| 690 |
+
${items.map(item => `
|
| 691 |
+
<label class="flex items-center justify-between gap-3 rounded-2xl p-3 cursor-pointer" style="background: color-mix(in srgb, var(--bg) 64%, transparent); border: 1px solid color-mix(in srgb, var(--border) 72%, transparent);">
|
| 692 |
+
<span class="font-bold text-sm">${escapeHtml(item.name)}</span>
|
| 693 |
+
<input type="checkbox" class="auto-setting-checkbox switch-input hidden" value="${escapeHtml(item.key)}" ${item.enabled ? 'checked' : ''}>
|
| 694 |
+
<span class="switch"></span>
|
| 695 |
+
</label>
|
| 696 |
+
`).join('')}
|
| 697 |
+
</div>
|
| 698 |
+
</div>
|
| 699 |
+
`).join('');
|
| 700 |
+
} catch (error) {
|
| 701 |
+
box.innerHTML = `<div class="empty-state p-4 text-red-400">${escapeHtml(error.message || 'Failed to load settings')}</div>`;
|
| 702 |
+
}
|
| 703 |
+
}
|
| 704 |
+
|
| 705 |
+
async function saveAutoCatalogSettings() {
|
| 706 |
+
const btn = document.getElementById('save-auto-settings-btn');
|
| 707 |
+
const old = btn ? btn.textContent : '';
|
| 708 |
+
const enabledKeys = Array.from(document.querySelectorAll('.auto-setting-checkbox:checked')).map(el => el.value);
|
| 709 |
+
try {
|
| 710 |
+
if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }
|
| 711 |
+
const res = await fetch('/api/custom-catalogs/auto-sync/settings', {
|
| 712 |
+
method: 'PUT',
|
| 713 |
+
headers: { 'Content-Type': 'application/json' },
|
| 714 |
+
body: JSON.stringify({ enabled_keys: enabledKeys })
|
| 715 |
+
});
|
| 716 |
+
const data = await res.json().catch(() => ({}));
|
| 717 |
+
if (!res.ok) throw new Error(data.detail || 'Failed to save settings');
|
| 718 |
+
showToast('Auto catalog selection saved. Run Full Rebuild once to remove disabled catalog items.', 'success', 'Saved');
|
| 719 |
+
await loadAutoCatalogSettings();
|
| 720 |
+
} catch (error) {
|
| 721 |
+
showToast(error.message || 'Failed to save settings', 'error', 'Error');
|
| 722 |
+
} finally {
|
| 723 |
+
if (btn) { btn.disabled = false; btn.textContent = old; }
|
| 724 |
+
}
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
let autoSyncPollTimer = null;
|
| 728 |
+
|
| 729 |
+
async function loadAutoSyncStatus() {
|
| 730 |
+
const pill = document.getElementById('auto-sync-status');
|
| 731 |
+
const syncBtn = document.getElementById('auto-sync-btn');
|
| 732 |
+
const rebuildBtn = document.getElementById('auto-rebuild-btn');
|
| 733 |
+
if (!pill) return;
|
| 734 |
+
try {
|
| 735 |
+
const res = await fetch('/api/custom-catalogs/auto-sync/status');
|
| 736 |
+
const data = await res.json().catch(() => ({}));
|
| 737 |
+
const status = data.status || {};
|
| 738 |
+
const mode = status.mode === 'full_rebuild' ? 'Full rebuild' : 'Quick sync';
|
| 739 |
+
|
| 740 |
+
if (status.running) {
|
| 741 |
+
pill.textContent = `${mode} running: ${status.scanned || 0} scanned · ${status.classified || 0} checked`;
|
| 742 |
+
if (syncBtn) syncBtn.disabled = true;
|
| 743 |
+
if (rebuildBtn) rebuildBtn.disabled = true;
|
| 744 |
+
if (!autoSyncPollTimer) {
|
| 745 |
+
autoSyncPollTimer = setInterval(loadAutoSyncStatus, 3000);
|
| 746 |
+
}
|
| 747 |
+
} else {
|
| 748 |
+
if (status.finished_at) {
|
| 749 |
+
pill.textContent = status.error
|
| 750 |
+
? `${mode} failed`
|
| 751 |
+
: `${mode}: ${status.classified || 0} checked · ${status.skipped || 0} skipped`;
|
| 752 |
+
} else {
|
| 753 |
+
pill.textContent = 'Quick sync runs on boot';
|
| 754 |
+
}
|
| 755 |
+
if (syncBtn) syncBtn.disabled = false;
|
| 756 |
+
if (rebuildBtn) rebuildBtn.disabled = false;
|
| 757 |
+
if (autoSyncPollTimer) {
|
| 758 |
+
clearInterval(autoSyncPollTimer);
|
| 759 |
+
autoSyncPollTimer = null;
|
| 760 |
+
await loadCatalogs();
|
| 761 |
+
}
|
| 762 |
+
}
|
| 763 |
+
} catch (e) {
|
| 764 |
+
pill.textContent = 'Status unavailable';
|
| 765 |
+
}
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
async function runAutoSync(fullRebuild = false) {
|
| 769 |
+
const btn = document.getElementById(fullRebuild ? 'auto-rebuild-btn' : 'auto-sync-btn');
|
| 770 |
+
const otherBtn = document.getElementById(fullRebuild ? 'auto-sync-btn' : 'auto-rebuild-btn');
|
| 771 |
+
const old = btn.textContent;
|
| 772 |
+
btn.disabled = true;
|
| 773 |
+
if (otherBtn) otherBtn.disabled = true;
|
| 774 |
+
btn.textContent = fullRebuild ? '⏳ Rebuilding...' : '⏳ Syncing...';
|
| 775 |
+
try {
|
| 776 |
+
const url = `/api/custom-catalogs/auto-sync?full_rebuild=${fullRebuild ? 'true' : 'false'}`;
|
| 777 |
+
const res = await fetch(url, { method: 'POST' });
|
| 778 |
+
const data = await res.json().catch(() => ({}));
|
| 779 |
+
if (!res.ok) throw new Error(data.detail || 'Auto sync failed');
|
| 780 |
+
const result = data.result || {};
|
| 781 |
+
const title = fullRebuild ? 'Full rebuild started' : 'Quick sync started';
|
| 782 |
+
showToast(result.message || data.message || 'Auto sync started in background.', 'info', title);
|
| 783 |
+
await loadAutoSyncStatus();
|
| 784 |
+
} catch (error) {
|
| 785 |
+
showToast(error.message || 'Auto sync failed', 'error', 'Error');
|
| 786 |
+
} finally {
|
| 787 |
+
btn.textContent = old;
|
| 788 |
+
await loadAutoSyncStatus();
|
| 789 |
+
}
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
document.addEventListener('DOMContentLoaded', () => { loadCatalogs(); loadAutoSyncStatus(); loadAutoCatalogSettings(); });
|
| 793 |
</script>
|
| 794 |
{% endblock %}
|
Backend/helper/auto_catalog.py
ADDED
|
@@ -0,0 +1,694 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Dict, List, Optional, Set, Tuple
|
| 4 |
+
|
| 5 |
+
import httpx
|
| 6 |
+
|
| 7 |
+
from Backend.config import Telegram
|
| 8 |
+
from Backend.logger import LOGGER
|
| 9 |
+
|
| 10 |
+
# -----------------------------
|
| 11 |
+
# Auto catalog settings
|
| 12 |
+
# -----------------------------
|
| 13 |
+
AUTO_CATALOG_REGION = getattr(Telegram, "AUTO_CATALOG_REGION", "IN")
|
| 14 |
+
AUTO_CATALOG_ON_STARTUP = getattr(Telegram, "AUTO_CATALOG_ON_STARTUP", True)
|
| 15 |
+
AUTO_CATALOG_FULL_REBUILD_ON_STARTUP = getattr(Telegram, "AUTO_CATALOG_FULL_REBUILD_ON_STARTUP", False)
|
| 16 |
+
AUTO_SYNC_DELAY_SECONDS = getattr(Telegram, "AUTO_SYNC_DELAY_SECONDS", 20)
|
| 17 |
+
AUTO_SYNC_CONCURRENCY = getattr(Telegram, "AUTO_SYNC_CONCURRENCY", 5)
|
| 18 |
+
|
| 19 |
+
# Hourly quick sync. It only starts after the admin has saved at least one
|
| 20 |
+
# auto-catalog option from /catalogs, so first boot stays clean.
|
| 21 |
+
AUTO_CATALOG_INTERVAL_SYNC = getattr(Telegram, "AUTO_CATALOG_INTERVAL_SYNC", True)
|
| 22 |
+
AUTO_CATALOG_SYNC_INTERVAL_MINUTES = int(getattr(Telegram, "AUTO_CATALOG_SYNC_INTERVAL_MINUTES", 60))
|
| 23 |
+
|
| 24 |
+
# User can choose exactly which auto catalogs are enabled.
|
| 25 |
+
AUTO_CATALOG_DEFINITIONS = [
|
| 26 |
+
{"key": "bollywood", "name": "Bollywood", "group": "Language"},
|
| 27 |
+
{"key": "hollywood", "name": "Hollywood", "group": "Language"},
|
| 28 |
+
{"key": "anime", "name": "Anime", "group": "Language"},
|
| 29 |
+
{"key": "kdrama", "name": "K-Drama", "group": "Language"},
|
| 30 |
+
{"key": "bengali", "name": "Bengali", "group": "Language"},
|
| 31 |
+
{"key": "south_indian", "name": "South Indian", "group": "Language"},
|
| 32 |
+
{"key": "tamil", "name": "Tamil", "group": "Language"},
|
| 33 |
+
{"key": "telugu", "name": "Telugu", "group": "Language"},
|
| 34 |
+
{"key": "malayalam", "name": "Malayalam", "group": "Language"},
|
| 35 |
+
{"key": "kannada", "name": "Kannada", "group": "Language"},
|
| 36 |
+
{"key": "japanese", "name": "Japanese", "group": "Language"},
|
| 37 |
+
{"key": "korean", "name": "Korean", "group": "Language"},
|
| 38 |
+
|
| 39 |
+
{"key": "top_rated", "name": "Top Rated", "group": "Smart"},
|
| 40 |
+
{"key": "recently_added", "name": "Recently Added", "group": "Smart"},
|
| 41 |
+
|
| 42 |
+
{"key": "netflix", "name": "Netflix", "group": "OTT"},
|
| 43 |
+
{"key": "prime_video", "name": "Prime Video", "group": "OTT"},
|
| 44 |
+
{"key": "hotstar", "name": "Hotstar", "group": "OTT"},
|
| 45 |
+
{"key": "apple_tv", "name": "Apple TV", "group": "OTT"},
|
| 46 |
+
{"key": "hulu", "name": "Hulu", "group": "OTT"},
|
| 47 |
+
{"key": "hbo", "name": "HBO", "group": "OTT"},
|
| 48 |
+
{"key": "jiocinema", "name": "JioCinema", "group": "OTT"},
|
| 49 |
+
{"key": "zee5", "name": "ZEE5", "group": "OTT"},
|
| 50 |
+
{"key": "sonyliv", "name": "SonyLIV", "group": "OTT"},
|
| 51 |
+
{"key": "mx_player", "name": "MX Player", "group": "OTT"},
|
| 52 |
+
{"key": "crunchyroll", "name": "Crunchyroll", "group": "OTT"},
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
CATALOG_BY_NAME = {item["name"]: item for item in AUTO_CATALOG_DEFINITIONS}
|
| 56 |
+
CATALOG_BY_KEY = {item["key"]: item for item in AUTO_CATALOG_DEFINITIONS}
|
| 57 |
+
DEFAULT_ENABLED_AUTO_CATALOG_KEYS = set(getattr(
|
| 58 |
+
Telegram,
|
| 59 |
+
"AUTO_CATALOG_ENABLED_KEYS",
|
| 60 |
+
[item["key"] for item in AUTO_CATALOG_DEFINITIONS]
|
| 61 |
+
))
|
| 62 |
+
|
| 63 |
+
_LANGUAGE_CATALOGS = {
|
| 64 |
+
"hi": ["Bollywood"],
|
| 65 |
+
"en": ["Hollywood"],
|
| 66 |
+
"ja": ["Japanese"],
|
| 67 |
+
"ko": ["Korean"],
|
| 68 |
+
"bn": ["Bengali"],
|
| 69 |
+
"te": ["South Indian", "Telugu"],
|
| 70 |
+
"ta": ["South Indian", "Tamil"],
|
| 71 |
+
"ml": ["South Indian", "Malayalam"],
|
| 72 |
+
"kn": ["South Indian", "Kannada"],
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
_PROVIDER_ALIASES = {
|
| 76 |
+
"netflix": "Netflix",
|
| 77 |
+
"amazon prime video": "Prime Video",
|
| 78 |
+
"prime video": "Prime Video",
|
| 79 |
+
"amazon video": "Prime Video",
|
| 80 |
+
"hotstar": "Hotstar",
|
| 81 |
+
"disney plus hotstar": "Hotstar",
|
| 82 |
+
"disney+ hotstar": "Hotstar",
|
| 83 |
+
"jiohotstar": "Hotstar",
|
| 84 |
+
"hulu": "Hulu",
|
| 85 |
+
"apple tv": "Apple TV",
|
| 86 |
+
"apple tv plus": "Apple TV",
|
| 87 |
+
"apple tv+": "Apple TV",
|
| 88 |
+
"hbo max": "HBO",
|
| 89 |
+
"max": "HBO",
|
| 90 |
+
"jio cinema": "JioCinema",
|
| 91 |
+
"jiocinema": "JioCinema",
|
| 92 |
+
"zee5": "ZEE5",
|
| 93 |
+
"sony liv": "SonyLIV",
|
| 94 |
+
"sonyliv": "SonyLIV",
|
| 95 |
+
"mx player": "MX Player",
|
| 96 |
+
"crunchyroll": "Crunchyroll",
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
_auto_sync_lock = asyncio.Lock()
|
| 100 |
+
_auto_sync_task: Optional[asyncio.Task] = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _tmdb_api_key() -> str:
|
| 104 |
+
return getattr(Telegram, "TMDB_API", "") or ""
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _media_type(doc: dict) -> str:
|
| 108 |
+
return "tv" if doc.get("media_type") in ["tv", "series"] else "movie"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _catalog_key(name: str) -> str:
|
| 112 |
+
value = (name or "").strip().lower().replace("&", "and")
|
| 113 |
+
value = "_".join(value.split())
|
| 114 |
+
value = "".join(ch for ch in value if ch.isalnum() or ch == "_")
|
| 115 |
+
return f"auto_{value}"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _doc_identity(doc: dict) -> Tuple[str, int, int]:
|
| 119 |
+
return (_media_type(doc), int(doc.get("tmdb_id")), int(doc.get("db_index", 1)))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _doc_item(doc: dict) -> dict:
|
| 123 |
+
media_type, tmdb_id, db_index = _doc_identity(doc)
|
| 124 |
+
return {
|
| 125 |
+
"tmdb_id": tmdb_id,
|
| 126 |
+
"db_index": db_index,
|
| 127 |
+
"media_type": media_type,
|
| 128 |
+
"added_at": datetime.utcnow(),
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _provider_bucket(provider_name: str) -> Optional[str]:
|
| 133 |
+
value = (provider_name or "").strip().lower()
|
| 134 |
+
if not value:
|
| 135 |
+
return None
|
| 136 |
+
for needle, bucket in _PROVIDER_ALIASES.items():
|
| 137 |
+
if needle in value:
|
| 138 |
+
return bucket
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _extract_provider_names(watch_data: dict) -> List[str]:
|
| 143 |
+
results = (watch_data or {}).get("results") or {}
|
| 144 |
+
region_data = results.get(AUTO_CATALOG_REGION) or results.get("US") or {}
|
| 145 |
+
names: List[str] = []
|
| 146 |
+
for group in ["flatrate", "ads", "free", "rent", "buy"]:
|
| 147 |
+
for provider in region_data.get(group, []) or []:
|
| 148 |
+
name = provider.get("provider_name")
|
| 149 |
+
if name:
|
| 150 |
+
names.append(name)
|
| 151 |
+
return names
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _is_already_synced(doc: dict) -> bool:
|
| 155 |
+
auto_catalog = doc.get("auto_catalog") or {}
|
| 156 |
+
if not auto_catalog.get("synced"):
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
synced_at = auto_catalog.get("synced_at")
|
| 160 |
+
source_updated_on = auto_catalog.get("source_updated_on")
|
| 161 |
+
doc_updated_on = doc.get("updated_on")
|
| 162 |
+
|
| 163 |
+
if not synced_at:
|
| 164 |
+
return False
|
| 165 |
+
if doc_updated_on and source_updated_on and doc_updated_on != source_updated_on:
|
| 166 |
+
return False
|
| 167 |
+
return True
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
async def has_auto_catalog_settings(db) -> bool:
|
| 171 |
+
"""Return True only after the admin saved auto-catalog options at least once."""
|
| 172 |
+
state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"})
|
| 173 |
+
return bool(state and isinstance(state.get("enabled_keys"), list))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
async def get_auto_catalog_settings(db) -> dict:
|
| 177 |
+
state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"}) or {}
|
| 178 |
+
configured = isinstance(state.get("enabled_keys"), list)
|
| 179 |
+
|
| 180 |
+
# Important: first boot should not auto-create catalogs.
|
| 181 |
+
# Until the admin saves settings from /catalogs, enabled_keys stays empty.
|
| 182 |
+
enabled_keys = state.get("enabled_keys") if configured else []
|
| 183 |
+
|
| 184 |
+
enabled_set = {key for key in enabled_keys if key in CATALOG_BY_KEY}
|
| 185 |
+
definitions = []
|
| 186 |
+
for item in AUTO_CATALOG_DEFINITIONS:
|
| 187 |
+
definitions.append({
|
| 188 |
+
**item,
|
| 189 |
+
"enabled": item["key"] in enabled_set,
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
return {
|
| 193 |
+
"configured": configured,
|
| 194 |
+
"enabled_keys": sorted(enabled_set),
|
| 195 |
+
"definitions": definitions,
|
| 196 |
+
"region": AUTO_CATALOG_REGION,
|
| 197 |
+
"genre_catalogs_removed": True,
|
| 198 |
+
"interval_sync_enabled": bool(AUTO_CATALOG_INTERVAL_SYNC),
|
| 199 |
+
"interval_minutes": AUTO_CATALOG_SYNC_INTERVAL_MINUTES,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
async def update_auto_catalog_settings(db, enabled_keys: List[str]) -> dict:
|
| 204 |
+
clean_keys = sorted({str(key) for key in enabled_keys if str(key) in CATALOG_BY_KEY})
|
| 205 |
+
now = datetime.utcnow()
|
| 206 |
+
await db.dbs["tracking"]["state"].update_one(
|
| 207 |
+
{"_id": "auto_catalog_settings"},
|
| 208 |
+
{"$set": {"enabled_keys": clean_keys, "updated_at": now}},
|
| 209 |
+
upsert=True,
|
| 210 |
+
)
|
| 211 |
+
return await get_auto_catalog_settings(db)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
async def _enabled_catalog_names(db) -> Set[str]:
|
| 215 |
+
settings = await get_auto_catalog_settings(db)
|
| 216 |
+
keys = settings.get("enabled_keys") or []
|
| 217 |
+
return {CATALOG_BY_KEY[key]["name"] for key in keys if key in CATALOG_BY_KEY}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled_names: Set[str]) -> dict:
|
| 221 |
+
tags: Set[str] = set()
|
| 222 |
+
providers: Set[str] = set()
|
| 223 |
+
|
| 224 |
+
media_type = _media_type(doc)
|
| 225 |
+
original_language = details.get("original_language") or doc.get("original_language") or ""
|
| 226 |
+
|
| 227 |
+
origin_country = details.get("origin_country") or []
|
| 228 |
+
production_countries = [
|
| 229 |
+
c.get("iso_3166_1")
|
| 230 |
+
for c in details.get("production_countries", []) or []
|
| 231 |
+
if c.get("iso_3166_1")
|
| 232 |
+
]
|
| 233 |
+
|
| 234 |
+
for tag in _LANGUAGE_CATALOGS.get(original_language, []):
|
| 235 |
+
tags.add(tag)
|
| 236 |
+
|
| 237 |
+
if original_language == "hi" and ("IN" in origin_country or "IN" in production_countries or not origin_country):
|
| 238 |
+
tags.add("Bollywood")
|
| 239 |
+
|
| 240 |
+
if original_language == "ko" and media_type == "tv":
|
| 241 |
+
tags.add("K-Drama")
|
| 242 |
+
|
| 243 |
+
genre_names = [g.get("name", "") for g in details.get("genres", []) or []]
|
| 244 |
+
genre_lower = {g.lower() for g in genre_names}
|
| 245 |
+
|
| 246 |
+
keyword_payload = details.get("keywords") or {}
|
| 247 |
+
keywords = keyword_payload.get("keywords") or keyword_payload.get("results") or []
|
| 248 |
+
keyword_names = {k.get("name", "").lower() for k in keywords if isinstance(k, dict)}
|
| 249 |
+
|
| 250 |
+
if original_language == "ja" and ("animation" in genre_lower or "anime" in keyword_names):
|
| 251 |
+
tags.add("Anime")
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
if float(doc.get("rating") or 0) >= 7.5:
|
| 255 |
+
tags.add("Top Rated")
|
| 256 |
+
except Exception:
|
| 257 |
+
pass
|
| 258 |
+
|
| 259 |
+
if doc.get("release_year"):
|
| 260 |
+
try:
|
| 261 |
+
if int(doc.get("release_year")) >= datetime.utcnow().year - 1:
|
| 262 |
+
tags.add("Recently Added")
|
| 263 |
+
except Exception:
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
for provider_name in _extract_provider_names(watch_data):
|
| 267 |
+
bucket = _provider_bucket(provider_name)
|
| 268 |
+
if bucket:
|
| 269 |
+
providers.add(bucket)
|
| 270 |
+
tags.add(bucket)
|
| 271 |
+
|
| 272 |
+
tags = {tag for tag in tags if tag in enabled_names}
|
| 273 |
+
|
| 274 |
+
return {
|
| 275 |
+
"original_language": original_language,
|
| 276 |
+
"origin_country": origin_country,
|
| 277 |
+
"production_countries": production_countries,
|
| 278 |
+
"watch_providers": sorted(providers),
|
| 279 |
+
"auto_tags": sorted(tags),
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
async def _fetch_tmdb_data(client: httpx.AsyncClient, doc: dict) -> tuple[dict, dict]:
|
| 284 |
+
api_key = _tmdb_api_key()
|
| 285 |
+
if not api_key:
|
| 286 |
+
return {}, {}
|
| 287 |
+
|
| 288 |
+
media_type = _media_type(doc)
|
| 289 |
+
tmdb_id = doc.get("tmdb_id")
|
| 290 |
+
|
| 291 |
+
if not tmdb_id and doc.get("imdb_id"):
|
| 292 |
+
find_url = f"https://api.themoviedb.org/3/find/{doc.get('imdb_id')}"
|
| 293 |
+
params = {"api_key": api_key, "external_source": "imdb_id"}
|
| 294 |
+
resp = await client.get(find_url, params=params)
|
| 295 |
+
if resp.status_code == 200:
|
| 296 |
+
data = resp.json()
|
| 297 |
+
result_key = "tv_results" if media_type == "tv" else "movie_results"
|
| 298 |
+
results = data.get(result_key) or []
|
| 299 |
+
if results:
|
| 300 |
+
tmdb_id = results[0].get("id")
|
| 301 |
+
|
| 302 |
+
if not tmdb_id:
|
| 303 |
+
return {}, {}
|
| 304 |
+
|
| 305 |
+
detail_url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}"
|
| 306 |
+
detail_params = {
|
| 307 |
+
"api_key": api_key,
|
| 308 |
+
"language": "en-US",
|
| 309 |
+
"append_to_response": "keywords",
|
| 310 |
+
}
|
| 311 |
+
provider_url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}/watch/providers"
|
| 312 |
+
|
| 313 |
+
detail_resp, provider_resp = await asyncio.gather(
|
| 314 |
+
client.get(detail_url, params=detail_params),
|
| 315 |
+
client.get(provider_url, params={"api_key": api_key}),
|
| 316 |
+
return_exceptions=True,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
details = detail_resp.json() if not isinstance(detail_resp, Exception) and detail_resp.status_code == 200 else {}
|
| 320 |
+
providers = provider_resp.json() if not isinstance(provider_resp, Exception) and provider_resp.status_code == 200 else {}
|
| 321 |
+
return details, providers
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
async def _iter_all_media(db, *, full_rebuild: bool = False):
|
| 325 |
+
for db_index in range(1, db.current_db_index + 1):
|
| 326 |
+
db_key = f"storage_{db_index}"
|
| 327 |
+
if db_key not in db.dbs:
|
| 328 |
+
continue
|
| 329 |
+
|
| 330 |
+
for collection_name in ["movie", "tv"]:
|
| 331 |
+
cursor = db.dbs[db_key][collection_name].find({"tmdb_id": {"$exists": True, "$ne": None}})
|
| 332 |
+
async for doc in cursor:
|
| 333 |
+
doc["db_index"] = int(doc.get("db_index", db_index))
|
| 334 |
+
doc["media_type"] = "tv" if collection_name == "tv" else "movie"
|
| 335 |
+
if not full_rebuild and _is_already_synced(doc):
|
| 336 |
+
yield collection_name, db_index, doc, True
|
| 337 |
+
else:
|
| 338 |
+
yield collection_name, db_index, doc, False
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaphore, doc: dict, enabled_names: Set[str]) -> tuple[dict, dict]:
|
| 342 |
+
async with semaphore:
|
| 343 |
+
try:
|
| 344 |
+
details, watch_data = await _fetch_tmdb_data(client, doc)
|
| 345 |
+
classification = classify_media_from_tmdb(doc, details, watch_data, enabled_names) if details else {
|
| 346 |
+
"original_language": doc.get("original_language", ""),
|
| 347 |
+
"origin_country": doc.get("origin_country", []),
|
| 348 |
+
"production_countries": doc.get("production_countries", []),
|
| 349 |
+
"watch_providers": doc.get("watch_providers", []),
|
| 350 |
+
"auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names],
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
now = datetime.utcnow()
|
| 354 |
+
update_data = {
|
| 355 |
+
"original_language": classification.get("original_language"),
|
| 356 |
+
"origin_country": classification.get("origin_country", []),
|
| 357 |
+
"production_countries": classification.get("production_countries", []),
|
| 358 |
+
"watch_providers": classification.get("watch_providers", []),
|
| 359 |
+
"auto_tags": classification.get("auto_tags", []),
|
| 360 |
+
"auto_tags_updated_at": now,
|
| 361 |
+
"auto_catalog": {
|
| 362 |
+
"synced": True,
|
| 363 |
+
"synced_at": now,
|
| 364 |
+
"source_updated_on": doc.get("updated_on"),
|
| 365 |
+
},
|
| 366 |
+
}
|
| 367 |
+
await db.update_document(_media_type(doc), int(doc.get("tmdb_id")), int(doc.get("db_index", 1)), update_data)
|
| 368 |
+
return doc, classification
|
| 369 |
+
except Exception as e:
|
| 370 |
+
LOGGER.warning(f"Auto catalog classification failed for {doc.get('title')} ({doc.get('tmdb_id')}): {e}")
|
| 371 |
+
return doc, {"auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names]}
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
|
| 375 |
+
collection = db.dbs["tracking"]["custom_catalogs"]
|
| 376 |
+
now = datetime.utcnow()
|
| 377 |
+
|
| 378 |
+
for name, items in catalog_items.items():
|
| 379 |
+
auto_key = _catalog_key(name)
|
| 380 |
+
await collection.update_one(
|
| 381 |
+
{"auto_key": auto_key},
|
| 382 |
+
{
|
| 383 |
+
"$setOnInsert": {
|
| 384 |
+
"name": name,
|
| 385 |
+
"visible": True,
|
| 386 |
+
"auto": True,
|
| 387 |
+
"auto_key": auto_key,
|
| 388 |
+
"items": [],
|
| 389 |
+
"item_count": 0,
|
| 390 |
+
"created_at": now,
|
| 391 |
+
},
|
| 392 |
+
"$set": {
|
| 393 |
+
"updated_at": now,
|
| 394 |
+
"last_auto_sync": now,
|
| 395 |
+
},
|
| 396 |
+
},
|
| 397 |
+
upsert=True,
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
for item in items:
|
| 401 |
+
await collection.update_one(
|
| 402 |
+
{
|
| 403 |
+
"auto_key": auto_key,
|
| 404 |
+
"items": {
|
| 405 |
+
"$not": {
|
| 406 |
+
"$elemMatch": {
|
| 407 |
+
"tmdb_id": item["tmdb_id"],
|
| 408 |
+
"db_index": item["db_index"],
|
| 409 |
+
"media_type": item["media_type"],
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
},
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"$push": {"items": {"$each": [item], "$position": 0}},
|
| 416 |
+
"$set": {"updated_at": now},
|
| 417 |
+
"$inc": {"item_count": 1},
|
| 418 |
+
},
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
async def _rebuild_auto_catalogs(db, catalog_items: Dict[str, List[dict]], enabled_names: Set[str]) -> None:
|
| 423 |
+
collection = db.dbs["tracking"]["custom_catalogs"]
|
| 424 |
+
now = datetime.utcnow()
|
| 425 |
+
|
| 426 |
+
for name, items in catalog_items.items():
|
| 427 |
+
seen = set()
|
| 428 |
+
unique_items = []
|
| 429 |
+
for item in items:
|
| 430 |
+
key = (item["media_type"], item["tmdb_id"], item["db_index"])
|
| 431 |
+
if key in seen:
|
| 432 |
+
continue
|
| 433 |
+
seen.add(key)
|
| 434 |
+
unique_items.append(item)
|
| 435 |
+
|
| 436 |
+
await collection.update_one(
|
| 437 |
+
{"auto_key": _catalog_key(name)},
|
| 438 |
+
{
|
| 439 |
+
"$set": {
|
| 440 |
+
"name": name,
|
| 441 |
+
"visible": True,
|
| 442 |
+
"auto": True,
|
| 443 |
+
"auto_key": _catalog_key(name),
|
| 444 |
+
"items": unique_items,
|
| 445 |
+
"item_count": len(unique_items),
|
| 446 |
+
"updated_at": now,
|
| 447 |
+
"last_auto_sync": now,
|
| 448 |
+
},
|
| 449 |
+
"$setOnInsert": {"created_at": now},
|
| 450 |
+
},
|
| 451 |
+
upsert=True,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
active_keys = {_catalog_key(name) for name in enabled_names}
|
| 456 |
+
await collection.update_many(
|
| 457 |
+
{"auto": True, "auto_key": {"$nin": list(active_keys)}},
|
| 458 |
+
{"$set": {"visible": False, "items": [], "item_count": 0, "updated_at": now}},
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
async def _write_status(db, data: dict) -> None:
|
| 463 |
+
await db.dbs["tracking"]["state"].update_one(
|
| 464 |
+
{"_id": "auto_catalog_sync"},
|
| 465 |
+
{"$set": data},
|
| 466 |
+
upsert=True,
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool = False, delay_seconds: int = 0) -> dict:
|
| 471 |
+
if delay_seconds:
|
| 472 |
+
await asyncio.sleep(delay_seconds)
|
| 473 |
+
|
| 474 |
+
if _auto_sync_lock.locked() and not force:
|
| 475 |
+
return {"running": True, "message": "Auto catalog sync is already running."}
|
| 476 |
+
|
| 477 |
+
async with _auto_sync_lock:
|
| 478 |
+
started_at = datetime.utcnow()
|
| 479 |
+
await _write_status(db, {
|
| 480 |
+
"running": True,
|
| 481 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 482 |
+
"message": "Auto catalog sync running...",
|
| 483 |
+
"started_at": started_at,
|
| 484 |
+
"finished_at": None,
|
| 485 |
+
"scanned": 0,
|
| 486 |
+
"skipped": 0,
|
| 487 |
+
"classified": 0,
|
| 488 |
+
"tagged": 0,
|
| 489 |
+
"catalogs": 0,
|
| 490 |
+
})
|
| 491 |
+
|
| 492 |
+
catalog_items: Dict[str, List[dict]] = {}
|
| 493 |
+
scanned = 0
|
| 494 |
+
skipped = 0
|
| 495 |
+
classified = 0
|
| 496 |
+
tagged = 0
|
| 497 |
+
error_message = None
|
| 498 |
+
settings_configured = await has_auto_catalog_settings(db)
|
| 499 |
+
enabled_names = await _enabled_catalog_names(db)
|
| 500 |
+
|
| 501 |
+
if not settings_configured or not enabled_names:
|
| 502 |
+
finished_at = datetime.utcnow()
|
| 503 |
+
summary = {
|
| 504 |
+
"running": False,
|
| 505 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 506 |
+
"message": "Auto catalog skipped. Save auto catalog selection first.",
|
| 507 |
+
"scanned": 0,
|
| 508 |
+
"skipped": 0,
|
| 509 |
+
"classified": 0,
|
| 510 |
+
"tagged": 0,
|
| 511 |
+
"catalogs": 0,
|
| 512 |
+
"enabled_catalogs": [],
|
| 513 |
+
"started_at": started_at,
|
| 514 |
+
"finished_at": finished_at,
|
| 515 |
+
"error": None,
|
| 516 |
+
}
|
| 517 |
+
await _write_status(db, summary)
|
| 518 |
+
LOGGER.info(f"Auto catalog sync skipped: {summary}")
|
| 519 |
+
return summary
|
| 520 |
+
|
| 521 |
+
try:
|
| 522 |
+
timeout = httpx.Timeout(18.0, connect=10.0)
|
| 523 |
+
limits = httpx.Limits(max_connections=AUTO_SYNC_CONCURRENCY + 2, max_keepalive_connections=AUTO_SYNC_CONCURRENCY)
|
| 524 |
+
semaphore = asyncio.Semaphore(AUTO_SYNC_CONCURRENCY)
|
| 525 |
+
|
| 526 |
+
async def consume_result(media_doc: dict, classification: dict) -> None:
|
| 527 |
+
nonlocal tagged
|
| 528 |
+
tags = classification.get("auto_tags", []) or []
|
| 529 |
+
if tags:
|
| 530 |
+
tagged += 1
|
| 531 |
+
item = _doc_item(media_doc)
|
| 532 |
+
for tag in tags:
|
| 533 |
+
if tag in enabled_names:
|
| 534 |
+
catalog_items.setdefault(tag, []).append(item)
|
| 535 |
+
|
| 536 |
+
async with httpx.AsyncClient(timeout=timeout, limits=limits, follow_redirects=True) as client:
|
| 537 |
+
pending = []
|
| 538 |
+
async for _, _, doc, already_synced in _iter_all_media(db, full_rebuild=full_rebuild):
|
| 539 |
+
scanned += 1
|
| 540 |
+
|
| 541 |
+
if already_synced and not force and not full_rebuild:
|
| 542 |
+
skipped += 1
|
| 543 |
+
continue
|
| 544 |
+
|
| 545 |
+
if already_synced and force and not full_rebuild:
|
| 546 |
+
skipped += 1
|
| 547 |
+
continue
|
| 548 |
+
|
| 549 |
+
classified += 1
|
| 550 |
+
pending.append(_classify_one(db, client, semaphore, doc, enabled_names))
|
| 551 |
+
|
| 552 |
+
if len(pending) >= 40:
|
| 553 |
+
for media_doc, classification in await asyncio.gather(*pending):
|
| 554 |
+
await consume_result(media_doc, classification)
|
| 555 |
+
pending = []
|
| 556 |
+
await _write_status(db, {
|
| 557 |
+
"running": True,
|
| 558 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 559 |
+
"started_at": started_at,
|
| 560 |
+
"scanned": scanned,
|
| 561 |
+
"skipped": skipped,
|
| 562 |
+
"classified": classified,
|
| 563 |
+
"tagged": tagged,
|
| 564 |
+
"catalogs": len(catalog_items),
|
| 565 |
+
})
|
| 566 |
+
|
| 567 |
+
if pending:
|
| 568 |
+
for media_doc, classification in await asyncio.gather(*pending):
|
| 569 |
+
await consume_result(media_doc, classification)
|
| 570 |
+
|
| 571 |
+
if full_rebuild:
|
| 572 |
+
await _rebuild_auto_catalogs(db, catalog_items, enabled_names)
|
| 573 |
+
else:
|
| 574 |
+
await _flush_quick_items(db, catalog_items)
|
| 575 |
+
|
| 576 |
+
finished_at = datetime.utcnow()
|
| 577 |
+
summary = {
|
| 578 |
+
"running": False,
|
| 579 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 580 |
+
"scanned": scanned,
|
| 581 |
+
"skipped": skipped,
|
| 582 |
+
"classified": classified,
|
| 583 |
+
"tagged": tagged,
|
| 584 |
+
"catalogs": len(catalog_items),
|
| 585 |
+
"enabled_catalogs": sorted(enabled_names),
|
| 586 |
+
"started_at": started_at,
|
| 587 |
+
"finished_at": finished_at,
|
| 588 |
+
"error": None,
|
| 589 |
+
}
|
| 590 |
+
await _write_status(db, summary)
|
| 591 |
+
LOGGER.info(f"Auto catalog sync complete: {summary}")
|
| 592 |
+
return summary
|
| 593 |
+
except Exception as exc:
|
| 594 |
+
error_message = str(exc)
|
| 595 |
+
finished_at = datetime.utcnow()
|
| 596 |
+
summary = {
|
| 597 |
+
"running": False,
|
| 598 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 599 |
+
"scanned": scanned,
|
| 600 |
+
"skipped": skipped,
|
| 601 |
+
"classified": classified,
|
| 602 |
+
"tagged": tagged,
|
| 603 |
+
"catalogs": len(catalog_items),
|
| 604 |
+
"enabled_catalogs": sorted(enabled_names),
|
| 605 |
+
"started_at": started_at,
|
| 606 |
+
"finished_at": finished_at,
|
| 607 |
+
"error": error_message,
|
| 608 |
+
}
|
| 609 |
+
await _write_status(db, summary)
|
| 610 |
+
LOGGER.error(f"Auto catalog sync failed: {summary}")
|
| 611 |
+
raise
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
async def start_auto_catalog_sync_background(db, *, full_rebuild: bool = False, force: bool = False, delay_seconds: int = 0) -> dict:
|
| 615 |
+
global _auto_sync_task
|
| 616 |
+
|
| 617 |
+
if _auto_sync_lock.locked() or (_auto_sync_task and not _auto_sync_task.done()):
|
| 618 |
+
return {"running": True, "message": "Auto catalog sync is already running."}
|
| 619 |
+
|
| 620 |
+
started_at = datetime.utcnow()
|
| 621 |
+
await _write_status(db, {
|
| 622 |
+
"running": True,
|
| 623 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 624 |
+
"message": "Auto catalog sync queued...",
|
| 625 |
+
"started_at": started_at,
|
| 626 |
+
"finished_at": None,
|
| 627 |
+
"scanned": 0,
|
| 628 |
+
"skipped": 0,
|
| 629 |
+
"classified": 0,
|
| 630 |
+
"tagged": 0,
|
| 631 |
+
"catalogs": 0,
|
| 632 |
+
})
|
| 633 |
+
|
| 634 |
+
async def runner():
|
| 635 |
+
try:
|
| 636 |
+
await run_auto_catalog_sync(db, force=force, full_rebuild=full_rebuild, delay_seconds=delay_seconds)
|
| 637 |
+
except Exception:
|
| 638 |
+
LOGGER.exception("Background auto catalog sync crashed")
|
| 639 |
+
|
| 640 |
+
_auto_sync_task = asyncio.create_task(runner())
|
| 641 |
+
return {
|
| 642 |
+
"running": True,
|
| 643 |
+
"message": "Full rebuild started in background." if full_rebuild else "Quick sync started in background.",
|
| 644 |
+
"mode": "full_rebuild" if full_rebuild else "quick_sync",
|
| 645 |
+
"started_at": started_at,
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
async def start_auto_catalog_interval_loop(db) -> None:
|
| 650 |
+
"""Run quick sync every N minutes after auto-catalog settings exist.
|
| 651 |
+
|
| 652 |
+
This avoids per-upload TMDb calls and prevents first boot from creating
|
| 653 |
+
catalogs until the admin chooses options from /catalogs.
|
| 654 |
+
"""
|
| 655 |
+
if not AUTO_CATALOG_INTERVAL_SYNC:
|
| 656 |
+
LOGGER.info("Auto catalog interval sync disabled.")
|
| 657 |
+
return
|
| 658 |
+
|
| 659 |
+
interval_minutes = max(1, int(AUTO_CATALOG_SYNC_INTERVAL_MINUTES or 60))
|
| 660 |
+
interval_seconds = interval_minutes * 60
|
| 661 |
+
LOGGER.info(f"Auto catalog interval sync loop started. Interval: {interval_minutes} minutes")
|
| 662 |
+
|
| 663 |
+
while True:
|
| 664 |
+
try:
|
| 665 |
+
await asyncio.sleep(interval_seconds)
|
| 666 |
+
|
| 667 |
+
if not await has_auto_catalog_settings(db):
|
| 668 |
+
LOGGER.info("Hourly auto catalog quick sync skipped: no auto catalog selection saved yet.")
|
| 669 |
+
continue
|
| 670 |
+
|
| 671 |
+
if _auto_sync_lock.locked() or (_auto_sync_task and not _auto_sync_task.done()):
|
| 672 |
+
LOGGER.info("Hourly auto catalog quick sync skipped: another sync is already running.")
|
| 673 |
+
continue
|
| 674 |
+
|
| 675 |
+
result = await start_auto_catalog_sync_background(
|
| 676 |
+
db,
|
| 677 |
+
full_rebuild=False,
|
| 678 |
+
force=False,
|
| 679 |
+
delay_seconds=0,
|
| 680 |
+
)
|
| 681 |
+
LOGGER.info(f"Hourly auto catalog quick sync queued: {result}")
|
| 682 |
+
|
| 683 |
+
except asyncio.CancelledError:
|
| 684 |
+
LOGGER.info("Auto catalog interval sync loop stopped.")
|
| 685 |
+
break
|
| 686 |
+
except Exception as exc:
|
| 687 |
+
LOGGER.error(f"Hourly auto catalog quick sync failed: {exc}")
|
| 688 |
+
await asyncio.sleep(300)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
async def get_auto_catalog_sync_status(db) -> dict:
|
| 692 |
+
state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_sync"}) or {}
|
| 693 |
+
state.pop("_id", None)
|
| 694 |
+
return state
|
pyproject.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
-
version = "3.
|
| 4 |
description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
+
version = "3.1.0"
|
| 4 |
description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|