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
 
 
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
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
"""
Media API - Telegram Storage Integration

Provides streaming proxy for files stored on Telegram,
organized by categories. Supports MTProto streaming up to 2GB.
Enhanced with anti-bot validation and canvas watermarks.
"""

import time
import logging
import re
import secrets
import threading
from flask import Blueprint, request, jsonify, Response, make_response, g, stream_with_context
from config import Config
from models.database import get_db
from auth.middleware import require_auth, require_admin

try:
    import requests as http_requests
except ImportError:
    http_requests = None

try:
    from telegram_client import TelegramStreamer
    _streamer_available = True
except ImportError:
    _streamer_available = False

logger = logging.getLogger(__name__)


def _get_streamer():
    """Get the TelegramStreamer singleton if available and ready."""
    if not _streamer_available:
        return None
    try:
        streamer = TelegramStreamer.get_instance()
        if streamer and streamer.is_ready():
            return streamer
    except Exception as e:
        logger.debug(f"MTProto streamer not available: {e}")
    return None


media_bp = Blueprint('media', __name__, url_prefix='/api/media')

# Caches
_file_path_cache = {}
_CACHE_TTL = 1800

_chunk_cache = {}
_CHUNK_CACHE_TTL = 600
_CHUNK_CACHE_MAX = 200


