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
|
import datetime
from difflib import SequenceMatcher
from functools import lru_cache
import json
import re
import redis
import os
import dotenv
import requests
from user_profile.models import UserHistory
from watch.tmdbmapper import get_anime_episodes as gae, get_tv_episode_group_details
dotenv.load_dotenv()
r = redis.Redis(
host=os.getenv("REDIS_HOST"),
port=os.getenv("REDIS_PORT"),
password=os.getenv("REDIS_PASSWORD"),
)
# r.flushall()
# print("Redis cache flushed")
def get_episode_metadata(anime_data, episode):
episode_metadata = get_all_episode_metadata(anime_data)
current_episode_metadata = episode_metadata[episode - 1] if len(episode_metadata) >= episode else None
return current_episode_metadata
@lru_cache(maxsize=100)
def get_anime_data(anime_id, provider="gogo", dub=False):
if provider == "gogo":
provider = "gogoanime"
print(f"Fetching anime data: ID={anime_id}, provider={provider}, initial dub={dub}")
sub_cache_key = f"anime_{anime_id}_anime_data_{provider}_sub"
dub_cache_key = f"anime_{anime_id}_anime_data_{provider}_dub"
sub_dub_cache_key = f"anime_{anime_id}_anime_data_{provider}_sub_dub_count"
if not dub:
anime_data = get_from_redis_cache(sub_cache_key)
else:
anime_data = get_from_redis_cache(dub_cache_key)
if not anime_data:
sub_dub_count = {
"sub": 0,
"dub": 0
}
base_url = f"{os.getenv('CONSUMET_URL')}/meta/anilist/info/{anime_id}?provider={provider}"
print(f"Trying URL: {base_url}")
response = requests.get(base_url, timeout=10)
sub_data = response.json()
if "message" in sub_data:
return get_anime_data(anime_id)
if "status" in sub_data and sub_data["status"] == "Completed":
store_in_redis_cache(sub_cache_key, json.dumps(sub_data), 3600 * 24 * 30)
else:
store_in_redis_cache(sub_cache_key, json.dumps(sub_data), 3600 * 12)
sub_dub_count["sub"] = len(sub_data["episodes"]) if "episodes" in sub_data else 0
base_url = f"{os.getenv('CONSUMET_URL')}/meta/anilist/info/{anime_id}?provider={provider}&dub=true"
print(f"Trying URL: {base_url}")
response = requests.get(base_url, timeout=10)
dub_data = response.json()
if "status" in dub_data and dub_data["status"] == "Completed":
store_in_redis_cache(dub_cache_key, json.dumps(dub_data), 3600 * 24 * 30)
else:
store_in_redis_cache(dub_cache_key, json.dumps(dub_data), 3600 * 12)
sub_dub_count["dub"] = len(dub_data["episodes"]) if "episodes" in dub_data else 0
if not dub:
anime_data = sub_data
else:
anime_data = dub_data
if "status" in anime_data and anime_data["status"] == "Completed":
store_in_redis_cache(sub_dub_cache_key, json.dumps(sub_dub_count), 3600 * 24 * 30)
else:
store_in_redis_cache(sub_dub_cache_key, json.dumps(sub_dub_count), 3600 * 12)
anime_data["subDubCount"] = sub_dub_count
else:
anime_data = json.loads(anime_data)
anime_data["subDubCount"] = json.loads(get_from_redis_cache(sub_dub_cache_key))
episodes = anime_data["episodes"] if "episodes" in anime_data else []
for i, episode in enumerate(episodes, start=1):
episode["number"] = i
anime_data["episodes"] = episodes
return anime_data
def find_zoro_server (episode_id, mode):
base_url = f"{os.getenv('ZORO_URL')}/anime/servers?episodeId={episode_id}"
print(base_url)
response = requests.get(base_url)
response = response.json()
if "message" in response:
return None, mode
if mode == "dub" and "dub" in response and len(response["dub"]) > 0:
server_id = response["dub"][0]["serverName"]
mode = "dub"
elif len(response["sub"]) > 0 and "sub" in response:
server_id = response["sub"][0]["serverName"]
mode = "sub"
elif len(response["raw"]) > 0:
server_id = response["raw"][0]["serverName"]
mode = "raw"
return server_id, mode
@lru_cache(maxsize=100)
def get_zoro_episode_streaming_data(episode_url, dub=False):
episode_url = episode_url.split("watch/")[1]
cache_key = f"zoro_episode_streaming_data_{episode_url}_{'dub' if dub else 'sub'}"
episode_data = get_from_redis_cache(cache_key)
category = "dub" if dub else "sub"
server, category = find_zoro_server(episode_url, category)
if not episode_data:
base_url = f"{os.getenv('ZORO_URL')}/anime/episode-srcs?id={episode_url}&category={category}&server={server}"
print(f"Trying URL: {base_url}")
response = requests.get(base_url, timeout=10)
episode_data = response.json()
if "message" not in episode_data:
store_in_redis_cache(cache_key, json.dumps(episode_data), 3600 * 12)
else:
episode_data = json.loads(episode_data)
return episode_data
@lru_cache(maxsize=100)
def get_gogo_episode_streaming_data(episode_id):
cache_key = f"gogo_episode_streaming_data_{episode_id}"
episode_data = get_from_redis_cache(cache_key)
if not episode_data:
base_url = f"{os.getenv('CONSUMET_URL')}/meta/anilist/watch/{episode_id}"
print(f"Trying URL: {base_url}")
response = requests.get(base_url, timeout=10)
episode_data = response.json()
store_in_redis_cache(cache_key, json.dumps(episode_data), 3600 * 12)
else:
episode_data = json.loads(episode_data)
return convert_gogo_stream_data(episode_data)
def convert_gogo_stream_data(input_data):
# Create the new structure
new_data = {
'tracks': [],
'intro': {'start': 0, 'end': 0},
'outro': {'start': 0, 'end': 0},
'sources': [],
'anilistID': 0,
'malID': 0
}
# Add the default stream to sources
default_source = next((s for s in input_data['sources'] if s['quality'] == 'default'), None)
if default_source:
new_data['sources'].append({
'url': default_source['url'],
'type': 'hls'
})
return new_data
def fetch_anime_seasons(anime_id):
url = 'https://graphql.anilist.co'
query = '''
query ($id: Int) {
Media(id: $id, type: ANIME) {
id
title {
romaji
english
native
userPreferred
}
format
episodes
startDate {
year
}
coverImage {
large
medium
}
bannerImage
relations {
edges {
relationType(version: 2)
node {
... on Media {
id
title {
romaji
english
native
userPreferred
}
format
episodes
startDate {
year
}
coverImage {
large
medium
}
bannerImage
relations {
edges {
relationType(version: 2)
node {
... on Media {
id
title {
romaji
english
native
userPreferred
}
format
episodes
startDate {
year
}
coverImage {
large
medium
}
bannerImage
}
}
}
}
}
}
}
}
}
}
'''
variables = {'id': anime_id}
response = requests.post(url, json={'query': query, 'variables': variables})
return response.json()
def extract_seasons(data):
seasons = {}
main_media = data['data']['Media']
main_title = main_media['title']['english'] or main_media['title']['romaji']
def similarity(a, b):
return SequenceMatcher(None, a, b).ratio()
def clean_title(title):
return re.sub(r'[^\w\s]', '', title.lower())
def is_related_content(title, main_title):
clean_main = clean_title(main_title)
clean_title_check = clean_title(title)
return (similarity(clean_main, clean_title_check) > 0.6 or
clean_main in clean_title_check or
'season' in clean_title_check)
def add_content(media, depth=0):
if media['id'] in seasons:
return
english_title = media['title']['english'] or ''
romaji_title = media['title']['romaji'] or ''
if depth == 0 or is_related_content(english_title, main_title) or is_related_content(romaji_title, main_title):
seasons[media['id']] = {
'id': media['id'],
'title': media['title'],
'format': media['format'],
'episodes': media['episodes'],
'startYear': media['startDate']['year'] if media['startDate']['year'] else 9999,
'coverImage': media['coverImage']['large'] if media['coverImage'] else None,
'bannerImage': media['bannerImage']
}
if 'relations' in media:
process_relations(media['relations'], depth + 1)
def process_relations(relations, depth):
for edge in relations['edges']:
if edge['relationType'] in ['SEQUEL', 'PREQUEL', 'ALTERNATIVE', 'PARENT', 'SIDE_STORY'] and edge['node']['format'] in ['TV', 'TV_SHORT', 'MOVIE', 'SPECIAL', 'OVA']:
add_content(edge['node'], depth)
# Start with the main media
add_content(main_media)
# Sort the seasons
sorted_seasons = sorted(seasons.values(), key=lambda x: (x['startYear'], x['id']))
return sorted_seasons
def get_anime_seasons(anime_id):
cache_key = f"anime_{anime_id}_seasons"
fetched_data = get_from_redis_cache(cache_key)
if not fetched_data:
fetched_data = fetch_anime_seasons(anime_id)
seasons = extract_seasons(fetched_data)
store_in_redis_cache(cache_key, json.dumps(seasons), 3600 * 12)
else:
seasons = json.loads(fetched_data)
return seasons
def attach_episode_metadata(anime_data, anime_episodes):
anime_episodes_metadata = get_all_episode_metadata(anime_data)
if anime_episodes_metadata:
for i, episode in enumerate(anime_episodes):
if i < len(anime_episodes_metadata):
episode["metadata"] = anime_episodes_metadata[i]
else:
episode["metadata"] = None
return anime_episodes
def get_info_by_zid(zid):
cache_key = f"anime_{zid}_anime_selected"
print(cache_key)
try:
anime_selected = get_from_redis_cache(cache_key)
anime_selected = json.loads(anime_selected)
except:
base_url = f"{os.getenv('ZORO_URL')}/anime/info?id={zid}"
response = requests.get(base_url)
anime_selected = response.json()
if "message" not in anime_selected:
store_in_redis_cache(cache_key, json.dumps(anime_selected), 3600 * 12)
return anime_selected
def get_seasons_by_zid(zid):
if not zid:
return []
fetched_info = get_info_by_zid(zid)
seasons = fetched_info["seasons"] if "seasons" in fetched_info else []
for season in seasons:
season["poster"] = season["poster"].replace("100x200/100", "400x800/100")
return seasons
def get_episodes_by_zid(z_anime_id):
cache_key = f"anime_{z_anime_id}_episodes"
try:
fetched_episodes = get_from_redis_cache(cache_key)
fetched_episodes = json.loads(fetched_episodes)
except:
base_url = f"{os.getenv('ZORO_URL')}/anime/episodes/{z_anime_id}"
response = requests.get(base_url)
fetched_episodes = response.json()
store_in_redis_cache(cache_key, json.dumps(fetched_episodes), 3600 * 12)
return fetched_episodes
def get_all_episode_metadata(anime_data):
special_case = False
special_cases = {
"Clannad": "5de8c6127646fd00139b883d",
"Clannad: After Story": "5de8c6bda313b80012935f55"
}
if anime_data["title"]["english"] in special_cases:
special_case = True
episode_metadata = get_from_redis_cache(f"anime_{anime_data['id']}_episode_metadata")
if episode_metadata:
episode_metadata = json.loads(episode_metadata)
else:
if not special_case:
episode_metadata = gae(anime_data)
else:
group_id = special_cases[anime_data["title"]["english"]]
episode_metadata = get_tv_episode_group_details(group_id)
store_in_redis_cache(f"anime_{anime_data['id']}_episode_metadata", json.dumps(episode_metadata))
# Special cases
if anime_data["title"]["english"] == "Attack on Titan Final Season THE FINAL CHAPTERS Special 1":
episode_metadata.insert(0, episode_metadata[0])
return episode_metadata
def update_anime_user_history(user, anime, episode, time_watched, additional_data=None):
# per episode history
history, created = UserHistory.objects.get_or_create(user=user, anime=anime, episode=episode)
history.time_watched = time_watched
# last watched
last_watched = UserHistory.objects.filter(user=user, anime=anime, last_watched=True)
if last_watched:
last_watched = last_watched[0]
last_watched.last_watched = False
last_watched.save()
history.last_watched = True
history.last_updated = datetime.datetime.now()
if additional_data:
if "anime_title_english" in additional_data:
history.anime_title_english = additional_data["anime_title_english"]
else:
history.anime_title_english = ""
if "anime_title_romaji" in additional_data:
history.anime_title_romaji = additional_data["anime_title_romaji"]
else:
history.anime_title_romaji = ""
if "anime_title_native" in additional_data:
history.anime_title_native = additional_data["anime_title_native"]
else:
history.anime_title_native = ""
if "anime_cover_image" in additional_data:
history.anime_cover_image = additional_data["anime_cover_image"]
else:
history.anime_cover_image = ""
if "episode_title" in additional_data:
history.episode_title = additional_data["episode_title"]
else:
history.episode_title = ""
history.save()
def get_anime_user_history(user, anime):
history = UserHistory.objects.filter(user=user, anime=anime)
return history
def store_in_redis_cache(anime_id, data, cache_time=60*60*12):
try:
print("Storing in cache=>", anime_id)
r.set(anime_id, data, ex=cache_time) # 1 hour
except Exception as e:
print(e)
pass
def get_from_redis_cache(anime_id):
data = r.get(anime_id)
return data if data else None
|