File size: 28,599 Bytes
c12bb0b
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
36dde81
 
 
c12bb0b
36dde81
c12bb0b
 
 
36dde81
 
 
c12bb0b
36dde81
 
 
c12bb0b
36dde81
c12bb0b
36dde81
c12bb0b
 
28d4695
36dde81
 
 
 
c12bb0b
 
 
36dde81
c12bb0b
 
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
36dde81
 
 
 
c12bb0b
36dde81
 
 
c12bb0b
 
36dde81
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
28d4695
36dde81
 
c12bb0b
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
28d4695
36dde81
28d4695
36dde81
 
28d4695
36dde81
 
c12bb0b
36dde81
 
 
 
 
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
36dde81
 
 
 
c12bb0b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
c12bb0b
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
c12bb0b
36dde81
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
36dde81
 
 
 
c12bb0b
 
 
36dde81
 
 
 
 
 
 
 
 
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
36dde81
 
c12bb0b
 
36dde81
 
 
 
c12bb0b
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
36dde81
c12bb0b
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
import asyncio
import re
import time
from typing import Dict, List, Optional

import PTN
from pyrogram import enums
from pyrogram.errors import (
    FloodWait,
    ChatAdminRequired,
    ChannelPrivate,
    PeerIdInvalid,
    UserNotParticipant,
    AuthKeyUnregistered,
    SessionRevoked,
    RPCError,
)

from Backend.helper.bounded import BoundedDict
from Backend.logger import LOGGER
from Backend.helper.settings_manager import SettingsManager
from Backend.helper.encrypt import encode_string
from Backend.helper.pyro import get_readable_file_size
from Backend.helper.split_files import parse_combined_episodes, parse_split_info, strip_part_suffix
import Backend.pyrofork.bot as botmod

MAX_RESULTS = 50
MAX_RESULTS_PER_CHAT = 50
SEARCH_COOLDOWN_SECONDS = 5
MAX_CONCURRENT_SEARCHES = 3
MAX_CONCURRENT_CHANNELS = 5
MIN_TITLE_SCORE = 0.7
RESULT_CACHE_SECONDS = 60

_last_search_ts = BoundedDict(500)
_inflight_tasks: Dict[str, asyncio.Task] = {}
_result_cache = BoundedDict(200)
_search_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEARCHES)
_channel_semaphore = asyncio.Semaphore(MAX_CONCURRENT_CHANNELS)
_userbot_session_dead = False
_chat_title_cache = BoundedDict(500)

_TOKEN_RE = re.compile(r"[a-z0-9]+")
_MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
_VIDEO_EXTS = (".mkv", ".mp4", ".avi", ".ts", ".m4v", ".mov", ".wmv", ".webm", ".flv")
SPLIT_SCAN_WINDOW = 20
_APOSTROPHE_RE = re.compile(r"['\u2018\u2019`\u00B4]")
_SYMBOL_STRIP_RE = re.compile(r"[&.\-:]+")


def is_userbot_available() -> bool:
    return botmod.Userbot is not None and not _userbot_session_dead


def is_global_search_enabled() -> bool:
    if not is_userbot_available():
        return False
    s = SettingsManager.current()
    return bool(s.global_search)


def _tokens(s: str) -> set:
    return set(_TOKEN_RE.findall((s or "").lower()))


def _title_score(
    result_title: str,
    expected_title: str,
) -> float:
    expected = _tokens(expected_title)
    result = _tokens(result_title)

    if not expected or not result:
        return 0.0

    common = len(expected & result)

    if common == 0:
        return 0.0

    precision = common / len(result)
    recall = common / len(expected)

    return (2 * precision * recall) / (precision + recall)

_ABS_EP_BOUNDARY_RE = re.compile(
    r"(?i)(?:^|[^0-9])(?:e|ep|episode)?\s*0*(\d{1,4})(?=[^0-9]|$)"
)


def _filename_has_exact_episode(filename: str, episode: int) -> bool:
    if not filename or episode is None:
        return False
    target = int(episode)
    for m in _ABS_EP_BOUNDARY_RE.finditer(filename):
        try:
            if int(m.group(1)) == target:
                return True
        except (TypeError, ValueError):
            continue
    return False


