Karan Adhikari commited on
Commit
e2c4766
Β·
unverified Β·
1 Parent(s): 580ed85

Add Anime Support + fix auto catalog

Browse files
Backend/fastapi/routes/api_routes.py CHANGED
@@ -1026,7 +1026,7 @@ async def update_settings_api(payload: dict) -> dict:
1026
  if key in payload:
1027
  payload[key] = bool(payload[key])
1028
 
1029
- list_str_keys = {"auth_channels", "multi_tokens", "extra_databases", "global_search_channels"}
1030
  for key in list_str_keys:
1031
  if key in payload:
1032
  if not isinstance(payload[key], list):
@@ -1069,6 +1069,21 @@ async def update_settings_api(payload: dict) -> dict:
1069
  cleaned.append(channel)
1070
  payload["global_search_channels"] = cleaned
1071
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1072
  # Strip whitespace from string fields
1073
  for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
1074
  "admin_username", "admin_password", "http_proxy_url",
 
1026
  if key in payload:
1027
  payload[key] = bool(payload[key])
1028
 
1029
+ list_str_keys = {"auth_channels", "multi_tokens", "extra_databases", "global_search_channels", "anime_channels"}
1030
  for key in list_str_keys:
1031
  if key in payload:
1032
  if not isinstance(payload[key], list):
 
1069
  cleaned.append(channel)
1070
  payload["global_search_channels"] = cleaned
1071
 
1072
+ if "anime_channels" in payload:
1073
+ cleaned = []
1074
+ for channel in payload["anime_channels"]:
1075
+ channel = str(channel).strip()
1076
+ if not channel:
1077
+ continue
1078
+ try:
1079
+ int(channel.replace("-100", ""))
1080
+ except ValueError:
1081
+ raise HTTPException(status_code=400,
1082
+ detail=f"Invalid anime channel id: {channel}"
1083
+ )
1084
+ cleaned.append(channel)
1085
+ payload["anime_channels"] = cleaned
1086
+
1087
  # Strip whitespace from string fields
1088
  for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
1089
  "admin_username", "admin_password", "http_proxy_url",
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -177,22 +177,29 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
177
  try:
178
  custom_catalogs = await db.get_custom_catalogs(visible_only=True)
179
  for catalog in custom_catalogs:
 
 
 
 
 
180
  catalog_id = str(catalog.get("_id"))
181
  catalog_name = catalog.get("name") or "Custom Catalog"
182
- catalogs.append({
183
- "type": "movie",
184
- "id": f"custom_{catalog_id}",
185
- "name": catalog_name,
186
- "extra": [{"name": "skip"}],
187
- "extraSupported": ["skip"],
188
- })
189
- catalogs.append({
190
- "type": "series",
191
- "id": f"custom_{catalog_id}",
192
- "name": catalog_name,
193
- "extra": [{"name": "skip"}],
194
- "extraSupported": ["skip"],
195
- })
 
 
196
  except Exception:
197
  pass
198
 
 
177
  try:
178
  custom_catalogs = await db.get_custom_catalogs(visible_only=True)
179
  for catalog in custom_catalogs:
180
+ items = catalog.get("items") or []
181
+ has_movie = any(i.get("media_type") == "movie" for i in items)
182
+ has_series = any(i.get("media_type") == "tv" for i in items)
183
+ if not has_movie and not has_series:
184
+ continue
185
  catalog_id = str(catalog.get("_id"))
186
  catalog_name = catalog.get("name") or "Custom Catalog"
187
+ if has_movie:
188
+ catalogs.append({
189
+ "type": "movie",
190
+ "id": f"custom_{catalog_id}",
191
+ "name": catalog_name,
192
+ "extra": [{"name": "skip"}],
193
+ "extraSupported": ["skip"],
194
+ })
195
+ if has_series:
196
+ catalogs.append({
197
+ "type": "series",
198
+ "id": f"custom_{catalog_id}",
199
+ "name": catalog_name,
200
+ "extra": [{"name": "skip"}],
201
+ "extraSupported": ["skip"],
202
+ })
203
  except Exception:
204
  pass
205
 
Backend/fastapi/templates/settings.html CHANGED
@@ -189,6 +189,36 @@
189
  onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('auth_channels')}">
190
  <button class="add-btn" onclick="addItem('auth_channels')">+ Add Channel</button>
191
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  </div>
193
 
194
  <!-- ── Media & Content ─────────────────────────────────────────────── -->
@@ -595,6 +625,7 @@ async function saveSettings() {
595
  upstream_repo: document.getElementById('upstream_repo').value.trim(),
596
  upstream_branch: document.getElementById('upstream_branch').value.trim(),
597
  auth_channels: collectList('auth_channels'),
 
598
  subscription: document.getElementById('subscription').checked,
599
  subscription_group_id: parseInt(document.getElementById('subscription_group_id').value || '0', 10),
600
  payment_instructions: document.getElementById('payment_instructions').value.trim(),
@@ -690,6 +721,7 @@ function renderSettings(s) {
690
 
691
  // Simple multi-value lists
692
  rebuildSimpleList('auth_channels_items', s.auth_channels, 'text');
 
693
  rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
694
  rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
695
  rebuildSimpleList('global_search_channels_items', s.global_search_channels, 'text');
 
189
  onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('auth_channels')}">
190
  <button class="add-btn" onclick="addItem('auth_channels')">+ Add Channel</button>
191
  </div>
192
+
193
+ <hr class="divider">
194
+
195
+ <!-- Anime Channels -->
196
+ <label class="s-label">ANIME_CHANNELS
197
+ <span style="font-weight:400;text-transform:none;letter-spacing:0">
198
+ β€” files from these channels use AniList + api.ani.zip for accurate metadata</span>
199
+ </label>
200
+ <p style="font-size:0.78rem;color:var(--text-sec);margin-bottom:0.75rem">
201
+ Enter numeric channel IDs (e.g. <code>-1001234567890</code> or bare
202
+ <code>1234567890</code>). Use this for anime channels where IMDb/TMDB
203
+ matching is inaccurate.
204
+ </p>
205
+ <div class="multi-list-items" id="anime_channels_items">
206
+ {% for ch in settings.anime_channels %}
207
+ <div class="multi-item">
208
+ <input type="text" class="s-input" value="{{ ch }}" data-list="anime_channels"
209
+ placeholder="-100xxxxxxxxxx">
210
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
211
+ <i class="fa-solid fa-xmark"></i>
212
+ </button>
213
+ </div>
214
+ {% endfor %}
215
+ </div>
216
+ <div class="add-row">
217
+ <input type="text" id="anime_channels_new" class="s-input"
218
+ placeholder="-100xxxxxxxxxx or bare numeric ID"
219
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('anime_channels')}">
220
+ <button class="add-btn" onclick="addItem('anime_channels')">+ Add Channel</button>
221
+ </div>
222
  </div>
223
 
224
  <!-- ── Media & Content ─────────────────────────────────────────────── -->
 
625
  upstream_repo: document.getElementById('upstream_repo').value.trim(),
626
  upstream_branch: document.getElementById('upstream_branch').value.trim(),
627
  auth_channels: collectList('auth_channels'),
628
+ anime_channels: collectList('anime_channels'),
629
  subscription: document.getElementById('subscription').checked,
630
  subscription_group_id: parseInt(document.getElementById('subscription_group_id').value || '0', 10),
631
  payment_instructions: document.getElementById('payment_instructions').value.trim(),
 
