Commit 9349fe3c66

9349fe3c66c4d7c8dfc959a4087c597aaff5af34

parent: 2ccc8b057f

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-10 08:04 UTC

graceful exit everywhere :)

Layout: unified · split

PKGBUILD added +46
@@ -0,0 +1,46 @@
1# Maintainer: Wraient <rushikeshwastaken@gmail.com>
2pkgname='curd'
3pkgver='r86.2ccc8b0'
4pkgrel=1
5pkgdesc="Watch anime in cli with Anilist Tracking, Discord RPC, Intro Outro Skipping, etc."
6arch=("x86_64")
7url="https://github.com/Wraient/curd"
8license=('GPL')
9depends=('python' 'mpv' 'socat')
10makedepends=('python-pip')
11source=("https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/curd.py")
12sha256sums=('SKIP')
13
14package() {
15 # Create the directory for the virtual environment
16 install -dm755 "$pkgdir/usr/share/curd"
17
18 # Create a virtual environment
19 python -m venv "$pkgdir/usr/share/curd/venv"
20
21 # Install pypresence in the virtual environment
22 "$pkgdir/usr/share/curd/venv/bin/pip" install pypresence requests
23
24 # Install the Python script
25 install -Dm755 "$srcdir/curd.py" "$pkgdir/usr/bin/curd.py"
26
27 # Create the run script
28 cat << 'EOF' > "$pkgdir/usr/bin/curd"
29#!/bin/bash
30
31# Path to the virtual environment
32VENV_DIR="/usr/share/curd/venv"
33
34# Activate the virtual environment
35source "$VENV_DIR/bin/activate"
36
37# Run the Python script
38python /usr/bin/curd.py
39
40# Deactivate the virtual environment after running
41deactivate
42EOF
43
44 # Make the run script executable
45 chmod +x "$pkgdir/usr/bin/curd"
46}
curd.py +206 −157
@@ -35,6 +35,9 @@ def get_aniskip_data(anime_id, episode):
35 response = requests.get(url) 35 response = requests.get(url)
36 response.raise_for_status() # Raise an exception for bad status codes 36 response.raise_for_status() # Raise an exception for bad status codes
37 return response.text 37 return response.text
38 except KeyboardInterrupt:
39 print("bye")
40 exit(0)
38 except requests.RequestException as e: 41 except requests.RequestException as e:
39 print(f"Error fetching data from AniSkip API: {e}") 42 print(f"Error fetching data from AniSkip API: {e}")
40 return None 43 return None
@@ -301,6 +304,9 @@ def search_anime_by_title(json_data, search_title):
301 'episodes': episodes, 304 'episodes': episodes,
302 'duration': duration, 305 'duration': duration,
303 }) 306 })
307 except KeyboardInterrupt:
308 print("bye")
309 exit(0)
304 except: 310 except:
305 pass 311 pass
306 312
@@ -503,6 +509,9 @@ def select_anime(anime_list):
503 # Refresh screen 509 # Refresh screen
504 stdscr.refresh() 510 stdscr.refresh()
505 511
512 except KeyboardInterrupt:
513 print("bye")
514 exit(0)
506 except Exception as e: 515 except Exception as e:
507 # If an exception occurs, print it after exiting curses 516 # If an exception occurs, print it after exiting curses
508 curses.endwin() 517 curses.endwin()
@@ -535,6 +544,9 @@ def select_anime(anime_list):
535 # Initialize curses 544 # Initialize curses
536 try: 545 try:
537 curses.wrapper(main) 546 curses.wrapper(main)
547 except KeyboardInterrupt:
548 print("bye")
549 exit(0)
538 except: 550 except:
539 pass 551 pass
540 552
@@ -620,6 +632,9 @@ def mpv_send_command(ipc_socket_path, command):
620 response_data = json.loads(response) 632 response_data = json.loads(response)
621 if 'data' in response_data: 633 if 'data' in response_data:
622 return response_data['data'] 634 return response_data['data']
635 except KeyboardInterrupt:
636 print("bye")
637 exit(0)
623 except json.JSONDecodeError: 638 except json.JSONDecodeError:
624 return None 639 return None
625 return None 640 return None
@@ -743,6 +758,9 @@ def update_anime(database_file: str, anilist_id:str, allanime_id: str, episode:s
743 writer.writerow([anime['anilist_id'], anime['allanime_id'], anime['episode'], anime['time'], anime['duration'], anime['name']]) 758 writer.writerow([anime['anilist_id'], anime['allanime_id'], anime['episode'], anime['time'], anime['duration'], anime['name']])
744 759
745 # print("Updated the file") 760 # print("Updated the file")
761 except KeyboardInterrupt:
762 print("bye")
763 exit(0)
746 except Exception as e: 764 except Exception as e:
747 print_error(f"This: {e}") 765 print_error(f"This: {e}")
748 766
@@ -803,6 +821,9 @@ def download_anilist_data(access_token, user_id):
803 print("Cannot process user data.") 821 print("Cannot process user data.")
804 # print(anilist_user_data) 822 # print(anilist_user_data)
805 exit() 823 exit()
824 except KeyboardInterrupt:
825 print("bye")
826 exit(0)
806 except: 827 except:
807 pass 828 pass
808 829
@@ -865,6 +886,9 @@ def load_config() -> dict:
865 try: 886 try:
866 print("making folder") 887 print("making folder")
867 os.makedirs(folder_name) 888 os.makedirs(folder_name)
889 except KeyboardInterrupt:
890 print("bye")
891 exit(0)
868 except: 892 except:
869 print("error making folder") 893 print("error making folder")
870 pass 894 pass
@@ -895,6 +919,9 @@ def load_config() -> dict:
895 919
896 try: 920 try:
897 value = int(value) 921 value = int(value)
922 except KeyboardInterrupt:
923 print("bye")
924 exit(0)
898 except Exception as e: 925 except Exception as e:
899 # print_error("878: {e}") 926 # print_error("878: {e}")
900 pass 927 pass
@@ -1108,112 +1135,124 @@ get_episode_url
1108 os.chmod(script_path, 0o755) 1135 os.chmod(script_path, 0o755)
1109 1136
1110# ----------------------------------------------- Start of script ---------------------------------------- 1137# ----------------------------------------------- Start of script ----------------------------------------
1138try:
1139 current_dir = Path(__file__).parent
1140 # current_dir = os.path.dirname(os.path.abspath(__file__))
1141 # print(current_dir)
1142 if not os.path.exists(f"/tmp/curd/"):
1143 try:
1144 print("making tmp directory")
1145 os.makedirs(os.path.dirname(f"/tmp/curd/"))
1146 except KeyboardInterrupt:
1147 print("bye")
1148 exit(0)
1149 except:
1150 pass
1111 1151
1112current_dir = Path(__file__).parent 1152 rewatching = False
1113# current_dir = os.path.dirname(os.path.abspath(__file__))
1114# print(current_dir)
1115if not os.path.exists(f"/tmp/curd/"):
1116 try:
1117 print("making tmp directory")
1118 os.makedirs(os.path.dirname(f"/tmp/curd/"))
1119 except:
1120 pass
1121 1153
1122rewatching = False 1154 parser = argparse.ArgumentParser(description="Print a greeting message.")
1155 # parser.add_argument("--name", type=str, required=True, help="Your name")
1156 parser.add_argument("-new", action='store_true', help="Add new anime to watching (optional)")
1157 parser.add_argument("-sub", action='store_true', help="Anime audio type (optional)")
1158 parser.add_argument("-dub", action='store_true', help="Anime audio type (optional)")
1159 parser.add_argument("-c", action='store_true', help="Continue last watching anime (optional)")
1160 parser.add_argument("-u", action='store_true', help="Update script (optional)")
1161 parser.add_argument("-e", action='store_true', help="Edit config (optional)")
1162 args = parser.parse_args()
1123 1163
1124parser = argparse.ArgumentParser(description="Print a greeting message.") 1164 if args.u:
1125# parser.add_argument("--name", type=str, required=True, help="Your name") 1165 update_script()
1126parser.add_argument("-new", action='store_true', help="Add new anime to watching (optional)") 1166 exit(0)
1127parser.add_argument("-sub", action='store_true', help="Anime audio type (optional)")
1128parser.add_argument("-dub", action='store_true', help="Anime audio type (optional)")
1129parser.add_argument("-c", action='store_true', help="Continue last watching anime (optional)")
1130parser.add_argument("-u", action='store_true', help="Update script (optional)")
1131parser.add_argument("-e", action='store_true', help="Edit config (optional)")
1132args = parser.parse_args()
1133 1167
1134if args.u: 1168 user_config = load_config() # python dictionary containing all the configs as key value pairs
1135 update_script() 1169 history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file"))
1136 exit(0) 1170 history_file_path_ = os.path.dirname(history_file_path_)
1171 access_token_path = os.path.join(history_file_path_, "token")
1137 1172
1138user_config = load_config() # python dictionary containing all the configs as key value pairs 1173 if args.e:
1139history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file")) 1174 os.system("vim "+get_userconfig_value(user_config, "history_file"))
1140history_file_path_ = os.path.dirname(history_file_path_) 1175 print("updated config.")
1141access_token_path = os.path.join(history_file_path_, "token") 1176 exit(0)
1142 1177
1143if args.e: 1178 create_anime_list()
1144 os.system("vim "+get_userconfig_value(user_config, "history_file")) 1179 create_episode_list()
1145 print("updated config.") 1180 create_episode_url()
1146 exit(0)
1147 1181
1148create_anime_list() 1182 if os.path.exists(access_token_path):
1149create_episode_list() 1183 # Read and use the token
1150create_episode_url() 1184 with open(access_token_path, "r") as token_file:
1185 access_token = token_file.read().strip()
1186 # print(f"Token found: {access_token}")
1151 1187
1152if os.path.exists(access_token_path): 1188 else:
1153 # Read and use the token 1189 print("Generate the token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token ")
1154 with open(access_token_path, "r") as token_file: 1190 access_token = input("Token file not found. Please generate and enter your token: ")
1155 access_token = token_file.read().strip() 1191 if "https://" in access_token:
1156 # print(f"Token found: {access_token}") 1192 # Parse the URL fragment part (after the `#`)
1193 fragment = urllib.parse.urlparse(access_token).fragment
1157 1194
1158else: 1195 # Parse the fragment into components
1159 print("Generate the token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token ") 1196 params = urllib.parse.parse_qs(fragment)
1160 access_token = input("Token file not found. Please generate and enter your token: ")
1161 if "https://" in access_token:
1162 # Parse the URL fragment part (after the `#`)
1163 fragment = urllib.parse.urlparse(access_token).fragment
1164 1197
1165 # Parse the fragment into components 1198 # Extract only the access_token without any other parameters
1166 params = urllib.parse.parse_qs(fragment) 1199 access_token = params['access_token'][0] if 'access_token' in params else None
1167 1200
1168 # Extract only the access_token without any other parameters 1201 print("Access Token:", access_token)
1169 access_token = params['access_token'][0] if 'access_token' in params else None 1202 with open(access_token_path, "w") as token_file:
1203 token_file.write(access_token)
1204 print(f"Token saved to {access_token_path}")
1170 1205
1171 print("Access Token:", access_token) 1206 if access_token == None:
1172 with open(access_token_path, "w") as token_file: 1207 print("No Access_token provided.")
1173 token_file.write(access_token) 1208 exit(1)
1174 print(f"Token saved to {access_token_path}")
1175 1209
1176if access_token == None: 1210 user_id, user_name = get_anilist_user_id(access_token)
1177 print("No Access_token provided.") 1211 mark_episode_as_completed_at = get_userconfig_value(user_config, "percentage_to_mark_complete")
1178 exit(1) 1212 anilist_user_data = download_anilist_data(access_token, user_id)
1213 anime_dict = extract_anime_info(anilist_user_data)[0]
1179 1214
1180user_id, user_name = get_anilist_user_id(access_token) 1215 search_for_new_anime = False
1181mark_episode_as_completed_at = get_userconfig_value(user_config, "percentage_to_mark_complete") 1216 if not args.c and not args.new:
1182anilist_user_data = download_anilist_data(access_token, user_id) 1217 select_anime(anime_dict)
1183anime_dict = extract_anime_info(anilist_user_data)[0] 1218 if read_tmp("anime") == 'Add new anime':
1219 search_for_new_anime = True
1184 1220
1185search_for_new_anime = False 1221 if args.c:
1186if not args.c and not args.new: 1222 try:
1187 select_anime(anime_dict) 1223 with open(os.path.join(history_file_path_, "curd_id"), "r") as temp1_:
1188 if read_tmp("anime") == 'Add new anime': 1224 write_to_tmp("id", temp1_.read())
1189 search_for_new_anime = True 1225 with open(os.path.join(history_file_path_, "curd_anime"), "r") as temp1_:
1226 write_to_tmp("anime", temp1_.read())
1227 except KeyboardInterrupt:
1228 print("bye")
1229 exit(0)
1230 except:
1231 print("No previous history!")
1232
1233 if args.new or search_for_new_anime:
1234 new_anime_name_ = input("Enter anime name: ")
1235 temp__ = search_anime_anilist(new_anime_name_, access_token)
1236 if temp__ :
1237 select_anime(temp__)
1238 add_anime_to_watching_list(read_tmp('id'), access_token)
1239 anilist_user_data = download_anilist_data(access_token, user_id)
1240 else:
1241 print("No anime found")
1242 exit(0)
1190 1243
1191if args.c: 1244 anime_name = read_tmp("anime")
1192 try: 1245 write_to_tmp("query", anime_name)
1193 with open(os.path.join(history_file_path_, "curd_id"), "r") as temp1_: 1246 run_script("anime_list")
1194 write_to_tmp("id", temp1_.read()) 1247 anime_dict = load_anime_data(f"/tmp/curd/curd_anime_list")
1195 with open(os.path.join(history_file_path_, "curd_anime"), "r") as temp1_: 1248 cleaned_text = re.sub(r'\(.*$', '', anime_name).strip() # clean anime name
1196 write_to_tmp("anime", temp1_.read()) 1249 # print(cleaned_text)
1197 except: 1250except KeyboardInterrupt:
1198 print("No previous history!") 1251 print('bye')
1199 1252 exit(0)
1200if args.new or search_for_new_anime: 1253except Exception as e:
1201 new_anime_name_ = input("Enter anime name: ") 1254 print("error: ", e)
1202 temp__ = search_anime_anilist(new_anime_name_, access_token)
1203 if temp__ :
1204 select_anime(temp__)
1205 add_anime_to_watching_list(read_tmp('id'), access_token)
1206 anilist_user_data = download_anilist_data(access_token, user_id)
1207 else:
1208 print("No anime found")
1209 exit(0)
1210 1255
1211anime_name = read_tmp("anime")
1212write_to_tmp("query", anime_name)
1213run_script("anime_list")
1214anime_dict = load_anime_data(f"/tmp/curd/curd_anime_list")
1215cleaned_text = re.sub(r'\(.*$', '', anime_name).strip() # clean anime name
1216# print(cleaned_text)
1217try: 1256try:
1218 result = search_anime_by_title(anilist_user_data, cleaned_text)[0] 1257 result = search_anime_by_title(anilist_user_data, cleaned_text)[0]
1219 # print(result) 1258 # print(result)
@@ -1248,79 +1287,82 @@ except Exception as e:
1248 print("Please select anime") 1287 print("Please select anime")
1249 select_anime(anime_dict) 1288 select_anime(anime_dict)
1250 1289
1251if get_userconfig_value(user_config, "sub_or_dub")=="sub": 1290try:
1252 write_to_tmp("mode", "sub") 1291 if get_userconfig_value(user_config, "sub_or_dub")=="sub":
1253elif get_userconfig_value(user_config, "sub_or_dub")=="dub": 1292 write_to_tmp("mode", "sub")
1254 write_to_tmp("mode", "dub") 1293 elif get_userconfig_value(user_config, "sub_or_dub")=="dub":
1255 1294 write_to_tmp("mode", "dub")
1256if args.sub: # arguments take precidence 1295
1257 write_to_tmp("mode", "sub") 1296 if args.sub: # arguments take precidence
1258if args.dub: 1297 write_to_tmp("mode", "sub")
1259 write_to_tmp("mode", "dub") 1298 if args.dub:
1260 1299 write_to_tmp("mode", "dub")
1261run_script("episode_list") 1300
1262 1301 run_script("episode_list")
1263binge_watching = False 1302
1264mpv_args = [] 1303 binge_watching = False
1265last_episode = int(read_tmp("episode_list").split()[-1]) 1304 mpv_args = []
1266anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file')) 1305 last_episode = int(read_tmp("episode_list").split()[-1])
1267anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id")) 1306 anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
1268episode_completed = False 1307 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
1269 1308 episode_completed = False
1270if anime_history: # if it exists in local history 1309
1271 # print(f"came in history {str(progress)}") 1310 if anime_history: # if it exists in local history
1272 # print(anime_history['episode']) 1311 # print(f"came in history {str(progress)}")
1273 if progress == last_episode or int(anime_history['episode']) == int(progress)+1: 1312 # print(anime_history['episode'])
1313 if progress == last_episode or int(anime_history['episode']) == int(progress)+1:
1314 if progress == last_episode:
1315 rewatching = True
1316 mpv_args.append(f"--start={anime_history['time']}")
1317 watching_ep = int(anime_history['episode'])
1318 write_to_tmp("ep_no", str(watching_ep))
1319 # print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
1320 elif int(anime_history['episode']) < progress+1: # if the upstream progress is ahead
1321 write_to_tmp("ep_no", str(int(progress)+1))
1322 print(f"Starting anime from upstream {str(progress + 1)}")
1323 watching_ep = progress + 1
1324 else: # if history does not exist
1274 if progress == last_episode: 1325 if progress == last_episode:
1275 rewatching = True 1326 user_input = input("Do you want to start this anime from beginning? (y/n):")
1276 mpv_args.append(f"--start={anime_history['time']}") 1327 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
1277 watching_ep = int(anime_history['episode']) 1328 progress = 0
1329 rewatching = True
1330 else:
1331 print("Starting last episode of anime")
1332 progress = last_episode - 1
1333 watching_ep = int(progress)+1
1278 write_to_tmp("ep_no", str(watching_ep)) 1334 write_to_tmp("ep_no", str(watching_ep))
1279 # print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}") 1335 # print(watching_ep)
1280 elif int(anime_history['episode']) < progress+1: # if the upstream progress is ahead 1336 # os.system("{current_dir}/scripts/episode_url.sh")
1281 write_to_tmp("ep_no", str(int(progress)+1)) 1337 print("Fetching anime")
1282 print(f"Starting anime from upstream {str(progress + 1)}") 1338 run_script("episode_url")
1283 watching_ep = progress + 1 1339
1284else: # if history does not exist 1340 # Print the result
1285 if progress == last_episode: 1341 if media_id:
1286 user_input = input("Do you want to start this anime from beginning? (y/n):") 1342 # print(f"Anime ID: {media_id}")
1287 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "": 1343 pass
1288 progress = 0 1344 else:
1289 rewatching = True 1345 print("Anime not found.")
1290 else: 1346 exit(1)
1291 print("Starting last episode of anime")
1292 progress = last_episode - 1
1293 watching_ep = int(progress)+1
1294 write_to_tmp("ep_no", str(watching_ep))
1295# print(watching_ep)
1296# os.system("{current_dir}/scripts/episode_url.sh")
1297print("Fetching anime")
1298run_script("episode_url")
1299
1300# Print the result
1301if media_id:
1302 # print(f"Anime ID: {media_id}")
1303 pass
1304else:
1305 print("Anime not found.")
1306 exit(1)
1307
1308links = load_links(f"/tmp/curd/curd_links")
1309 1347
1310if get_userconfig_value(user_config, "discord_presence") == True: 1348 links = load_links(f"/tmp/curd/curd_links")
1311 from pypresence import Presence
1312 # print("imported pypresence")
1313 rpc = Presence(discord_client_id)
1314 rpc.connect()
1315 anime_mal_id, anime_image_url = get_anime_id_and_image(media_id)
1316else:
1317 anime_mal_id = get_anime_mal_id(media_id)
1318 1349
1319# default variable declaration 1350 if get_userconfig_value(user_config, "discord_presence") == True:
1320watched_percentage = 0 1351 from pypresence import Presence
1321is_paused = False 1352 # print("imported pypresence")
1322mpv_playback_speed = 1.0 1353 rpc = Presence(discord_client_id)
1354 rpc.connect()
1355 anime_mal_id, anime_image_url = get_anime_id_and_image(media_id)
1356 else:
1357 anime_mal_id = get_anime_mal_id(media_id)
1323 1358
1359 # default variable declaration
1360 watched_percentage = 0
1361 is_paused = False
1362 mpv_playback_speed = 1.0
1363except KeyboardInterrupt:
1364 print("bye")
1365 exit(0)
1324while True: 1366while True:
1325 try: 1367 try:
1326 salt = random.randint(0,1500) 1368 salt = random.randint(0,1500)
@@ -1421,6 +1463,9 @@ while True:
1421 print("Have a great day!") 1463 print("Have a great day!")
1422 exit(0) 1464 exit(0)
1423 1465
1466 except KeyboardInterrupt:
1467 print("bye")
1468 exit(0)
1424 except Exception as e: # user did not close the stream 1469 except Exception as e: # user did not close the stream
1425 print(e) 1470 print(e)
1426 if killing_error == "property unavailable": # mpv is not started yet 1471 if killing_error == "property unavailable": # mpv is not started yet
@@ -1448,6 +1493,7 @@ while True:
1448 exit(0) 1493 exit(0)
1449 finally: 1494 finally:
1450 binge_watching=True 1495 binge_watching=True
1496
1451 try: 1497 try:
1452 # print("binge watching") 1498 # print("binge watching")
1453 current_ep = int(read_tmp("ep_no")) 1499 current_ep = int(read_tmp("ep_no"))
@@ -1491,6 +1537,9 @@ while True:
1491 binge_watching = True 1537 binge_watching = True
1492 else: 1538 else:
1493 exit(0) 1539 exit(0)
1540 except KeyboardInterrupt:
1541 print("bye")
1542 exit(0)
1494 except Exception as e: 1543 except Exception as e:
1495 # print(f"error:{e}\nMaybe try running again!") 1544 # print(f"error:{e}\nMaybe try running again!")
1496 print_error(f"{e}") 1545 print_error(f"{e}")