File size: 11,619 Bytes
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Telegram MTProto Client Singleton

Manages a Telethon client running in a background thread for use with
synchronous Flask routes. Supports streaming files up to 2GB from
Telegram channels via MTProto API.

Requires TELEGRAM_API_ID and TELEGRAM_API_HASH from https://my.telegram.org
Falls back gracefully when credentials are not configured.
"""

import asyncio
import logging
import os
import queue as thread_queue
import threading
from config import Config

logger = logging.getLogger(__name__)

try:
    from telethon import TelegramClient
    from telethon.tl.types import DocumentAttributeFilename
    HAS_TELETHON = True
except ImportError:
    HAS_TELETHON = False
    logger.warning("Telethon not installed. MTProto streaming unavailable.")


class TelegramStreamer:
    """
    Singleton that manages a Telethon client in a background asyncio loop.

    Usage from synchronous Flask code:
        streamer = TelegramStreamer.get_instance()
        if streamer and streamer.is_ready():
            data = streamer.get_file_chunk(message_id, offset, limit)
    """

    _instance = None
    _lock = threading.Lock()

    def __init__(self):
        self._client = None
        self._loop = None
        self._thread = None
        self._ready = False
        self._channel_entity = None
        self._media_cache = {}

    @classmethod
    def get_instance(cls):
        """Get or create the singleton instance. Returns None if MTProto is not configured."""
        if not HAS_TELETHON:
            return None
        if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
            return None
        if not Config.TELEGRAM_BOT_TOKEN:
            return None

        with cls._lock:
            if cls._instance is None:
                cls._instance = cls()
                cls._instance._start_loop()
            return cls._instance

    def is_ready(self):
        return self._ready and self._client is not None

    def _start_loop(self):
        self._loop = asyncio.new_event_loop()
        self._thread = threading.Thread(target=self._run_loop, daemon=True, name="telethon-loop")
        self._thread.start()

        try:
            future = asyncio.run_coroutine_threadsafe(self._init_client(), self._loop)
            future.result(timeout=30)
            self._ready = True
            logger.info("Telethon MTProto client initialized successfully")
        except Exception as e:
            logger.error(f"Failed to initialize Telethon client: {e}")
            self._ready = False

    def _run_loop(self):
        asyncio.set_event_loop(self._loop)
        self._loop.run_forever()

    async def _init_client(self):
        session_dir = os.path.join(os.path.dirname(__file__), 'data')
        os.makedirs(session_dir, exist_ok=True)
        session_path = os.path.join(session_dir, 'bot_session')

        self._client = TelegramClient(
            session_path,
            Config.TELEGRAM_API_ID,
            Config.TELEGRAM_API_HASH,
            loop=self._loop
        )
        await self._client.start(bot_token=Config.TELEGRAM_BOT_TOKEN)
        logger.info("Telethon client connected")

        channel_id = Config.TELEGRAM_CHANNEL_ID
        if channel_id:
            try:
                self._channel_entity = await self._client.get_entity(int(channel_id))
                logger.info(f"Channel entity cached: {channel_id}")
            except Exception as e:
                logger.warning(f"Could not pre-fetch channel entity: {e}")

    def _run_async(self, coro, timeout=300):
        if not self._ready or not self._loop:
            raise RuntimeError("Telethon client not ready")
        future = asyncio.run_coroutine_threadsafe(coro, self._loop)
        return future.result(timeout=timeout)

    # ===== Public sync API =====

    def get_file_info(self, message_id):
        try:
            return self._run_async(self._async_get_file_info(message_id), timeout=30)
        except Exception as e:
            logger.error(f"get_file_info error for msg {message_id}: {e}")
            return None

    def get_file_chunk(self, message_id, offset=0, limit=None, timeout=None):
        if timeout is None:
            timeout = 15 if (limit and limit < 1024 * 1024) else 300
        try:
            return self._run_async(
                self._async_get_file_chunk(message_id, offset, limit),
                timeout=timeout
            )
        except Exception as e:
            logger.error(f"get_file_chunk error for msg {message_id}: {e}")
            return b''

    def stream_file_generator(self, message_id, offset=0, limit=None, chunk_size=1024 * 1024):
        q = thread_queue.Queue(maxsize=4)

        async def _producer():
            try:
                media = await self._async_get_media(message_id)
                if not media:
                    q.put(None)
                    return

                downloaded = 0
                async for chunk in self._client.iter_download(
                    media,
                    offset=offset,
                    request_size=chunk_size
                ):
                    if limit and downloaded + len(chunk) > limit:
                        remaining = limit - downloaded
                        if remaining > 0:
                            q.put(chunk[:remaining])
                        break
                    q.put(chunk)
                    downloaded += len(chunk)
                q.put(None)
            except Exception as e:
                logger.error(f"Stream producer error for msg {message_id}: {e}")
                q.put(None)

        try:
            asyncio.run_coroutine_threadsafe(_producer(), self._loop)
            while True:
                try:
                    chunk = q.get(timeout=60)
                except thread_queue.Empty:
                    logger.error(f"Stream timeout waiting for chunk (msg {message_id})")
                    break
                if chunk is None:
                    break
                yield chunk
        except Exception as e:
            logger.error(f"stream_file_generator error for msg {message_id}: {e}")
            return

    def upload_file_sync(self, filepath, category, caption=None):
        try:
            return self._run_async(
                self._async_upload_file(filepath, category, caption),
                timeout=600
            )
        except Exception as e:
            logger.error(f"upload_file_sync error: {e}")
            return None

    # ===== Private async methods =====

    async def _async_get_file_info(self, message_id):
        channel = self._channel_entity
        if not channel:
            try:
                channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))
                self._channel_entity = channel
            except Exception as e:
                logger.error(f"Cannot resolve channel: {e}")
                return None

        try:
            messages = await self._client.get_messages(channel, ids=[message_id])
            message = messages[0] if messages else None
        except Exception as e:
            logger.error(f"get_messages failed for msg_id={message_id}: {e}")
            return None

        if not message or not message.media:
            return None

        doc = getattr(message.media, 'document', None)
        if doc:
            filename = None
            for attr in doc.attributes:
                if isinstance(attr, DocumentAttributeFilename):
                    filename = attr.file_name
                    break
            return {
                'size': doc.size,
                'filename': filename,
                'mime_type': doc.mime_type,
                'id': doc.id,
                'access_hash': doc.access_hash,
            }

        photo = getattr(message.media, 'photo', None)
        if photo:
            sizes = getattr(photo, 'sizes', [])
            if sizes:
                largest = max(sizes, key=lambda s: getattr(s, 'size', 0))
                return {
                    'size': getattr(largest, 'size', 0),
                    'filename': f'photo_{photo.id}.jpg',
                    'mime_type': 'image/jpeg',
                }
        return None

    async def _async_get_media(self, message_id):
        if message_id in self._media_cache:
            return self._media_cache[message_id]

        channel = self._channel_entity
        if not channel:
            channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))
            self._channel_entity = channel

        messages = await self._client.get_messages(channel, ids=[message_id])
        message = messages[0] if messages else None
        if not message or not message.media:
            return None

        self._media_cache[message_id] = message.media
        if len(self._media_cache) > 50:
            oldest = list(self._media_cache.keys())[0]
            del self._media_cache[oldest]
        return message.media

    async def _async_get_file_chunk(self, message_id, offset, limit):
        media = await self._async_get_media(message_id)
        if not media:
            return b''

        CHUNK = 1024 * 1024  # 1MB
        aligned_offset = (offset // CHUNK) * CHUNK
        skip_bytes = offset - aligned_offset
        need_total = skip_bytes + (limit or CHUNK)

        data = bytearray()
        try:
            async for chunk in self._client.iter_download(
                media,
                offset=aligned_offset,
                request_size=CHUNK
            ):
                data.extend(chunk)
                if len(data) >= need_total:
                    break
        except Exception as e:
            logger.error(f"iter_download error msg={message_id}: {e}")
            self._media_cache.pop(message_id, None)
            return b''

        result = bytes(data[skip_bytes:])
        if limit and len(result) > limit:
            result = result[:limit]
        return result

    async def _async_upload_file(self, filepath, category, caption=None):
        channel = self._channel_entity
        if not channel:
            channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))

        if not caption:
            caption = category

        filename = os.path.basename(filepath)
        file_size = os.path.getsize(filepath)
        logger.info(f"MTProto uploading {filename} ({file_size} bytes)")

        ext = os.path.splitext(filename)[1].lower()
        is_video = ext in {'.mp4', '.mkv', '.avi', '.mov'}

        if is_video:
            message = await self._client.send_file(
                channel, filepath,
                caption=caption,
                supports_streaming=True,
                force_document=False,
            )
        else:
            message = await self._client.send_file(
                channel, filepath,
                caption=caption,
                force_document=True,
            )

        if not message:
            return None

        result = {'message_id': message.id, 'size': file_size}

        doc = getattr(message.media, 'document', None) if message.media else None
        if doc:
            result['file_id'] = str(doc.id)
            result['file_unique_id'] = f"mtproto_{doc.id}"
            result['access_hash'] = doc.access_hash
        elif message.media and hasattr(message.media, 'photo'):
            photo = message.media.photo
            result['file_id'] = str(photo.id)
            result['file_unique_id'] = f"mtproto_{photo.id}"

        logger.info(f"MTProto upload complete: msg_id={message.id}")
        return result