721
 
722
  // Simple multi-value lists
723
  rebuildSimpleList('auth_channels_items', s.auth_channels, 'text');
724
+ rebuildSimpleList('anime_channels_items', s.anime_channels, 'text');
725
  rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
726
  rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
727
  rebuildSimpleList('global_search_channels_items', s.global_search_channels, 'text');
Backend/helper/anime.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import re
3
+ from typing import Optional, List
4
+
5
+ import httpx
6
+
7
+ from Backend.logger import LOGGER
8
+
9
+ ANILIST_URL = "https://graphql.anilist.co"
10
+ ANIZIP_URL = "https://api.ani.zip/mappings"
11
+
12
+ _client: Optional[httpx.AsyncClient] = None
13
+ _client_lock = asyncio.Lock()
14
+
15
+ _SEARCH_CACHE: dict = {}
16
+ _MAP_CACHE: dict = {}
17
+
18
+ _HTML_RE = re.compile(r"<[^>]+>")
19
+
20
+ _ANILIST_FIELDS = """
21
+ id
22
+ title { romaji english }
23
+ seasonYear
24
+ startDate { year }
25
+ description(asHtml: false)
26
+ genres
27
+ averageScore
28
+ duration
29
+ coverImage { extraLarge large }
30
+ bannerImage
31
+ """
32
+
33
+ _ANILIST_QUERY = """
34
+ query ($search: String) {
35
+ Media(search: $search, type: ANIME) {
36
+ """ + _ANILIST_FIELDS + """
37
+ }
38
+ }
39
+ """
40
+
41
+ _ANILIST_MOVIE_QUERY = """
42
+ query ($search: String) {
43
+ Media(search: $search, type: ANIME, format: MOVIE) {
44
+ """ + _ANILIST_FIELDS + """
45
+ }
46
+ }
47
+ """
48
+
49
+
50
+ async def _get_client() -> httpx.AsyncClient:
51
+ global _client
52
+ async with _client_lock:
53
+ if _client is None or _client.is_closed:
54
+ _client = httpx.AsyncClient(
55
+ timeout=20.0,
56
+ follow_redirects=True,
57
+ headers={"User-Agent": "Telegram-Stremio (+https://github.com/weebzone/Telegram-Stremio)"},
58
+ )
59
+ return _client
60
+
61
+
62
+ def _strip_html(text: str) -> str:
63
+ if not text:
64
+ return ""
65
+ return re.sub(r"\s+", " ", _HTML_RE.sub(" ", text)).strip()
66
+
67
+
68
+ def _season_queries(title: str, season: Optional[int]) -> List[str]:
69
+ if season and int(season) > 1:
70
+ return [f"{title} Season {season}", f"{title} {season}", title]
71
+ return [title]
72
+
73
+
74
+ async def _anilist_request(search: str, query: str = _ANILIST_QUERY) -> Optional[dict]:
75
+ try:
76
+ client = await _get_client()
77
+ resp = await client.post(ANILIST_URL, json={"query": query, "variables": {"search": search}})
78
+ if resp.status_code != 200:
79
+ return None
80
+ return ((resp.json() or {}).get("data") or {}).get("Media")
81
+ except Exception as e:
82
+ LOGGER.warning(f"[ANIME] AniList search failed for '{search}': {e}")
83
+ return None
84
+
85
+
86
+ async def search_anime(title: str, season: Optional[int] = None) -> Optional[dict]:
87
+ cache_key = f"{title}::{season}"
88
+ if cache_key in _SEARCH_CACHE:
89
+ return _SEARCH_CACHE[cache_key]
90
+ media = None
91
+ for query in _season_queries(title, season):
92
+ media = await _anilist_request(query)
93
+ if media:
94
+ break
95
+ _SEARCH_CACHE[cache_key] = media
96
+ return media
97
+
98
+
99
+ async def search_anime_movie(title: str) -> Optional[dict]:
100
+ cache_key = f"movie::{title}"
101
+ if cache_key in _SEARCH_CACHE:
102
+ return _SEARCH_CACHE[cache_key]
103
+ media = await _anilist_request(title, _ANILIST_MOVIE_QUERY)
104
+ _SEARCH_CACHE[cache_key] = media
105
+ return media
106
+
107
+
108
+ async def get_anizip_mappings(anilist_id: int) -> Optional[dict]:
109
+ if anilist_id in _MAP_CACHE:
110
+ return _MAP_CACHE[anilist_id]
111
+ try:
112
+ client = await _get_client()
113
+ resp = await client.get(ANIZIP_URL, params={"anilist_id": anilist_id})
114
+ data = resp.json() if resp.status_code == 200 else None
115
+ except Exception as e:
116
+ LOGGER.warning(f"[ANIME] ani.zip mappings failed for {anilist_id}: {e}")
117
+ data = None
118
+ _MAP_CACHE[anilist_id] = data
119
+ return data
120
+
121
+
122
+ def _anizip_image(images, cover_type: str) -> str:
123
+ for img in images or []:
124
+ if str(img.get("coverType", "")).lower() == cover_type.lower() and img.get("url"):
125
+ return img["url"]
126
+ return ""
127
+
128
+
129
+ # Build the fields shared by anime movie/TV payloads from AniList + ani.zip data.
130
+ # imdb_id may be None when ani.zip lacks it β€” the caller resolves it from tmdb_id.
131
+ def _common_payload(media: dict, doc: dict, title: str) -> dict:
132
+ mappings = doc.get("mappings") or {}
133
+ tmdb_id = mappings.get("themoviedb_id")
134
+ try:
135
+ tmdb_id = int(tmdb_id) if tmdb_id else None
136
+ except (ValueError, TypeError):
137
+ tmdb_id = None
138
+
139
+ titles = media.get("title") or {}
140
+ images = doc.get("images") or []
141
+ cover = media.get("coverImage") or {}
142
+ score = media.get("averageScore")
143
+ duration = media.get("duration")
144
+ return {
145
+ "tmdb_id": tmdb_id,
146
+ "imdb_id": mappings.get("imdb_id"),
147
+ "title": titles.get("english") or titles.get("romaji") or title,
148
+ "year": media.get("seasonYear") or (media.get("startDate") or {}).get("year") or 0,
149
+ "rate": round(score / 10, 1) if score else 0,
150
+ "description": _strip_html(media.get("description") or ""),
151
+ "poster": cover.get("extraLarge") or cover.get("large") or _anizip_image(images, "Poster"),
152
+ "backdrop": media.get("bannerImage") or _anizip_image(images, "Fanart") or _anizip_image(images, "Banner"),
153
+ "logo": _anizip_image(images, "Clearlogo"),
154
+ "genres": media.get("genres") or [],
155
+ "cast": [],
156
+ "runtime": f"{duration} min" if duration else "",
157
+ }
158
+
159
+
160
+ # Resolve accurate anime TV metadata via AniList (search) + api.ani.zip (mappings/episodes).
161
+ async def fetch_anime_metadata(title, season, episode, encoded_string, year=None, quality=None) -> Optional[dict]:
162
+ media = await search_anime(title, season)
163
+ if not media:
164
+ LOGGER.info(f"[ANIME] No AniList match for '{title}' (season={season})")
165
+ return None
166
+
167
+ doc = await get_anizip_mappings(media["id"]) or {}
168
+ payload = _common_payload(media, doc, title)
169
+ if not payload["imdb_id"] and not payload["tmdb_id"]:
170
+ LOGGER.info(f"[ANIME] No imdb/tmdb mapping for AniList {media['id']} ('{title}') -> fallback")
171
+ return None
172
+
173
+ ep = (doc.get("episodes") or {}).get(str(episode)) or {}
174
+ ep_title = (ep.get("title") or {}).get("en") if isinstance(ep.get("title"), dict) else None
175
+
176
+ payload.update({
177
+ "media_type": "tv",
178
+ "season_number": season,
179
+ "episode_number": episode,
180
+ "episode_title": ep_title or f"S{season:02d}E{episode:02d}",
181
+ "episode_backdrop": ep.get("image", "") or "",
182
+ "episode_overview": ep.get("overview") or ep.get("summary") or "",
183
+ "episode_released": ep.get("airDate") or ep.get("airdate") or "",
184
+ "quality": quality,
185
+ "encoded_string": encoded_string,
186
+ })
187
+ return payload
188
+
189
+
190
+ # Resolve accurate anime movie metadata via AniList (format MOVIE) + api.ani.zip.
191
+ async def fetch_anime_movie_metadata(title, encoded_string, year=None, quality=None) -> Optional[dict]:
192
+ media = await search_anime_movie(title)
193
+ if not media:
194
+ LOGGER.info(f"[ANIME] No AniList movie match for '{title}'")
195
+ return None
196
+
197
+ doc = await get_anizip_mappings(media["id"]) or {}
198
+ payload = _common_payload(media, doc, title)
199
+ if not payload["imdb_id"] and not payload["tmdb_id"]:
200
+ LOGGER.info(f"[ANIME] No imdb/tmdb mapping for AniList movie {media['id']} ('{title}') -> fallback")
201
+ return None
202
+
203
+ payload.update({"media_type": "movie", "quality": quality, "encoded_string": encoded_string})
204
+ return payload
Backend/helper/auto_catalog.py CHANGED
@@ -13,8 +13,6 @@ from Backend.logger import LOGGER
13
  AUTO_CATALOG_REGION = "IN"
