-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.py
740 lines (595 loc) · 31.6 KB
/
Controller.py
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
import io, time, m3u8, os
import webbrowser
import threading
import logging
import requests
from datetime import datetime, timedelta
from urllib.parse import urlparse
from flask import Flask, Response, request, session, redirect, url_for, stream_with_context, jsonify, render_template, g
from flask_caching import Cache
from flask_session import Session
from werkzeug.serving import make_server
from MalAuthenticator import TokenGenerator, TokenLoader
from MalRequester import Requester
from AnimeScrape.VideoDownloader import VideoDownloader
from AnimeScrape.AnimeScraper import AnimeScraper
class AnimeController:
logging.basicConfig(level=logging.info)
def __init__(self):
self.scraper = AnimeScraper()
self.downloader = VideoDownloader()
self.server = None
self.app = Flask(__name__, template_folder='templates', static_folder='webapp/static')
self.token_path = 'src/tokens.json'
# Configure session
self.app.secret_key = '3a4d8f5b6c9e827a0b9d7c8f3e5d1f8a2b4c6d8e9f7b3a1d5e7f9c0b8a1d2c3'
self.app.config['SESSION_TYPE'] = 'filesystem'
self.app.config['SESSION_FILE_DIR'] = 'flask_session/'
self.app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=100)
Session(self.app)
self.requesters = {} # Store Requester objects per user
self.cache = Cache(self.app, config={
'CACHE_TYPE': 'redis',
'CACHE_REDIS_HOST': 'localhost',
'CACHE_REDIS_PORT': 6379,
'CACHE_DEFAULT_TIMEOUT': 300
})
self.http_session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=6,
pool_connections=100,
pool_maxsize=100,
)
self.http_session.mount('http://', adapter)
self.http_session.mount('https://', adapter)
# Initialize in-memory cache for m3u8 playlists
self.playlist_cache = {} # Key: m3u8_url, Value: (playlist_content, timestamp)
self.cache_timeout = 300 # 5 minutes
self.build_flask()
threading.Thread(target=self.run_flask).start()
def watch_anime(self, mal_anime_id, episode_number):
"""
Optimized endpoint to handle anime watching requests.
"""
try:
resolution = request.args.get('resolution')
if not resolution:
return jsonify({'error': 'Resolution parameter is missing.'}), 400
# Attempt to retrieve the m3u8 link from cache
cache_key = f"m3u8_{mal_anime_id}_{episode_number}_{resolution}"
cached_playlist = self.get_cached_playlist(cache_key)
if cached_playlist:
logging.info(f"Serving cached m3u8 for Anime ID {mal_anime_id}, Episode {episode_number}, Resolution {resolution}")
return Response(cached_playlist, mimetype='application/vnd.apple.mpegurl')
# Fetch or scrape the m3u8 link
video_source_url = self.get_video_source_url(mal_anime_id, episode_number)
if not video_source_url:
return jsonify({'error': 'Video source URL not found.'}), 404
# Fetch the m3u8 URL for the specified resolution
m3u8_url = self.downloader.get_m3u8_url_by_resolution(video_source_url, resolution)
if not m3u8_url:
return jsonify({'error': 'Specified resolution not available.'}), 404
# Fetch and modify the m3u8 content
m3u8_content = self.get_m3u8_content(m3u8_url)
if not m3u8_content:
return jsonify({'error': 'Failed to retrieve m3u8 content.'}), 500
modified_m3u8_content = self.downloader.modify_m3u8_content(m3u8_content, m3u8_url)
# Cache the modified m3u8 content
self.set_cached_playlist(cache_key, modified_m3u8_content)
# Return the modified m3u8 playlist
return Response(modified_m3u8_content, mimetype='application/vnd.apple.mpegurl')
except ValueError as ve:
logging.error(f"Resolution error: {ve}")
return jsonify({'error': str(ve)}), 400
except Exception as e:
logging.error(f"Error serving anime: {e}", exc_info=True)
return jsonify({'error': 'Internal Server Error'}), 500
def proxy_ts_segment(self, segment_url):
"""
Efficiently proxies the .ts segment to the client using generator for streaming.
"""
try:
# Validate URL
parsed_url = urlparse(segment_url)
if parsed_url.scheme not in ('http', 'https'):
logging.error(f"Invalid URL scheme for segment: {segment_url}")
return "Invalid segment URL.", 400
# Fetch the .ts segment using the HTTP session
req = self.http_session.get(segment_url, headers={}, stream=True, timeout=10)
if req.status_code != 200:
logging.error(f"Failed to fetch segment: {segment_url}, Status Code: {req.status_code}")
return f"Failed to fetch segment.", 500
# Stream the content to the client directly without stream_with_context
return Response(
req.iter_content(chunk_size=8192),
content_type=req.headers.get('Content-Type', 'application/octet-stream'),
headers={
'Content-Disposition': f'inline; filename="{os.path.basename(parsed_url.path)}"',
'Cache-Control': 'public, max-age=300'
}
)
except requests.exceptions.Timeout:
logging.error(f"Timeout while fetching segment: {segment_url}")
return "Request timed out while fetching the segment.", 504
except requests.exceptions.RequestException as e:
logging.error(f"Request exception for segment {segment_url}: {e}", exc_info=True)
return "An error occurred while fetching the segment.", 500
except Exception as e:
logging.error(f"Unexpected error proxying segment {segment_url}: {e}", exc_info=True)
return "Internal Server Error.", 500
def get_video_source_url(self, mal_anime_id, episode_number):
"""
Retrieves the video source URL, either from saved JSON or by scraping.
"""
# Attempt to get the saved m3u8 link
saved_m3u8_link = self.downloader.get_m3u8_from_json(mal_anime_id, episode_number)
if saved_m3u8_link:
return saved_m3u8_link
# Scrape to obtain the m3u8 link
logging.info(f"Scraping Anime ID {mal_anime_id}, Episode {episode_number} for m3u8 link.")
anime_id, anime_name = self.scraper.get_anilist_id_from_mal(mal_anime_id)
if not anime_id or not anime_name:
logging.error(f"Failed to retrieve AniList ID or Anime Name for MAL ID {mal_anime_id}.")
return None
m3u8_link = self.scraper.get_video_source_url_selenium(anime_id, episode_number)
if not m3u8_link:
logging.error(f"Video source URL not found for MAL ID {mal_anime_id}, Episode {episode_number}")
return None
# Validate the scraped episode number
actual_ep = self.scraper.extract_episode_from_video_url(m3u8_link)
if int(actual_ep) != int(episode_number):
logging.warning(f"Found Episode {actual_ep} instead of requested Episode {episode_number} for MAL ID {mal_anime_id}")
return None
# Save the m3u8 link for future requests
self.downloader.save_m3u8_to_json(mal_anime_id, episode_number, m3u8_link)
return m3u8_link
def get_m3u8_content(self, m3u8_url):
"""
Retrieves and caches the m3u8 content.
"""
try:
# Check if the playlist is cached
cached = self.playlist_cache.get(m3u8_url)
if cached:
playlist_content, timestamp = cached
if time.time() - timestamp < self.cache_timeout:
logging.info(f"Serving cached m3u8 content for URL: {m3u8_url}")
return playlist_content
# Fetch the m3u8 content
logging.info(f"Fetching m3u8 content from URL: {m3u8_url}")
response = self.http_session.get(m3u8_url, timeout=10)
if response.status_code != 200:
logging.error(f"Failed to fetch m3u8 from {m3u8_url}, Status Code: {response.status_code}")
return None
playlist_content = response.text
# Update the cache
self.playlist_cache[m3u8_url] = (playlist_content, time.time())
return playlist_content
except requests.exceptions.Timeout:
logging.error(f"Timeout while fetching m3u8 content from {m3u8_url}")
return None
except requests.exceptions.RequestException as e:
logging.error(f"Request exception while fetching m3u8 content from {m3u8_url}: {e}", exc_info=True)
return None
except Exception as e:
logging.error(f"Unexpected error fetching m3u8 content from {m3u8_url}: {e}", exc_info=True)
return None
def get_cached_playlist(self, cache_key):
"""
Retrieves a cached playlist if available and not expired.
"""
cached = self.playlist_cache.get(cache_key)
if cached:
playlist_content, timestamp = cached
if time.time() - timestamp < self.cache_timeout:
return playlist_content
else:
# Cache expired
del self.playlist_cache[cache_key]
return None
def set_cached_playlist(self, cache_key, playlist_content):
"""
Caches the playlist content with the current timestamp.
"""
self.playlist_cache[cache_key] = (playlist_content, time.time())
def build_flask(self):
@self.app.before_request
def load_requester():
if 'user_id' in session:
user_id = session['user_id']
g.user_id = user_id
g.requester = self.requesters.get(user_id)
else:
g.user_id = None
g.requester = None
@self.app.route('/')
def index():
if 'user_id' not in session:
session['user_id'] = os.urandom(8).hex()
user_id = session['user_id']
if 'tokens' not in session:
return redirect(url_for('login'))
tokens = session['tokens']
tokens_loader = TokenLoader()
tokens_loader.access_token = tokens['access_token']
tokens_loader.refresh_token = tokens['refresh_token']
tokens_loader.expires_at = tokens['expires_at']
tokens_loader.client_id = tokens['client_id']
tokens_loader.client_secret = tokens['client_secret']
if not tokens_loader.ensure_valid_tokens():
return redirect(url_for('login'))
# Update tokens in session
session['tokens']['access_token'] = tokens_loader.access_token
session['tokens']['refresh_token'] = tokens_loader.refresh_token
session['tokens']['expires_at'] = tokens_loader.expires_at
if user_id not in self.requesters:
requester = Requester(tokens_loader=tokens_loader)
self.requesters[user_id] = requester
else:
requester = self.requesters[user_id]
g.requester = requester
return render_template('index.html')
@self.app.route('/login')
def login():
# Step 1: Start the token generation flow
token_generator = TokenGenerator()
auth_url = token_generator.get_auth_url()
# Step 2: Redirect the user to the authorization URL
session['state'] = token_generator.state
session['code_verifier'] = token_generator.code_verifier
session['client_id'] = token_generator.client_id
session['client_secret'] = token_generator.client_secret
# Open the authorization URL in the user's browser
webbrowser.open(auth_url)
# Step 3: Wait for the token generator to complete (in a separate thread)
token = token_generator.run() # This will block until the token is generated
# Step 4: Once the token is obtained, store it in the session
if token:
session['tokens'] = {
'access_token': token['access_token'],
'refresh_token': token.get('refresh_token'),
'expires_at': datetime.now() + timedelta(seconds=token['expires_in']),
'client_id': token_generator.client_id,
'client_secret': token_generator.client_secret
}
logging.info(f"Session with token successfully esthablished. Details: {session['tokens']}")
return redirect(url_for('index'))
else:
return "Failed to log in.", 500
@self.app.route('/callback')
def callback():
error = request.args.get('error')
if error:
return f'Error: {error}', 400
state = request.args.get('state')
if state != session.get('state'):
return 'Invalid state parameter', 400
code = request.args.get('code')
if not code:
return 'Authorization failed.', 400
code_verifier = session.get('code_verifier')
client_id = session.get('client_id')
client_secret = session.get('client_secret')
token_generator = TokenGenerator(self.token_path)
token_generator.code_verifier = code_verifier
token_generator.client_id = client_id
token_generator.client_secret = client_secret
token = token_generator.get_token(code)
session['tokens'] = {
'access_token': token['access_token'],
'refresh_token': token.get('refresh_token'),
'expires_at': datetime.now() + timedelta(seconds=token['expires_in']),
'client_id': client_id,
'client_secret': client_secret
}
print('Clients token expires at:', datetime.now() + timedelta(seconds=token['expires_in']))
return redirect(url_for('index'))
@self.app.route('/api/save_playback_time', methods=['POST'])
def save_playback_time():
data = request.get_json()
malAnimeId = str(data.get('malAnimeId'))
episodeNumber = str(data.get('episodeNumber'))
currentTime = data.get('currentTime')
if not all([malAnimeId, episodeNumber, currentTime is not None]):
return jsonify({'error': 'Missing data fields.'}), 400
key = f"watched_{malAnimeId}_{episodeNumber}"
session[key] = currentTime
return jsonify({'message': 'Playback time saved.'}), 200
@self.app.route('/api/get_playback_time', methods=['GET'])
def get_playback_time():
malAnimeId = request.args.get('malAnimeId')
episodeNumber = request.args.get('episodeNumber')
if not all([malAnimeId, episodeNumber]):
return jsonify({'error': 'Missing query parameters.'}), 400
key = f"watched_{malAnimeId}_{episodeNumber}"
currentTime = session.get(key)
if currentTime is not None:
return jsonify({'currentTime': currentTime}), 200
else:
return jsonify({'currentTime': None}), 200
@self.app.route('/api/remove_playback_time', methods=['POST'])
def remove_playback_time():
data = request.get_json()
malAnimeId = str(data.get('malAnimeId'))
episodeNumber = str(data.get('episodeNumber'))
if not all([malAnimeId, episodeNumber]):
return jsonify({'error': 'Missing data fields.'}), 400
key = f"watched_{malAnimeId}_{episodeNumber}"
session.pop(key, None)
return jsonify({'message': 'Playback time removed.'}), 200
@self.app.route('/api/save_last_watched', methods=['POST'])
def save_last_watched():
data = request.get_json()
malAnimeId = str(data.get('malAnimeId'))
episodeNumber = data.get('episodeNumber')
if not all([malAnimeId, episodeNumber]):
return jsonify({'error': 'Missing data fields.'}), 400
key = f"last_watched_{malAnimeId}"
session[key] = {
'episodeNumber': episodeNumber,
'timestamp': int(time.time() * 1000) # Unix timestamp in milliseconds
}
return jsonify({'message': 'Last watched episode saved.'}), 200
@self.app.route('/api/get_last_watched', methods=['GET'])
def get_last_watched():
malAnimeId = request.args.get('malAnimeId')
if not malAnimeId:
return jsonify({'error': 'Missing malAnimeId parameter.'}), 400
key = f"last_watched_{malAnimeId}"
last_watched = session.get(key)
if last_watched:
return jsonify({'lastWatched': last_watched}), 200
else:
return jsonify({'lastWatched': None}), 200
@self.app.route('/api/clear_last_watched', methods=['POST']) #TODO: Implement in frontend when user decline 'resume last watched alert'.
def clear_last_watched():
data = request.get_json()
malAnimeId = str(data.get('malAnimeId'))
if not malAnimeId:
return jsonify({'error': 'Missing malAnimeId field.'}), 400
key = f"last_watched_{malAnimeId}"
session.pop(key, None)
return jsonify({'message': 'Last watched episode cleared.'}), 200
@self.app.route('/api/get_last_watched_all', methods=['GET'])
def get_last_watched_all():
"""
Retrieves all last watched episodes from the session.
"""
last_watched = {}
for key in session:
if key.startswith('last_watched_'):
malAnimeId = key.replace('last_watched_', '')
last_watched[malAnimeId] = session[key]
return jsonify({'lastWatched': last_watched}), 200
@self.app.route('/api/clear_all_last_watched', methods=['POST'])
def clear_all_last_watched():
"""
Deletes all 'last_watched' entries from the session.
"""
keys_to_remove = [key for key in session.keys() if key.startswith('last_watched_')]
for key in keys_to_remove:
session.pop(key, None)
return jsonify({'message': 'All last watched episodes cleared.'}), 200
@self.app.route('/api/get_episode_data/<int:mal_anime_id>/<int:episode_number>', methods=['GET'])
@self.cache.cached(timeout=600, key_prefix=lambda: f"episode_data_{request.view_args['mal_anime_id']}_{request.view_args['episode_number']}")
def get_episode_data(mal_anime_id, episode_number):
"""
Retrieves both available episodes and the next airing date for a specific anime and episode.
Parameters:
mal_anime_id (int): The MyAnimeList (MAL) ID of the anime.
episode_number (int): The episode number.
Returns:
JSON response containing 'availableEpisodes' and 'nextAiringDate'.
"""
try:
episode_data = self.scraper.get_episode_data(mal_anime_id)
available_episodes = episode_data.get('availableEpisodes', [])
next_airing_date = episode_data.get('nextAiringDate')
# Save available episodes to session
available_key = f"available_episodes_{mal_anime_id}"
session[available_key] = available_episodes
# Save next airing date to session
if next_airing_date:
airing_key = f"next_airing_{mal_anime_id}_{episode_number}"
session[airing_key] = next_airing_date # ISO format string
else:
airing_key = f"next_airing_{mal_anime_id}_{episode_number}"
session.pop(airing_key, None) # Remove if exists
return jsonify({
'availableEpisodes': available_episodes,
'nextAiringDate': next_airing_date
}), 200
except Exception as e:
logging.error(f"Error in get_episode_data API: {e}", exc_info=True)
return jsonify({'error': 'Internal Server Error'}), 500
from flask import jsonify, session
@self.app.route('/api/get_all_episode_data', methods=['GET'])
def get_all_episode_data():
"""
Retrieves all the session data stored by the controller function.
Returns:
JSON response containing all stored 'availableEpisodes' and 'nextAiringDate' data.
"""
try:
all_episode_data = {}
# Iterate over all session keys to find stored episodes and airing dates
for key in session.keys():
if key.startswith("available_episodes_"):
anime_id = key.split("_")[-1]
all_episode_data[f"available_episodes_{anime_id}"] = session[key]
elif key.startswith("next_airing_"):
anime_id_episode = "_".join(key.split("_")[2:])
all_episode_data[f"next_airing_{anime_id_episode}"] = session[key]
return jsonify(all_episode_data), 200
except Exception as e:
logging.error(f"Error in get_all_episode_data API: {e}", exc_info=True)
return jsonify({'error': 'Internal Server Error'}), 500
@self.app.route('/animes')
def animes():
requester = g.requester
if not requester:
return redirect(url_for('index'))
try:
anime_objs_json = {}
for anime in requester.anime_repo.get_all_animes():
anime_objs_json[anime.id] = anime.to_dict()
return jsonify(anime_objs_json)
except Exception as e:
logging.error(f"Error rendering template: {e}")
return str(e), 500
@self.app.route('/user_animes')
def user_animes():
requester = g.requester
if not requester:
return redirect(url_for('index'))
try:
return jsonify(requester.anime_repo.user_anime_list)
except Exception as e:
logging.error(f"Error rendering template: {e}")
return str(e), 500
@self.app.route('/refresh_user_list_status')
def refresh_user_list_status():
requester = g.requester
if not requester:
return redirect(url_for('index'))
try:
requester.get_user_anime_list() # TODO: RENAME REFRESH ANIME
return "SUCCESSFUL", 200
except Exception as e:
logging.error(f"Error rendering template: {e}")
return str(e), 500
@self.app.route('/lineage_data')
def lineage_data():
requester = g.requester
if not requester:
return redirect(url_for('index'))
try:
lineage = requester.anime_repo.generate_anime_seasons_liniage()
return jsonify(lineage)
except Exception as e:
logging.error(f"Error generating lineage data: {e}")
return str(e), 500
@self.app.route('/download_anime/<int:mal_anime_id>/<int:episode_number>')
def download_anime(mal_anime_id, episode_number):
try:
# Step 1: Retrieve Anime Information
anime_id, anime_name = self.scraper.get_anilist_id_from_mal(mal_anime_id)
video_source_url = self.scraper.get_video_source_url_selenium(anime_id, episode_number)
if not video_source_url:
logging.error(f"Video source URL not found for MAL ID {mal_anime_id}, Episode {episode_number}")
return "Video source URL not found", 404
logging.info(f"Initiating download for Anime ID: {anime_id}, Name: {anime_name}")
# Step 2: Download and Parse the .m3u8 Playlist with base_uri
playlist_response = self.http_session.get(video_source_url)
if playlist_response.status_code != 200:
logging.error(f"Failed to download m3u8 playlist from {video_source_url}, Status Code: {playlist_response.status_code}")
return "Failed to download video playlist", 500
playlist_content = playlist_response.text
logging.debug(f"M3U8 Playlist Content:\n{playlist_content}")
# Parse the playlist with base_uri set to video_source_url
playlist = m3u8.loads(playlist_content, uri=video_source_url)
logging.info(f"Parsed m3u8 playlist: {len(playlist.segments)} segments found")
# Initialize variables
total_size = 0
segment_urls = []
if playlist.is_variant:
logging.info("Playlist is a master playlist. Selecting the highest quality variant.")
# Sort variants by bandwidth in descending order and select the highest
variants = sorted(playlist.playlists, key=lambda p: p.stream_info.bandwidth, reverse=True)
selected_variant = variants[0] # Highest bandwidth
variant_url = selected_variant.absolute_uri
logging.info(f"Selected variant playlist URL: {variant_url}")
# Download the variant playlist
variant_response = self.http_session.get(variant_url)
if variant_response.status_code != 200:
logging.error(f"Failed to download variant playlist from {variant_url}, Status Code: {variant_response.status_code}")
return "Failed to download variant playlist", 500
variant_content = variant_response.text
logging.debug(f"Variant Playlist Content:\n{variant_content}")
# Parse the variant playlist with base_uri set to variant_url
variant_playlist = m3u8.loads(variant_content, uri=variant_url)
logging.info(f"Parsed variant playlist: {len(variant_playlist.segments)} segments found")
# Collect all segment URLs
for segment in variant_playlist.segments:
segment_urls.append(segment.absolute_uri)
else:
# It's a media playlist
logging.info("Playlist is a media playlist.")
for segment in playlist.segments:
segment_urls.append(segment.absolute_uri)
# Step 3: Calculate the total size by sending HEAD requests
logging.info("Calculating total download size by sending HEAD requests to each segment.")
for segment_url in segment_urls:
try:
head = requests.head(segment_url, allow_redirects=True)
if head.status_code == 200:
size = int(head.headers.get('Content-Length', 0))
total_size += size
else:
logging.warning(f"Failed to get Content-Length for {segment_url}, Status Code: {head.status_code}")
except Exception as e:
logging.warning(f"Error fetching HEAD for {segment_url}: {e}")
if total_size == 0:
logging.warning("Could not determine total size. Proceeding without Content-Length.")
content_length = None
else:
content_length = total_size
# Step 4: Define the generator
def generate():
for idx, segment_url in enumerate(segment_urls):
logging.info(f"Downloading segment {idx + 1}/{len(segment_urls)}: {segment_url}")
try:
segment_response = self.http_session.get(segment_url, stream=True)
if segment_response.status_code != 200:
logging.warning(f"Failed to download segment {segment_url}, Status Code: {segment_response.status_code}")
continue # Skip to the next segment
for chunk in segment_response.iter_content(chunk_size=8192):
if chunk:
yield chunk # Stream chunk to client
except Exception as e:
logging.warning(f"Error downloading segment {segment_url}: {e}")
continue # Skip to the next segment
# Step 5: Generate a Valid Filename
anime_name_clean = self.downloader.get_valid_filename(anime_name)
filename = f'{anime_name_clean}_episode_{episode_number}.ts'
# Step 6: Create the Streaming Response
headers = {
'Content-Disposition': f'attachment; filename="{filename}"',
'Content-Type': 'video/mp2t'
}
if content_length:
headers['Content-Length'] = str(content_length)
logging.info(f"Serving file {filename} to the client with Content-Length={content_length}")
return Response(
stream_with_context(generate()),
headers=headers,
mimetype='video/mp2t'
)
except Exception as e:
logging.error(f"Error serving Anime ID {mal_anime_id}, Episode {episode_number}: {e}", exc_info=True)
return "Internal Server Error", 500
@self.app.route('/watch_anime/<int:mal_anime_id>/<int:episode_number>')
def watch_anime_route(mal_anime_id, episode_number):
return self.watch_anime(mal_anime_id, episode_number)
@self.app.route('/api/get_available_resolutions/<int:mal_anime_id>/<int:episode_number>', methods=['GET'])
def get_available_resolutions(mal_anime_id, episode_number):
try:
m3u8_link = self.downloader.get_m3u8_from_json(mal_anime_id, episode_number)
if not m3u8_link:
return jsonify({"error": "M3U8 link not found"}), 404
resolutions = self.downloader.get_available_resolutions(m3u8_link)
return jsonify({"resolutions": resolutions}), 200
except Exception as e:
logging.error(f"Error fetching available resolutions: {e}")
return jsonify({"error": str(e)}), 500
@self.app.route('/ts_segment')
def ts_segment_route():
# URL of the .ts segment to fetch
segment_url = request.args.get('url')
if not segment_url:
return "Segment URL not provided", 400
# Stream the .ts segment to the client
return self.proxy_ts_segment(segment_url)
def run_flask(self):
self.server = make_server('0.0.0.0', 5000, self.app)
self.server.serve_forever()