def _matches_episode(parsed: dict, season: Optional[int], episode: Optional[int], filename: str = "") -> bool:
    wants_episode = season is not None or episode is not None
    is_episode_like = parsed.get("season") is not None or parsed.get("episode") is not None

    if season is None and episode is not None:
        rv = parsed.get("episode")
        if rv is not None:
            if isinstance(rv, list):
                try:
                    if int(episode) in [int(x) for x in rv]:
                        return True
                except (TypeError, ValueError):
                    pass
            else:
                try:
                    if int(rv) == int(episode):
                        return True
                except (TypeError, ValueError):
                    pass
        return _filename_has_exact_episode(filename, int(episode))

    if wants_episode and not is_episode_like:
        return False
    if not wants_episode and is_episode_like:
        return False

    for value, parsed_key in ((season, "season"), (episode, "episode")):
        if value is None:
            continue
        rv = parsed.get(parsed_key)
        if rv is None:
            continue
        if isinstance(rv, list):
            if value not in rv:
                return False
        elif int(rv) != int(value):
            return False
    return True


def _is_combined_filename(filename: str, parsed: Optional[dict] = None) -> bool:
    if not filename:
        return False
    if parse_combined_episodes(filename):
        return True
    if re.search(r"(?i)\bcombined\b", filename):
        return True
    if parsed and "excess" in parsed:
        if any("combined" in str(item).lower() for item in (parsed.get("excess") or [])):
            return True
    return False


def _validate_name(filename: str, expected_title: str, season: Optional[int], episode: Optional[int]) -> Optional[dict]:
    try:
        parsed = PTN.parse(filename)
    except Exception:
        return None
    if _is_combined_filename(filename, parsed):
        LOGGER.info(f"Skipping {filename}: combined episode pack")
        return None
    if not _matches_episode(parsed, season, episode, filename=filename):
        return None

    result_title = parsed.get("title", "")

    score = _title_score(result_title, expected_title)
    if score < MIN_TITLE_SCORE:
        stripped_expected = _strip_symbols(expected_title)
        if stripped_expected and stripped_expected.lower() != expected_title.lower():
            score = _title_score(result_title, stripped_expected)

    if score < MIN_TITLE_SCORE:
        return None
    return parsed


def _parse_and_validate(filename: str, expected_title: str, season: Optional[int], episode: Optional[int]) -> Optional[dict]:
    if _MULTIPART_RE.search(filename):
        return None
    return _validate_name(filename, expected_title, season, episode)


def _split_part_info(filename: str) -> Optional[tuple]:
    if not filename:
        return None
    zm = _ZIP_SPLIT_RE.match(filename)
    if zm:
        base_raw = zm.group("base")
        base = _NORMALIZE_ALT_RE.sub(".", base_raw).strip(".").lower() + ".zip"
        return base, int(zm.group("num")), base_raw, True
    info = parse_split_info(filename)
    if info:
        return info[0], info[1], strip_part_suffix(filename), False
    return None


_NORMALIZE_ALT_RE = re.compile(r"[\s._-]+")
_ZIP_SPLIT_RE = re.compile(r"^(?P<base>.+)\.zip\.(?P<num>\d{2,3})$", re.IGNORECASE)


def _video_filename(message) -> Optional[str]:
    if message.video:
        return (message.caption or "").strip() or getattr(message.video, "file_name", None) or "video.mkv"
    if message.document:
        mime = message.document.mime_type or ""
        name = message.document.file_name
        # Include single .zip archives (STORED inner video is streamable)
        if mime.startswith("video/") or (name and (name.lower().endswith(_VIDEO_EXTS) or name.lower().endswith(".zip"))):
            return (message.caption or "").strip() or name or "video.mkv"
    return None


def _raw_media_name(message) -> Optional[str]:
    media = message.video or message.document
    if not media:
        return None
    return (message.caption or "").strip() or getattr(media, "file_name", None)


async def _gather_split_parts(client, chat_id: int, seed_id: int, base: str) -> Dict[int, dict]:
    ids = list(range(max(1, seed_id - SPLIT_SCAN_WINDOW), seed_id + SPLIT_SCAN_WINDOW + 1))
    parts: Dict[int, dict] = {}
    t0 = time.monotonic()
    try:
        messages = await client.get_messages(chat_id, ids)
    except Exception as e:
        LOGGER.warning(f"[GLOBAL SEARCH] Could not gather split parts near {seed_id}: {e}")
        return parts
    finally:
        elapsed = time.monotonic() - t0
        LOGGER.info(f"[GLOBAL SEARCH] get_messages({len(ids)} ids, base={base}) took {elapsed:.1f}s")
    for msg in (messages or []):
        if not msg or getattr(msg, "empty", False):
            continue
        raw = _raw_media_name(msg)
        if not raw:
            continue
        info = _split_part_info(raw)
        if not info or info[0] != base:
            continue
        media = msg.video or msg.document
        parts[info[1]] = {"msg_id": msg.id, "size_bytes": getattr(media, "file_size", 0) or 0}
    return parts


