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):
3535 response = requests.get(url)
3636 response.raise_for_status() # Raise an exception for bad status codes
3737 return response.text
38 except KeyboardInterrupt:
39 print("bye")
40 exit(0)
3841 except requests.RequestException as e:
3942 print(f"Error fetching data from AniSkip API: {e}")
4043 return None
@@ -301,6 +304,9 @@ def search_anime_by_title(json_data, search_title):
301304 'episodes': episodes,
302305 'duration': duration,
303306 })
307 except KeyboardInterrupt:
308 print("bye")
309 exit(0)
304310 except:
305311 pass
306312
@@ -503,6 +509,9 @@ def select_anime(anime_list):
503509 # Refresh screen
504510 stdscr.refresh()
505511
512 except KeyboardInterrupt:
513 print("bye")
514 exit(0)
506515 except Exception as e:
507516 # If an exception occurs, print it after exiting curses
508517 curses.endwin()
@@ -535,6 +544,9 @@ def select_anime(anime_list):
535544 # Initialize curses
536545 try:
537546 curses.wrapper(main)
547 except KeyboardInterrupt:
548 print("bye")
549 exit(0)
538550 except:
539551 pass
540552
@@ -620,6 +632,9 @@ def mpv_send_command(ipc_socket_path, command):
620632 response_data = json.loads(response)
621633 if 'data' in response_data:
622634 return response_data['data']
635 except KeyboardInterrupt:
636 print("bye")
637 exit(0)
623638 except json.JSONDecodeError:
624639 return None
625640 return None
@@ -743,6 +758,9 @@ def update_anime(database_file: str, anilist_id:str, allanime_id: str, episode:s
743758 writer.writerow([anime['anilist_id'], anime['allanime_id'], anime['episode'], anime['time'], anime['duration'], anime['name']])
744759
745760 # print("Updated the file")
761 except KeyboardInterrupt:
762 print("bye")
763 exit(0)
746764 except Exception as e:
747765 print_error(f"This: {e}")
748766
@@ -803,6 +821,9 @@ def download_anilist_data(access_token, user_id):
803821 print("Cannot process user data.")
804822 # print(anilist_user_data)
805823 exit()
824 except KeyboardInterrupt:
825 print("bye")
826 exit(0)
806827 except:
807828 pass
808829
@@ -865,6 +886,9 @@ def load_config() -> dict:
865886 try:
866887 print("making folder")
867888 os.makedirs(folder_name)
889 except KeyboardInterrupt:
890 print("bye")
891 exit(0)
868892 except:
869893 print("error making folder")
870894 pass
@@ -895,6 +919,9 @@ def load_config() -> dict:
895919
896920 try:
897921 value = int(value)
922 except KeyboardInterrupt:
923 print("bye")
924 exit(0)
898925 except Exception as e:
899926 # print_error("878: {e}")
900927 pass
@@ -1108,112 +1135,124 @@ get_episode_url
11081135 os.chmod(script_path, 0o755)
11091136
11101137# ----------------------------------------------- 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
11111151
1112current_dir = Path(__file__).parent
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
1152 rewatching = False
11211153
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()
11231163
1124parser = argparse.ArgumentParser(description="Print a greeting message.")
1125# parser.add_argument("--name", type=str, required=True, help="Your name")
1126parser.add_argument("-new", action='store_true', help="Add new anime to watching (optional)")
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()
1164 if args.u:
1165 update_script()
1166 exit(0)
11331167
1134if args.u:
1135 update_script()
1136 exit(0)
1168 user_config = load_config() # python dictionary containing all the configs as key value pairs
1169 history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file"))
1170 history_file_path_ = os.path.dirname(history_file_path_)
1171 access_token_path = os.path.join(history_file_path_, "token")
11371172
1138user_config = load_config() # python dictionary containing all the configs as key value pairs
1139history_file_path_ = os.path.expandvars(get_userconfig_value(user_config, "history_file"))
1140history_file_path_ = os.path.dirname(history_file_path_)
1141access_token_path = os.path.join(history_file_path_, "token")
1173 if args.e:
1174 os.system("vim "+get_userconfig_value(user_config, "history_file"))
1175 print("updated config.")
1176 exit(0)
11421177
1143if args.e:
1144 os.system("vim "+get_userconfig_value(user_config, "history_file"))
1145 print("updated config.")
1146 exit(0)
1178 create_anime_list()
1179 create_episode_list()
1180 create_episode_url()
11471181
1148create_anime_list()
1149create_episode_list()
1150create_episode_url()
1182 if os.path.exists(access_token_path):
1183 # Read and use the token
1184 with open(access_token_path, "r") as token_file:
1185 access_token = token_file.read().strip()
1186 # print(f"Token found: {access_token}")
11511187
1152if os.path.exists(access_token_path):
1153 # Read and use the token
1154 with open(access_token_path, "r") as token_file:
1155 access_token = token_file.read().strip()
1156 # print(f"Token found: {access_token}")
1188 else:
1189 print("Generate the token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token ")
1190 access_token = input("Token file not found. Please generate and enter your token: ")
1191 if "https://" in access_token:
1192 # Parse the URL fragment part (after the `#`)
1193 fragment = urllib.parse.urlparse(access_token).fragment
11571194
1158else:
1159 print("Generate the token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token ")
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
1195 # Parse the fragment into components
1196 params = urllib.parse.parse_qs(fragment)
11641197
1165 # Parse the fragment into components
1166 params = urllib.parse.parse_qs(fragment)
1198 # Extract only the access_token without any other parameters
1199 access_token = params['access_token'][0] if 'access_token' in params else None
11671200
1168 # Extract only the access_token without any other parameters
1169 access_token = params['access_token'][0] if 'access_token' in params else None
1201 print("Access Token:", access_token)
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}")
11701205
1171 print("Access Token:", access_token)
1172 with open(access_token_path, "w") as token_file:
1173 token_file.write(access_token)
1174 print(f"Token saved to {access_token_path}")
1206 if access_token == None:
1207 print("No Access_token provided.")
1208 exit(1)
11751209
1176if access_token == None:
1177 print("No Access_token provided.")
1178 exit(1)
1210 user_id, user_name = get_anilist_user_id(access_token)
1211 mark_episode_as_completed_at = get_userconfig_value(user_config, "percentage_to_mark_complete")
1212 anilist_user_data = download_anilist_data(access_token, user_id)
1213 anime_dict = extract_anime_info(anilist_user_data)[0]
11791214
1180user_id, user_name = get_anilist_user_id(access_token)
1181mark_episode_as_completed_at = get_userconfig_value(user_config, "percentage_to_mark_complete")
1182anilist_user_data = download_anilist_data(access_token, user_id)
1183anime_dict = extract_anime_info(anilist_user_data)[0]
1215 search_for_new_anime = False
1216 if not args.c and not args.new:
1217 select_anime(anime_dict)
1218 if read_tmp("anime") == 'Add new anime':
1219 search_for_new_anime = True
11841220
1185search_for_new_anime = False
1186if not args.c and not args.new:
1187 select_anime(anime_dict)
1188 if read_tmp("anime") == 'Add new anime':
1189 search_for_new_anime = True
1221 if args.c:
1222 try:
1223 with open(os.path.join(history_file_path_, "curd_id"), "r") as temp1_:
1224 write_to_tmp("id", temp1_.read())
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)
11901243
1191if args.c:
1192 try:
1193 with open(os.path.join(history_file_path_, "curd_id"), "r") as temp1_:
1194 write_to_tmp("id", temp1_.read())
1195 with open(os.path.join(history_file_path_, "curd_anime"), "r") as temp1_:
1196 write_to_tmp("anime", temp1_.read())
1197 except:
1198 print("No previous history!")
1199
1200if args.new or search_for_new_anime:
1201 new_anime_name_ = input("Enter anime name: ")
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)
1244 anime_name = read_tmp("anime")
1245 write_to_tmp("query", anime_name)
1246 run_script("anime_list")
1247 anime_dict = load_anime_data(f"/tmp/curd/curd_anime_list")
1248 cleaned_text = re.sub(r'\(.*$', '', anime_name).strip() # clean anime name
1249 # print(cleaned_text)
1250except KeyboardInterrupt:
1251 print('bye')
1252 exit(0)
1253except Exception as e:
1254 print("error: ", e)
12101255
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)
12171256try:
12181257 result = search_anime_by_title(anilist_user_data, cleaned_text)[0]
12191258 # print(result)
@@ -1248,79 +1287,82 @@ except Exception as e:
12481287 print("Please select anime")
12491288 select_anime(anime_dict)
12501289
1251if get_userconfig_value(user_config, "sub_or_dub")=="sub":
1252 write_to_tmp("mode", "sub")
1253elif get_userconfig_value(user_config, "sub_or_dub")=="dub":
1254 write_to_tmp("mode", "dub")
1255
1256if args.sub: # arguments take precidence
1257 write_to_tmp("mode", "sub")
1258if args.dub:
1259 write_to_tmp("mode", "dub")
1260
1261run_script("episode_list")
1262
1263binge_watching = False
1264mpv_args = []
1265last_episode = int(read_tmp("episode_list").split()[-1])
1266anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
1267anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
1268episode_completed = False
1269
1270if anime_history: # if it exists in local history
1271 # print(f"came in history {str(progress)}")
1272 # print(anime_history['episode'])
1273 if progress == last_episode or int(anime_history['episode']) == int(progress)+1:
1290try:
1291 if get_userconfig_value(user_config, "sub_or_dub")=="sub":
1292 write_to_tmp("mode", "sub")
1293 elif get_userconfig_value(user_config, "sub_or_dub")=="dub":
1294 write_to_tmp("mode", "dub")
1295
1296 if args.sub: # arguments take precidence
1297 write_to_tmp("mode", "sub")
1298 if args.dub:
1299 write_to_tmp("mode", "dub")
1300
1301 run_script("episode_list")
1302
1303 binge_watching = False
1304 mpv_args = []
1305 last_episode = int(read_tmp("episode_list").split()[-1])
1306 anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
1307 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
1308 episode_completed = False
1309
1310 if anime_history: # if it exists in local history
1311 # print(f"came in history {str(progress)}")
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
12741325 if progress == last_episode:
1275 rewatching = True
1276 mpv_args.append(f"--start={anime_history['time']}")
1277 watching_ep = int(anime_history['episode'])
1326 user_input = input("Do you want to start this anime from beginning? (y/n):")
1327 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
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
12781334 write_to_tmp("ep_no", str(watching_ep))
1279 # print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
1280 elif int(anime_history['episode']) < progress+1: # if the upstream progress is ahead
1281 write_to_tmp("ep_no", str(int(progress)+1))
1282 print(f"Starting anime from upstream {str(progress + 1)}")
1283 watching_ep = progress + 1
1284else: # if history does not exist
1285 if progress == last_episode:
1286 user_input = input("Do you want to start this anime from beginning? (y/n):")
1287 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
1288 progress = 0
1289 rewatching = True
1290 else:
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")
1335 # print(watching_ep)
1336 # os.system("{current_dir}/scripts/episode_url.sh")
1337 print("Fetching anime")
1338 run_script("episode_url")
1339
1340 # Print the result
1341 if media_id:
1342 # print(f"Anime ID: {media_id}")
1343 pass
1344 else:
1345 print("Anime not found.")
1346 exit(1)
13091347
1310if get_userconfig_value(user_config, "discord_presence") == True:
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)
1348 links = load_links(f"/tmp/curd/curd_links")
13181349
1319# default variable declaration
1320watched_percentage = 0
1321is_paused = False
1322mpv_playback_speed = 1.0
1350 if get_userconfig_value(user_config, "discord_presence") == True:
1351 from pypresence import Presence
1352 # print("imported pypresence")
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)
13231358
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)
13241366while True:
13251367 try:
13261368 salt = random.randint(0,1500)
@@ -1421,6 +1463,9 @@ while True:
14211463 print("Have a great day!")
14221464 exit(0)
14231465
1466 except KeyboardInterrupt:
1467 print("bye")
1468 exit(0)
14241469 except Exception as e: # user did not close the stream
14251470 print(e)
14261471 if killing_error == "property unavailable": # mpv is not started yet
@@ -1448,6 +1493,7 @@ while True:
14481493 exit(0)
14491494 finally:
14501495 binge_watching=True
1496
14511497 try:
14521498 # print("binge watching")
14531499 current_ep = int(read_tmp("ep_no"))
@@ -1491,6 +1537,9 @@ while True:
14911537 binge_watching = True
14921538 else:
14931539 exit(0)
1540 except KeyboardInterrupt:
1541 print("bye")
1542 exit(0)
14941543 except Exception as e:
14951544 # print(f"error:{e}\nMaybe try running again!")
14961545 print_error(f"{e}")