File size: 26,098 Bytes
12f0507
2ab2d4a
 
 
12f0507
 
 
2ab2d4a
 
 
 
12f0507
2ab2d4a
12f0507
2ab2d4a
12f0507
 
2ab2d4a
12f0507
 
 
 
2ab2d4a
2406c44
 
 
 
2ab2d4a
12f0507
2ab2d4a
 
 
12f0507
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
2ab2d4a
12f0507
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
2ab2d4a
12f0507
2ab2d4a
 
12f0507
2ab2d4a
 
 
 
12f0507
2ab2d4a
 
 
12f0507
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
2ab2d4a
12f0507
 
2ab2d4a
 
 
12f0507
 
 
2ab2d4a
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab2d4a
 
12f0507
 
 
2ab2d4a
12f0507
 
 
 
2ab2d4a
 
12f0507
 
 
 
 
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406c44
 
2ab2d4a
 
 
 
 
 
2406c44
 
 
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
2406c44
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
2406c44
 
2ab2d4a
 
 
 
 
 
 
2406c44
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
2ab2d4a
 
 
12f0507
 
 
2ab2d4a
12f0507
2ab2d4a
 
 
 
 
 
12f0507
 
2ab2d4a
 
 
12f0507
 
2ab2d4a
 
 
 
 
2406c44
 
2ab2d4a
 
2406c44
 
 
 
2ab2d4a
2406c44
 
2ab2d4a
 
2406c44
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406c44
 
 
 
2ab2d4a
 
12f0507
 
 
 
 
2ab2d4a
12f0507
 
2ab2d4a
12f0507
 
2ab2d4a
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
2ab2d4a
12f0507
 
 
 
 
 
 
 
 
 
2ab2d4a
12f0507
 
 
 
 
 
2ab2d4a
12f0507
 
 
 
 
 
2ab2d4a
12f0507
 
