-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1718 lines (1418 loc) · 67.1 KB
/
app.py
File metadata and controls
1718 lines (1418 loc) · 67.1 KB
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import logging
from flask import Flask, request, jsonify, send_file, render_template, Response, send_from_directory, session, redirect, url_for, make_response
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_cors import CORS
import yt_dlp
from dotenv import load_dotenv
import datetime
import requests
import re
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
from video_processor import YouTubeProcessor
from lib.cache_manager import CacheManager
from lib.local_video_manager import LocalVideoManager
from lib.config_manager import ConfigManager
from lib.movie_api import movie_api
from lib.summarizer import summarize_text
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Create the Flask app
app = Flask(__name__)
app.secret_key = os.environ.get("SESSION_SECRET", "dev-secret-key-change-in-production")
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(days=7) # Session lasts 7 days
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
CORS(app)
# Configure upload folder
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'downloads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Ensure upload folder exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Initialize cache manager
cache_manager = CacheManager()
# Initialize YouTube processor
youtube_processor = YouTubeProcessor()
# Initialize local video manager
local_video_manager = LocalVideoManager()
# Initialize config manager
config_manager = ConfigManager()
# Context processor to make config available in all templates
@app.context_processor
def inject_config():
"""Inject config into all templates"""
return {'config': config_manager.get_config()}
@app.route('/api/config')
def generate_config_js():
"""Generate dynamic config.js file with actual config values"""
config = config_manager.get_config()
js_content = f"""// Global configuration object accessible to all JavaScript files
// This file is generated by the server with actual config values
// Generated at: {datetime.datetime.now().isoformat()}
window.APP_CONFIG = {{
videos_per_page: {config.get('videos_per_page', 24)},
logo_text: "{config.get('logo_text', 'KCTube')}",
theme: "{config.get('theme', 'dark')}",
language: "{config.get('language', 'vi')}",
auto_play: {str(config.get('auto_play', False)).lower()},
background_play: {str(config.get('background_play', False)).lower()},
download_path: "{config.get('download_path', '/downloads')}",
cache_enabled: {str(config.get('cache_enabled', True)).lower()},
cache_duration: {config.get('cache_duration', 3600)},
max_downloads: {config.get('max_downloads', 5)},
quality_preference: "{config.get('quality_preference', 'best')}",
format_preference: "{config.get('format_preference', 'mp4')}"
}};
// Helper function to get config value with default
window.getConfig = function(key, defaultValue = null) {{
return window.APP_CONFIG[key] !== undefined ? window.APP_CONFIG[key] : defaultValue;
}};
// Helper function to update config value (for runtime updates)
window.updateConfig = function(key, value) {{
window.APP_CONFIG[key] = value;
// Trigger custom event for config changes
window.dispatchEvent(new CustomEvent('configChanged', {{
detail: {{ key: key, value: value }}
}}));
}};
// Helper function to listen for config changes
window.onConfigChange = function(callback) {{
window.addEventListener('configChanged', function(event) {{
callback(event.detail.key, event.detail.value);
}});
}};
// Helper function to get videos per page
window.getVideosPerPage = function() {{
return window.getConfig('videos_per_page', 24);
}};
// Helper function to get logo text
window.getLogoText = function() {{
return window.getConfig('logo_text', 'KCTube');
}};
// Helper function to get theme
window.getTheme = function() {{
return window.getConfig('theme', 'dark');
}};
// Helper function to check if auto play is enabled
window.isAutoPlayEnabled = function() {{
return window.getConfig('auto_play', false);
}};
// Helper function to check if background play is enabled
window.isBackgroundPlayEnabled = function() {{
return window.getConfig('background_play', false);
}};
"""
response = Response(js_content, mimetype='application/javascript')
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
# Configure yt-dlp options
ydl_opts = {
'format': 'best',
'quiet': True,
'no_warnings': True,
'extract_flat': True,
'force_generic_extractor': False
}
def format_duration(seconds):
if not seconds:
return '0:00'
minutes, seconds = divmod(int(seconds), 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
return f'{hours}:{minutes:02d}:{seconds:02d}'
return f'{minutes}:{seconds:02d}'
def format_view_count(count):
if not count:
return '0 lượt xem'
if count >= 1000000:
return f'{count/1000000:.1f}M lượt xem'
elif count >= 1000:
return f'{count/1000:.1f}K lượt xem'
return f'{count} lượt xem'
@app.route('/player')
def player_page():
"""Test page for KCTube player"""
return render_template('player.html')
@app.route('/my-videos', methods=['GET', 'POST'])
def my_videos_page():
"""Render the My Videos page, protected by password if set"""
print(f"DEBUG: Accessing /my-videos, method: {request.method}")
print(f"DEBUG: Has password: {config_manager.has_password()}")
# Check if password protection is enabled
if config_manager.has_password():
print("DEBUG: Password protection is enabled")
# Check authentication cookie
auth_cookie = request.cookies.get('my_videos_auth')
print(f"DEBUG: Auth cookie: {auth_cookie}")
if request.method == 'POST':
# Handle password submission
password = request.form.get('password', '')
print(f"DEBUG: Password submitted: {bool(password)}")
if config_manager.check_password(password):
print("DEBUG: Password is correct, setting cookie and redirecting")
response = redirect(url_for('my_videos_page'))
response.set_cookie('my_videos_auth', 'true', max_age=7*24*60*60) # 7 days
return response
else:
print("DEBUG: Password is incorrect, redirecting to login with error")
return redirect(url_for('my_videos_login', error='invalid'))
# GET request - check if authenticated
if not auth_cookie or auth_cookie != 'true':
print("DEBUG: Not authenticated, redirecting to login")
return redirect(url_for('my_videos_login'))
# Authenticated - show my videos
print("DEBUG: Authenticated, showing my videos")
response = make_response(render_template('my_videos.html'))
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
# No password protection - show my videos directly
print("DEBUG: No password protection, showing my videos directly")
response = make_response(render_template('my_videos.html'))
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
@app.route('/my-videos/login', methods=['GET', 'POST'])
def my_videos_login():
"""Login page for My Videos"""
print(f"DEBUG: Accessing /my-videos/login, method: {request.method}")
# Check if password protection is enabled
if not config_manager.has_password():
print("DEBUG: No password protection, redirecting to my videos")
return redirect(url_for('my_videos_page'))
# Check if already authenticated
auth_cookie = request.cookies.get('my_videos_auth')
if auth_cookie == 'true':
print("DEBUG: Already authenticated, redirecting to my videos")
return redirect(url_for('my_videos_page'))
# Handle password submission
if request.method == 'POST':
password = request.form.get('password', '')
print(f"DEBUG: Password submitted: {bool(password)}")
if config_manager.check_password(password):
print("DEBUG: Password is correct, setting cookie and redirecting")
response = redirect(url_for('my_videos_page'))
response.set_cookie('my_videos_auth', 'true', max_age=7*24*60*60) # 7 days
return response
else:
print("DEBUG: Password is incorrect")
return render_template('my_videos_login.html', error=True)
# GET request - show login form
error = request.args.get('error') == 'invalid'
print(f"DEBUG: Showing login form, error: {error}")
return render_template('my_videos_login.html', error=error)
@app.route('/my-videos/logout')
def my_videos_logout():
"""Logout from My Videos (clear cookie)"""
response = redirect(url_for('my_videos_page'))
response.delete_cookie('my_videos_auth')
return response
@app.route('/movies')
def movies_page():
"""Render the Movies page"""
return render_template('movies.html')
@app.route('/tienganh')
def tienganh_page():
"""Render the English Learning page"""
return render_template('tienganh.html')
@app.route('/torrent')
def torrent_page():
"""Render the Torrent Player page"""
return render_template('torrent.html')
@app.route('/pwa-debug')
def pwa_debug_page():
"""Render the PWA Debug page"""
return render_template('pwa_debug.html')
@app.route('/about')
def about_page():
"""Render the About (Giới thiệu) page"""
return render_template('about_kct.html')
@app.route('/test')
def test():
"""Render the About (Giới thiệu) page"""
return render_template('test.html')
@app.route('/api/category/<category>')
def get_category_videos(category):
page = int(request.args.get('page', 1))
config = config_manager.get_config()
max_results = int(request.args.get('max_results', config.get('videos_per_page', 24)))
# Map category to search terms
category_map = {
'music': 'music',
'gaming': 'gaming',
'news': 'news',
'live': 'live stream',
'shorts': 'shorts'
}
try:
search_term = category_map.get(category)
if not search_term:
return jsonify({'error': 'Invalid category'}), 400
# Configure yt-dlp for search
search_opts = ydl_opts.copy()
search_opts.update({
'default_search': 'ytsearch',
'extract_flat': True,
'quiet': True,
'no_warnings': True
})
# Perform search
with yt_dlp.YoutubeDL(search_opts) as ydl:
# Add page number to search query
search_query = f"{search_term} -p{page}"
result = ydl.extract_info(search_query, download=False)
if not result or 'entries' not in result:
return jsonify({'videos': [], 'nextPageToken': None})
# Transform the response
videos = []
for entry in result['entries'][:max_results]:
if not entry:
continue
video = {
'id': entry.get('id', ''),
'title': entry.get('title', ''),
'author': entry.get('uploader', ''),
'thumbnail': entry.get('thumbnail', ''),
'duration': format_duration(entry.get('duration')),
'stats': format_view_count(entry.get('view_count', 0))
}
videos.append(video)
return jsonify({
'videos': videos,
'nextPageToken': str(page + 1) if len(videos) == max_results else None
})
except Exception as e:
logging.error(f"Error getting category videos: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/search')
def search_videos():
"""Search YouTube videos"""
query = request.args.get('q', '')
config = config_manager.get_config()
max_results = int(request.args.get('max_results', config.get('videos_per_page', 24)))
page = int(request.args.get('page', 1))
if not query:
return jsonify({'videos': [], 'total': 0, 'has_more': False})
try:
# Generate cache key from query, max_results and page
cache_key = f"search_{query}_{max_results}_{page}"
# Try to get from cache first
cached_results = cache_manager.get(cache_key)
if cached_results:
logging.info(f"Cache hit for query: {query} (page {page})")
return jsonify(cached_results)
# If not in cache, perform search
logging.info(f"Cache miss for query: {query} (page {page})")
results = youtube_processor.search_videos(query, max_results, page)
# Cache the results
cache_manager.set(cache_key, results)
return jsonify(results)
except Exception as e:
logging.error(f"Search error: {e}")
return jsonify({'error': f'Search failed: {str(e)}'}), 500
@app.route('/api/related/<video_id>')
def get_related_videos(video_id):
"""Get related videos for a specific video"""
config = config_manager.get_config()
max_results = int(request.args.get('max_results', config.get('videos_per_page', 24)))
try:
# Generate cache key
cache_key = f"related_{video_id}_{max_results}"
# Try to get from cache first
cached_results = cache_manager.get(cache_key)
if cached_results:
logging.info(f"Cache hit for related videos: {video_id}")
return jsonify(cached_results)
# If not in cache, get related videos
logging.info(f"Cache miss for related videos: {video_id}")
results = youtube_processor.get_related_videos(video_id, max_results)
# Cache the results
cache_manager.set(cache_key, results)
return jsonify(results)
except Exception as e:
logging.error(f"Related videos error: {e}")
return jsonify({'error': f'Failed to get related videos: {str(e)}'}), 500
@app.route('/api/local/videos')
def get_local_videos():
"""Get paginated list of local videos with optional search"""
page = int(request.args.get('page', 1))
config = config_manager.get_config()
per_page = int(request.args.get('per_page', config.get('videos_per_page', 24)))
search = request.args.get('search')
videos, total = local_video_manager.get_videos(page, per_page, search)
# If no videos found, try scanning once
if total == 0:
try:
logging.info("No videos found, performing scan...")
local_video_manager.scan_videos()
videos, total = local_video_manager.get_videos(page, per_page, search)
logging.info(f"Scan completed, found {total} videos")
except Exception as e:
logging.error(f"Error during automatic scan: {e}")
return jsonify({
'videos': videos,
'total': total,
'page': page,
'per_page': per_page,
'total_pages': (total + per_page - 1) // per_page
})
@app.route('/api/local/videos/<video_id>')
def get_local_video(video_id):
"""Get specific local video by ID"""
video = local_video_manager.get_video(video_id)
if not video:
return jsonify({'error': 'Video not found'}), 404
return jsonify(video)
@app.route('/api/local/videos/<video_id>/summary')
def get_local_video_summary(video_id):
"""Get AI summary for local video subtitle"""
subtitle = local_video_manager.get_subtitle(video_id)
if not subtitle:
return jsonify({'error': 'Subtitle not found'}), 404
try:
summary = summarize_text(subtitle)
return jsonify({'summary': summary})
except Exception as e:
return jsonify({'error': f'Failed to summarize: {str(e)}'}), 500
@app.route('/api/local/videos/<video_id>/stream')
def stream_local_video(video_id):
"""Stream local video file"""
video = local_video_manager.get_video(video_id)
if not video:
return jsonify({'error': 'Video not found'}), 404
return send_file(
video['path'],
mimetype='video/mp4',
as_attachment=False
)
@app.route('/api/local/videos/scan', methods=['GET'])
def scan_local_videos():
"""Scan for new local videos"""
try:
local_video_manager.scan_videos()
return jsonify({'message': 'Scan completed successfully'})
except Exception as e:
logging.error(f"Error scanning videos: {e}")
return jsonify({'error': str(e)}), 500
# Movie API Routes
@app.route('/api/movies/scenes')
def get_movie_scenes():
"""Get list of movie scenes/categories"""
try:
# Get credentials from config or request
email = request.args.get('email')
password = request.args.get('password')
scenes = movie_api.get_scenes(email, password)
return jsonify({
'scenes': scenes,
'total': len(scenes)
})
except Exception as e:
logging.error(f"Error getting movie scenes: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/scenes/<scene_name>/videos')
def get_movies_by_scene(scene_name):
"""Get videos from a specific movie scene/category"""
try:
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 24))
email = request.args.get('email')
password = request.args.get('password')
videos = movie_api.get_videos_by_scene(scene_name, email, password)
# Simple pagination
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
paginated_videos = videos[start_idx:end_idx]
return jsonify({
'videos': paginated_videos,
'total': len(videos),
'page': page,
'per_page': per_page,
'total_pages': (len(videos) + per_page - 1) // per_page,
'scene_name': scene_name
})
except Exception as e:
logging.error(f"Error getting movies for scene {scene_name}: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/search')
def search_movies():
"""Search movies across all scenes"""
try:
query = request.args.get('q', '')
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 24))
email = request.args.get('email')
password = request.args.get('password')
if not query:
return jsonify({'videos': [], 'total': 0, 'page': page, 'per_page': per_page, 'total_pages': 0})
videos = movie_api.search_videos(query, email, password)
# Simple pagination
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
paginated_videos = videos[start_idx:end_idx]
return jsonify({
'videos': paginated_videos,
'total': len(videos),
'page': page,
'per_page': per_page,
'total_pages': (len(videos) + per_page - 1) // per_page,
'query': query
})
except Exception as e:
logging.error(f"Error searching movies: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/all')
def get_all_movies():
"""Get all movies from all scenes with pagination"""
try:
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 24))
limit = int(request.args.get('limit', 100))
email = request.args.get('email')
password = request.args.get('password')
videos = movie_api.get_all_videos(email, password, limit)
# Simple pagination
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
paginated_videos = videos[start_idx:end_idx]
return jsonify({
'videos': paginated_videos,
'total': len(videos),
'page': page,
'per_page': per_page,
'total_pages': (len(videos) + per_page - 1) // per_page
})
except Exception as e:
logging.error(f"Error getting all movies: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/video/<video_id>')
def get_movie_video(video_id):
"""Get specific movie video by ID"""
try:
email = request.args.get('email')
password = request.args.get('password')
# Get all videos and find the specific one
all_videos = movie_api.get_all_videos(email, password, limit=1000)
for video in all_videos:
if video.get('id') == video_id:
return jsonify(video)
return jsonify({'error': 'Video not found'}), 404
except Exception as e:
logging.error(f"Error getting movie video {video_id}: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/stream/<video_id>')
def stream_movie_video(video_id):
"""Stream movie video by ID"""
try:
logging.info(f"Stream request for video_id: '{video_id}'")
email = request.args.get('email')
password = request.args.get('password')
# Get all videos and find the specific one
all_videos = movie_api.get_all_videos(email, password, limit=1000)
logging.info(f"Found {len(all_videos)} total videos")
target_video = None
for i, video in enumerate(all_videos):
video_id_from_api = video.get('id', '')
logging.info(f"Video {i}: id='{video_id_from_api}', title='{video.get('title', '')}'")
if video_id_from_api == video_id:
target_video = video
logging.info(f"Found target video: {video.get('title', '')}")
break
if not target_video:
logging.warning(f"Video not found for ID: '{video_id}'")
return jsonify({'error': f'Video not found for ID: {video_id}'}), 404
video_url = target_video.get('video_url')
if not video_url:
logging.warning(f"Video URL not available for video: {target_video.get('title', '')}")
return jsonify({'error': 'Video URL not available'}), 404
response_data = {
'video_url': video_url,
'title': target_video.get('title'),
'thumbnail': target_video.get('thumbnail'),
'id': target_video.get('id')
}
logging.info(f"Returning video data: {response_data}")
return jsonify(response_data)
except Exception as e:
logging.error(f"Error streaming movie video {video_id}: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/proxy/<video_id>')
def proxy_movie_video(video_id):
"""Proxy movie video stream to avoid CORS issues"""
try:
logging.info(f"Proxy request for video_id: '{video_id}'")
email = request.args.get('email')
password = request.args.get('password')
# Check if it's a generated ID (starts with 'movie_')
if video_id.startswith('movie_'):
# Extract index from generated ID: movie_{index}_{timestamp}_{random}
try:
index = int(video_id.split('_')[1])
logging.info(f"Generated ID detected, using index: {index}")
# Get all videos and use the index
all_videos = movie_api.get_all_videos(email, password, limit=1000)
if index < 0 or index >= len(all_videos):
return jsonify({'error': f'Video index {index} out of range'}), 404
target_video = all_videos[index]
logging.info(f"Found video by index: {target_video.get('title', '')}")
except (ValueError, IndexError) as e:
logging.error(f"Error parsing generated ID {video_id}: {e}")
return jsonify({'error': 'Invalid generated video ID'}), 400
else:
# Original ID - search by ID
all_videos = movie_api.get_all_videos(email, password, limit=1000)
target_video = None
for video in all_videos:
if video.get('id') == video_id:
target_video = video
break
if not target_video:
return jsonify({'error': 'Video not found'}), 404
video_url = target_video.get('video_url')
if not video_url:
return jsonify({'error': 'Video URL not available'}), 404
# Import requests here to avoid circular imports
import requests
# Stream the video content
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://meocon.xyz/',
}
# Get the video stream
response = requests.get(video_url, headers=headers, stream=True, verify=False)
if response.status_code != 200:
return jsonify({'error': f'Failed to fetch video: {response.status_code}'}), 500
# Create a Flask response that streams the content
def generate():
for chunk in response.iter_content(chunk_size=8192):
if chunk:
yield chunk
# Determine content type
content_type = response.headers.get('content-type', 'video/mp4')
return Response(
generate(),
content_type=content_type,
headers={
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Length': response.headers.get('content-length', ''),
'Accept-Ranges': 'bytes',
}
)
except Exception as e:
logging.error(f"Error proxying movie video {video_id}: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/proxy-hls/<video_id>')
def proxy_hls_manifest(video_id):
"""Proxy HLS manifest to avoid CORS issues"""
try:
logging.info(f"HLS proxy request for video_id: '{video_id}'")
email = request.args.get('email')
password = request.args.get('password')
# Check if it's a generated ID (starts with 'movie_')
if video_id.startswith('movie_'):
# Extract index from generated ID: movie_{index}_{timestamp}_{random}
try:
index = int(video_id.split('_')[1])
logging.info(f"Generated ID detected for HLS, using index: {index}")
# Get all videos and use the index
all_videos = movie_api.get_all_videos(email, password, limit=1000)
if index < 0 or index >= len(all_videos):
return jsonify({'error': f'Video index {index} out of range'}), 404
target_video = all_videos[index]
logging.info(f"Found video by index for HLS: {target_video.get('title', '')}")
except (ValueError, IndexError) as e:
logging.error(f"Error parsing generated ID {video_id}: {e}")
return jsonify({'error': 'Invalid generated video ID'}), 400
else:
# Original ID - search by ID
all_videos = movie_api.get_all_videos(email, password, limit=1000)
target_video = None
for video in all_videos:
if video.get('id') == video_id:
target_video = video
break
if not target_video:
return jsonify({'error': 'Video not found'}), 404
video_url = target_video.get('video_url')
if not video_url:
return jsonify({'error': 'Video URL not available'}), 404
# Import requests here to avoid circular imports
import requests
# Get the HLS manifest
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://meocon.xyz/',
}
response = requests.get(video_url, headers=headers, verify=False)
if response.status_code != 200:
return jsonify({'error': f'Failed to fetch HLS manifest: {response.status_code}'}), 500
# Get the manifest content
manifest_content = response.text
# Replace segment URLs to use our FFmpeg proxy
base_url = video_url.rsplit('/', 1)[0] + '/'
proxy_base = f'/api/movies/ffmpeg-segment/{video_id}/'
# Replace segment URLs in the manifest
import re
# Function to properly replace segment URLs
def replace_segment_urls_in_manifest(manifest_content, proxy_base):
lines = manifest_content.split('\n')
modified_lines = []
for line in lines:
stripped_line = line.strip()
# Check if this line contains a segment URL (not a comment and contains segment extension)
if (stripped_line and
not stripped_line.startswith('#') and
(stripped_line.endswith('.ts') or stripped_line.endswith('.m4s') or stripped_line.endswith('.mp4'))):
# If it's an absolute URL, extract just the filename
if stripped_line.startswith('http'):
segment_name = stripped_line.split('/')[-1]
modified_line = proxy_base + segment_name
else:
# It's a relative URL, just prepend the proxy base
modified_line = proxy_base + stripped_line
logging.info(f"Replaced segment URL: {stripped_line} -> {modified_line}")
modified_lines.append(modified_line)
else:
# Keep the line as is
modified_lines.append(line)
return '\n'.join(modified_lines)
# Apply the replacement
manifest_content = replace_segment_urls_in_manifest(manifest_content, proxy_base)
# Also replace audio and subtitle URLs if they exist
manifest_content = re.sub(r'URI="([^"]+\.m3u8)"', r'URI="/api/movies/ffmpeg-hls-audio/' + video_id + r'/\1"', manifest_content)
# Replace subtitle URLs (VTT, SRT, ASS files)
manifest_content = re.sub(r'URI="([^"]+\.(vtt|srt|ass|ssa))"', r'URI="/api/movies/ffmpeg-subtitle/' + video_id + r'/\1"', manifest_content)
# Add debug logging for manifest content
logging.info(f"Original manifest length: {len(response.text)}")
logging.info(f"Modified manifest length: {len(manifest_content)}")
logging.info(f"Segment replacements made: {manifest_content.count(proxy_base)}")
# Log a sample of the modified manifest
lines = manifest_content.split('\n')
segment_lines = [line for line in lines if '.ts' in line or '.m4s' in line or '.mp4' in line]
if segment_lines:
logging.info(f"Sample segment lines: {segment_lines[:3]}")
# Add CORS headers for the manifest
return Response(
manifest_content,
content_type='application/vnd.apple.mpegurl',
headers={
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Range',
'Access-Control-Expose-Headers': 'Content-Length, Content-Range',
'Cache-Control': 'public, max-age=300',
}
)
except Exception as e:
logging.error(f"Error in FFmpeg HLS proxy for video {video_id}: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/movies/ffmpeg-segment/<video_id>/<segment>')
def ffmpeg_segment_proxy(video_id, segment):
"""Proxy HLS segments using FFmpeg"""
try:
logging.info(f"FFmpeg segment proxy request for video_id: '{video_id}', segment: '{segment}'")
# Get the original video URL to construct segment URL
email = request.args.get('email')
password = request.args.get('password')
# Check if it's a generated ID (starts with 'movie_')
if video_id.startswith('movie_'):
# Extract index from generated ID: movie_{index}_{timestamp}_{random}
try:
index = int(video_id.split('_')[1])
logging.info(f"Generated ID detected for segment, using index: {index}")
# Get all videos and use the index
all_videos = movie_api.get_all_videos(email, password, limit=1000)
if index < 0 or index >= len(all_videos):
return jsonify({'error': f'Video index {index} out of range'}), 404
target_video = all_videos[index]
logging.info(f"Found video by index for segment: {target_video.get('title', '')}")
except (ValueError, IndexError) as e:
logging.error(f"Error parsing generated ID {video_id}: {e}")
return jsonify({'error': 'Invalid generated video ID'}), 400
else:
# Original ID - search by ID
all_videos = movie_api.get_all_videos(email, password, limit=1000)
target_video = None
for video in all_videos:
if video.get('id') == video_id:
target_video = video
break
if not target_video:
return jsonify({'error': 'Video not found'}), 404
video_url = target_video.get('video_url')
if not video_url:
return jsonify({'error': 'Video URL not available'}), 404
# Try multiple base URL strategies
possible_base_urls = []
# Strategy 1: Use the same directory as the manifest
base_url = video_url.rsplit('/', 1)[0] + '/'
possible_base_urls.append(base_url)
# Strategy 2: Try parent directory
if '/' in base_url.rstrip('/'):
parent_base = base_url.rstrip('/').rsplit('/', 1)[0] + '/'
possible_base_urls.append(parent_base)
# Strategy 3: Try common HLS directory patterns
common_patterns = ['segments/', 'chunks/', 'fragments/', 'ts/', 'hls/']
for pattern in common_patterns:
possible_base_urls.append(base_url + pattern)
# Strategy 4: Try removing common prefixes from segment name
segment_variations = [segment]
if segment.startswith('segment_'):
segment_variations.append(segment[8:]) # Remove 'segment_' prefix
if segment.startswith('chunk_'):
segment_variations.append(segment[6:]) # Remove 'chunk_' prefix
# Strategy 5: Try different segment naming patterns
# If segment is like "0_1.ts", try "segment_0_1.ts", "chunk_0_1.ts", etc.
if '_' in segment and segment.endswith('.ts'):
base_name = segment.replace('.ts', '')
parts = base_name.split('_')
if len(parts) >= 2:
# Try different naming patterns
segment_variations.extend([
f"segment_{base_name}.ts",
f"chunk_{base_name}.ts",
f"fragment_{base_name}.ts",
f"{parts[0]}_{parts[1]}.ts", # Keep original
f"{parts[1]}_{parts[0]}.ts", # Reverse order
])
# Import requests here to avoid circular imports
import requests
# Get the segment
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://meocon.xyz/',
}
response = None
successful_url = None
# Try each possible base URL and segment variation
for base_url in possible_base_urls:
for segment_var in segment_variations:
segment_url = base_url + segment_var
logging.info(f"Trying segment URL: {segment_url}")
try:
response = requests.get(segment_url, headers=headers, stream=True, verify=False, timeout=10)
if response.status_code == 200:
successful_url = segment_url
logging.info(f"Successfully found segment at: {successful_url}")
break
except Exception as e:
logging.warning(f"Failed to fetch segment from {segment_url}: {e}")
continue
if successful_url:
break
if not response or response.status_code != 200:
# If all strategies failed, try the original approach
segment_url = video_url.rsplit('/', 1)[0] + '/' + segment
logging.info(f"Trying fallback segment URL: {segment_url}")
try:
response = requests.get(segment_url, headers=headers, stream=True, verify=False, timeout=10)
successful_url = segment_url
except Exception as e:
logging.error(f"Failed to fetch segment from fallback URL: {e}")
return jsonify({'error': f'Failed to fetch segment: {segment}'}), 500
if response.status_code != 200:
return jsonify({'error': f'Failed to fetch segment: {response.status_code}'}), 500
# Check if response has content
content_length = response.headers.get('content-length', '0')