File size: 14,898 Bytes
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
from asyncio import Lock, Queue, create_task
from asyncio import sleep as asleep

from pyrogram import Client, filters
from pyrogram.enums.parse_mode import ParseMode
from pyrogram.errors import FloodWait
from pyrogram.types import Message

import Backend
from Backend import db
from Backend.helper.announcer import announce_new_media
from Backend.helper.auto_catalog import start_single_media_catalog_sync
from Backend.helper.encrypt import encode_string
from Backend.helper.manual_add import resolve_telegram_message, stamp_caption_with_id
from Backend.helper.requests_manager import auto_fulfill
from Backend.helper.metadata import caption_with_links, extract_default_id, has_raw_ref, metadata
from Backend.helper.pyro import apply_video_thumb_to_metadata, clean_filename, finalize_media_name, get_readable_file_size, resolve_video_thumb_url
from Backend.helper.settings_manager import SettingsManager
from Backend.helper.skip_channel import is_skip_channel, route_to_skip_channel
from Backend.helper.split_files import parse_split_info
from Backend.helper.subtitles import ingest_subtitle, is_subtitle_file, remove_subtitle
from Backend.helper.task_manager import delete_message
from Backend.logger import LOGGER

file_queue = Queue()
db_lock = Lock()
manual_session_lock = Lock()


#----- True when the message carries a streamable video or a split-archive part
def _is_supported_media(message: Message) -> bool:
    if message.video:
        return True
    if message.document:
        mime_type = message.document.mime_type or ""
        if mime_type.startswith("video/"):
            return True
        candidate = message.caption or message.document.file_name or ""
        if parse_split_info(candidate):
            return True
        # Single (non-split) STORED zip archives containing a video
        name = (message.document.file_name or candidate or "").lower()
        if name.endswith(".zip") and not parse_split_info(name):
            return True
    return False


#----- True when a chat id belongs to a manual channel (files added by hand, not auto-indexed)
def _is_manual_channel(chat_id) -> bool:
    target = str(chat_id).replace("-100", "")
    return any(str(c).strip().replace("-100", "") == target for c in SettingsManager.current().manual_channels)


#----- Common message field extraction shared by the channel handlers
def _extract_fields(message: Message):
    file = message.video or message.document
    title = message.caption or file.file_name
    channel = str(message.chat.id).replace("-100", "")
    return file, title, message.id, file.file_size, get_readable_file_size(file.file_size), channel


#----- Strip URLs/part suffix from a title and ensure a video extension
def _finalize_title(title: str, metadata_info: dict) -> str:
    return finalize_media_name(title, bool(metadata_info.get('group_key')))


#----- Serialize DB inserts from the queue and trigger catalog sync
async def process_file():
    while True:
        metadata_info, channel, msg_id, size, raw_size, title, stamp = await file_queue.get()
        insert_status: dict = {}
        async with db_lock:
            updated_id = await db.insert_media(metadata_info, channel=channel, msg_id=msg_id, size=size, raw_size=raw_size, name=title, status=insert_status)
            if updated_id:
                LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
            else:
                LOGGER.info("Update failed due to validation errors.")

        if updated_id and insert_status.get("duplicate_skipped"):
            LOGGER.info(f"Duplicate protection: deleting duplicate message {msg_id} from channel {channel}.")
            create_task(delete_message(int(f"-100{channel}"), msg_id))
            file_queue.task_done()
            continue

        if updated_id:
            if stamp:
                create_task(stamp_caption_with_id(stamp, metadata_info))
            start_single_media_catalog_sync(
                db,
                tmdb_id=metadata_info.get("tmdb_id"),
                media_type=metadata_info.get("media_type"),
            )
            announce_new_media(metadata_info)
            create_task(auto_fulfill(
                tmdb_id=metadata_info.get("tmdb_id"),
                imdb_id=metadata_info.get("imdb_id"),
                media_type=metadata_info.get("media_type"),
            ))
        file_queue.task_done()


create_task(process_file())


#----- Build a title-level metadata base from an existing media document
def _base_from_doc(doc: dict) -> dict:
    return {
        "tmdb_id": doc.get("tmdb_id"),
        "imdb_id": doc.get("imdb_id"),
        "title": doc.get("title") or "",
        "year": doc.get("release_year") or 0,
        "rate": doc.get("rating") or 0,
        "description": doc.get("description") or "",
        "poster": doc.get("poster") or "",
        "backdrop": doc.get("backdrop") or "",
        "logo": doc.get("logo") or "",
        "genres": doc.get("genres") or [],
        "cast": doc.get("cast") or [],
        "runtime": str(doc.get("runtime") or ""),
        "original_language": doc.get("original_language"),
        "origin_country": doc.get("origin_country") or [],
    }