14
  AUTO_SYNC_CONCURRENCY = 5
15
 
16
- # Hourly quick sync. It only starts after the admin has saved at least one
17
- # auto-catalog option from /catalogs, so first boot stays clean.
18
  AUTO_CATALOG_INTERVAL_SYNC = True
19
  AUTO_CATALOG_SYNC_INTERVAL_MINUTES = 60
20
 
@@ -96,8 +94,18 @@ _PROVIDER_ALIASES = {
96
  _auto_sync_lock = asyncio.Lock()
97
  _auto_sync_task: Optional[asyncio.Task] = None
98
 
 
 
 
99
 
100
  def _tmdb_api_key() -> str:
 
 
 
 
 
 
 
101
  return getattr(Telegram, "TMDB_API", "") or ""
102
 
103
 
@@ -174,8 +182,6 @@ async def get_auto_catalog_settings(db) -> dict:
174
  state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"}) or {}
175
  configured = isinstance(state.get("enabled_keys"), list)
176
 
177
- # Important: first boot should not auto-create catalogs.
178
- # Until the admin saves settings from /catalogs, enabled_keys stays empty.
179
  enabled_keys = state.get("enabled_keys") if configured else []
180
 
181
  enabled_set = {key for key in enabled_keys if key in CATALOG_BY_KEY}
@@ -205,9 +211,25 @@ async def update_auto_catalog_settings(db, enabled_keys: List[str]) -> dict:
205
  {"$set": {"enabled_keys": clean_keys, "updated_at": now}},
206
  upsert=True,
207
  )
 
208
  return await get_auto_catalog_settings(db)
209
 
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  async def _enabled_catalog_names(db) -> Set[str]:
212
  settings = await get_auto_catalog_settings(db)
213
  keys = settings.get("enabled_keys") or []
@@ -221,12 +243,15 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
221
  media_type = _media_type(doc)
222
  original_language = details.get("original_language") or doc.get("original_language") or ""
223
 
224
- origin_country = details.get("origin_country") or []
 
 
 
225
  production_countries = [
226
  c.get("iso_3166_1")
227
  for c in details.get("production_countries", []) or []
228
  if c.get("iso_3166_1")
229
- ]
230
 
231
  for tag in _LANGUAGE_CATALOGS.get(original_language, []):
232
  tags.add(tag)
@@ -260,11 +285,21 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
260
  except Exception:
261
  pass
262
 
263
- for provider_name in _extract_provider_names(watch_data):
264
- bucket = _provider_bucket(provider_name)
265
- if bucket:
266
- providers.add(bucket)
267
- tags.add(bucket)
 
 
 
 
 
 
 
 
 
 
268
 
269
  tags = {tag for tag in tags if tag in enabled_names}
270
 
@@ -327,7 +362,7 @@ async def _iter_all_media(db, *, full_rebuild: bool = False):
327
  for collection_name in ["movie", "tv"]:
328
  cursor = db.dbs[db_key][collection_name].find({"tmdb_id": {"$exists": True, "$ne": None}})
329
  async for doc in cursor:
330
- doc["db_index"] = int(doc.get("db_index", db_index))
331
  doc["media_type"] = "tv" if collection_name == "tv" else "movie"
332
  if not full_rebuild and _is_already_synced(doc):
333
  yield collection_name, db_index, doc, True
@@ -338,14 +373,8 @@ async def _iter_all_media(db, *, full_rebuild: bool = False):
338
  async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaphore, doc: dict, enabled_names: Set[str]) -> tuple[dict, dict]:
339
  async with semaphore:
340
  try:
341
- details, watch_data = await _fetch_tmdb_data(client, doc)
342
- classification = classify_media_from_tmdb(doc, details, watch_data, enabled_names) if details else {
343
- "original_language": doc.get("original_language", ""),
344
- "origin_country": doc.get("origin_country", []),
345
- "production_countries": doc.get("production_countries", []),
346
- "watch_providers": doc.get("watch_providers", []),
347
- "auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names],
348
- }
349
 
350
  now = datetime.utcnow()
351
  update_data = {
@@ -361,13 +390,82 @@ async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaph
361
  "source_updated_on": doc.get("updated_on"),
362
  },
363
  }
364
- await db.update_document(_media_type(doc), int(doc.get("tmdb_id")), int(doc.get("db_index", 1)), update_data)
 
 
 
 
 
 
 
 
 
365
  return doc, classification
366
  except Exception as e:
367
  LOGGER.warning(f"Auto catalog classification failed for {doc.get('title')} ({doc.get('tmdb_id')}): {e}")