def _resolve_channel_ids(channel_ids: List[str]) -> List[int]:
    resolved: List[int] = []
    seen: set = set()
    for c in channel_ids:
        c = str(c).strip()
        if not c:
            continue
        try:
            raw = int(c)
        except ValueError:
            continue
        canonical = raw if raw < 0 else int(f"-100{raw}")
        if canonical not in seen:
            seen.add(canonical)
            resolved.append(canonical)
    return resolved


async def _get_chat_title(client, chat_id: int) -> str:
    if chat_id in _chat_title_cache:
        return _chat_title_cache[chat_id]
    try:
        chat = await client.get_chat(chat_id)
        title = chat.title or str(chat_id)
    except Exception as e:
        LOGGER.warning(f"[USERBOT] Could not fetch chat title for {chat_id}: {e}")
        title = str(chat_id)
    _chat_title_cache[chat_id] = title
    return title


def _strip_symbols(text: str) -> str:
    if not text:
        return ""
    text = _APOSTROPHE_RE.sub("", text)
    text = _SYMBOL_STRIP_RE.sub(" ", text)
    return re.sub(r"\s+", " ", text).strip()


def _absolute_ep_forms(episode: int) -> List[str]:
    ep = int(episode)
    if ep < 1:
        return [str(ep)]
    if ep < 10:
        return [f"{ep:03d}", f"{ep:02d}", str(ep)]
    if ep < 100:
        return [f"{ep:03d}", str(ep)]
    return [str(ep)]


def _build_search_query(expected_title: str, year: Optional[int], season: Optional[int], episode: Optional[int]) -> str:
    if season is not None and episode is not None:
        return f"{expected_title} S{int(season):02d}E{int(episode):02d}"
    if season is None and episode is not None:
        forms = _absolute_ep_forms(int(episode))
        return f"{expected_title} {forms[0]}"
    if year is not None:
        return f"{expected_title} {year}"
    return expected_title


def _build_query_candidates(
    expected_title: str, year: Optional[int], season: Optional[int], episode: Optional[int]
) -> List[str]:
    candidates: List[str] = []

    def add(q: Optional[str]) -> None:
        q = (q or "").strip()
        if q and q.lower() not in (c.lower() for c in candidates):
            candidates.append(q)

    if season is None and episode is not None:
        titles = [expected_title]
        stripped_title = _strip_symbols(expected_title)
        if stripped_title and stripped_title.lower() != expected_title.lower():
            titles.append(stripped_title)
        for form in _absolute_ep_forms(int(episode)):
            for title in titles:
                add(f"{title} {form}")
                add(f"{title} E{form}")
        return candidates

    add(_build_search_query(expected_title, year, season, episode))

    if season is None and episode is None and year is not None:
        add(expected_title)

    stripped_title = _strip_symbols(expected_title)
    if stripped_title and stripped_title.lower() != expected_title.lower():
        add(_build_search_query(stripped_title, year, season, episode))
        if season is None and episode is None and year is not None:
            add(stripped_title)

    return candidates