#----- Highest existing episode number in a season, or 0 if none
def _max_episode(doc: dict, season_number: int) -> int:
    for season in doc.get("seasons", []) or []:
        if season.get("season_number") == season_number:
            eps = [e.get("episode_number", 0) for e in season.get("episodes", []) or []]
            return max(eps) if eps else 0
    return 0


async def _handle_personal_session(client: Client, message: Message) -> None:
    session = Backend.MANUAL_SESSION
    if not session:
        return
    async with manual_session_lock:
        channel = str(message.chat.id).replace("-100", "")
        try:
            resolved = await resolve_telegram_message(client, chat_id=channel, msg_id=message.id)
        except Exception as e:
            LOGGER.warning(f"[Manual Session] Could not resolve message {message.id}: {e}")
            return

        tmdb_id = session["tmdb_id"]
        media_type = session["media_type"]
        location = await db.find_media_doc(media_type, tmdb_id)
        if not location:
            LOGGER.warning(f"[Manual Session] Target id {tmdb_id} not found; ignoring file.")
            return
        doc = location[0]

        p_channel = int(resolved["chat_id"])
        p_msg = int(resolved["msg_id"])
        encoded = await encode_string({"chat_id": p_channel, "msg_id": p_msg})
        name = resolved["name"]
        quality = resolved.get("quality") or session.get("quality") or "HD"

        split_key = resolved.get("split_key")
        metadata_info = _base_from_doc(doc)
        metadata_info.update({
            "media_type": media_type,
            "quality": quality,
            "encoded_string": encoded,
            "group_key": f"{channel}:{quality}:{split_key}" if split_key else None,
            "part_number": resolved.get("part_number"),
            "is_anime": bool(doc.get("is_anime")),
        })

        if media_type == "tv":
            season_number = session["season"]
            episode_number = session["episode"]
            if episode_number is None:
                episode_number = _max_episode(doc, season_number) + 1
            thumb_url = ""
            if resolved.get("has_thumb"):
                thumb_url = await resolve_video_thumb_url(client, message, encoded)
            metadata_info.update({
                "season_number": season_number,
                "episode_number": episode_number,
                "episode_title": f"S{season_number:02d}E{episode_number:02d}",
                "episode_backdrop": thumb_url or metadata_info.get("backdrop") or "",
                "episode_overview": "",
                "episode_released": "",
            })
        else:
            await apply_video_thumb_to_metadata(metadata_info, message, encoded, client)

        async with db_lock:
            updated_id = await db.insert_media(
                metadata_info, channel=p_channel, msg_id=p_msg,
                size=resolved["size"], name=name, raw_size=int(resolved.get("raw_size") or 0),
            )

        if updated_id:
            where = (f"S{metadata_info['season_number']:02d}E{metadata_info['episode_number']:02d} "
                     if media_type == "tv" else "")
            LOGGER.info(f"[Manual Session] Added {quality} {where}to '{metadata_info.get('title')}' (id {tmdb_id}).")
            create_task(stamp_caption_with_id(message, metadata_info))
        else:
            LOGGER.warning(f"[Manual Session] Insert failed for message {message.id}.")