368
  return doc, {"auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names]}
369
 
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
372
  collection = db.dbs["tracking"]["custom_catalogs"]
373
  now = datetime.utcnow()
@@ -515,9 +613,15 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
515
  LOGGER.info(f"Auto catalog sync skipped: {summary}")
516
  return summary
517
 
 
 
 
 
 
 
518
  try:
519
  timeout = httpx.Timeout(18.0, connect=10.0)
520
- limits = httpx.Limits(max_connections=AUTO_SYNC_CONCURRENCY + 2, max_keepalive_connections=AUTO_SYNC_CONCURRENCY)
521
  semaphore = asyncio.Semaphore(AUTO_SYNC_CONCURRENCY)
522
 
523
  async def consume_result(media_doc: dict, classification: dict) -> None:
@@ -535,11 +639,7 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
535
  async for _, _, doc, already_synced in _iter_all_media(db, full_rebuild=full_rebuild):
536
  scanned += 1
537
 
538
- if already_synced and not force and not full_rebuild:
539
- skipped += 1
540
- continue
541
-
542
- if already_synced and force and not full_rebuild:
543
  skipped += 1
544
  continue
545
 
 
13
  AUTO_CATALOG_REGION = "IN"
14
  AUTO_SYNC_CONCURRENCY = 5
15
 
 
 
16
  AUTO_CATALOG_INTERVAL_SYNC = True
17
  AUTO_CATALOG_SYNC_INTERVAL_MINUTES = 60
18
 
 
94
  _auto_sync_lock = asyncio.Lock()
95
  _auto_sync_task: Optional[asyncio.Task] = None
96
 
97
+ INSTANT_SYNC_CONCURRENCY = 3
98
+ _instant_sync_semaphore = asyncio.Semaphore(INSTANT_SYNC_CONCURRENCY)
99
+
100
 
101
  def _tmdb_api_key() -> str:
102
+ try:
103
+ from Backend.helper.settings_manager import SettingsManager
104
+ key = SettingsManager.current().tmdb_api
105
+ if key:
106
+ return key
107
+ except Exception:
108
+ pass
109
  return getattr(Telegram, "TMDB_API", "") or ""
110
 
111
 
 
182
  state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"}) or {}
183
  configured = isinstance(state.get("enabled_keys"), list)
184
 
 
 
185
  enabled_keys = state.get("enabled_keys") if configured else []
186
 
187
  enabled_set = {key for key in enabled_keys if key in CATALOG_BY_KEY}
 
211
  {"$set": {"enabled_keys": clean_keys, "updated_at": now}},
212
  upsert=True,
213
  )
214
+ await _invalidate_synced_flags(db)
215
  return await get_auto_catalog_settings(db)
216
 
217
 
218
+ async def _invalidate_synced_flags(db) -> None:
219
+ for db_index in range(1, db.current_db_index + 1):
220
+ db_key = f"storage_{db_index}"
221
+ if db_key not in db.dbs:
222
+ continue
223
+ for collection_name in ["movie", "tv"]:
224
+ try:
225
+ await db.dbs[db_key][collection_name].update_many(
226
+ {"auto_catalog.synced": True},
227
+ {"$set": {"auto_catalog.synced": False}},
228
+ )
229
+ except Exception as e:
230
+ LOGGER.warning(f"Auto catalog: failed to reset synced flags in {db_key}.{collection_name}: {e}")
231
+
232
+
233
  async def _enabled_catalog_names(db) -> Set[str]:
234
  settings = await get_auto_catalog_settings(db)
235
  keys = settings.get("enabled_keys") or []
 
243
  media_type = _media_type(doc)
244
  original_language = details.get("original_language") or doc.get("original_language") or ""
245
 
246
+ if doc.get("is_anime"):
247
+ tags.add("Anime")
248
+
249
+ origin_country = details.get("origin_country") or doc.get("origin_country") or []
250
  production_countries = [
251
  c.get("iso_3166_1")
252
  for c in details.get("production_countries", []) or []
253
  if c.get("iso_3166_1")
254
+ ] or (doc.get("production_countries") or [])
255
 
256
  for tag in _LANGUAGE_CATALOGS.get(original_language, []):
257
  tags.add(tag)
 
285
  except Exception:
286
  pass
287
 
288
+ provider_names = _extract_provider_names(watch_data)
289
+ if provider_names:
290
+ for provider_name in provider_names:
291
+ bucket = _provider_bucket(provider_name)
292
+ if bucket:
293
+ providers.add(bucket)
294
+ else:
295
+ # No live watch-provider data (fetch failed / quota / no key): reuse the
296
+ # OTT buckets already stored on the doc so a re-classify keeps OTT tags.
297
+ for stored in (doc.get("watch_providers") or []):
298
+ if stored:
299
+ providers.add(stored)
300
+
301
+ for bucket in providers:
302
+ tags.add(bucket)
303
 
304
  tags = {tag for tag in tags if tag in enabled_names}
305
 
 
362
  for collection_name in ["movie", "tv"]:
363
  cursor = db.dbs[db_key][collection_name].find({"tmdb_id": {"$exists": True, "$ne": None}})
364
  async for doc in cursor:
365
+ doc["db_index"] = db_index
366
  doc["media_type"] = "tv" if collection_name == "tv" else "movie"
367
  if not full_rebuild and _is_already_synced(doc):
368
  yield collection_name, db_index, doc, True
 
373
  async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaphore, doc: dict, enabled_names: Set[str]) -> tuple[dict, dict]:
374
  async with semaphore:
375
  try:
376
+ details, watch_data = await asyncio.wait_for(_fetch_tmdb_data(client, doc), timeout=30)
377
+ classification = classify_media_from_tmdb(doc, details or {}, watch_data or {}, enabled_names)
 
 
 
 
 
 
378
 
379
  now = datetime.utcnow()
380
  update_data = {
 
390
  "source_updated_on": doc.get("updated_on"),
391
  },
392
  }
393
+ persisted = await asyncio.wait_for(
394
+ db.update_document(_media_type(doc), int(doc.get("tmdb_id")), int(doc.get("db_index", 1)), update_data),
395
+ timeout=30,
396
+ )
397
+ if persisted is False:
398
+ LOGGER.warning(
399
+ "Auto catalog sync flag not persisted for "
400
+ f"{doc.get('title')} (tmdb_id={doc.get('tmdb_id')}, "
401
+ f"db_index={doc.get('db_index')}); document not found in that storage DB."
402
+ )
403
  return doc, classification
404
  except Exception as e:
405
  LOGGER.warning(f"Auto catalog classification failed for {doc.get('title')} ({doc.get('tmdb_id')}): {e}")