async def _search_channel(
    client,
    chat_id: int,
    chat_title: str,
    search_query: str,
    expected_title: str,
    season: Optional[int],
    episode: Optional[int],
) -> List[Dict]:
    global _userbot_session_dead

    async with _channel_semaphore:
        results: List[Dict] = []
        split_groups: Dict[str, dict] = {}
        seen_msg_ids: set = set()

        for msg_filter in (enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT):
            if len(results) >= MAX_RESULTS_PER_CHAT:
                break
            try:
                async for message in client.search_messages(
                    chat_id=chat_id,
                    query=search_query,
                    filter=msg_filter,
                    limit=MAX_RESULTS_PER_CHAT,
                ):
                    if message.id in seen_msg_ids:
                        continue
                    seen_msg_ids.add(message.id)

                    raw_name = _raw_media_name(message)
                    if not raw_name:
                        continue

                    split = _split_part_info(raw_name)
                    if split:
                        base, _part_num, display, is_zip = split
                        if base in split_groups:
                            continue
                        parsed = _validate_name(display, expected_title, season, episode)
                        if parsed is None:
                            continue
                        parts = await _gather_split_parts(client, chat_id, message.id, base)
                        if len(parts) < 2 or sorted(parts) != list(range(1, len(parts) + 1)):
                            continue
                        split_groups[base] = {
                            "parts": parts,
                            "display": display,
                            "quality": parsed.get("resolution") or "HD",
                            "zip": is_zip,
                        }
                        continue

                    filename = _video_filename(message)
                    if not filename:
                        continue
                    parsed = _parse_and_validate(filename, expected_title, season, episode)
                    if parsed is None:
                        continue

                    media = message.video or message.document
                    size = get_readable_file_size(getattr(media, "file_size", 0) or 0)
                    quality = parsed.get("resolution") or "HD"

                    is_single_zip = bool(filename and filename.lower().endswith(".zip"))
                    payload = {
                        "global": True,
                        "chat_id": chat_id,
                        "msg_id": message.id,
                        "title": filename,
                        "size": size,
                        "quality": quality,
                        "source": chat_title,
                    }
                    if is_single_zip:
                        # Represent as a one-part zip so stream routes use the zip path
                        payload["zip"] = True
                        payload["parts"] = [{"chat_id": chat_id, "msg_id": message.id}]
                        del payload["chat_id"]
                        del payload["msg_id"]
                    token = await encode_string(payload)

                    results.append({
                        "token": token,
                        "title": filename,
                        "size": size,
                        "source_chat": chat_title,
                        "quality": quality,
                        "is_zip": is_single_zip,
                    })
                    LOGGER.debug(f"[GLOBAL SEARCH] Result found: {filename} in {chat_title}")

                    if len(results) >= MAX_RESULTS_PER_CHAT:
                        break

            except FloodWait as e:
                LOGGER.warning(f"[USERBOT] FloodWait for {chat_title}: sleeping {e.value}s")
                await asyncio.sleep(e.value)
            except (ChatAdminRequired, ChannelPrivate, PeerIdInvalid, UserNotParticipant, RPCError) as e:
                LOGGER.warning(f"[USERBOT] Cannot access channel {chat_title} ({chat_id}): {e}")
                break
            except (AuthKeyUnregistered, SessionRevoked) as e:
                LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
                _userbot_session_dead = True
                break
            except Exception as e:
                LOGGER.warning(f"[USERBOT] Unexpected error searching {chat_title} ({chat_id}): {e}")
                break

        for group in split_groups.values():
            ordered = [group["parts"][pn] for pn in sorted(group["parts"])]
            total_bytes = sum(p["size_bytes"] for p in ordered)
            size = get_readable_file_size(total_bytes)
            is_zip = bool(group.get("zip"))
            payload = {
                "global": True,
                "parts": [{"chat_id": chat_id, "msg_id": p["msg_id"]} for p in ordered],
                "title": group["display"],
                "size": size,
                "quality": group["quality"],
                "source": chat_title,
            }
            if is_zip:
                payload["zip"] = True
            token = await encode_string(payload)
            results.append({
                "token": token,
                "title": group["display"],
                "size": size,
                "source_chat": chat_title,
                "quality": group["quality"],
                "is_split": True,
                "is_zip": is_zip,
                "part_count": len(ordered),
            })
            kind = "zip parts" if is_zip else "parts"
            LOGGER.info(f"[GLOBAL SEARCH] Split stream: {group['display']} ({len(ordered)} {kind}) in {chat_title}")

        return results


