Commit 1ee89b307c

1ee89b307cdd74cb6a1d76fc7babb7a472c901a0

parent: a5fbb4e3fb

Unsigned

Wraient <wraient.911@gmail.com> · 2024-09-22 01:05 UTC

refactor way to get user config and create user config

Layout: unified · split

curd.py +49 −62
@@ -74,7 +74,37 @@ def download_anilist_data(access_token, user_id):
74 74
75 return anilist_user_data 75 return anilist_user_data
76 76
77def load_config(): 77default_config = {
78 "player":"mpv",
79 "show_adult_content":False,
80 "history_file":"$HOME/.local/share/curd/curd_history.txt",
81 "subs_language":"english",
82 "sub_or_dub":"sub",
83 "next_episode_prompt":False,
84 "score_on_completion":False,
85 "save_mpv_speed": True,
86 "discord_presence": True,
87 "presence_script_path":"curddiscordpresence.py"
88}
89
90def get_userconfig_value(userconfig:dict, key:str):
91 return userconfig.get(key, default_config.get(key))
92
93def create_default_user_config(default_config):
94 output_string = ""
95 for key, value in default_config.items():
96 # Convert Python True/False to lowercase true/false
97 if isinstance(value, bool):
98 value_str = 'true' if value else 'false'
99 else:
100 value_str = str(value)
101
102 # Write the key=value to the file with no spaces
103 output_string+=f"{key}={value_str}\n"
104
105 return output_string
106
107def load_config() -> dict:
78 command = """echo $(xdg-user-dir CONFIG)""" 108 command = """echo $(xdg-user-dir CONFIG)"""
79 109
80 result = subprocess.run(command, shell=True, capture_output=True, text=True) 110 result = subprocess.run(command, shell=True, capture_output=True, text=True)
@@ -97,16 +127,7 @@ def load_config():
97 pass 127 pass
98 128
99 with open(config_file_path, 'w') as file: 129 with open(config_file_path, 'w') as file:
100 file.write(r"""player="mpv" 130 file.write(create_default_user_config(default_config))
101show_adult_content=false
102history_file="$HOME/.local/share/curd/curd_history.txt"
103subs_language="english"
104sub_or_dub="sub"
105score_on_completion=true
106save_mpv_speed=true
107discord_presence=true
108presence_script_path="curddiscordpresence.py"
109""")
110 131
111 config_dict = {} 132 config_dict = {}
112 133
@@ -150,23 +171,14 @@ presence_script_path="curddiscordpresence.py"
150# START OF SCRIPT 171# START OF SCRIPT
151 172
152user_config = load_config() # python dictionary containing all the configs as key value pairs 173user_config = load_config() # python dictionary containing all the configs as key value pairs
153
154anilist_user_data = download_anilist_data(access_token, user_id) 174anilist_user_data = download_anilist_data(access_token, user_id)
155
156anime_dict = extract_anime_info(anilist_user_data)[0] 175anime_dict = extract_anime_info(anilist_user_data)[0]
157
158select_anime(anime_dict) 176select_anime(anime_dict)
159
160anime_name = read_tmp("anime") 177anime_name = read_tmp("anime")
161
162write_to_tmp("query", anime_name) 178write_to_tmp("query", anime_name)
163
164run_script("anime_list") 179run_script("anime_list")
165
166anime_dict = load_anime_data("scripts/tmp/anime_list") 180anime_dict = load_anime_data("scripts/tmp/anime_list")
167 181cleaned_text = re.sub(r'\(.*$', '', anime_name).strip() # clean anime name
168#clean anime name
169cleaned_text = re.sub(r'\(.*$', '', anime_name).strip()
170 182
171try: 183try:
172 result = search_anime_by_title(anilist_user_data, cleaned_text)[0] 184 result = search_anime_by_title(anilist_user_data, cleaned_text)[0]
@@ -184,7 +196,7 @@ except Exception as e:
184 exit(1) 196 exit(1)
185 197
186try: 198try:
187 finding_anime = find_anime(get_all_anime(user_config["history_file"]), anilist_id=str(media_id)) 199 finding_anime = find_anime(get_all_anime(get_userconfig_value(user_config, "history_file")), anilist_id=str(media_id))
188 # print(finding_anime) 200 # print(finding_anime)
189 if finding_anime: 201 if finding_anime:
190 print("Found anime in history") 202 print("Found anime in history")
@@ -203,29 +215,19 @@ except:
203 215
204run_script("episode_list") 216run_script("episode_list")
205 217
206# with open("scripts/tmp/episode_list") as ep_list:
207# temp = ep_list.read()
208# temp = temp.split()
209# last_episode = temp[-1]
210# ep_no = input(f"Enter episode number: (number of episodes: {last_episode})\n")
211
212binge_watching = False 218binge_watching = False
213
214mpv_args = [] 219mpv_args = []
215
216last_episode = int(read_tmp("episode_list").split()[-1]) 220last_episode = int(read_tmp("episode_list").split()[-1])
217 221anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
218anime_watch_history = get_all_anime(user_config['history_file'])
219# anime_watch_history[]
220anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id")) 222anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
221episode_completed = False 223episode_completed = False
222rewatching = False 224rewatching = False
225
223if anime_history: # if it exists in local history 226if anime_history: # if it exists in local history
224 # print(f"came in history {str(progress)}") 227 # print(f"came in history {str(progress)}")
225 if int(anime_history['episode']) != progress+1: # if the upstream progress is ahead 228 if int(anime_history['episode']) != progress+1: # if the upstream progress is ahead
226 write_to_tmp("ep_no", str(int(progress)+1)) 229 write_to_tmp("ep_no", str(int(progress)+1))
227 # print(f"Starting anime from upstream {str(progress + 1)}") 230 # print(f"Starting anime from upstream {str(progress + 1)}")
228
229 watching_ep = progress + 1 231 watching_ep = progress + 1
230 232
231 elif int(anime_history['episode']) == int(progress)+1: # if the upstream progress is NOT ahead 233 elif int(anime_history['episode']) == int(progress)+1: # if the upstream progress is NOT ahead
@@ -265,18 +267,13 @@ while True:
265 salt = random.randint(0,1500) 267 salt = random.randint(0,1500)
266 # print("SALT IS:"+str(salt)) 268 # print("SALT IS:"+str(salt))
267 start_video(links[0][1], salt, mpv_args) 269 start_video(links[0][1], salt, mpv_args)
268
269 mpv_socket_path = "/tmp/mpvsocket"+str(salt) 270 mpv_socket_path = "/tmp/mpvsocket"+str(salt)
270
271 connect_mpv_command = """echo '{ "command": ["get_property", "playback-time"] }' | socat - """+mpv_socket_path 271 connect_mpv_command = """echo '{ "command": ["get_property", "playback-time"] }' | socat - """+mpv_socket_path
272
273 mpv_pos_command = """echo '{ "command": ["get_property", "time-pos"] }' | socat - """+mpv_socket_path 272 mpv_pos_command = """echo '{ "command": ["get_property", "time-pos"] }' | socat - """+mpv_socket_path
274
275 mpv_duration_command = """echo '{ "command": ["get_property", "duration"] }' | socat - """+mpv_socket_path 273 mpv_duration_command = """echo '{ "command": ["get_property", "duration"] }' | socat - """+mpv_socket_path
276 274
277 while True: 275 while True:
278 time.sleep(2) 276 time.sleep(2)
279
280 result = subprocess.run(connect_mpv_command, shell=True, capture_output=True, text=True) 277 result = subprocess.run(connect_mpv_command, shell=True, capture_output=True, text=True)
281 # print(result) 278 # print(result)
282 if result.returncode == 0: 279 if result.returncode == 0:
@@ -288,18 +285,13 @@ while True:
288 data = json.loads(output) 285 data = json.loads(output)
289 if data["error"] == "success": 286 if data["error"] == "success":
290 playback_time = round(int(data["data"]), 2) 287 playback_time = round(int(data["data"]), 2)
291 288 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))
292 # print(user_config['history_file'])
293
294 update_anime(user_config['history_file'], str(media_id), str(get_contents_of("id")), str(watching_ep), str(playback_time), str(duration), str(title))
295 # print("Playback time:", playback_time) 289 # print("Playback time:", playback_time)
296
297 watched_percentage = get_percentage_watched(mpv_socket_path) 290 watched_percentage = get_percentage_watched(mpv_socket_path)
298 mpv_playback_speed = get_mpv_playback_speed(mpv_socket_path) 291 mpv_playback_speed = get_mpv_playback_speed(mpv_socket_path)
299 # print("mpv speed", mpv_playback_speed) 292 # print("mpv speed", mpv_playback_speed)
300 # print("watched percentage", watched_percentage) 293 # print("watched percentage", watched_percentage)
301 if watched_percentage > mark_episode_as_completed_at: 294 if watched_percentage > mark_episode_as_completed_at:
302
303 episode_completed = True 295 episode_completed = True
304 binge_watching = True 296 binge_watching = True
305 # else: 297 # else:
@@ -353,7 +345,7 @@ while True:
353 if watched_percentage > mark_episode_as_completed_at and not rewatching: 345 if watched_percentage > mark_episode_as_completed_at and not rewatching:
354 update_anime_progress(access_token, int(media_id), int(watching_ep)) 346 update_anime_progress(access_token, int(media_id), int(watching_ep))
355 watching_ep = int(watching_ep)+1 347 watching_ep = int(watching_ep)+1
356 update_anime(user_config['history_file'], str(media_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title)) 348 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))
357 349
358 print("bye") 350 print("bye")
359 exit(0) 351 exit(0)
@@ -364,12 +356,12 @@ while True:
364 current_ep = int(read_tmp("ep_no")) 356 current_ep = int(read_tmp("ep_no"))
365 357
366 if current_ep == last_episode: 358 if current_ep == last_episode:
367 if binge_watching == True and not rewatching and user_config['score_on_completion'] == True: # Completed anime 359 if binge_watching == True and not rewatching and get_userconfig_value(user_config, 'score_on_completion') == True: # Completed anime
368 anime_rating_by_user = input("Rate this anime:\n") 360 anime_rating_by_user = input("Rate this anime:\n")
369 update_anime_progress(access_token, int(media_id), int(watching_ep)) 361 update_anime_progress(access_token, int(media_id), int(watching_ep))
370 rate_anime(access_token, media_id, anime_rating_by_user) 362 rate_anime(access_token, media_id, anime_rating_by_user)
371 print("completed anime.") 363 print("completed anime.")
372 delete_anime(user_config['history_file'], media_id, get_contents_of("id")) 364 delete_anime(get_userconfig_value(user_config, 'history_file'), media_id, get_contents_of("id"))
373 exit(0) 365 exit(0)
374 366
375 else: 367 else:
@@ -382,8 +374,8 @@ while True:
382 update_anime_progress(access_token, int(media_id), int(watching_ep)) 374 update_anime_progress(access_token, int(media_id), int(watching_ep))
383 watching_ep = int(watching_ep)+1 375 watching_ep = int(watching_ep)+1
384 write_to_tmp("ep_no", str(watching_ep)) 376 write_to_tmp("ep_no", str(watching_ep))
385 update_anime(user_config['history_file'], str(media_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title)) 377 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))
386 anime_watch_history = get_all_anime(user_config['history_file']) 378 anime_watch_history = get_all_anime(get_userconfig_value(user_config, 'history_file'))
387 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id")) 379 anime_history = find_anime(anime_watch_history, anilist_id=media_id, allanime_id=get_contents_of("id"))
388 episode_completed = False 380 episode_completed = False
389 run_script("episode_url") 381 run_script("episode_url")
@@ -391,18 +383,13 @@ while True:
391 mpv_args = [] 383 mpv_args = []
392 watched_percentage = 0 384 watched_percentage = 0
393 385
394 if user_config['save_mpv_speed']==True: 386 if get_userconfig_value(user_config, 'save_mpv_speed') ==True:
395 mpv_args.append(f'--speed={mpv_playback_speed}') 387 mpv_args.append(f'--speed={mpv_playback_speed}')
396 388
397 # watching_ep = current_ep+1 389 # watching_ep = current_ep+1
398 390 if get_userconfig_value(user_config, 'next_episode_prompt') == True:
399 # to_continue_or_not_to_continue = input("Continue? (y/n)\n") 391 to_continue_or_not_to_continue = input("Continue? (y/n)\n")
400 # try: 392 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 == "":
401 # # print("percentage watched",percentage_watched(playback_time, duration), "%") 393 binge_watching = True
402 # except: 394 else:
403 # pass 395 exit(0)\ No newline at end of file
404 # 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 == "":
405 # binge_watching = True
406 # ep_no_file
407 # else:
408 # break