406
  return doc, {"auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names]}
407
 
408
 
409
+ async def sync_single_media(db, *, tmdb_id, media_type: str) -> dict:
410
+ if tmdb_id in (None, "", 0):
411
+ return {"ok": False, "reason": "no_tmdb_id"}
412
+
413
+ try:
414
+ tmdb_id = int(tmdb_id)
415
+ except (TypeError, ValueError):
416
+ return {"ok": False, "reason": "bad_tmdb_id"}
417
+
418
+ if not await has_auto_catalog_settings(db):
419
+ return {"ok": False, "reason": "not_configured"}
420
+
421
+ enabled_names = await _enabled_catalog_names(db)
422
+ if not enabled_names:
423
+ return {"ok": False, "reason": "no_enabled_catalogs"}
424
+
425
+ if _auto_sync_lock.locked():
426
+ return {"ok": False, "reason": "sync_running"}
427
+
428
+ located = await db.find_media_doc(media_type, tmdb_id)
429
+ if not located:
430
+ return {"ok": False, "reason": "not_found"}
431
+
432
+ doc, db_index = located
433
+ doc["db_index"] = db_index
434
+ doc["media_type"] = "tv" if media_type in ["tv", "series"] else "movie"
435
+
436
+ timeout = httpx.Timeout(18.0, connect=10.0)
437
+ semaphore = asyncio.Semaphore(1)
438
+ async with _instant_sync_semaphore:
439
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
440
+ media_doc, classification = await _classify_one(db, client, semaphore, doc, enabled_names)
441
+
442
+ tags = [tag for tag in (classification.get("auto_tags") or []) if tag in enabled_names]
443
+ if tags:
444
+ item = _doc_item(media_doc)
445
+ await _flush_quick_items(db, {tag: [item] for tag in tags})
446
+
447
+ LOGGER.info(
448
+ f"Auto catalog instant index: '{media_doc.get('title')}' "
449
+ f"(tmdb_id={tmdb_id}) -> {tags or 'no matching catalogs'}"
450
+ )
451
+ return {"ok": True, "tags": tags}
452
+
453
+
454
+ def start_single_media_catalog_sync(db, *, tmdb_id, media_type: str) -> None:
455
+ """Fire-and-forget launcher for instant per-item categorization."""
456
+ async def runner():
457
+ try:
458
+ await sync_single_media(db, tmdb_id=tmdb_id, media_type=media_type)
459
+ except Exception:
460
+ LOGGER.exception("Instant auto catalog index failed")
461
+
462
+ try:
463
+ asyncio.create_task(runner())
464
+ except RuntimeError:
465
+ # No running loop (shouldn't happen inside the bot); ignore.
466
+ LOGGER.warning("Instant auto catalog index skipped: no running event loop.")
467
+
468
+
469
  async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
470
  collection = db.dbs["tracking"]["custom_catalogs"]
471
  now = datetime.utcnow()
 
613
  LOGGER.info(f"Auto catalog sync skipped: {summary}")
614
  return summary
615
 
616
+ if not _tmdb_api_key():
617
+ LOGGER.warning(
618
+ "Auto catalog: no TMDB API key configured β€” only 'Top Rated' and "
619
+ "'Recently Added' will populate; language & OTT catalogs need a TMDB key."
620
+ )
621
+
622
  try:
623
  timeout = httpx.Timeout(18.0, connect=10.0)
624
+ limits = httpx.Limits(max_connections=AUTO_SYNC_CONCURRENCY * 2 + 4, max_keepalive_connections=AUTO_SYNC_CONCURRENCY)
625
  semaphore = asyncio.Semaphore(AUTO_SYNC_CONCURRENCY)
626
 
627
  async def consume_result(media_doc: dict, classification: dict) -> None:
 
639
  async for _, _, doc, already_synced in _iter_all_media(db, full_rebuild=full_rebuild):
640
  scanned += 1
641
 
642
+ if already_synced and not full_rebuild:
 
 
 
 
643
  skipped += 1
644
  continue
645
 
Backend/helper/database.py CHANGED
@@ -510,6 +510,83 @@ class Database:
510
  except Exception:
511
  return False
512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  async def custom_catalog_contains_item(
514
  self, catalog_id: str, tmdb_id: int, db_index: int, media_type: str
515
  ) -> bool:
@@ -701,6 +778,7 @@ class Database:
701
 
702
  if len(new_telegram) == 0:
703
  await db["movie"].delete_one({"_id": movie["_id"]})
 
704
  else:
705
  movie["telegram"] = new_telegram
706
  movie["updated_on"] = datetime.utcnow()
@@ -731,6 +809,7 @@ class Database:
731
 
732
  if len(tv["seasons"]) == 0:
733
  await db["tv"].delete_one({"_id": tv["_id"]})
 
734
  else:
735
  tv["updated_on"] = datetime.utcnow()
736
  await db["tv"].replace_one({"_id": tv["_id"]}, tv)
@@ -786,6 +865,9 @@ class Database:
786
  cast=metadata_info['cast'],
787
  runtime=metadata_info['runtime'],
788
  media_type=metadata_info['media_type'],
 
 
 
789
  telegram=[quality_detail]
790
  )
791
  return await self.update_movie(media)
@@ -805,6 +887,9 @@ class Database:
805
  cast=metadata_info['cast'],
806
  runtime=metadata_info['runtime'],
807
  media_type=metadata_info['media_type'],
 
 
 
