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