def _get_cached_chunk(streamer, message_id, offset, limit):
    now = time.time()
    cache_key = (message_id, offset, limit)

    cached = _chunk_cache.get(cache_key)
    if cached and (now - cached['cached_at']) < _CHUNK_CACHE_TTL:
        return cached['data']

    if len(_chunk_cache) > _CHUNK_CACHE_MAX:
        expired = [k for k, v in _chunk_cache.items() if now - v['cached_at'] > _CHUNK_CACHE_TTL]
        for k in expired:
            del _chunk_cache[k]
        if len(_chunk_cache) > _CHUNK_CACHE_MAX:
            oldest = sorted(_chunk_cache.items(), key=lambda x: x[1]['cached_at'])
            for k, _ in oldest[:len(_chunk_cache) // 2]:
                del _chunk_cache[k]

    chunk = streamer.get_file_chunk(message_id, offset=offset, limit=limit)
    if chunk:
        _chunk_cache[cache_key] = {'data': chunk, 'cached_at': now}
    return chunk


CONTENT_TYPES = {
    '.mp4': 'video/mp4', '.mkv': 'video/x-matroska', '.avi': 'video/x-msvideo',
    '.mov': 'video/quicktime', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
    '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
}

STREAM_SIZE_LIMIT_BOT = 20 * 1024 * 1024
STREAM_SIZE_LIMIT_MTPROTO = 2 * 1024 * 1024 * 1024


def _get_telegram_file_path(file_id):
    now = time.time()
    cached = _file_path_cache.get(file_id)
    if cached and (now - cached['cached_at']) < _CACHE_TTL:
        return cached['file_path']

    token = Config.TELEGRAM_BOT_TOKEN
    if not token or not http_requests:
        return None

    try:
        resp = http_requests.get(
            f'https://api.telegram.org/bot{token}/getFile',
            params={'file_id': file_id}, timeout=10
        )
        if resp.status_code != 200:
            return None
        data = resp.json()
        if not data.get('ok'):
            return None
        file_path = data['result'].get('file_path')
        if file_path:
            _file_path_cache[file_id] = {'file_path': file_path, 'cached_at': now}
        return file_path
    except Exception as e:
        logger.error(f"getFile exception: {e}")
        return None


def _proxy_telegram_file(file_path, content_type, size_bytes=0):
    token = Config.TELEGRAM_BOT_TOKEN
    download_url = f'https://api.telegram.org/file/bot{token}/{file_path}'
    range_header = request.headers.get('Range')

    headers = {}
    if range_header:
        headers['Range'] = range_header

    try:
        upstream = http_requests.get(download_url, headers=headers, stream=True, timeout=30)
    except Exception as e:
        return jsonify({'error': 'Erro ao carregar arquivo'}), 502

    status = 206 if upstream.status_code == 206 else 200 if upstream.status_code == 200 else None
    if status is None:
        return jsonify({'error': 'Arquivo indisponivel'}), 502

    def generate():
        try:
            for chunk in upstream.iter_content(chunk_size=64 * 1024):
                if chunk:
                    yield chunk
        finally:
            upstream.close()

    response_headers = {
        'Content-Type': content_type,
        'Accept-Ranges': 'bytes',
        'Cache-Control': 'private, max-age=1800',
        'Content-Disposition': 'inline',
    }

    if 'Content-Length' in upstream.headers:
        response_headers['Content-Length'] = upstream.headers['Content-Length']
    elif size_bytes and not range_header:
        response_headers['Content-Length'] = str(size_bytes)

    if 'Content-Range' in upstream.headers:
        response_headers['Content-Range'] = upstream.headers['Content-Range']

    return Response(stream_with_context(generate()), status=status, headers=response_headers)


def _stream_via_mtproto(streamer, message_id, content_type, total_size):
    range_header = request.headers.get('Range')

    start = 0
    end = total_size - 1 if total_size > 0 else 0
    status = 200

    if range_header and total_size > 0:
        range_match = re.match(r'bytes=(\d+)-(\d*)', range_header)
        if range_match:
            start = int(range_match.group(1))
            end = min(int(range_match.group(2)), total_size - 1) if range_match.group(2) else total_size - 1
            status = 206

    content_length = end - start + 1
    chunk_size = 1024 * 1024

    def generate():
        try:
            offset = start
            remaining = content_length
            while remaining > 0:
                read_size = min(chunk_size, remaining)
                chunk = _get_cached_chunk(streamer, message_id, offset=offset, limit=read_size)
                if not chunk:
                    break
                yield chunk
                offset += len(chunk)
                remaining -= len(chunk)
                if len(chunk) < read_size:
                    break
        except Exception as e:
            logger.error(f"MTProto stream error for msg {message_id}: {e}")

    response_headers = {
        'Content-Type': content_type,
        'Accept-Ranges': 'bytes',
        'Content-Length': str(content_length),
        'Cache-Control': 'private, max-age=3600',
        'Content-Disposition': 'inline',
    }

    if status == 206:
        response_headers['Content-Range'] = f'bytes {start}-{end}/{total_size}'

    return Response(stream_with_context(generate()), status=status, headers=response_headers)


def _prefetch_video_moov(streamer, message_id, total_size):
    def _do_prefetch():
        try:
            CHUNK = 1024 * 1024
            if total_size <= CHUNK:
                _get_cached_chunk(streamer, message_id, offset=0, limit=total_size)
            else:
                moov_offset = total_size - CHUNK
                _get_cached_chunk(streamer, message_id, offset=moov_offset, limit=CHUNK)
        except Exception:
            pass

    t = threading.Thread(target=_do_prefetch, daemon=True)
    t.start()


# ===== API Routes =====

@media_bp.route('/stream/<int:media_id>', methods=['GET'])
@require_auth
def stream_file(media_id):
    """Stream a file from Telegram. Supports Range requests for seeking."""
    db = get_db()
    media = db.execute("SELECT * FROM media_files WHERE id = ?", (media_id,)).fetchone()

    if not media:
        return jsonify({'error': 'Arquivo nao encontrado'}), 404

    size_bytes = media['size_bytes'] or 0
    message_id = media['telegram_message_id']

    ext = '.' + media['filename'].rsplit('.', 1)[-1].lower() if '.' in media['filename'] else ''
    content_type = CONTENT_TYPES.get(ext, 'application/octet-stream')

    streamer = _get_streamer()
    if streamer and message_id:
        if size_bytes and size_bytes < 1024 * 1024:
            try:
                data = streamer.get_file_chunk(message_id, offset=0, limit=size_bytes + 4096)
                if data and len(data) > 0:
                    resp = make_response(data)
                    resp.headers['Content-Type'] = content_type
                    resp.headers['Content-Length'] = str(len(data))
                    resp.headers['Cache-Control'] = 'private, max-age=3600'
                    resp.headers['Content-Disposition'] = 'inline'
                    return resp
            except Exception:
                pass
        else:
            try:
                return _stream_via_mtproto(streamer, message_id, content_type, size_bytes)
            except Exception as e:
                logger.error(f"MTProto streaming failed for media_id={media_id}: {e}")

    # Fallback to Bot API (20MB limit)
    if size_bytes > STREAM_SIZE_LIMIT_BOT:
        return jsonify({'error': 'MTProto nao disponivel e arquivo muito grande para Bot API'}), 413

    file_path = _get_telegram_file_path(media['file_id'])
    if not file_path:
        return jsonify({'error': 'Arquivo indisponivel no Telegram'}), 502

    return _proxy_telegram_file(file_path, content_type, size_bytes)


@media_bp.route('/stream-by-filename/<path:filename>', methods=['GET'])
@require_auth
def stream_by_filename(filename):
    """Stream a file by filename (used by video_proxy for question videos)."""
    db = get_db()
    media = db.execute(
        "SELECT * FROM media_files WHERE filename = ?", (filename,)
    ).fetchone()

    if not media:
        return jsonify({'error': 'Arquivo nao encontrado'}), 404

    # Redirect to stream endpoint
    return stream_file.__wrapped__(media['id']) if hasattr(stream_file, '__wrapped__') else _stream_media(media)


def _stream_media(media):
    """Internal: stream a media row."""
    size_bytes = media['size_bytes'] or 0
    message_id = media['telegram_message_id']

    ext = '.' + media['filename'].rsplit('.', 1)[-1].lower() if '.' in media['filename'] else ''
    content_type = CONTENT_TYPES.get(ext, 'application/octet-stream')

    streamer = _get_streamer()
    if streamer and message_id:
        if size_bytes and size_bytes < 1024 * 1024:
            try:
                data = streamer.get_file_chunk(message_id, offset=0, limit=size_bytes + 4096)
                if data:
                    resp = make_response(data)
                    resp.headers['Content-Type'] = content_type
                    resp.headers['Content-Length'] = str(len(data))
                    resp.headers['Cache-Control'] = 'private, max-age=3600'
                    resp.headers['Content-Disposition'] = 'inline'
                    return resp
            except Exception:
                pass
        try:
            return _stream_via_mtproto(streamer, message_id, content_type, size_bytes)
        except Exception as e:
            logger.error(f"MTProto error: {e}")

    if size_bytes > STREAM_SIZE_LIMIT_BOT:
        return jsonify({'error': 'Arquivo muito grande'}), 413

    file_path = _get_telegram_file_path(media['file_id'])
    if not file_path:
        return jsonify({'error': 'Indisponivel'}), 502
    return _proxy_telegram_file(file_path, content_type, size_bytes)


@media_bp.route('/player/<int:media_id>', methods=['GET'])
@require_auth
def media_player(media_id):
    """Serve isolated HTML video player with watermarks."""
    db = get_db()
    media = db.execute("SELECT * FROM media_files WHERE id = ?", (media_id,)).fetchone()
    if not media:
        return _error_page('Arquivo nao encontrado'), 404

    # Pre-fetch moov atom for videos
    if media['file_type'] == 'video' and media['telegram_message_id'] and media['size_bytes']:
        streamer = _get_streamer()
        if streamer:
            _prefetch_video_moov(streamer, media['telegram_message_id'], media['size_bytes'])

    user = g.current_user
    token = g.token

    user_email = user.get('email', '') if user else ''
    user_name = user.get('display_name', '') or (user_email.split('@')[0] if user_email else '---')
    user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or '---'
    if user_ip and ',' in user_ip:
        user_ip = user_ip.split(',')[0].strip()
    wm_text = f"{user_name} | {user_email} | IP: {user_ip}"

    stream_url = f'/api/media/stream/{media_id}?token={token}'

    content_html = f'''
    <video id="vid" controls autoplay preload="auto" style="width:100%;height:100%;background:#000"
           controlsList="nodownload noremoteplayback">
        <source src="{stream_url}" type="video/mp4">
        Seu navegador nao suporta video HTML5.
    </video>
    <div id="loading" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);
         color:#fff;font:16px sans-serif;text-align:center">
        <div style="border:3px solid #333;border-top:3px solid #fff;border-radius:50%;width:40px;height:40px;
                    animation:spin 1s linear infinite;margin:0 auto 10px"></div>
        Carregando video...
    </div>
    <style>@keyframes spin {{ from{{transform:rotate(0deg)}} to{{transform:rotate(360deg)}} }}</style>
    <script>
    var v=document.getElementById("vid"), ld=document.getElementById("loading");
    v.addEventListener("canplay",function(){{ ld.style.display="none"; }});
    v.addEventListener("playing",function(){{ ld.style.display="none"; }});
    v.addEventListener("error",function(){{
        ld.style.display="none";
        var err=document.createElement("div");
        err.style.cssText="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#ff5252;font:16px sans-serif;text-align:center;background:rgba(0,0,0,.8);padding:20px;border-radius:8px";
        err.textContent="Erro ao carregar video. Tente novamente.";
        document.body.appendChild(err);
    }});
    </script>
    '''

    player_session = secrets.token_urlsafe(24)

    html = f'''<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<meta name="robots" content="noindex,nofollow">
<style>
* {{ margin:0; padding:0; box-sizing:border-box; }}
body {{ background:#000; overflow:hidden; width:100vw; height:100vh; }}
video {{ display:block; }}
[id*="IDM"],[id*="idm"],[class*="IDM"],[class*="idm"],
[id*="EagleGet"],[class*="eagleget"],[id*="xdm"],[class*="xdm"] {{
    display:none!important; visibility:hidden!important;
    width:0!important; height:0!important;
}}
.wm {{ position:fixed; pointer-events:none; z-index:9999;
       font: 700 14px sans-serif; color:rgba(255,255,255,0.22);
       transform:rotate(-25deg); white-space:nowrap;
       user-select:none; -webkit-user-select:none; }}
#cv-overlay {{ position:fixed; top:0; left:0; width:100vw; height:100vh;
              pointer-events:none; z-index:9998; opacity:0.08; }}
</style>
</head><body>
{content_html}

<canvas id="cv-overlay"></canvas>

<div class="wm" style="top:6%;left:3%">{wm_text}</div>
<div class="wm" style="top:6%;left:55%">{wm_text}</div>
<div class="wm" style="top:30%;left:20%">{wm_text}</div>
<div class="wm" style="top:30%;left:70%">{wm_text}</div>
<div class="wm" style="top:55%;left:5%">{wm_text}</div>
<div class="wm" style="top:55%;left:50%">{wm_text}</div>
<div class="wm" style="top:80%;left:15%">{wm_text}</div>
<div class="wm" style="top:80%;left:65%">{wm_text}</div>
<script>
(function() {{
  "use strict";

  var WM_TEXT = "{wm_text}";

  // Block blob URL creation for video content
  var _origCreateObjectURL = URL.createObjectURL;
  URL.createObjectURL = function(obj) {{
    if (obj instanceof Blob && obj.type && obj.type.startsWith('video/')) {{
      return 'about:blank';
    }}
    return _origCreateObjectURL.call(URL, obj);
  }};

  // Block video.src access from console
  var vid = document.getElementById('vid');
  if (vid) {{
    try {{
      Object.defineProperty(vid, 'currentSrc', {{
        get: function() {{ return ''; }},
        configurable: false
      }});
    }} catch(e) {{}}
  }}

  // Canvas watermark overlay
  var canvas = document.getElementById('cv-overlay');
  var ctx = canvas.getContext('2d');
  function drawWatermark() {{
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.font = '14px sans-serif';
    ctx.fillStyle = 'rgba(255,255,255,0.15)';
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate(-25 * Math.PI / 180);
    for (var y = -canvas.height; y < canvas.height; y += 120) {{
      for (var x = -canvas.width; x < canvas.width; x += 400) {{
        ctx.fillText(WM_TEXT, x, y);
      }}
    }}
    ctx.restore();
  }}
  drawWatermark();
  window.addEventListener('resize', drawWatermark);
  setInterval(drawWatermark, 2000);

  // Context menu / keyboard blocking
  document.addEventListener('contextmenu', function(e) {{ e.preventDefault(); }});
  document.addEventListener('keydown', function(e) {{
    if (e.key === 'F12' ||
        (e.ctrlKey && e.shiftKey && 'IJC'.includes(e.key.toUpperCase())) ||
        (e.ctrlKey && e.key.toLowerCase() === 's') ||
        (e.ctrlKey && e.key.toLowerCase() === 'u'))
    {{ e.preventDefault(); e.stopPropagation(); }}
  }});

  // IDM/download manager removal
  setInterval(function() {{
    document.querySelectorAll('[id*="IDM"],[id*="idm"],[class*="IDM"],[class*="idm"],[id*="EagleGet"],[class*="xdm"]')
      .forEach(function(el) {{ el.remove(); }});
  }}, 300);
}})();
</script>
</body></html>'''

    response = make_response(html)
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate'
    response.headers['X-Frame-Options'] = 'SAMEORIGIN'
    response.headers['Referrer-Policy'] = 'no-referrer'
    return response


@media_bp.route('/health', methods=['GET'])
def media_health():
    """Health check for media streaming subsystem."""
    streamer = _get_streamer()
    mtproto_ok = streamer is not None

    db = get_db()
    total_media = db.execute("SELECT COUNT(*) as c FROM media_files").fetchone()
    total_media = total_media['c'] if total_media else 0

    return jsonify({
        'mtproto_ready': mtproto_ok,
        'telethon_available': _streamer_available,
        'bot_token_set': bool(Config.TELEGRAM_BOT_TOKEN),
        'api_id_set': bool(Config.TELEGRAM_API_ID),
        'total_media': total_media,
    })


def _error_page(msg):
    html = f'''<!DOCTYPE html><html><body style="background:#000;color:#fff;
    display:flex;align-items:center;justify-content:center;height:100vh;
    font-family:sans-serif"><h2>{msg}</h2></body></html>'''
    resp = make_response(html)
    resp.headers['Content-Type'] = 'text/html'
    return resp