808
  seasons=[Season(
809
  season_number=metadata_info['season_number'],
810
  episodes=[Episode(
@@ -987,6 +1072,8 @@ class Database:
987
  existing_movie["imdb_id"] = imdb_id
988
  if tmdb_id and not existing_movie.get("tmdb_id"):
989
  existing_movie["tmdb_id"] = tmdb_id
 
 
990
 
991
  existing_qualities = existing_movie.get("telegram", [])
992
 
@@ -1070,6 +1157,8 @@ class Database:
1070
  existing_tv["imdb_id"] = imdb_id
1071
  if tmdb_id and not existing_tv.get("tmdb_id"):
1072
  existing_tv["tmdb_id"] = tmdb_id
 
 
1073
 
1074
  for season in tv_show_dict["seasons"]:
1075
  existing_season = next(
@@ -1412,6 +1501,7 @@ class Database:
1412
  result = await self.dbs[db_key]["tv"].delete_one({"tmdb_id": tmdb_id})
1413
 
1414
  if result.deleted_count > 0:
 
1415
  LOGGER.info(f"{media_type} with tmdb_id {tmdb_id} deleted successfully.")
1416
  return True
1417
  LOGGER.info(f"No document found with tmdb_id {tmdb_id}.")
@@ -1452,6 +1542,7 @@ class Database:
1452
  movie["telegram"] = [q for q in movie.get("telegram", []) if q.get("id") != stream_id_hash]
1453
  if len(movie["telegram"]) == 0:
1454
  await db["movie"].delete_one({"_id": movie["_id"]})
 
1455
  else:
1456
  movie['updated_on'] = datetime.utcnow()
1457
  await db["movie"].replace_one({"_id": movie["_id"]}, movie)
@@ -1471,6 +1562,7 @@ class Database:
1471
  tv["seasons"] = [s for s in tv.get("seasons", []) if s.get("season_number") != season.get("season_number")]
1472
  if len(tv["seasons"]) == 0:
1473
  await db["tv"].delete_one({"_id": tv["_id"]})
 
1474
  return True
1475
  tv['updated_on'] = datetime.utcnow()
1476
  await db["tv"].replace_one({"_id": tv["_id"]}, tv)
 
510
  except Exception:
511
  return False
512
 
513
+ async def find_media_doc(self, media_type: str, tmdb_id: int) -> Optional[Tuple[dict, int]]:
514
+ """Locate a media doc by tmdb_id across storage DBs.
515
+
516
+ Returns (doc, db_index) using the storage DB the doc physically lives
517
+ in (not the possibly-stale db_index field), or None if not found.
518
+ """
519
+ collection_name = "tv" if str(media_type).lower() in ["tv", "series"] else "movie"
520
+ try:
521
+ tmdb_id = int(tmdb_id)
522
+ except (TypeError, ValueError):
523
+ return None
524
+
525
+ for i in range(1, self.current_db_index + 1):
526
+ db_key = f"storage_{i}"
527
+ if db_key not in self.dbs:
528
+ continue
529
+ doc = await self.dbs[db_key][collection_name].find_one({"tmdb_id": tmdb_id})
530
+ if doc:
531
+ doc["db_index"] = i
532
+ return doc, i
533
+ return None
534
+
535
+ async def purge_media_from_catalogs(self, tmdb_id: int, media_type: str) -> int:
536
+ """Remove a media item from every catalog (auto + manual).
537
+
538
+ Called when a movie/TV doc is fully deleted so dead entries do not
539
+ linger in any catalog. Matches on tmdb_id + media_type only (db_index
540
+ omitted) so stale indexes are still cleaned up. Keeps item_count in
541
+ sync via an aggregation-pipeline update.
542
+ """
543
+ if tmdb_id in (None, "", 0):
544
+ return 0
545
+ try:
546
+ tmdb_id = int(tmdb_id)
547
+ except (TypeError, ValueError):
548
+ return 0
549
+
550
+ media_type = "tv" if str(media_type).lower() in ["tv", "series"] else "movie"
551
+ collection = self.dbs["tracking"]["custom_catalogs"]
552
+ now = datetime.utcnow()
553
+ try:
554
+ result = await collection.update_many(
555
+ {"items": {"$elemMatch": {"tmdb_id": tmdb_id, "media_type": media_type}}},
556
+ [
557
+ {
558
+ "$set": {
559
+ "items": {
560
+ "$filter": {
561
+ "input": "$items",
562
+ "as": "it",
563
+ "cond": {
564
+ "$not": [
565
+ {
566
+ "$and": [
567
+ {"$eq": ["$$it.tmdb_id", tmdb_id]},
568
+ {"$eq": ["$$it.media_type", media_type]},
569
+ ]
570
+ }
571
+ ]
572
+ },
573
+ }
574
+ }
575
+ }
576
+ },
577
+ {"$set": {"item_count": {"$size": "$items"}, "updated_at": now}},
578
+ ],
579
+ )
580
+ if result.modified_count:
581
+ LOGGER.info(
582
+ f"Purged {media_type} tmdb_id {tmdb_id} from "
583
+ f"{result.modified_count} catalog(s)."
584
+ )
585
+ return result.modified_count
586
+ except Exception as e:
587
+ LOGGER.error(f"Failed to purge tmdb_id {tmdb_id} from catalogs: {e}")
588
+ return 0
589
+
590
  async def custom_catalog_contains_item(
591
  self, catalog_id: str, tmdb_id: int, db_index: int, media_type: str
592
  ) -> bool:
 
778
 
779
  if len(new_telegram) == 0:
780
  await db["movie"].delete_one({"_id": movie["_id"]})
781
+ await self.purge_media_from_catalogs(movie.get("tmdb_id"), "movie")
782
  else:
783
  movie["telegram"] = new_telegram
784
  movie["updated_on"] = datetime.utcnow()
 
809
 
810
  if len(tv["seasons"]) == 0:
811
  await db["tv"].delete_one({"_id": tv["_id"]})
812
+ await self.purge_media_from_catalogs(tv.get("tmdb_id"), "tv")
813
  else:
814
  tv["updated_on"] = datetime.utcnow()
815
  await db["tv"].replace_one({"_id": tv["_id"]}, tv)
 
865
  cast=metadata_info['cast'],
866
  runtime=metadata_info['runtime'],
867
  media_type=metadata_info['media_type'],
868
+ is_anime=metadata_info.get('is_anime', False),
869
+ original_language=metadata_info.get('original_language'),
870
+ origin_country=metadata_info.get('origin_country', []) or [],
871
  telegram=[quality_detail]
872
  )
873
  return await self.update_movie(media)
 
887
  cast=metadata_info['cast'],
888
  runtime=metadata_info['runtime'],
889
  media_type=metadata_info['media_type'],
890
+ is_anime=metadata_info.get('is_anime', False),
891
+ original_language=metadata_info.get('original_language'),
892
+ origin_country=metadata_info.get('origin_country', []) or [],
893
  seasons=[Season(
894
  season_number=metadata_info['season_number'],
895
  episodes=[Episode(
 
1072
  existing_movie["imdb_id"] = imdb_id
1073
  if tmdb_id and not existing_movie.get("tmdb_id"):
1074
  existing_movie["tmdb_id"] = tmdb_id
1075
+ if movie_dict.get("is_anime"):
1076
+ existing_movie["is_anime"] = True
1077
 
1078
  existing_qualities = existing_movie.get("telegram", [])
1079
 
 
1157
  existing_tv["imdb_id"] = imdb_id
1158
  if tmdb_id and not existing_tv.get("tmdb_id"):
1159
  existing_tv["tmdb_id"] = tmdb_id
1160
+ if tv_show_dict.get("is_anime"):
1161
+ existing_tv["is_anime"] = True
1162
 
1163
  for season in tv_show_dict["seasons"]:
1164
  existing_season = next(
 
1501
  result = await self.dbs[db_key]["tv"].delete_one({"tmdb_id": tmdb_id})
1502
 
1503
  if result.deleted_count > 0:
1504
+ await self.purge_media_from_catalogs(tmdb_id, "tv" if media_type != "Movie" else "movie")
1505
  LOGGER.info(f"{media_type} with tmdb_id {tmdb_id} deleted successfully.")
1506
  return True
1507
  LOGGER.info(f"No document found with tmdb_id {tmdb_id}.")
 
1542
  movie["telegram"] = [q for q in movie.get("telegram", []) if q.get("id") != stream_id_hash]
1543
  if len(movie["telegram"]) == 0:
1544
  await db["movie"].delete_one({"_id": movie["_id"]})
1545
+ await self.purge_media_from_catalogs(movie.get("tmdb_id"), "movie")
1546
  else:
1547
  movie['updated_on'] = datetime.utcnow()
1548
  await db["movie"].replace_one({"_id": movie["_id"]}, movie)
 
1562
  tv["seasons"] = [s for s in tv.get("seasons", []) if s.get("season_number") != season.get("season_number")]
1563
  if len(tv["seasons"]) == 0:
1564
  await db["tv"].delete_one({"_id": tv["_id"]})
1565
+ await self.purge_media_from_catalogs(tv.get("tmdb_id"), "tv")
1566
  return True
1567
  tv['updated_on'] = datetime.utcnow()
1568
  await db["tv"].replace_one({"_id": tv["_id"]}, tv)
Backend/helper/metadata.py CHANGED
@@ -11,6 +11,7 @@ from Backend.helper.imdb import get_detail, get_season, search_title, search_tit
11
  from Backend.helper.settings_manager import SettingsManager
12
  from Backend.helper.encrypt import encode_string
13
  from Backend.helper.split_files import parse_split_info, parse_combined_episodes
 
14
  from themoviedb import aioTMDb
15
  from rapidfuzz import fuzz
16
  from guessit import guessit as _guessit
@@ -47,20 +48,24 @@ API_SEMAPHORE = asyncio.Semaphore(12)
47
 
48
  _MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
49
 
50
- # Combined episode files (e.g. "S01 [E04-06]" or "S01 Combined") are grouped under a special season.
 
51
  COMBINED_SEASON = 0
 
52
 
53
 
54
- # Re-file a combined entry under the special season with a descriptive title.
 
 
55
  def _apply_combined_override(payload: dict, combined: dict) -> None:
56
  season, start, end = combined["season"], combined["start"], combined["end"]
57
  payload["season_number"] = COMBINED_SEASON
58
- if start is None:
59
- payload["episode_number"] = season * 1000
60
- payload["episode_title"] = f"S{season:02d} Complete (Combined)"
61
- else:
62
- payload["episode_number"] = season * 1000 + start
63
- payload["episode_title"] = f"S{season:02d} E{start:02d}-E{end:02d} (Combined)"
64
 
65
  _tmdb_client: aioTMDb | None = None
66
  _tmdb_client_key: str | None = None
@@ -425,6 +430,20 @@ def _extract_cast(details) -> list:
425
  return [getattr(c, "name", None) or getattr(c, "original_name", None) for c in cast]
426
 
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  def _format_runtime(minutes) -> str:
429
  return f"{minutes} min" if minutes else ""
430
 
@@ -446,6 +465,8 @@ def _build_tmdb_movie_payload(movie, quality, encoded_string) -> dict:
446
  "runtime": str(_format_runtime(getattr(movie, "runtime", None))),
447
  "media_type": "movie",
448
  "genres": [g.name for g in (movie.genres or [])],
 
 
449
  "quality": quality,
450
  "encoded_string": encoded_string,
451
  }
@@ -471,6 +492,8 @@ def _build_tmdb_tv_payload(tv, ep, season, episode, quality, encoded_string) ->
471
  "media_type": "tv",
472
  "cast": _extract_cast(tv),
473
  "runtime": str(runtime),
 
 
474
  "season_number": season,
475
  "episode_number": episode,
476
  "episode_title": getattr(ep, "name", fallback_ep_title) if ep else fallback_ep_title,
@@ -534,6 +557,51 @@ def _build_imdb_tv_payload(imdb, ep, imdb_id, title, season, episode, quality, e
534
 
535
  # ----------------- Main entry-point -----------------
536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  # Parse a filename/caption and resolve full movie or TV metadata for the indexer.
538
  async def metadata(filename: str, channel: int, msg_id, override_id: str = None) -> dict | None:
539
  try:
@@ -567,9 +635,10 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
567
  elif isinstance(season, list) or isinstance(episode, list):
568
  LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
569
  return None
570
- if season and not episode:
571
- LOGGER.warning(f"Missing episode in {filename}: {parsed}")
572
- return None
 
573
  if not quality:
574
  LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
575
  return None
@@ -586,16 +655,28 @@ async def metadata(filename: str, channel: int, msg_id, override_id: str = None)
586
 
587
  group_key = f"{channel}:{quality}:{split_info[0]}" if split_info else None
588
 
 
 
589
  try:
590
  if season and episode:
591
  LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
592
- result = await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
 
 
 
 
593
  if result is not None and combined:
594
  _apply_combined_override(result, combined)
595
  else:
596
  LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
597
- result = await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
 
 
 
 
598
  if result is not None:
 
 
599
  result["group_key"] = group_key
600
  result["part_number"] = part_number
601
  return result
 
11
  from Backend.helper.settings_manager import SettingsManager
12
  from Backend.helper.encrypt import encode_string
13
  from Backend.helper.split_files import parse_split_info, parse_combined_episodes
14
+ from Backend.helper.anime import fetch_anime_metadata, fetch_anime_movie_metadata
15
  from themoviedb import aioTMDb
16
  from rapidfuzz import fuzz
17
  from guessit import guessit as _guessit
 
48
 
49
  _MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
50
 
51
+ # Combined files are grouped in the Specials folder (season 0) as a single
52
+ # "Season N Combined" entry per real season.
53
  COMBINED_SEASON = 0
54
+ COMBINED_EPISODE_BASE = 1000
55
 
56
 
57
+ # Re-file a combined entry into its season's single Combined slot inside Specials.
58
+ # A range/Full label is appended to the quality so distinct combined files coexist
59
+ # while an identical re-upload still replaces correctly under replace mode.
60
  def _apply_combined_override(payload: dict, combined: dict) -> None:
61
  season, start, end = combined["season"], combined["start"], combined["end"]
62
  payload["season_number"] = COMBINED_SEASON
63
+ payload["episode_number"] = COMBINED_EPISODE_BASE + season
64
+ payload["episode_title"] = f"Season {season} Combined"
65
+ label = "Full" if start is None else f"E{start:02d}-E{end:02d}"
66
+ payload["quality"] = f"{payload.get('quality') or 'HD'} {label}"
67
+ if not payload.get("episode_backdrop"):
68
+ payload["episode_backdrop"] = payload.get("backdrop") or payload.get("poster") or ""
69
 
70
  _tmdb_client: aioTMDb | None = None
71
  _tmdb_client_key: str | None = None
 
430
  return [getattr(c, "name", None) or getattr(c, "original_name", None) for c in cast]
431
 
432
 
433
+ # Collect ISO 3166-1 country codes from a TMDb details object (origin_country
434
+ # and production_countries), used by the auto-catalog classifier.
435
+ def _tmdb_country_codes(details) -> list:
436
+ codes: list = []
437
+ for code in (getattr(details, "origin_country", None) or []):
438
+ if code and code not in codes:
439
+ codes.append(code)
440
+ for country in (getattr(details, "production_countries", None) or []):
441
+ code = getattr(country, "iso_3166_1", None) or (country.get("iso_3166_1") if isinstance(country, dict) else None)
442
+ if code and code not in codes:
443
+ codes.append(code)
444
+ return codes
445
+
446
+
447
  def _format_runtime(minutes) -> str:
448
  return f"{minutes} min" if minutes else ""
449
 
 
465
  "runtime": str(_format_runtime(getattr(movie, "runtime", None))),
466
  "media_type": "movie",
467
  "genres": [g.name for g in (movie.genres or [])],
468
+ "original_language": getattr(movie, "original_language", None),
469
+ "origin_country": _tmdb_country_codes(movie),
470
  "quality": quality,
471
  "encoded_string": encoded_string,
472
  }
 
492
  "media_type": "tv",
493
  "cast": _extract_cast(tv),
494
  "runtime": str(runtime),
495
+ "original_language": getattr(tv, "original_language", None),
496
+ "origin_country": _tmdb_country_codes(tv),
497
  "season_number": season,
498
  "episode_number": episode,
499
  "episode_title": getattr(ep, "name", fallback_ep_title) if ep else fallback_ep_title,
 
557
 
558
  # ----------------- Main entry-point -----------------
559
 
560
+ # True when a file's channel is configured as an anime channel.
561
+ def _is_anime_channel(channel) -> bool:
562
+ anime_channels = SettingsManager.current().anime_channels
563
+ if not anime_channels:
564
+ return False
565
+ target = str(channel).replace("-100", "")
566
+ return any(str(c).strip().replace("-100", "") == target for c in anime_channels)
567
+
568
+
569
+ # Resolve anime TV metadata, filling the imdb_id from tmdb when ani.zip lacks it.
570
+ async def _fetch_anime_tv(title, season, episode, encoded_string, year, quality) -> dict | None:
571
+ try:
572
+ result = await fetch_anime_metadata(title, season, episode, encoded_string, year, quality)
573
+ except Exception as e:
574
+ LOGGER.warning(f"[ANIME] metadata error for '{title}': {e}")
575
+ return None
576
+ if result is None:
577
+ return None
578
+ if not result.get("imdb_id") and result.get("tmdb_id"):
579
+ result["imdb_id"] = await _tmdb_external_imdb_id("tv", result["tmdb_id"])
580
+ if not result.get("imdb_id"):
581
+ LOGGER.info(f"[ANIME] No imdb id for '{title}' -> falling back to TMDb/Cinemeta")
582
+ return None
583
+ LOGGER.info(f"[ANIME] Matched '{result.get('title')}' [{result.get('imdb_id')}] S{season:02d}E{episode:02d}")
584
+ return result
585
+
586
+
587
+ # Resolve anime movie metadata, filling the imdb_id from tmdb when ani.zip lacks it.
588
+ async def _fetch_anime_movie(title, encoded_string, year, quality) -> dict | None:
589
+ try:
590
+ result = await fetch_anime_movie_metadata(title, encoded_string, year, quality)
591
+ except Exception as e:
592
+ LOGGER.warning(f"[ANIME] movie metadata error for '{title}': {e}")
593
+ return None
594
+ if result is None:
595
+ return None
596
+ if not result.get("imdb_id") and result.get("tmdb_id"):
597
+ result["imdb_id"] = await _tmdb_external_imdb_id("movie", result["tmdb_id"])
598
+ if not result.get("imdb_id"):
599
+ LOGGER.info(f"[ANIME] No imdb id for movie '{title}' -> falling back to TMDb/Cinemeta")
600
+ return None
601
+ LOGGER.info(f"[ANIME] Matched movie '{result.get('title')}' [{result.get('imdb_id')}]")
602
+ return result
603
+
604
+
605
  # Parse a filename/caption and resolve full movie or TV metadata for the indexer.
606
  async def metadata(filename: str, channel: int, msg_id, override_id: str = None) -> dict | None:
607
  try:
 
635
  elif isinstance(season, list) or isinstance(episode, list):
636
  LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
637
  return None
638
+ elif season and not episode:
639
+ # Season pack with no episode number (e.g. "Season 01") -> whole-season combined.
640
+ combined = {"season": season, "start": None, "end": None}
641
+ episode = 1
642
  if not quality:
643
  LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
644
  return None
 
655
 
656
  group_key = f"{channel}:{quality}:{split_info[0]}" if split_info else None
657
 
658
+ anime_channel = _is_anime_channel(channel)
659
+
660
  try:
661
  if season and episode:
662
  LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
663
+ result = None
664
+ if not default_id and anime_channel:
665
+ result = await _fetch_anime_tv(title, season, episode, encoded_string, year, quality)
666
+ if result is None:
667
+ result = await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
668
  if result is not None and combined:
669
  _apply_combined_override(result, combined)
670
  else:
671
  LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
672
+ result = None
673
+ if not default_id and anime_channel:
674
+ result = await _fetch_anime_movie(title, encoded_string, year, quality)
675
+ if result is None:
676
+ result = await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
677
  if result is not None:
678
+ if anime_channel:
679
+ result["is_anime"] = True
680
  result["group_key"] = group_key
681
  result["part_number"] = part_number
682
  return result
Backend/helper/modal.py CHANGED
@@ -61,6 +61,13 @@ class TVShowSchema(BaseModel):
61
  media_type: str
62
  updated_on: datetime = Field(default_factory=datetime.utcnow)
63
  seasons: List[Season] = Field(default_factory=list)
 
 
 
 
 
 
 
64
 
65
 
66
  # ---------------------------
@@ -83,3 +90,10 @@ class MovieSchema(BaseModel):
83
  media_type: str
84
  updated_on: datetime = Field(default_factory=datetime.utcnow)
85
  telegram: Optional[List[QualityDetail]]
 
 
 
 
 
 
 
 
61
  media_type: str
62
  updated_on: datetime = Field(default_factory=datetime.utcnow)
63
  seasons: List[Season] = Field(default_factory=list)
64
+ is_anime: Optional[bool] = False
65
+ original_language: Optional[str] = None
66
+ origin_country: Optional[List[str]] = Field(default_factory=list)
67
+ production_countries: Optional[List[str]] = Field(default_factory=list)
68
+ watch_providers: Optional[List[str]] = Field(default_factory=list)
69
+ auto_tags: Optional[List[str]] = Field(default_factory=list)
70
+ auto_catalog: Optional[dict] = None
71
 
72
 
73
  # ---------------------------
 
90
  media_type: str
91
  updated_on: datetime = Field(default_factory=datetime.utcnow)
92
  telegram: Optional[List[QualityDetail]]
93
+ is_anime: Optional[bool] = False
94
+ original_language: Optional[str] = None
95
+ origin_country: Optional[List[str]] = Field(default_factory=list)
96
+ production_countries: Optional[List[str]] = Field(default_factory=list)
97
+ watch_providers: Optional[List[str]] = Field(default_factory=list)
98
+ auto_tags: Optional[List[str]] = Field(default_factory=list)
99
+ auto_catalog: Optional[dict] = None
Backend/helper/settings_manager.py CHANGED
@@ -26,6 +26,7 @@ _DEFAULTS: Dict[str, Any] = {
26
  "extra_databases": [],
27
  "global_search": False,
28
  "global_search_channels": [],
 
29
  }
30
 
31
 
@@ -92,6 +93,10 @@ class Settings:
92
  def global_search_channels(self):
93
  return list(self._d.get("global_search_channels") or [])
94
 
 
 
 
 
95
  # ── Strings ──────────────────────────────────────────────────────────────
96
  @property
97
  def tmdb_api(self) -> str:
 
26
  "extra_databases": [],
27
  "global_search": False,
28
  "global_search_channels": [],
29
+ "anime_channels": [],
30
  }
31
 
32
 
 
93
  def global_search_channels(self):
94
  return list(self._d.get("global_search_channels") or [])
95
 
96
+ @property
97
+ def anime_channels(self) -> List[str]:
98
+ return list(self._d.get("anime_channels") or [])
99
+
100
  # ── Strings ──────────────────────────────────────────────────────────────
101
  @property
102
  def tmdb_api(self) -> str:
Backend/helper/split_files.py CHANGED
@@ -72,15 +72,6 @@ def parse_combined_episodes(filename: str) -> Optional[dict]:
72
  return None
73
 
74
 
75
- # True when a combined file covers the requested season/episode.
76
- def combined_covers(combined: dict, season: Optional[int], episode: Optional[int]) -> bool:
77
- if season is not None and combined["season"] != int(season):
78
- return False
79
- if episode is None or combined["start"] is None:
80
- return True
81
- return combined["start"] <= int(episode) <= combined["end"]
82
-
83
-
84
  def strip_part_suffix(filename: str) -> str:
85
  if not filename:
86
  return filename
 
72
  return None
73
 
74
 
 
 
 
 
 
 
 
 
 
75
  def strip_part_suffix(filename: str) -> str:
76
  if not filename:
77
  return filename
Backend/pyrofork/plugins/reciever.py CHANGED
@@ -6,6 +6,7 @@ from Backend import db
6
  from Backend.helper.settings_manager import SettingsManager
7
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
8
  from Backend.helper.metadata import metadata
 
9
  from pyrogram import filters, Client
10
  from pyrogram.types import Message
11
  from pyrogram.errors import FloodWait
@@ -40,6 +41,12 @@ async def process_file():
40
  LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
41
  else:
42
  LOGGER.info("Update failed due to validation errors.")
 
 
 
 
 
 
43
  file_queue.task_done()
44
 
45
  for _ in range(1):
 
6
  from Backend.helper.settings_manager import SettingsManager
7
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
8
  from Backend.helper.metadata import metadata
9
+ from Backend.helper.auto_catalog import start_single_media_catalog_sync
10
  from pyrogram import filters, Client
11
  from pyrogram.types import Message
12
  from pyrogram.errors import FloodWait
 
41
  LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
42
  else:
43
  LOGGER.info("Update failed due to validation errors.")
44
+ if updated_id:
45
+ start_single_media_catalog_sync(
46
+ db,
47
+ tmdb_id=metadata_info.get("tmdb_id"),
48
+ media_type=metadata_info.get("media_type"),
49
+ )
50
  file_queue.task_done()
51
 
52
  for _ in range(1):