#----- Ingest new channel media into the queue after building metadata
@Client.on_message(filters.channel & (filters.document | filters.video))
async def file_receive_handler(client: Client, message: Message):
    if is_skip_channel(message):
        return

    session = Backend.MANUAL_SESSION
    is_manual = _is_manual_channel(message.chat.id)

    #----- Manual channel + personal session: add straight onto the personal title
    if is_manual and session and session.get("kind") == "personal":
        await _handle_personal_session(client, message)
        return

    #----- Manual channel otherwise only proceeds during a real (TMDB/IMDb) session;
    #----- real files are parsed from their name/caption and forced onto the session id.
    if is_manual:
        if not (session and session.get("kind") == "real"):
            return
    elif str(message.chat.id) not in SettingsManager.current().auth_channels:
        return

    is_real_session = bool(session and session.get("kind") == "real")
    override_id = session["default_id"] if is_real_session else None
    season_hint = session.get("season") if is_real_session else None
    try:
        sub_name = (message.document.file_name if message.document else "") or ""
        if sub_name and is_subtitle_file(sub_name):
            channel = str(message.chat.id).replace("-100", "")
            create_task(ingest_subtitle(sub_name, int(channel), message.id))
            return

        if not _is_supported_media(message):
            await message.reply_text("> Not supported")
            return

        _, title, msg_id, raw_size, size, channel = _extract_fields(message)

        metadata_info = await metadata(clean_filename(title), int(channel), msg_id, override_id=override_id or extract_default_id(caption_with_links(message)), season_hint=season_hint)
        if metadata_info is None:
            LOGGER.warning(f"Metadata failed for file: {title} (ID: {msg_id})")
            await route_to_skip_channel(client, message)
            return

        title = _finalize_title(title, metadata_info)
        encoded = metadata_info.get("encoded_string") or await encode_string({"chat_id": int(channel), "msg_id": msg_id})
        await apply_video_thumb_to_metadata(metadata_info, message, encoded, client)

        stamp = message if is_real_session or has_raw_ref(message.caption) else None
        await file_queue.put((metadata_info, int(channel), msg_id, size, raw_size, title, stamp))
    except FloodWait as e:
        LOGGER.info(f"Sleeping for {str(e.value)}s")
        await asleep(e.value)
        await message.reply_text(
            text=f"Got Floodwait of {str(e.value)}s",
            disable_web_page_preview=True,
            parse_mode=ParseMode.MARKDOWN
        )


def _override_matches_indexed(override_id: str, imdb_id, tmdb_id) -> bool:
    oid = str(override_id).strip().lower()
    if oid.startswith("tt"):
        return bool(imdb_id) and oid == str(imdb_id).strip().lower()
    if oid.isdigit():
        return tmdb_id not in (None, "") and oid == str(tmdb_id).strip()
    return False


#----- Edited file: same title (or no id) renames it, another title's id re-indexes it
@Client.on_edited_message(filters.channel & (filters.document | filters.video))
async def file_edited_handler(client: Client, message: Message):
    if str(message.chat.id) not in SettingsManager.current().auth_channels:
        return
    try:
        if not _is_supported_media(message):
            return

        _, title, msg_id, raw_size, size, channel = _extract_fields(message)
        override_id = extract_default_id(caption_with_links(message))
        existing = await db.get_media_ids_by_part(int(channel), msg_id)
        if existing and (not override_id or _override_matches_indexed(override_id, existing[0], existing[1])):
            if title:
                async with db_lock:
                    await db.rename_media_part(int(channel), msg_id, finalize_media_name(title, bool(parse_split_info(clean_filename(title)))))
            if has_raw_ref(message.caption):
                await stamp_caption_with_id(message, {"imdb_id": existing[0], "tmdb_id": existing[1], "media_type": existing[2]})
            return
        if not override_id:
            return

        LOGGER.info(f"Detected override ID '{override_id}' in edited message {msg_id}")
        metadata_info = await metadata(clean_filename(title), int(channel), msg_id, override_id=override_id)
        if metadata_info is None:
            LOGGER.warning(f"Metadata failed for edited file: {title} (ID: {msg_id})")
            return
        await db.remove_media_part(int(channel), msg_id)

        title = _finalize_title(title, metadata_info)
        encoded = metadata_info.get("encoded_string") or await encode_string({"chat_id": int(channel), "msg_id": msg_id})
        await apply_video_thumb_to_metadata(metadata_info, message, encoded, client)
        await file_queue.put((metadata_info, int(channel), msg_id, size, raw_size, title, message))
    except Exception as e:
        LOGGER.error(f"Error handling edited generic file {message.id}: {e}")


#----- Purge database entries for messages deleted from auth channels
@Client.on_deleted_messages(filters.channel)
async def file_deleted_handler(client: Client, messages: list[Message]):
    try:
        for message in messages:
            if not message.chat:
                continue
            if not (str(message.chat.id) in SettingsManager.current().auth_channels or _is_manual_channel(message.chat.id)):
                continue
            channel = str(message.chat.id).replace("-100", "")
            msg_id = message.id
            try:
                if await db.remove_media_part(int(channel), msg_id):
                    LOGGER.info(f"Automatically purged deleted message {msg_id} from database.")
                if await remove_subtitle(int(channel), msg_id):
                    LOGGER.info(f"Automatically purged deleted subtitle {msg_id} from database.")
            except Exception as ex:
                LOGGER.error(f"Failed to scrub deleted message {msg_id}: {ex}")
    except Exception as e:
        LOGGER.error(f"Error handling deleted messages: {e}")