Commit 10723194b0

10723194b0c4c38676cc9775cae98d2600c5179c

parent: 522795f304

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-16 18:01 UTC

init

Layout: unified · split

curd.py deleted −1646
@@ -1,1646 +0,0 @@
1#!/bin/python3
2# if you are trying to read this code, god help you.
3# this is how my implementation of the ani-cli code to get the anime works
4
5# search (anime_list.sh) -> tmp/anime_list
6# anime_id -> episode_list.sh
7# episode_number -> episdoe_url.sh -> tmp/links
8
9from pathlib import Path
10import re
11import os
12import json
13import random
14import subprocess
15import time
16import curses
17import argparse
18import traceback
19import requests
20import csv
21import math
22import socket
23import urllib.parse
24# pypresence is also imported later if user enabled it in the config
25
26discord_client_id = "1287457464148820089"
27
28
29# ----------------------------------------------- Jikan Functions ----------------------------------------
30
31def get_episode_data(anime_id: int, episode_no: int):
32 url = f"https://api.jikan.moe/v4/anime/{anime_id}/episodes/{episode_no}"
33 try:
34 response = requests.get(url)
35 response.raise_for_status()
36 json_data = json.loads(response.text)
37 return json_data['data']
38 except requests.RequestException as e:
39 print(f"Error fetching data from Jikan (MyAnimeList) API: {e}")
40 return None
41 except Exception as e:
42 print(f"Error: ", e)
43 return None
44
45# response.text : {
46# "data": {
47# "mal_id": 0,
48# "url": "string",
49# "title": "string",
50# "title_japanese": "string",
51# "title_romanji": "string",
52# "duration": 0,
53# "aired": "string",
54# "filler": true,
55# "recap": true,
56# "synopsis": "string"
57# }
58# }
59
60# response = get_episode_data(21, 5)
61# print(response['title'])
62# exit(0)
63# ----------------------------------------------- AniSkip Functions ----------------------------------------
64
65def get_aniskip_data(anime_id, episode):
66 base_url = "https://api.aniskip.com/v1/skip-times"
67 url = f"{base_url}/{anime_id}/{episode}?types=op&types=ed"
68
69 try:
70 response = requests.get(url)
71 response.raise_for_status() # Raise an exception for bad status codes
72 return response.text
73 except KeyboardInterrupt:
74 print("bye")
75 exit(0)
76 except requests.RequestException as e:
77 print(f"Error fetching data from AniSkip API: {e}")
78 return None
79
80def round_time(time_value, precision=0):
81 """
82 Round a time value to a specified precision.
83 precision=0 rounds to the nearest second.
84 precision=1 rounds to the nearest tenth of a second, etc.
85 """
86 multiplier = 10 ** precision
87 return math.floor(time_value * multiplier + 0.5) / multiplier
88
89def parse_aniskip_response(response_text, time_precision=1):
90 if response_text is None:
91 return None
92
93 data = json.loads(response_text)
94
95 if not data['found']:
96 return None
97
98 skip_intervals = {}
99 op = data['results'][0]['interval']
100 # print(op)
101 skip_intervals['op'] = {'start_time': round_time(op['start_time'], time_precision),
102 'end_time': round_time(op['end_time'], time_precision),
103 }
104 ed = data['results'][-1]['interval']
105 skip_intervals['ed'] = {'start_time': round_time(ed['start_time'], time_precision),
106 'end_time': round_time(ed['end_time'], time_precision),
107 }
108
109 return skip_intervals
110
111def get_and_parse_aniskip_data(anime_id, episode, time_precision=1):
112 response_text = get_aniskip_data(anime_id, episode)
113 return parse_aniskip_response(response_text, time_precision)
114
115# Example usage
116# anime_id = 28223
117# episode = 10
118
119# skip_intervals = get_and_parse_aniskip_data(anime_id, episode)
120
121# print(skip_intervals)
122
123# exit(0)
124
125# if skip_intervals:
126# for interval in skip_intervals:
127# print(f"{interval['skip_type'].upper()} - Start: {interval['start_time']:.2f}, End: {interval['end_time']:.2f}")
128# else:
129# print("No skip intervals found.")
130
131
132# ----------------------------------------------- AniList Functions ----------------------------------------
133
134def search_anime_anilist(query, token):
135 url = "https://graphql.anilist.co"
136
137 query_string = '''
138 query ($search: String) {
139 Page(page: 1, perPage: 10) {
140 media(search: $search, type: ANIME) {
141 id
142 title {
143 romaji
144 english
145 native
146 }
147 }
148 }
149 }
150 '''
151
152 variables = {
153 'search': query
154 }
155
156 headers = {
157 'Authorization': f'Bearer {token}',
158 'Content-Type': 'application/json'
159 }
160 try:
161 response = requests.post(url, json={'query': query_string, 'variables': variables}, headers=headers)
162 except KeyboardInterrupt:
163 print("bye")
164 exit(0)
165
166 if response.status_code == 200:
167 anime_list = response.json()['data']['Page']['media']
168 anime_dict = {}
169 for anime in anime_list:
170 if anime['title']['english']==None:
171 anime_dict[anime['title']['romaji']] = anime['id']
172 else:
173 anime_dict[anime['title']['english']] = anime['id']
174
175 return anime_dict
176 else:
177 print(f"Failed to search for anime. Status Code: {response.status_code}, Response: {response.text}")
178 return {}
179
180def get_anilist_user_id(token):
181 url = "https://graphql.anilist.co"
182 query = '''
183 query {
184 Viewer {
185 id
186 name
187 }
188 }
189 '''
190
191 headers = {
192 "Authorization": f"Bearer {token}",
193 "Content-Type": "application/json",
194 "Accept": "application/json"
195 }
196 try:
197 response = requests.post(url, json={"query": query}, headers=headers)
198 except KeyboardInterrupt:
199 print("bye")
200 exit(0)
201
202 if response.status_code == 200:
203 data = response.json()
204 user_id = data['data']['Viewer']['id']
205 user_name = data['data']['Viewer']['name']
206 return user_id, user_name
207 else:
208 raise Exception(f"Error: {response.status_code}, {response.text}")
209
210def add_anime_to_watching_list(anime_id: int, token: str):
211 url = "https://graphql.anilist.co"
212
213 mutation = '''
214 mutation ($mediaId: Int) {
215 SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
216 id
217 status
218 }
219 }
220 '''
221
222 variables = {
223 'mediaId': anime_id
224 }
225
226 headers = {
227 'Authorization': f'Bearer {token}',
228 'Content-Type': 'application/json'
229 }
230 try:
231 response = requests.post(url, json={'query': mutation, 'variables': variables}, headers=headers)
232 except KeyboardInterrupt:
233 print("bye")
234 exit(0)
235
236 if response.status_code == 200:
237 print(f"Anime with ID {anime_id} has been added to your watching list.")
238 else:
239 print(f"Failed to add anime. Status Code: {response.status_code}, Response: {response.text}")
240
241def get_anime_mal_id(anilist_media_id):
242 url = "https://graphql.anilist.co"
243 query = '''
244 query ($id: Int) {
245 Media(id: $id) {
246 idMal
247 }
248 }
249 '''
250 variables = {
251 'id': anilist_media_id
252 }
253
254 # Make the API request
255 try:
256 response = requests.post(url, json={'query': query, 'variables': variables})
257 except KeyboardInterrupt:
258 print("bye")
259 exit(0)
260
261 if response.status_code == 200:
262 data = response.json()
263 malId = data['data']['Media']['idMal']
264 return malId
265 else:
266 raise Exception(f"Failed to retrieve data from AniList API. Status Code: {response.status_code}")
267
268def get_anime_id_and_image(anilist_media_id):
269 url = "https://graphql.anilist.co"
270 query = '''
271 query ($id: Int) {
272 Media(id: $id) {
273 coverImage {
274 large
275 }
276 idMal
277 }
278 }
279 '''
280 variables = {
281 'id': anilist_media_id
282 }
283
284 # Make the API request
285 try:
286 response = requests.post(url, json={'query': query, 'variables': variables})
287 except KeyboardInterrupt:
288 print("bye")
289 exit(0)
290 if response.status_code == 200:
291 data = response.json()
292 image_url = data['data']['Media']['coverImage']['large']
293 malId = data['data']['Media']['idMal']
294 return malId, image_url
295 else:
296 raise Exception(f"Failed to retrieve data from AniList API. Status Code: {response.status_code}")
297
298def get_user_data(access_token, user_id):
299 query = """
300 {
301 MediaListCollection(userId: %s, type: ANIME) {
302 lists {
303 entries {
304 media {
305 id
306 episodes
307 duration
308 title {
309 romaji
310 english
311 }
312 }
313 status
314 score
315 progress
316 }
317 }
318 }
319 }
320 """ % user_id
321
322 # Send the request
323 try:
324 response = requests.post(
325 'https://graphql.anilist.co',
326 json={'query': query},
327 headers={'Authorization': f'Bearer {access_token}'}
328 )
329 except KeyboardInterrupt:
330 print("bye")
331 exit(0)
332
333
334 # Print the response
335 return response.json()
336
337def load_json_file(file_path):
338 with open(file_path, 'r', encoding='utf-8') as file:
339 return json.load(file)
340
341def search_anime_by_title(json_data, search_title):
342 results = []
343 if search_title=="1P":
344 search_title = "ONE PIECE"
345 for list_item in json_data['data']['MediaListCollection']['lists']:
346 for entry in list_item['entries']:
347 media = entry['media']
348 romaji_title = media['title']['romaji']
349 english_title = media['title']['english']
350 episodes = media['episodes']
351 duration = media['duration']
352 try:
353 if search_title.lower() in romaji_title.lower() or search_title.lower() in english_title.lower():
354 results.append({
355 'id': media['id'],
356 'progress': entry['progress'],
357 'romaji_title': romaji_title,
358 'english_title': english_title,
359 'episodes': episodes,
360 'duration': duration,
361 })
362 except KeyboardInterrupt:
363 print("bye")
364 exit(0)
365 except:
366 pass
367
368 return results
369
370def update_anime_progress(token: str, media_id: int, progress: int):
371 url = "https://graphql.anilist.co"
372
373 query = '''
374 mutation($mediaId: Int, $progress: Int) {
375 SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
376 id
377 progress
378 }
379 }
380 '''
381
382 variables = {
383 "mediaId": media_id, # The AniList ID of the anime
384 "progress": progress # The number of the latest episode you watched
385 }
386
387 headers = {
388 "Authorization": f"Bearer {token}",
389 "Content-Type": "application/json",
390 "Accept": "application/json"
391 }
392 try:
393 response = requests.post(url, json={"query": query, "variables": variables}, headers=headers)
394 except KeyboardInterrupt:
395 print("bye")
396 exit(0)
397
398 if response.status_code == 200:
399 data = response.json()
400 updated_progress = data['data']['SaveMediaListEntry']['progress']
401 print("updating progress..")
402 print(f"Anime progress updated! Latest watched episode: {updated_progress}")
403 else:
404 print(f"Error {response.status_code}: {response.text}")
405
406def rate_anime(anilist_token, media_id, score):
407 url = 'https://graphql.anilist.co'
408
409 # GraphQL mutation to rate anime
410 query = '''
411 mutation($mediaId: Int, $score: Float) {
412 SaveMediaListEntry(mediaId: $mediaId, score: $score) {
413 id
414 mediaId
415 score
416 }
417 }
418 '''
419
420 # Variables for the mutation
421 variables = {
422 "mediaId": media_id,
423 "score": float(score)
424 }
425
426 headers = {
427 "Authorization": f"Bearer {anilist_token}",
428 "Content-Type": "application/json",
429 }
430
431 response = requests.post(url, json={'query': query, 'variables': variables}, headers=headers)
432
433 if response.status_code == 200:
434 data = response.json()
435 print(f"Successfully rated anime (mediaId: {media_id}) with score: {score}")
436 return data
437 else:
438 print(f"Failed to rate anime. Status Code: {response.status_code}, Response: {response.text}")
439 return None
440
441# ----------------------------------------------- Select Anime Functions ----------------------------------------
442
443def load_anime_data(filename):
444 anime_list = {}
445 with open(filename, "r") as file:
446 data = file.read().strip()
447 entries = data.split("NEWLINEFROMHERE")
448 for entry in entries:
449 if entry.strip():
450 parts = entry.split(maxsplit=1)
451 if len(parts) == 2:
452 anime_id, anime_name = parts
453 anime_list[anime_name] = anime_id
454 return anime_list
455
456def extract_anime_info(json_data):
457 anime_info_list = []
458 anime_info_dict = {}
459
460 # Traverse the JSON structure to get to the list of entries
461 for list_entry in json_data['data']['MediaListCollection']['lists']:
462 for entry in list_entry['entries']:
463 anime = entry['media']
464 anime_info = {
465 'id': anime['id'],
466 'romaji_name': anime['title']['romaji'],
467 'english_name': anime['title']['english'],
468 'status': entry['status'],
469 'episodes': anime['episodes'],
470 }
471
472 if anime['title']['english'] == None:
473 anime['title']['english'] = anime['title']['romaji']
474 # if anime['title'][''] == None:
475 # anime['title']['english'] = anime['title']['romanji']
476
477 anime_info_dict[anime['title']['english']] = str(anime['id']) # {anime_name: anime_id, ...}
478 anime_info_list.append(anime_info) # [{"id": anime_id, "romaji_name": anime_name_romnaji, "english_name": anime_name_english, status: anime_status}, ...]
479
480 return [anime_info_dict, anime_info_list]
481
482def select_anime(anime_list):
483 def main(stdscr):
484 # Clear screen
485 curses.curs_set(1)
486 stdscr.clear()
487 stdscr.refresh()
488
489 # Initial values
490 current_input = ""
491 filtered_list = list(anime_list.keys())
492 selected_index = 0
493 scroll_position = 0 # Position to start displaying the list from
494
495 try:
496 while True:
497 stdscr.clear()
498
499 # Get terminal dimensions
500 height, width = stdscr.getmaxyx()
501 list_height = height - 2 # Leave space for input and status lines
502
503 # Handle edge case where terminal window is too small
504 if height < 5 or width < len("Search Anime: ") + len(current_input):
505 stdscr.addstr(0, 0, "Terminal window too small!")
506 stdscr.refresh()
507 continue
508
509 # Display search prompt
510 stdscr.addstr(0, 0, "Search Anime: " + current_input)
511
512 # Calculate scrolling parameters
513 if selected_index < scroll_position:
514 scroll_position = selected_index
515 elif selected_index >= scroll_position + list_height:
516 scroll_position = selected_index - list_height + 1
517
518 # Display filtered results with highlighting and scrolling
519 for idx in range(scroll_position, min(len(filtered_list), scroll_position + list_height)):
520 anime = filtered_list[idx]
521 display_idx = idx - scroll_position + 1
522 if idx == selected_index:
523 stdscr.addstr(display_idx, 0, anime, curses.A_REVERSE)
524 else:
525 stdscr.addstr(display_idx, 0, anime)
526
527 # Get user input
528 try:
529 key = stdscr.getch()
530 except KeyboardInterrupt:
531 curses.endwin()
532 print("Have a great day!")
533 os._exit(0)
534
535 # Handle key inputs
536 if key in [curses.KEY_BACKSPACE, 127, 8]:
537 current_input = current_input[:-1]
538 selected_index = 0
539 elif key == curses.KEY_DOWN:
540 if selected_index < len(filtered_list) - 1:
541 selected_index += 1
542 elif key == curses.KEY_UP:
543 if selected_index > 0:
544 selected_index -= 1
545 elif key == curses.KEY_ENTER or key in [10, 13]: # Enter key
546 if filtered_list:
547 selected_anime = filtered_list[selected_index]
548 if selected_anime == 'Add new anime':
549 selected_id = "0"
550 else:
551 selected_id = anime_list[selected_anime]
552 break
553 elif key == ord('q'): # Exit if 'q' is pressed
554 return
555 else:
556 try:
557 current_input += chr(key)
558 selected_index = 0
559 except:
560 pass
561
562 # Filter the anime list based on current input
563 filtered_list = [anime for anime in anime_list.keys() if current_input.lower() in anime.lower()]
564 if filtered_list == []:
565 tmp_anime_list = {'Add new anime': '0'}
566 filtered_list = [anime for anime in tmp_anime_list.keys()]
567
568 # Ensure selected index is within bounds after filtering
569 if selected_index >= len(filtered_list):
570 selected_index = len(filtered_list) - 1
571
572 # Refresh screen
573 stdscr.refresh()
574
575 except KeyboardInterrupt:
576 print("bye")
577 exit(0)
578 except Exception as e:
579 # If an exception occurs, print it after exiting curses
580 curses.endwin()
581 print("e:", e)
582 if e == 'Add new anime':
583 print("No anime selected.")
584 exit(0)
585 print(f"An error occurred: {e}")
586 finally:
587 # Ensure curses always exits cleanly
588 curses.endwin()
589
590 # Print selected anime and its ID after exiting curses mode
591 # print(f"Selected Anime: {selected_anime}, ID: {selected_id}")
592 write_to_tmp("anime", selected_anime)
593
594 write_to_tmp("id", str(selected_id))
595
596 history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file"))
597 history_file_path_ = os.path.dirname(history_file_path_)
598
599 with open(os.path.join(history_file_path_, "curd_id"), "w") as temp1_:
600 temp1_.write(selected_id)
601
602 with open(os.path.join(history_file_path_, "curd_anime"), "w") as temp1_:
603 temp1_.write(selected_anime)
604
605 return True
606
607 # Initialize curses
608 try:
609 curses.wrapper(main)
610 except KeyboardInterrupt:
611 print("bye")
612 exit(0)
613 except:
614 pass
615
616# ----------------------------------------------- Select Link Functions ----------------------------------------
617
618
619def load_links(filename):
620 links = []
621 with open(filename, 'r') as file:
622 content = file.read()
623 # Regex to match the name and URL pairs
624 matches = re.findall(r'(\S+)\s*>\s*(https?://\S+)', content)
625 links = [(name, url) for name, url in matches]
626 return links
627
628def display_links(stdscr, links):
629 curses.curs_set(0) # Hide the cursor
630 stdscr.clear()
631 h, w = stdscr.getmaxyx()
632 max_height = h - 1
633 start = 0
634 selected_index = 0
635
636 while True:
637 stdscr.clear()
638 for i in range(start, min(start + max_height, len(links))):
639 if i == selected_index:
640 stdscr.attron(curses.A_REVERSE) # Highlight the selected item
641 stdscr.addstr(i - start, 0, links[i][0])
642 if i == selected_index:
643 stdscr.attroff(curses.A_REVERSE) # Remove highlight after the line
644 stdscr.addstr(max_height, 0, "Use arrow keys to scroll, Enter to select, q to quit")
645 stdscr.refresh()
646
647 key = stdscr.getch()
648
649 if key == curses.KEY_DOWN:
650 if selected_index < len(links) - 1:
651 selected_index += 1
652 if selected_index >= start + max_height:
653 start += 1
654 elif key == curses.KEY_UP:
655 if selected_index > 0:
656 selected_index -= 1
657 if selected_index < start:
658 start -= 1
659 elif key == curses.KEY_ENTER or key == 10: # Enter key
660 stdscr.clear()
661 stdscr.addstr(0, 0, f"Selected URL: {links[selected_index][1]}")
662 # print("done")
663 with open(f"/tmp/curd/curd_link", "w") as temp:
664 temp.write(links[selected_index][1])
665 stdscr.refresh()
666 # stdscr.getch() # Wait for any key press to exit
667 return links[selected_index][1]
668 break
669 elif key == ord('q'):
670 break
671
672# ----------------------------------------------- Start Video Functions ----------------------------------------
673
674def start_video(link, salt:str, args:list=[]):
675 # print(f"SALT IS {salt}")
676
677 args_str = ' '.join(args)
678
679 # Build the complete command string
680 command = f"mpv {args_str} --no-terminal --really-quiet --input-ipc-server=/tmp/curd/curd_mpvsocket{salt} {link}"
681
682 subprocess.Popen(command, shell=True)
683
684def mpv_send_command(ipc_socket_path, command):
685 """
686 Sends a command to the MPV IPC socket and returns the response.
687 """
688 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
689 s.connect(ipc_socket_path)
690 command_str = json.dumps({"command": command}) + "\n"
691 s.sendall(command_str.encode())
692 response = s.recv(4096).decode()
693
694 try:
695 response_data = json.loads(response)
696 if 'data' in response_data:
697 return response_data['data']
698 except KeyboardInterrupt:
699 print("bye")
700 exit(0)
701 except json.JSONDecodeError:
702 return None
703 return None
704
705def seek_mpv(ipc_socket_path, time):
706 """Seek MPV to a specific time."""
707 command = ["seek", time, "absolute"]
708 return mpv_send_command(ipc_socket_path, command)
709
710
711def get_mpv_paused_status(ipc_socket_path):
712 status = mpv_send_command(ipc_socket_path, ["get_property", "pause"])
713 if status is not None:
714 return status
715 else:
716 return False
717
718def get_mpv_playback_speed(ipc_socket_path):
719 current_speed = mpv_send_command(ipc_socket_path, ["get_property", "speed"])
720 if current_speed is not None:
721 return current_speed
722 else:
723 print("Failed to get playback speed.")
724
725def get_percentage_watched(ipc_socket_path):
726 """
727 Calculates the percentage watched of the currently playing video.
728 """
729 # Get current playback time and total duration
730 current_time = mpv_send_command(ipc_socket_path, ["get_property", "time-pos"])
731 duration = mpv_send_command(ipc_socket_path, ["get_property", "duration"])
732
733 if current_time is not None and duration is not None and duration > 0:
734 percentage_watched = (current_time / duration) * 100
735 return percentage_watched
736 return 0
737
738def percentage_watched(playback_time:int, duration:int):
739 if playback_time is not None and duration is not None and duration > 0:
740 video_percentage_watched = (playback_time/duration) * 100
741 return video_percentage_watched
742 return None
743
744# ----------------------------------------------- Track Anime Functions ----------------------------------------
745def add_anime(database_file, anilist_id, allanime_id, episode, time, duration, name):
746 with open(database_file, mode='a', newline='') as file:
747 writer = csv.writer(file)
748 writer.writerow([anilist_id, allanime_id, episode, time, duration, name])
749 print("Written to file")
750
751# Function to delete an anime entry by Anilist ID and Allanime ID
752def delete_anime(database_file, anilist_id, allanime_id):
753 anime_list = []
754 with open(database_file, mode='r', newline='') as file:
755 reader = csv.reader(file)
756 for row in reader:
757 # Keep only entries that don't match the Anilist ID and Allanime ID
758 if row[0] != anilist_id or row[1] != allanime_id:
759 anime_list.append(row)
760
761 # Rewrite the database without the deleted entry
762 with open(database_file, mode='w', newline='') as file:
763 writer = csv.writer(file)
764 writer.writerows(anime_list)
765
766# Function to retrieve all anime entries
767def get_all_anime(database_file):
768 anime_list = []
769 with open(database_file, mode='r', newline='') as file:
770 reader = csv.reader(file)
771 for row in reader:
772 anime_list.append({
773 'anilist_id': row[0],
774 'allanime_id': row[1],
775 'episode': row[2],
776 'time': row[3],
777 'duration': row[4],
778 'name': row[5]
779 })
780 return anime_list
781
782# Function to update or add a new anime entry
783def update_anime(database_file: str, anilist_id:str, allanime_id: str, episode:str, time:str, duration:str, name:str):
784 try:
785 anime_list = get_all_anime(database_file)
786 updated = False
787
788 # Create a new list to store updated entries
789 updated_anime_list = []
790
791 # Check if the anime entry exists and update it
792 for anime in anime_list:
793 if anime['anilist_id'] == anilist_id and anime['allanime_id'] == allanime_id:
794 updated_anime_list.append({
795 'anilist_id': anilist_id,
796 'allanime_id': allanime_id,
797 'episode': episode,
798 'time': time,
799 'duration': duration,
800 'name': name
801 })
802 updated = True
803 else:
804 updated_anime_list.append(anime)
805
806 # If no entry was updated, add new entry
807 if not updated:
808 updated_anime_list.append({
809 'anilist_id': anilist_id,
810 'allanime_id': allanime_id,
811 'episode': episode,
812 'time': time,
813 'duration': duration,
814 'name': name
815 })
816
817 # Write all entries back to the file
818 with open(database_file, mode='w', newline='') as file:
819 writer = csv.writer(file)
820 for anime in updated_anime_list:
821 writer.writerow([anime['anilist_id'], anime['allanime_id'], anime['episode'], anime['time'], anime['duration'], anime['name']])
822
823 # print("Updated the file")
824 except KeyboardInterrupt:
825 print("bye")
826 exit(0)
827 except Exception as e:
828 print_error(f"This: {e}")
829
830def find_anime(anime_list, anilist_id=-1, allanime_id=-1):
831 for anime in anime_list:
832 if anime['anilist_id'] == anilist_id or anime['allanime_id'] == allanime_id:
833 return anime
834
835 return False
836
837# ----------------------------------------------- Curd Functions ----------------------------------------
838
839def print_error(message):
840 """Print error message with full traceback."""
841 print(f"ERROR: {message}")
842 print("Traceback:")
843 traceback.print_exc()
844
845def get_contents_of(tmp_file_name):
846 with open(f"/tmp/curd/curd_{tmp_file_name}", "r") as temp_file:
847 return temp_file.read()
848
849def run_script(script: str):
850 os.system(f"/tmp/curd/{script}.sh")
851
852def write_to_tmp(tmp_filename:str, content:str):
853 try:
854 with open(f"/tmp/curd/curd_{tmp_filename}", "w") as _:
855 _.write(content)
856 return True
857 except FileNotFoundError:
858 with open(f"/tmp/curd/curd_{tmp_filename}", "w") as _:
859 _.write(content)
860 return True
861 except:
862 print("fuck")
863 return False
864
865def read_tmp(tmp_filename:str):
866 try:
867 with open(f"/tmp/curd/curd_{tmp_filename}", "r") as _:
868 content = _.read()
869 return content
870 except FileNotFoundError:
871 with open(f"/tmp/curd/curd_{tmp_filename}", "w") as _:
872 _.write("")
873 return ""
874 except:
875 print("fuck")
876 return False
877
878def download_anilist_data(access_token, user_id):
879 ''' dowlnoad anilist user data'''
880 # print("downloading user data")
881 anilist_user_data = get_user_data(access_token, user_id)
882 try:
883 if anilist_user_data['data'] == None:
884 print("Cannot process user data.")
885 # print(anilist_user_data)
886 exit()
887 except KeyboardInterrupt:
888 print("bye")
889 exit(0)
890 except:
891 pass
892
893 return anilist_user_data
894
895default_config = {
896 "player":"mpv",
897 "show_adult_content":False,
898 "history_file":"$HOME/.local/share/curd/curd_history.txt",
899 "subs_language":"english",
900 "sub_or_dub":"sub",
901 "percentage_to_mark_complete":85,
902 "next_episode_prompt": False,
903 "skip_op": True,
904 "skip_ed": True,
905 "skip_filler": True,
906 "skip_recap": True,
907 "score_on_completion": True,
908 "save_mpv_speed": True,
909 "discord_presence": False,
910}
911
912def convert_seconds_to_minutes(seconds) -> str:
913 minutes = seconds // 60
914 remaining_seconds = seconds % 60
915 if remaining_seconds < 10:
916 return f"{minutes}:0{remaining_seconds}"
917 return f"{minutes}:{remaining_seconds}"
918
919def get_userconfig_value(userconfig:dict, key:str):
920 return userconfig.get(key, default_config.get(key))
921
922def create_default_user_config(default_config):
923 output_string = ""
924 for key, value in default_config.items():
925 # Convert Python True/False to lowercase true/false
926 if isinstance(value, bool):
927 value_str = 'true' if value else 'false'
928 else:
929 value_str = str(value)
930
931 # Write the key=value to the file with no spaces
932 output_string+=f"{key}={value_str}\n"
933
934 return output_string
935
936def get_config_file_path():
937 command = """echo $HOME"""
938
939 result = subprocess.run(command, shell=True, capture_output=True, text=True)
940 output = result.stdout.strip()
941
942 folder_name = f"{output}/.config/curd"
943 file_name = "curd.conf"
944
945 config_file_path = os.path.join(folder_name, file_name)
946
947 return config_file_path
948
949def load_config() -> dict:
950 command = """echo $HOME"""
951
952 result = subprocess.run(command, shell=True, capture_output=True, text=True)
953 output = result.stdout.strip()
954
955 folder_name = f"{output}/.config/curd"
956 file_name = "curd.conf"
957
958 config_file_path = os.path.join(folder_name, file_name)
959
960 # print(config_file_path)
961 if not os.path.exists(os.path.join(config_file_path)):
962 print("Creating config")
963
964 try:
965 print("making folder")
966 os.makedirs(folder_name)
967 except KeyboardInterrupt:
968 print("bye")
969 exit(0)
970 except:
971 print("error making folder")
972 pass
973
974 with open(config_file_path, 'w') as file:
975 file.write(create_default_user_config(default_config))
976
977 config_dict = {}
978
979 with open(config_file_path, 'r') as file:
980 for line in file:
981 # Strip whitespace and ignore comments or empty lines
982 line = line.strip()
983 if line and not line.startswith("#"):
984 # Split the line into key and value
985 key, value = line.split("=", 1)
986 key = key.strip()
987 value = value.strip().strip('"')
988
989 # Handle environment variables in the value
990 value = os.path.expandvars(value)
991
992 # Convert boolean strings to actual booleans
993 if value.lower() == "true":
994 value = True
995 elif value.lower() == "false":
996 value = False
997
998 try:
999 value = int(value)
1000 except KeyboardInterrupt:
1001 print("bye")
1002 exit(0)
1003 except Exception as e:
1004 # print_error("878: {e}")
1005 pass
1006
1007 # Store in the dictionary
1008 config_dict[key] = value
1009
1010 if not os.path.exists(config_dict['history_file']):
1011 try:
1012 os.makedirs(os.path.dirname(config_dict['history_file']))
1013 except Exception as e:
1014 print_error("888: {e}")
1015 print("creating history file")
1016 with open(config_dict["history_file"], "w") as history_file:
1017 history_file.write("")
1018
1019 return config_dict
1020
1021def update_script():
1022 script_dir = os.path.dirname(os.path.realpath(__file__))
1023 script_file = os.path.join(script_dir, "curd.py")
1024
1025 response = requests.get("https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/curd.py")
1026 if response.status_code == 200:
1027 # Write the content to a file
1028 with open(script_file, 'wb') as file:
1029 file.write(response.content)
1030 print(f"Script update successfully at {script_file}")
1031 else:
1032 print(f"Failed to download the script. Status code: {response.status_code}")
1033 exit(1)
1034
1035# ----------------------------------------------- Create Bash Script ----------------------------------------
1036
1037def create_anime_list():
1038 script_path = "/tmp/curd/anime_list.sh"
1039 with open(script_path, "w") as _:
1040 _.write(r"""search_anime() {
1041 search_gql="query( \$search: SearchInput \$limit: Int \$page: Int \$translationType: VaildTranslationTypeEnumType \$countryOrigin: VaildCountryOriginEnumType ) { shows( search: \$search limit: \$limit page: \$page translationType: \$translationType countryOrigin: \$countryOrigin ) { edges { _id name availableEpisodes __typename } }}"
1042
1043 curl -e "$allanime_refr" -s -G "${allanime_api}/api" --data-urlencode "variables={\"search\":{\"allowAdult\":false,\"allowUnknown\":false,\"query\":\"$1\"},\"limit\":40,\"page\":1,\"translationType\":\"$mode\",\"countryOrigin\":\"ALL\"}" --data-urlencode "query=$search_gql" -A "$agent" | sed 's|Show|\
1044|g' | sed -nE "s|.*_id\":\"([^\"]*)\",\"name\":\"([^\"]*)\".*${mode}\":([1-9][^,]*).*|\1 \2 (\3 episodes)NEWLINEFROMHERE|p"
1045}
1046
1047agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
1048allanime_refr="https://allanime.to"
1049allanime_base="allanime.day"
1050allanime_api="https://api.${allanime_base}"
1051mode="${ANI_CLI_MODE:-sub}"
1052download_dir="${ANI_CLI_DOWNLOAD_DIR:-.}"
1053quality="${ANI_CLI_QUALITY:-best}"
1054case "$(uname -a)" in
1055 *Darwin*) player_function="${ANI_CLI_PLAYER:-iina}" ;; # mac OS
1056 *ndroid*) player_function="${ANI_CLI_PLAYER:-android_mpv}" ;; # Android OS (termux)
1057 *steamdeck*) player_function="${ANI_CLI_PLAYER:-flatpak_mpv}" ;; # steamdeck OS
1058 *MINGW* | *WSL2*) player_function="${ANI_CLI_PLAYER:-mpv.exe}" ;; # Windows OS
1059 *ish*) player_function="${ANI_CLI_PLAYER:-iSH}" ;; # iOS (iSH)
1060 *) player_function="${ANI_CLI_PLAYER:-mpv}" ;; # Linux OS
1061esac
1062
1063# Read the entire file content into a variable
1064script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
1065query=$(cat /tmp/curd/curd_query) # This is a shorthand for cat "$filename"
1066
1067# query="one piece"
1068anime_list=$(search_anime "$query")
1069
1070echo $anime_list > /tmp/curd/curd_anime_list
1071""")
1072 os.chmod(script_path, 0o755)
1073
1074def create_episode_list():
1075 script_path = "/tmp/curd/episode_list.sh"
1076 with open(script_path, "w") as _:
1077 _.write(r"""episodes_list() {
1078 episodes_list_gql="query (\$showId: String!) { show( _id: \$showId ) { _id availableEpisodesDetail }}"
1079
1080 curl -e "$allanime_refr" -s -G "${allanime_api}/api" --data-urlencode "variables={\"showId\":\"$*\"}" --data-urlencode "query=$episodes_list_gql" -A "$agent" | sed -nE "s|.*$mode\":\[([0-9.\",]*)\].*|\1|p" | sed 's|,|\
1081|g; s|"||g' | sort -n -k 1
1082}
1083
1084# setup
1085agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
1086allanime_refr="https://allanime.to"
1087allanime_base="allanime.day"
1088allanime_api="https://api.${allanime_base}"
1089mode="${ANI_CLI_MODE:-sub}"
1090download_dir="${ANI_CLI_DOWNLOAD_DIR:-.}"
1091quality="${ANI_CLI_QUALITY:-best}"
1092case "$(uname -a)" in
1093 *Darwin*) player_function="${ANI_CLI_PLAYER:-iina}" ;; # mac OS
1094 *ndroid*) player_function="${ANI_CLI_PLAYER:-android_mpv}" ;; # Android OS (termux)
1095 *steamdeck*) player_function="${ANI_CLI_PLAYER:-flatpak_mpv}" ;; # steamdeck OS
1096 *MINGW* | *WSL2*) player_function="${ANI_CLI_PLAYER:-mpv.exe}" ;; # Windows OS
1097 *ish*) player_function="${ANI_CLI_PLAYER:-iSH}" ;; # iOS (iSH)
1098 *) player_function="${ANI_CLI_PLAYER:-mpv}" ;; # Linux OS
1099esac
1100script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
1101id=$(cat /tmp/curd/curd_id)
1102echo $(episodes_list "$id") > /tmp/curd/curd_episode_list
1103""")
1104 os.chmod(script_path, 0o755)
1105
1106def create_episode_url():
1107 script_path = "/tmp/curd/episode_url.sh"
1108 with open(script_path, "w") as _:
1109 _.write(r"""# # extract the video links from response of embed urls, extract mp4 links form m3u8 lists
1110get_links() {
1111 episode_link="$(curl -e "$allanime_refr" -s "https://${allanime_base}$*" -A "$agent" | sed 's|},{|\
1112|g' | sed -nE 's|.*link":"([^"]*)".*"resolutionStr":"([^"]*)".*|\2 >\1|p;s|.*hls","url":"([^"]*)".*"hardsub_lang":"en-US".*|\1|p')"
1113
1114 case "$episode_link" in
1115 *repackager.wixmp.com*)
1116 extract_link=$(printf "%s" "$episode_link" | cut -d'>' -f2 | sed 's|repackager.wixmp.com/||g;s|\.urlset.*||g')
1117 for j in $(printf "%s" "$episode_link" | sed -nE 's|.*/,([^/]*),/mp4.*|\1|p' | sed 's|,|\
1118|g'); do
1119 printf "%s >%s\n" "$j" "$extract_link" | sed "s|,[^/]*|${j}|g"
1120 done | sort -nr
1121 ;;
1122 *vipanicdn* | *anifastcdn*)
1123 if printf "%s" "$episode_link" | head -1 | grep -q "original.m3u"; then
1124 printf "%s" "$episode_link"
1125 else
1126 extract_link=$(printf "%s" "$episode_link" | head -1 | cut -d'>' -f2)
1127 relative_link=$(printf "%s" "$extract_link" | sed 's|[^/]*$||')
1128 curl -e "$allanime_refr" -s "$extract_link" -A "$agent" | sed 's|^#.*x||g; s|,.*|p|g; /^#/d; $!N; s|\
1129| >|' | sed "s|>|>${relative_link}|g" | sort -nr
1130 fi
1131 ;;
1132 *) [ -n "$episode_link" ] && printf "%s\n" "$episode_link" ;;
1133 esac
1134 # echo $episode_link >> links
1135 # [ -z "$ANI_CLI_NON_INTERACTIVE" ] && printf "\033[1;32m%s\033[0m Links Fetched\n" "$provider_name" 1>&2
1136 [ -z "$ANI_CLI_NON_INTERACTIVE" ] 1>&2
1137}
1138
1139# # innitialises provider_name and provider_id. First argument is the provider name, 2nd is the regex that matches that provider's link
1140provider_init() {
1141 provider_name=$1
1142 provider_id=$(printf "%s" "$resp" | sed -n "$2" | head -1 | cut -d':' -f2 | sed 's/../&\
1143/g' | sed 's/^01$/9/g;s/^08$/0/g;s/^05$/=/g;s/^0a$/2/g;s/^0b$/3/g;s/^0c$/4/g;s/^07$/?/g;s/^00$/8/g;s/^5c$/d/g;s/^0f$/7/g;s/^5e$/f/g;s/^17$/\//g;s/^54$/l/g;s/^09$/1/g;s/^48$/p/g;s/^4f$/w/g;s/^0e$/6/g;s/^5b$/c/g;s/^5d$/e/g;s/^0d$/5/g;s/^53$/k/g;s/^1e$/\&/g;s/^5a$/b/g;s/^59$/a/g;s/^4a$/r/g;s/^4c$/t/g;s/^4e$/v/g;s/^57$/o/g;s/^51$/i/g;' | tr -d '\n' | sed "s/\/clock/\/clock\.json/")
1144}
1145
1146# # +s links based on given provider
1147generate_link() {
1148 case $1 in
1149 1) provider_init "wixmp" "/Default :/p" ;; # wixmp(default)(m3u8)(multi) -> (mp4)(multi)
1150 2) provider_init "dropbox" "/Sak :/p" ;; # dropbox(mp4)(single)
1151 3) provider_init "wetransfer" "/Kir :/p" ;; # wetransfer(mp4)(single)
1152 4) provider_init "sharepoint" "/S-mp4 :/p" ;; # sharepoint(mp4)(single)
1153 *) provider_init "gogoanime" "/Luf-mp4 :/p" ;; # gogoanime(m3u8)(multi)
1154 esac
1155 [ -n "$provider_id" ] && get_links "$provider_id"
1156 # echo $links >> links
1157}
1158
1159select_quality() {
1160 case "$1" in
1161 best) result=$(printf "%s" "$links" | head -n1) ;;
1162 worst) result=$(printf "%s" "$links" | grep -E '^[0-9]{3,4}' | tail -n1) ;;
1163 *) result=$(printf "%s" "$links" | grep -m 1 "$1") ;;
1164 esac
1165 [ -z "$result" ] && printf "Specified quality not found, defaulting to best\n" 1>&2 && result=$(printf "%s" "$links" | head -n1)
1166 printf "%s" "$result" | cut -d'>' -f2
1167}
1168
1169script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
1170# # gets embed urls, collects direct links into provider files, selects one with desired quality into $episode
1171get_episode_url() {
1172 # get the embed urls of the selected episode
1173 episode_embed_gql="query (\$showId: String!, \$translationType: VaildTranslationTypeEnumType!, \$episodeString: String!) { episode( showId: \$showId translationType: \$translationType episodeString: \$episodeString ) { episodeString sourceUrls }}"
1174
1175 resp=$(curl -e "$allanime_refr" -s -G "${allanime_api}/api" --data-urlencode "variables={\"showId\":\"$id\",\"translationType\":\"$mode\",\"episodeString\":\"$ep_no\"}" --data-urlencode "query=$episode_embed_gql" -A "$agent" | tr '{}' '\n' | sed 's|\\u002F|\/|g;s|\\||g' | sed -nE 's|.*sourceUrl":"--([^"]*)".*sourceName":"([^"]*)".*|\2 :\1|p')
1176 # generate links into sequential files
1177 cache_dir="$(mktemp -d)"
1178 providers="1 2 3 4 5"
1179 for provider in $providers; do
1180 generate_link "$provider" >"$cache_dir"/"$provider" &
1181 done
1182 wait
1183 # echo $links > links
1184 # select the link with matching quality
1185 links=$(cat "$cache_dir"/* | sed 's|^Mp4-||g;/http/!d' | sort -g -r -s)
1186 rm -r "$cache_dir"
1187 episode=$(select_quality "$quality")
1188 echo $links > /tmp/curd/curd_links
1189 [ -z "$episode" ] && die "Episode not released!"
1190}
1191
1192# setup
1193agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
1194allanime_refr="https://allanime.to"
1195allanime_base="allanime.day"
1196allanime_api="https://api.${allanime_base}"
1197sub_or_dub=$(cat /tmp/curd/curd_mode)
1198mode="${ANI_CLI_MODE:-$sub_or_dub}"
1199download_dir="${ANI_CLI_DOWNLOAD_DIR:-.}"
1200quality="${ANI_CLI_QUALITY:-best}"
1201case "$(uname -a)" in
1202 *Darwin*) player_function="${ANI_CLI_PLAYER:-iina}" ;; # mac OS
1203 *ndroid*) player_function="${ANI_CLI_PLAYER:-android_mpv}" ;; # Android OS (termux)
1204 *steamdeck*) player_function="${ANI_CLI_PLAYER:-flatpak_mpv}" ;; # steamdeck OS
1205 *MINGW* | *WSL2*) player_function="${ANI_CLI_PLAYER:-mpv.exe}" ;; # Windows OS
1206 *ish*) player_function="${ANI_CLI_PLAYER:-iSH}" ;; # iOS (iSH)
1207 *) player_function="${ANI_CLI_PLAYER:-mpv}" ;; # Linux OS
1208esac
1209id=$(cat /tmp/curd/curd_id)
1210ep_no=$(cat /tmp/curd/curd_ep_no)
1211get_episode_url
1212""")
1213 os.chmod(script_path, 0o755)
1214
1215# ----------------------------------------------- Start of script ----------------------------------------
1216try:
1217 current_dir = Path(__file__).parent
1218 # current_dir = os.path.dirname(os.path.abspath(__file__))
1219 # print(current_dir)
1220 if not os.path.exists(f"/tmp/curd/"):
1221 try:
1222 print("making tmp directory")
1223 os.makedirs(os.path.dirname(f"/tmp/curd/"))
1224 except KeyboardInterrupt:
1225 print("bye")
1226 exit(0)
1227 except:
1228 pass
1229
1230 rewatching = False
1231
1232 parser = argparse.ArgumentParser(description="Print a greeting message.")
1233 # parser.add_argument("--name", type=str, required=True, help="Your name")
1234 parser.add_argument("-new", action='store_true', help="Add new anime to watching (optional)")
1235 parser.add_argument("-sub", action='store_true', help="Anime audio type (optional)")
1236 parser.add_argument("-dub", action='store_true', help="Anime audio type (optional)")
1237 parser.add_argument("-c", action='store_true', help="Continue last watching anime (optional)")
1238 parser.add_argument("-u", action='store_true', help="Update script (optional)")
1239 parser.add_argument("-e", action='store_true', help="Edit config (optional)")
1240 args = parser.parse_args()
1241
1242 if args.u:
1243 update_script()
1244 exit(0)
1245
1246 user_config = load_config() # python dictionary containing all the configs as key value pairs
1247 history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file"))
1248 history_file_path_ = os.path.dirname(history_file_path_)
1249 access_token_path = os.path.join(history_file_path_, "token")
1250
1251 if args.e:
1252 os.system("vim "+get_config_file_path())
1253 print("updated config.")
1254 exit(0)
1255
1256 create_anime_list()
1257 create_episode_list()
1258 create_episode_url()
1259
1260 if os.path.exists(access_token_path):
1261 # Read and use the token
1262 with open(access_token_path, "r") as token_file:
1263 access_token = token_file.read().strip()
1264 # print(f"Token found: {access_token}")
1265
1266 else:
1267 print("Generate the token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token ")
1268 access_token = input("Token file not found. Please generate and enter your token: ")
1269 if "https://" in access_token:
1270 # Parse the URL fragment part (after the `#`)
1271 fragment = urllib.parse.urlparse(access_token).fragment
1272
1273 # Parse the fragment into components
1274 params = urllib.parse.parse_qs(fragment)
1275
1276 # Extract only the access_token without any other parameters
1277 access_token = params['access_token'][0] if 'access_token' in params else None
1278
1279 print("Access Token:", access_token)
1280 with open(access_token_path, "w") as token_file:
1281 token_file.write(access_token)
1282 print(f"Token saved to {access_token_path}")
1283
1284 if access_token == None:
1285 print("No Access_token provided.")
1286 exit(1)
1287
1288 user_id, user_name = get_anilist_user_id(access_token)
1289 mark_episode_as_completed_at = get_userconfig_value(user_config, "percentage_to_mark_complete")
1290 anilist_user_data = download_anilist_data(access_token, user_id)
1291 anime_dict = extract_anime_info(anilist_user_data)[0]
1292
1293 search_for_new_anime = False
1294 if not args.c and not args.new:
1295 select_anime(anime_dict)
1296 if read_tmp("anime") == 'Add new anime':
1297 search_for_new_anime = True
1298
1299 if args.c:
1300 try:
1301 with open(os.path.join(history_file_path_, "curd_id"), "r") as temp1_:
1302 write_to_tmp("id", temp1_.read())
1303 with open(os.path.join(history_file_path_, "curd_anime"), "r") as temp1_:
1304 write_to_tmp("anime", temp1_.read())
1305 except KeyboardInterrupt:
1306 print("bye")
1307 exit(0)
1308 except:
1309 print("No previous history!")
1310
1311 if args.new or search_for_new_anime:
1312 new_anime_name_ = input("Enter anime name: ")
1313 temp__ = search_anime_anilist(new_anime_name_, access_token)
1314 if temp__ :
1315 select_anime(temp__)
1316 add_anime_to_watching_list(read_tmp('id'), access_token)
1317 anilist_user_data = download_anilist_data(access_token, user_id)
1318 else:
1319 print("No anime found")
1320 exit(0)
1321
1322 anime_name = read_tmp("anime")
1323 write_to_tmp("query", anime_name)
1324 run_script("anime_list")
1325 anime_dict = load_anime_data(f"/tmp/curd/curd_anime_list")
1326 cleaned_text = re.sub(r'\(.*$', '', anime_name).strip() # clean anime name
1327 # print(cleaned_text)
1328except KeyboardInterrupt:
1329 print('bye')
1330 exit(0)
1331except Exception as e:
1332 print("error: ", e)
1333
1334try:
1335 result = search_anime_by_title(anilist_user_data, cleaned_text)[0]
1336 # print(result)
1337 media_id = result['id']
1338 progress = int(result['progress'])
1339 title = result['english_title']
1340 total_episodes = result['episodes']
1341 duration = result['duration']
1342except KeyboardInterrupt:
1343 print("bye")
1344 exit(0)
1345except Exception as e:
1346 print(f"Searching anime error: {e}")
1347 exit(1)
1348
1349try:
1350 finding_anime = find_anime(get_all_anime(get_userconfig_value(user_config, "history_file")), anilist_id=str(media_id))
1351 # print(finding_anime)
1352 if finding_anime:
1353 print("Found anime in local history")
1354 write_to_tmp("id", finding_anime['allanime_id'])
1355 write_to_tmp("anime", finding_anime['name'])
1356 else:
1357 print("Trying to automate")
1358 write_to_tmp("id", anime_dict[anime_name+f" ({total_episodes} episodes)"])
1359 write_to_tmp("anime", anime_name)
1360except KeyboardInterrupt:
1361 print("bye")
1362 exit(0)
1363except Exception as e:
1364 # print_error(e)
1365 print("Please select anime")
1366 select_anime(anime_dict)
1367
1368try:
1369 if get_userconfig_value(user_config, "sub_or_dub")=="sub":
1370 write_to_tmp("mode", "sub")
1371 elif get_userconfig_value(user_config, "sub_or_dub")=="dub":
1372 write_to_tmp("mode", "dub")
1373
1374 if args.sub: # arguments take precidence
1375 write_to_tmp("mode", "sub")
1376 if args.dub:
1377 write_to_tmp("mode", "dub")
1378
1379 run_script("episode_list")
1380
1381 binge_watching = False
1382 mpv_args = []
1383 last_episode = int(read_tmp("episode_list").split()[-1])
1384 anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
1385 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
1386 episode_completed = False
1387
1388 if anime_history: # if it exists in local history
1389 # print(f"came in history {str(progress)}")
1390 # print(anime_history['episode'])
1391 if progress == last_episode or int(anime_history['episode']) == int(progress)+1:
1392 if progress == last_episode:
1393 rewatching = True
1394 mpv_args.append(f"--start={anime_history['time']}")
1395 watching_ep = int(anime_history['episode'])
1396 write_to_tmp("ep_no", str(watching_ep))
1397 # print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
1398 elif int(anime_history['episode']) < progress+1: # if the upstream progress is ahead
1399 write_to_tmp("ep_no", str(int(progress)+1))
1400 print(f"Starting anime from upstream {str(progress + 1)}")
1401 watching_ep = progress + 1
1402 else: # if history does not exist
1403 if progress == last_episode:
1404 user_input = input("Do you want to start this anime from beginning? (y/n):")
1405 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
1406 progress = 0
1407 rewatching = True
1408 else:
1409 print("Starting last episode of anime")
1410 progress = last_episode - 1
1411 watching_ep = int(progress)+1
1412 write_to_tmp("ep_no", str(watching_ep))
1413 # print(watching_ep)
1414 # os.system("{current_dir}/scripts/episode_url.sh")
1415 print("Fetching anime")
1416 run_script("episode_url")
1417
1418 # Print the result
1419 if media_id:
1420 # print(f"Anime ID: {media_id}")
1421 pass
1422 else:
1423 print("Anime not found.")
1424 exit(1)
1425
1426 links = load_links(f"/tmp/curd/curd_links")
1427
1428 if get_userconfig_value(user_config, "discord_presence") == True:
1429 from pypresence import Presence
1430 # print("imported pypresence")
1431 rpc = Presence(discord_client_id)
1432 rpc.connect()
1433 anime_mal_id, anime_image_url = get_anime_id_and_image(media_id)
1434 else:
1435 anime_mal_id = get_anime_mal_id(media_id)
1436
1437 # default variable declaration
1438 watched_percentage = 0
1439 is_paused = False
1440 mpv_playback_speed = 1.0
1441except KeyboardInterrupt:
1442 print("bye")
1443 exit(0)
1444while True: # loop for each episode
1445 try:
1446
1447 skip_filler = get_userconfig_value(user_config, "skip_filler")
1448 skip_recap = get_userconfig_value(user_config, "skip_recap")
1449
1450 if skip_filler == True or skip_recap == True:
1451 episode_data = get_episode_data(anime_mal_id, watching_ep)
1452 if episode_data:
1453 # print(episode_data)
1454 is_filler = episode_data['filler']
1455 is_recap = episode_data['recap']
1456 if skip_filler and is_filler or skip_recap and is_recap and not rewatching:
1457 print("starting next.")
1458 watched_percentage = 95
1459 raise Exception("Filler or Recap Episode. Starting next episode.")
1460
1461 else:
1462 print("Error fetching episode details")
1463
1464 salt = random.randint(0,1500)
1465 # print("SALT IS:"+str(salt))
1466 start_video(links[0][1], salt, mpv_args)
1467 mpv_socket_path = "/tmp/curd/curd_mpvsocket"+str(salt)
1468 connect_mpv_command = """echo '{ "command": ["get_property", "playback-time"] }' | socat - """+mpv_socket_path
1469 if get_userconfig_value(user_config, "skip_op") == True or get_userconfig_value(user_config, "skip_end"):
1470 skip_intervals = get_and_parse_aniskip_data(anime_mal_id, watching_ep)
1471 if skip_intervals == None:
1472 print("failed to get skip times")
1473
1474 while True: # loop while episode is being watched
1475 # Example usage
1476 # anime_id = 28223
1477 # episode = 10
1478
1479 time.sleep(2)
1480 result = subprocess.run(connect_mpv_command, shell=True, capture_output=True, text=True)
1481 # print(result)
1482 if result.returncode == 0:
1483 output = result.stdout.strip()
1484 if not output: # Check if output is empty
1485 print("No data received. Retrying...")
1486 try:
1487 data = json.loads(output)
1488 if data["error"] == "success":
1489 playback_time = round(int(data["data"]), 2)
1490 if get_userconfig_value(user_config, "discord_presence") == True:
1491 is_paused = get_mpv_paused_status(mpv_socket_path)
1492
1493 # print("mpv_status", mpv_status)
1494 # print("is_paused", is_paused)
1495 if is_paused:
1496 # Update presence with paused status
1497 rpc.update(
1498 details=f"Watching {title}",
1499 state=f"Episode {watching_ep} - {convert_seconds_to_minutes(playback_time)} (Paused)",
1500 large_image=anime_image_url,
1501 large_text=title,
1502 )
1503 else:
1504 # Update presence with playback time
1505 rpc.update(
1506 details=f"Watching {title}",
1507 state=f"Episode {watching_ep} - {convert_seconds_to_minutes(playback_time)}/{duration}:00",
1508 large_image=anime_image_url,
1509 large_text=title,
1510 )
1511 if skip_intervals:
1512 if get_userconfig_value(user_config, "skip_op") == True:
1513 if round(int(playback_time)) > round(int(skip_intervals['op']['start_time'])) and round(int(playback_time)) < round(int(skip_intervals['op']['start_time']))+10:
1514 print("skipped opening")
1515 seek_mpv(mpv_socket_path, int(skip_intervals['op']['end_time']))
1516
1517 if get_userconfig_value(user_config, "skip_ed") == True:
1518 if round(int(playback_time)) > round(int(skip_intervals['ed']['start_time'])) and round(int(playback_time)) < round(int(skip_intervals['ed']['start_time']))+10:
1519 print("skipped ending")
1520 seek_mpv(mpv_socket_path, int(skip_intervals['ed']['end_time']))
1521 watched_percentage = get_percentage_watched(mpv_socket_path)
1522
1523 update_anime(get_userconfig_value(user_config, 'history_file'), str(media_id), str(get_contents_of("id")), str(watching_ep), str(playback_time), str(duration), str(title))
1524 # print("Playback time:", playback_time)
1525 watched_percentage = get_percentage_watched(mpv_socket_path)
1526 mpv_playback_speed = get_mpv_playback_speed(mpv_socket_path)
1527
1528 if watched_percentage > mark_episode_as_completed_at:
1529 episode_completed = True
1530 binge_watching = True
1531 # else:
1532 # print(f"Episode not done: {watched_percentage} {mark_episode_as_completed_at}")
1533 # video_duration = subprocess.run(mpv_duration_command, shell=True, capture_output=True, text=True):
1534 elif data['error'] == "property unavailable": # Stream has not started yet
1535 pass
1536 else:
1537 print("Error (330):", data["error"])
1538 break
1539 except json.decoder.JSONDecodeError as e:
1540 print("Error decoding JSON:", e)
1541 break # Exit the loop on unexpected JSON error
1542 except KeyboardInterrupt:
1543 print("bye")
1544 exit(0)
1545 except Exception as e:
1546 print_error(f"Unknown:\n {e}")
1547 print("Unknown:\n", e)
1548 else:
1549 killing_error = str(result.stderr)
1550 # print(killing_error[-19:-1])
1551 try:
1552 if killing_error[-19:-1] == "Connection refused": # user closed the stream
1553 if watched_percentage > mark_episode_as_completed_at:
1554 # update_anime_progress(access_token, int(media_id), int(watching_ep))
1555 # watching_ep = int(watching_ep)+1
1556 # update_anime(user_config['history_file'], str(media_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title))
1557 break
1558 else:
1559 print("Have a great day!")
1560 exit(0)
1561
1562 except KeyboardInterrupt:
1563 print("bye")
1564 exit(0)
1565 except Exception as e: # user did not close the stream
1566 print(e)
1567 if killing_error == "property unavailable": # mpv is not started yet
1568 # print("passing")
1569 pass
1570 else: # Stream has ended (maybe)
1571 print("Error (346):", killing_error)
1572 # try:
1573
1574 # except Exception as e:
1575 # print("fuck")
1576 # print(f"Exception: {e}")
1577 break
1578 except ConnectionRefusedError: # execption is never reached ig
1579 print("Player Closed")
1580 # print("have a great")
1581 # exit(0)
1582 except KeyboardInterrupt:
1583 if watched_percentage > mark_episode_as_completed_at and not rewatching:
1584 update_anime_progress(access_token, int(media_id), int(watching_ep))
1585 watching_ep = int(watching_ep)+1
1586 update_anime(get_userconfig_value(user_config, 'history_file'), str(media_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title))
1587
1588 print("bye")
1589 exit(0)
1590 except Exception as e:
1591 print(e)
1592 finally:
1593 binge_watching=True
1594
1595 try:
1596 # print("binge watching")
1597 current_ep = int(read_tmp("ep_no"))
1598
1599 if current_ep == last_episode:
1600 if binge_watching == True and not rewatching and get_userconfig_value(user_config, 'score_on_completion') == True: # Completed anime
1601 anime_rating_by_user = input("Rate this anime:\n")
1602 update_anime_progress(access_token, int(media_id), int(watching_ep))
1603 rate_anime(access_token, media_id, anime_rating_by_user)
1604 print("completed anime.")
1605 delete_anime(get_userconfig_value(user_config, 'history_file'), str(media_id), str(get_contents_of("id")))
1606 exit(0)
1607
1608 else:
1609 print(f"Starting next episode: {int(watching_ep)+1}")
1610 # write_to_tmp("ep_no", str(int(current_ep)+1))
1611
1612 if watched_percentage > mark_episode_as_completed_at: # IF BINGE WATCHING
1613 last_episode = int(read_tmp("episode_list").split()[-1])
1614 if not rewatching:
1615 update_anime_progress(access_token, int(media_id), int(watching_ep))
1616 watching_ep = int(watching_ep)+1
1617 write_to_tmp("ep_no", str(watching_ep))
1618 update_anime(get_userconfig_value(user_config, 'history_file'), str(media_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title))
1619 anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
1620 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
1621 episode_completed = False
1622 print("Fetching anime")
1623 run_script("episode_url")
1624 links = load_links(f"/tmp/curd/curd_links")
1625 mpv_args = []
1626 watched_percentage = 0
1627
1628 if get_userconfig_value(user_config, 'save_mpv_speed') ==True:
1629 mpv_args.append(f'--speed={mpv_playback_speed}')
1630
1631 # watching_ep = current_ep+1
1632 if get_userconfig_value(user_config, 'next_episode_prompt') == True:
1633 to_continue_or_not_to_continue = input("Continue? (y/n)\n")
1634 if to_continue_or_not_to_continue.lower() == "yes" or to_continue_or_not_to_continue.lower() == "y" or to_continue_or_not_to_continue == "":
1635 binge_watching = True
1636 else:
1637 exit(0)
1638 except KeyboardInterrupt:
1639 print("bye")
1640 exit(0)
1641 except Exception as e:
1642 # print(f"error:{e}\nMaybe try running again!")
1643 print_error(f"{e}")
1644 print("Maybe try running again!")
1645 exit(1)
1646
main.go added +7
@@ -0,0 +1,7 @@
1package main
2
3import "fmt"
4
5func main(){
6 fmt.Println("Great future.")
7}\ No newline at end of file