2ab2d4a
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab2d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""
Video Proxy - Serves local video files with advanced DRM-like protection.
Uses HMAC-signed tokens, session binding, rate limiting, anti-bot validation,
chunked streaming with token rotation, and watermarked player pages.
"""
import os
import time
import json
import hmac
import hashlib
import base64
import secrets
import threading
import mimetypes
from collections import defaultdict
from flask import Blueprint, request, jsonify, make_response, g, send_file, Response
from auth.middleware import require_auth
from auth.session_manager import validate_session
from config import Config

video_bp = Blueprint('video', __name__, url_prefix='/api')

# ===== Configuration =====
TOKEN_EXPIRY = 600  # seconds (10 min — generous for slow connections / seeking)
CHUNK_ROTATION_BYTES = 500 * 1024 * 1024  # 500MB — effectively disabled for normal videos
RATE_LIMIT_TOKENS_PER_MIN = 15  # generous to allow multi-video pages + rotation
MAX_CONCURRENT_STREAMS = 5
RATE_WINDOW = 60  # seconds

# ===== In-memory stores =====
# {token_id: {payload, created, bytes_served, active_stream}}
_video_tokens = {}

# Rate limiting: {user_id: [timestamps]}
_token_request_times = defaultdict(list)

# Active streams: {user_id: set(token_ids)}
_active_streams = defaultdict(set)

# Lock for thread-safe access
_lock = threading.Lock()


def _get_secret_key():
    """Get the signing key from config."""
    return (Config.SECRET_KEY or 'change-me-in-production-use-secrets-token').encode('utf-8')


def _hash_user_agent(ua):
    """Hash user agent to a short fingerprint."""
    if not ua:
        return ''
    return hashlib.sha256(ua.encode('utf-8')).hexdigest()[:16]


def _get_client_ip():
    """Extract client IP from request."""
    ip = request.headers.get('X-Forwarded-For', request.remote_addr) or '0.0.0.0'
    if ',' in ip:
        ip = ip.split(',')[0].strip()
    return ip


def _sign_token(payload_dict):
    """Create an HMAC-signed token from a payload dict.
    Format: base64url(json_payload).base64url(hmac_signature)
    """
    payload_json = json.dumps(payload_dict, separators=(',', ':'), sort_keys=True)
    payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).rstrip(b'=').decode('ascii')
    signature = hmac.new(_get_secret_key(), payload_b64.encode('utf-8'), hashlib.sha256).digest()
    sig_b64 = base64.urlsafe_b64encode(signature).rstrip(b'=').decode('ascii')
    return f"{payload_b64}.{sig_b64}"


def _verify_token(token_str):
    """Verify an HMAC-signed token. Returns payload dict or None."""
    if not token_str or '.' not in token_str:
        return None

    parts = token_str.rsplit('.', 1)
    if len(parts) != 2:
        return None

    payload_b64, sig_b64 = parts

    # Recompute signature
    expected_sig = hmac.new(_get_secret_key(), payload_b64.encode('utf-8'), hashlib.sha256).digest()
    expected_b64 = base64.urlsafe_b64encode(expected_sig).rstrip(b'=').decode('ascii')

    if not hmac.compare_digest(sig_b64, expected_b64):
        return None

    # Decode payload
    try:
        padding = 4 - len(payload_b64) % 4
        if padding != 4:
            payload_b64 += '=' * padding
        payload_json = base64.urlsafe_b64decode(payload_b64.encode('utf-8')).decode('utf-8')
        return json.loads(payload_json)
    except Exception:
        return None


def _cleanup_stores():
    """Periodically clean up expired tokens and rate limit entries."""
    now = time.time()
    with _lock:
        # Clean expired tokens
        expired = [k for k, v in _video_tokens.items() if now - v['created'] > TOKEN_EXPIRY * 3]
        for k in expired:
            entry = _video_tokens.pop(k, None)
            if entry:
                uid = entry.get('user_id')
                if uid and k in _active_streams.get(uid, set()):
                    _active_streams[uid].discard(k)

        # Clean rate limit windows
        for uid in list(_token_request_times.keys()):
            _token_request_times[uid] = [t for t in _token_request_times[uid] if now - t < RATE_WINDOW]
            if not _token_request_times[uid]:
                del _token_request_times[uid]

        # Clean empty active stream sets
        for uid in list(_active_streams.keys()):
            # Remove token IDs no longer in _video_tokens
            _active_streams[uid] = {tid for tid in _active_streams[uid] if tid in _video_tokens}
            if not _active_streams[uid]:
                del _active_streams[uid]


def _check_rate_limit(user_id):
    """Check if user has exceeded token request rate limit. Returns True if OK."""
    now = time.time()
    with _lock:
        times = _token_request_times[user_id]
        times = [t for t in times if now - t < RATE_WINDOW]
        _token_request_times[user_id] = times
        if len(times) >= RATE_LIMIT_TOKENS_PER_MIN:
            return False
        _token_request_times[user_id].append(now)
    return True


def _check_concurrent_streams(user_id):
    """Check if user has exceeded max concurrent streams. Returns True if OK."""
    with _lock:
        active = _active_streams.get(user_id, set())
        # Only count tokens that are still valid
        now = time.time()
        valid_active = set()
        for tid in active:
            entry = _video_tokens.get(tid)
            if entry and entry.get('active_stream') and now - entry['created'] < TOKEN_EXPIRY * 3:
                valid_active.add(tid)
        _active_streams[user_id] = valid_active
        return len(valid_active) < MAX_CONCURRENT_STREAMS


def _register_stream(user_id, token_id):
    """Mark a stream as active."""
    with _lock:
        _video_tokens[token_id]['active_stream'] = True
        _active_streams[user_id].add(token_id)


def _unregister_stream(user_id, token_id):
    """Mark a stream as inactive."""
    with _lock:
        entry = _video_tokens.get(token_id)
        if entry:
            entry['active_stream'] = False
        _active_streams.get(user_id, set()).discard(token_id)


# ===== Routes =====

@video_bp.route('/video-token', methods=['POST'])
@require_auth
def create_video_token():
    """Create an HMAC-signed, session-bound video token."""
    data = request.get_json()
    if not data or 'filename' not in data:
        return jsonify({'error': 'Filename required'}), 400

    filename = data['filename']
    user = g.current_user
    session = g.current_session
    user_id = user.get('id', 0) if user else 0

    _cleanup_stores()

    # --- Rate Limiting ---
    if not _check_rate_limit(user_id):
        return jsonify({'error': 'Muitas solicitacoes. Aguarde um momento.'}), 429

    # --- Concurrent stream check ---
    if not _check_concurrent_streams(user_id):
        return jsonify({'error': 'Limite de streams simultaneos atingido.'}), 429

    # --- Session validation (ensure session is still active) ---
    session_token = g.token
    session_user, session_obj = validate_session(session_token)
    if not session_user:
        return jsonify({'error': 'Sessao invalida. Faca login novamente.'}), 401

    session_id = session.get('id', 0)

    # --- Build HMAC-signed token ---
    client_ip = _get_client_ip()
    ua_hash = _hash_user_agent(request.headers.get('User-Agent', ''))
    token_id = secrets.token_urlsafe(16)  # unique ID for internal tracking

    payload = {
        'tid': token_id,
        'uid': user_id,
        'email': user.get('email', '') if user else '',
        'ip': client_ip,
        'uah': ua_hash,
        'ts': int(time.time()),
        'fn': filename,
        'sid': session_id,
    }

    signed_token = _sign_token(payload)

    # Store server-side state for stream tracking
    with _lock:
        _video_tokens[token_id] = {
            'user_id': user_id,
            'user_email': user.get('email', '') if user else '',
            'user_name': user.get('display_name', '') if user else '',
            'filename': filename,
            'session_id': session_id,
            'session_token': session_token,
            'created': time.time(),
            'bytes_served': 0,
            'active_stream': False,
            'rotation_required': False,
        }

    return jsonify({'token': signed_token, 'expires_in': TOKEN_EXPIRY})


@video_bp.route('/video-player/<path:token>', methods=['GET'])
def serve_video_player(token):
    """Serve an isolated HTML page with the video player, watermarks, and advanced protections."""
    _cleanup_stores()

    # --- Verify HMAC signature ---
    payload = _verify_token(token)
    if not payload:
        return _error_page('Token invalido ou adulterado'), 403

    # --- Check expiry ---
    token_age = int(time.time()) - payload.get('ts', 0)
    if token_age > TOKEN_EXPIRY:
        return _error_page('Token expirado'), 403

    token_id = payload.get('tid', '')
    entry = _video_tokens.get(token_id)
    if not entry:
        return _error_page('Token nao encontrado'), 403

    # --- Session validation ---
    session_token = entry.get('session_token', '')
    if session_token:
        session_user, session_obj = validate_session(session_token)
        if not session_user:
            with _lock:
                _video_tokens.pop(token_id, None)
            return _error_page('Sessao expirada. Faca login novamente.'), 403

    filename = payload.get('fn', '')
    _user_email = entry.get('user_email', '')
    _user_name = entry.get('user_name', '') or (_user_email.split('@')[0] if _user_email else '---')
    _ip = _get_client_ip()
    wm_text = f"{_user_name} | {_user_email} | IP: {_ip}"

    # Generate a unique player session ID for anti-bot header
    player_session = secrets.token_urlsafe(24)

    # Build video URL pointing to our secure media endpoint
    video_url = f"/api/video-stream/{token}"

    # Origin for referer check
    origin = request.host_url.rstrip('/')

    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; }}
.vp {{ position:relative; width:100vw; height:100vh; }}
.vp video {{ width:100%; height:100%; object-fit:contain; }}
[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>
<div class="vp">
  <video id="vplayer" controls controlslist="nodownload noplaybackrate" disablepictureinpicture
         oncontextmenu="return false;" preload="metadata">
  </video>
</div>

<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";

  // ===== Configuration =====
  var PLAYER_SESSION = "{player_session}";
  var CURRENT_TOKEN = "{token}";
  var FILENAME = "{filename}";
  var SESSION_TOKEN = "{entry.get('session_token', '')}";
  var ORIGIN = "{origin}";
  var WM_TEXT = "{wm_text}";

  // ===== Anti-download: block blob URL interception =====
  var _origCreateObjectURL = URL.createObjectURL;
  URL.createObjectURL = function(obj) {{
    if (obj instanceof Blob && obj.type && obj.type.startsWith('video/')) {{
      console.warn('Blob URL creation blocked for video content');
      return 'about:blank';
    }}
    return _origCreateObjectURL.call(URL, obj);
  }};

  // ===== Block video.src access from console =====
  var vid = document.getElementById('vplayer');
  var _realSrc = '';

  function loadVideoWithToken(tkn) {{
    _realSrc = "/api/video-stream/" + tkn;
    var currentTime = vid.currentTime || 0;
    var wasPlaying = !vid.paused;
    vid.innerHTML = '';
    var src = document.createElement('source');
    src.type = 'video/mp4';
    src.src = _realSrc;
    vid.appendChild(src);
    vid.load();
    // Restore playback position after token rotation
    if (currentTime > 1) {{
      vid.addEventListener('loadedmetadata', function onMeta() {{
        vid.removeEventListener('loadedmetadata', onMeta);
        vid.currentTime = currentTime;
        if (wasPlaying) vid.play().catch(function(){{}});
      }});
    }}
  }}

  // Override src getter to hide URL
  try {{
    Object.defineProperty(vid, 'currentSrc', {{
      get: function() {{ return ''; }},
      configurable: false
    }});
  }} catch(e) {{}}

  // ===== Token rotation every 4 minutes =====
  var TOKEN_ROTATE_MS = 240000;
  function rotateToken() {{
    fetch('/api/video-token', {{
      method: 'POST',
      headers: {{
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + SESSION_TOKEN,
        'X-Player-Session': PLAYER_SESSION
      }},
      body: JSON.stringify({{ filename: FILENAME }})
    }})
    .then(function(r) {{ return r.json(); }})
    .then(function(data) {{
      if (data.token) {{
        CURRENT_TOKEN = data.token;
        // Update the video source so seeking/buffering uses the fresh token
        loadVideoWithToken(CURRENT_TOKEN);
      }}
    }})
    .catch(function(e) {{ /* silent */ }});
  }}

  setInterval(rotateToken, TOKEN_ROTATE_MS);

  // ===== Handle video errors — retry with fresh token =====
  vid.addEventListener('error', function() {{
    console.warn('Video error, attempting token refresh...');
    rotateToken();
  }});

  // ===== 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);
  // Redraw periodically in case someone tries to clear the canvas
  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);

  // ===== Initialize video =====
  loadVideoWithToken(CURRENT_TOKEN);
}})();
</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['X-Content-Type-Options'] = 'nosniff'
    response.headers['Referrer-Policy'] = 'same-origin'
    # Set the player session cookie for anti-bot validation
    response.set_cookie('_vps', player_session, httponly=True, samesite='Strict', max_age=TOKEN_EXPIRY * 3)
    return response


@video_bp.route('/video-stream/<path:token>', methods=['GET'])
def stream_video(token):
    """Stream the actual video file with advanced validation."""
    _cleanup_stores()

    # --- Verify HMAC signature ---
    payload = _verify_token(token)
    if not payload:
        return jsonify({'error': 'Token invalido'}), 403

    # --- Check expiry (use 3x for streaming to allow seeking) ---
    token_age = int(time.time()) - payload.get('ts', 0)
    if token_age > TOKEN_EXPIRY * 3:
        return jsonify({'error': 'Token expirado'}), 403

    token_id = payload.get('tid', '')
    entry = _video_tokens.get(token_id)
    if not entry:
        return jsonify({'error': 'Token nao encontrado'}), 403

    # --- IP check (relaxed — CDN/proxy can change IPs mid-session) ---
    # Only log mismatches; do NOT reject, as Cloudflare tunnels cause IP drift
    client_ip = _get_client_ip()
    if payload.get('ip') and payload['ip'] != client_ip:
        import logging
        logging.getLogger(__name__).debug(
            f"Video stream IP drift: token={payload['ip']} current={client_ip} user={payload.get('uid')}"
        )

    # --- User-Agent hash check (relaxed — some browsers update UA between requests) ---
    # Only log; do NOT reject
    current_ua_hash = _hash_user_agent(request.headers.get('User-Agent', ''))
    if payload.get('uah') and payload['uah'] != current_ua_hash:
        import logging
        logging.getLogger(__name__).debug(
            f"Video stream UA drift: user={payload.get('uid')}"
        )

    # --- Session validation ---
    session_token = entry.get('session_token', '')
    if session_token:
        session_user, session_obj = validate_session(session_token)
        if not session_user:
            with _lock:
                _video_tokens.pop(token_id, None)
            return jsonify({'error': 'Sessao expirada'}), 403

    # --- Anti-bot: Referer check (relaxed for initial load) ---
    referer = request.headers.get('Referer', '')
    if referer:
        # If referer is present, it must be from our domain
        if not referer.startswith(request.host_url) and not referer.startswith('/'):
            return jsonify({'error': 'Acesso negado'}), 403

    # --- Anti-bot: Cookie check ---
    player_session_cookie = request.cookies.get('_vps', '')
    # We allow the first request without cookie (initial video load sets it)
    # but if a cookie is present it should be non-empty
    # This is a soft check to not break the flow

    # --- Concurrent streams ---
    user_id = payload.get('uid', 0)
    if not entry.get('active_stream'):
        if not _check_concurrent_streams(user_id):
            return jsonify({'error': 'Limite de streams simultaneos atingido'}), 429
        _register_stream(user_id, token_id)

    # --- Token rotation flag (informational only) ---
    # NOTE: Previously this returned 403 mid-stream, which broke playback because
    # the HTML5 video element cannot handle mid-stream auth failures gracefully.
    # Now we just log it and let the stream continue.

    filename = payload.get('fn', '')
    safe_name = os.path.basename(filename)

    # Try local file first
    video_path = os.path.join(Config.MEDIA_DIR, safe_name)
    if os.path.exists(video_path):
        return _stream_local_video(video_path, token_id, user_id)

    # Fallback: stream from Telegram
    return _stream_telegram_video(safe_name, token_id, user_id)


def _stream_local_video(video_path, token_id, user_id):
    """Stream video from local filesystem with Range support and byte tracking."""
    file_size = os.path.getsize(video_path)
    range_header = request.headers.get('Range')

    if range_header:
        byte_start = 0
        byte_end = file_size - 1

        match = range_header.replace('bytes=', '').split('-')
        byte_start = int(match[0]) if match[0] else 0
        if match[1]:
            byte_end = int(match[1])

        content_length = byte_end - byte_start + 1

        def generate():
            try:
                with open(video_path, 'rb') as f:
                    f.seek(byte_start)
                    remaining = content_length
                    chunk_size = 1024 * 1024
                    total_sent = 0
                    while remaining > 0:
                        read_size = min(chunk_size, remaining)
                        data = f.read(read_size)
                        if not data:
                            break
                        remaining -= len(data)
                        total_sent += len(data)
                        yield data

                        # Track bytes served for rotation
                        with _lock:
                            entry = _video_tokens.get(token_id)
                            if entry:
                                entry['bytes_served'] = entry.get('bytes_served', 0) + len(data)
                                if entry['bytes_served'] >= CHUNK_ROTATION_BYTES:
                                    entry['rotation_required'] = True
            finally:
                _unregister_stream(user_id, token_id)

        response = Response(generate(), status=206, mimetype='video/mp4')
        response.headers['Content-Range'] = f'bytes {byte_start}-{byte_end}/{file_size}'
        response.headers['Content-Length'] = content_length
        response.headers['Accept-Ranges'] = 'bytes'
    else:
        def generate_full():
            try:
                with open(video_path, 'rb') as f:
                    chunk_size = 1024 * 1024
                    while True:
                        data = f.read(chunk_size)
                        if not data:
                            break
                        yield data
                        with _lock:
                            entry = _video_tokens.get(token_id)
                            if entry:
                                entry['bytes_served'] = entry.get('bytes_served', 0) + len(data)
                                if entry['bytes_served'] >= CHUNK_ROTATION_BYTES:
                                    entry['rotation_required'] = True
            finally:
                _unregister_stream(user_id, token_id)

        response = Response(generate_full(), status=200, mimetype='video/mp4')
        response.headers['Content-Length'] = file_size
        response.headers['Accept-Ranges'] = 'bytes'

    response.headers['Cache-Control'] = 'no-store'
    response.headers['Content-Disposition'] = 'inline'
    return response


def _stream_telegram_video(filename, token_id, user_id):
    """Stream video from Telegram via media API."""
    from models.database import get_db
    import re

    db = get_db()
    media = db.execute(
        "SELECT * FROM media_files WHERE filename = ?", (filename,)
    ).fetchone()

    if not media:
        _unregister_stream(user_id, token_id)
        return jsonify({'error': 'Video nao encontrado'}), 404

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

    if not message_id:
        _unregister_stream(user_id, token_id)
        return jsonify({'error': 'Video nao disponivel para streaming'}), 404

    try:
        from telegram_client import TelegramStreamer
        streamer = TelegramStreamer.get_instance()
        if not streamer or not streamer.is_ready():
            _unregister_stream(user_id, token_id)
            return jsonify({'error': 'Telegram nao disponivel'}), 503
    except ImportError:
        _unregister_stream(user_id, token_id)
        return jsonify({'error': 'Telegram nao configurado'}), 503

    range_header = request.headers.get('Range')
    start = 0
    end = size_bytes - 1 if size_bytes > 0 else 0
    status = 200

    if range_header and size_bytes > 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)), size_bytes - 1) if range_match.group(2) else size_bytes - 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 = streamer.get_file_chunk(message_id, offset=offset, limit=read_size)
                if not chunk:
                    break
                yield chunk
                offset += len(chunk)
                remaining -= len(chunk)

                # Track bytes for rotation
                with _lock:
                    entry = _video_tokens.get(token_id)
                    if entry:
                        entry['bytes_served'] = entry.get('bytes_served', 0) + len(chunk)
                        if entry['bytes_served'] >= CHUNK_ROTATION_BYTES:
                            entry['rotation_required'] = True

                if len(chunk) < read_size:
                    break
        finally:
            _unregister_stream(user_id, token_id)

    response_headers = {
        'Content-Type': 'video/mp4',
        'Accept-Ranges': 'bytes',
        'Content-Length': str(content_length),
        'Cache-Control': 'no-store',
        'Content-Disposition': 'inline',
    }

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

    from flask import stream_with_context
    return Response(stream_with_context(generate()), status=status, headers=response_headers)


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