async def global_search(
    expected_title: str,
    auth_channels: List[str],
    *,
    year: Optional[int] = None,
    season: Optional[int] = None,
    episode: Optional[int] = None,
) -> List[Dict]:
    expected_title = (expected_title or "").strip()
    if not expected_title or not is_global_search_enabled():
        return []

    settings = SettingsManager.current()
    target_ids = _resolve_channel_ids(settings.global_search_channels)

    query_candidates = _build_query_candidates(expected_title, year, season, episode)
    if not query_candidates:
        return []

    key = query_candidates[0].lower()
    now = time.time()

    existing_task = _inflight_tasks.get(key)
    if existing_task and not existing_task.done():
        LOGGER.info(f"[GLOBAL SEARCH] Joining in-flight search for '{query_candidates[0]}'")
        try:
            return await existing_task
        except Exception:
            return []

    cached = _result_cache.get(key)
    if cached is not None and (now - cached[0]) < RESULT_CACHE_SECONDS:
        LOGGER.info(f"[GLOBAL SEARCH] Serving cached results for '{query_candidates[0]}'")
        return cached[1]

    if now - _last_search_ts.get(key, 0) < SEARCH_COOLDOWN_SECONDS:
        if cached is not None:
            LOGGER.info(f"[GLOBAL SEARCH] Serving cached results for '{query_candidates[0]}' (cooldown)")
            return cached[1]
        LOGGER.info(f"[GLOBAL SEARCH] Cooldown active for '{query_candidates[0]}'")
        return []

    _last_search_ts[key] = now
    if target_ids:
        task = asyncio.create_task(
            _run_global_search(expected_title, query_candidates, target_ids, season, episode)
        )
    else:
        task = asyncio.create_task(
            _run_true_global_search(expected_title, query_candidates, season, episode)
        )
    _inflight_tasks[key] = task
    try:
        results = await task
        _result_cache[key] = (time.time(), results)
        return results
    finally:
        _inflight_tasks.pop(key, None)


async def _run_global_search(
    expected_title: str,
    query_candidates: List[str],
    target_ids: List[int],
    season: Optional[int],
    episode: Optional[int],
) -> List[Dict]:
    async with _search_semaphore:
        chat_titles = await asyncio.gather(
            *(_get_chat_title(botmod.Userbot, cid) for cid in target_ids),
            return_exceptions=True,
        )
        resolved_titles = [
            str(cid) if isinstance(t, Exception) else t
            for cid, t in zip(target_ids, chat_titles)
        ]

        all_results: List[Dict] = []
        for attempt_idx, search_query in enumerate(query_candidates):
            if _userbot_session_dead:
                break

            LOGGER.info(
                f"[USERBOT] Search attempt {attempt_idx + 1}/{len(query_candidates)}: "
                f"'{search_query}' across {len(target_ids)} channel(s)"
            )

            search_tasks = [
                _search_channel(botmod.Userbot, int(cid), title, search_query, expected_title, season, episode)
                for cid, title in zip(target_ids, resolved_titles)
            ]
            per_channel_results = await asyncio.gather(*search_tasks, return_exceptions=True)

            for r in per_channel_results:
                if isinstance(r, list):
                    all_results.extend(r)

            if all_results:
                LOGGER.info(
                    f"[USERBOT] Succeeded on attempt {attempt_idx + 1} "
                    f"('{search_query}') -> {len(all_results)} result(s)"
                )
                break
            if attempt_idx + 1 < len(query_candidates):
                LOGGER.info(f"[USERBOT] No results for '{search_query}', trying next fallback")

        all_results = all_results[:MAX_RESULTS]
        LOGGER.info(f"[USERBOT] Search completed: '{expected_title}' -> {len(all_results)} result(s)")
        return all_results


async def _run_true_global_search(
    expected_title: str,
    query_candidates: List[str],
    season: Optional[int],
    episode: Optional[int],
) -> List[Dict]:
    global _userbot_session_dead
    async with _search_semaphore:
        all_results: List[Dict] = []
        split_groups: Dict[str, dict] = {}
        seen_msg_ids: set = set()

        for attempt_idx, search_query in enumerate(query_candidates):
            if _userbot_session_dead:
                break

            LOGGER.info(
                f"[USERBOT] True global search attempt {attempt_idx + 1}/{len(query_candidates)}: '{search_query}'"
            )

            for msg_filter in (enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT):
                if len(all_results) + len(split_groups) >= MAX_RESULTS:
                    break
                try:
                    async for message in botmod.Userbot.search_global(
                        query=search_query,
                        filter=msg_filter,
                        channels_only=True,
                        limit=MAX_RESULTS,
                    ):
                        if not message or not message.chat:
                            continue
                        chat = message.chat
                        if chat.type != enums.ChatType.CHANNEL:
                            continue
                        chat_id = chat.id
                        chat_title = chat.title or str(chat_id)
                        _chat_title_cache[chat_id] = chat_title

                        msg_key = (chat_id, message.id)
                        if msg_key in seen_msg_ids:
                            continue
                        seen_msg_ids.add(msg_key)

                        raw_name = _raw_media_name(message)
                        if not raw_name:
                            continue

                        split = _split_part_info(raw_name)
                        if split:
                            base, _part_num, display, is_zip = split
                            group_key = f"{chat_id}:{base}"
                            if group_key in split_groups:
                                continue
                            parsed = _validate_name(display, expected_title, season, episode)
                            if parsed is None:
                                continue
                            parts = await _gather_split_parts(botmod.Userbot, chat_id, message.id, base)
                            if len(parts) < 2 or sorted(parts) != list(range(1, len(parts) + 1)):
                                continue
                            split_groups[group_key] = {
                                "chat_id": chat_id,
                                "chat_title": chat_title,
                                "parts": parts,
                                "display": display,
                                "quality": parsed.get("resolution") or "HD",
                                "zip": is_zip,
                            }
                            continue

                        filename = _video_filename(message)
                        if not filename:
                            continue
                        parsed = _parse_and_validate(filename, expected_title, season, episode)
                        if parsed is None:
                            continue

                        media = message.video or message.document
                        size = get_readable_file_size(getattr(media, "file_size", 0) or 0)
                        quality = parsed.get("resolution") or "HD"

                        is_single_zip = bool(filename and filename.lower().endswith(".zip"))
                        payload = {
                            "global": True,
                            "chat_id": chat_id,
                            "msg_id": message.id,
                            "title": filename,
                            "size": size,
                            "quality": quality,
                            "source": chat_title,
                        }
                        if is_single_zip:
                            payload["zip"] = True
                            payload["parts"] = [{"chat_id": chat_id, "msg_id": message.id}]
                            del payload["chat_id"]
                            del payload["msg_id"]
                        token = await encode_string(payload)

                        all_results.append({
                            "token": token,
                            "title": filename,
                            "size": size,
                            "source_chat": chat_title,
                            "quality": quality,
                            "is_zip": is_single_zip,
                        })
                        LOGGER.debug(f"[GLOBAL SEARCH] True global result: {filename} in {chat_title}")

                        if len(all_results) >= MAX_RESULTS:
                            break

                except FloodWait as e:
                    LOGGER.warning(f"[USERBOT] FloodWait on true global: sleeping {e.value}s")
                    await asyncio.sleep(e.value)
                except (AuthKeyUnregistered, SessionRevoked) as e:
                    LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
                    _userbot_session_dead = True
                    break
                except Exception as e:
                    LOGGER.warning(f"[USERBOT] True global search error: {e}")
                    break

            if all_results or split_groups:
                LOGGER.info(
                    f"[USERBOT] True global succeeded on attempt {attempt_idx + 1} "
                    f"('{search_query}') -> {len(all_results)} + {len(split_groups)} split group(s)"
                )
                break
            if attempt_idx + 1 < len(query_candidates):
                LOGGER.info(f"[USERBOT] No results for '{search_query}', trying next fallback")

        for group in split_groups.values():
            chat_id = group["chat_id"]
            chat_title = group["chat_title"]
            ordered = [group["parts"][pn] for pn in sorted(group["parts"])]
            total_bytes = sum(p["size_bytes"] for p in ordered)
            size = get_readable_file_size(total_bytes)
            is_zip = bool(group.get("zip"))
            payload = {
                "global": True,
                "parts": [{"chat_id": chat_id, "msg_id": p["msg_id"]} for p in ordered],
                "title": group["display"],
                "size": size,
                "quality": group["quality"],
                "source": chat_title,
            }
            if is_zip:
                payload["zip"] = True
            token = await encode_string(payload)
            all_results.append({
                "token": token,
                "title": group["display"],
                "size": size,
                "source_chat": chat_title,
                "quality": group["quality"],
                "is_split": True,
                "is_zip": is_zip,
                "part_count": len(ordered),
            })
            kind = "zip parts" if is_zip else "parts"
            LOGGER.info(f"[GLOBAL SEARCH] Split stream: {group['display']} ({len(ordered)} {kind}) in {chat_title}")

        all_results = all_results[:MAX_RESULTS]
        LOGGER.info(f"[USERBOT] True global search completed: '{expected_title}' -> {len(all_results)} result(s)")
        return all_results