Commit fce2f26817

fce2f268172212e857b7daa36f6645f0bbd28cdb

parent: 2c0027ec4a

Unsigned

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

complete rewrite:
1. Can work almost perfectly, locally.
2. added loop logic for local streaming

Layout: unified · split

curd.py +192 −129
@@ -14,15 +14,16 @@ import time
1414from anilist import search_anime_by_title
1515from anilist import get_user_data, get_anilist_user_id
1616from select_link import load_links
17from start_video import start_video, send_command, get_percentage_watched
17from start_video import start_video, send_command, get_percentage_watched, percentage_watched
1818from select_anime import load_anime_data
1919from select_anime import extract_anime_info
2020from select_anime import select_anime
2121
2222from track_anime import add_anime, update_anime, get_all_anime, delete_anime, find_anime
2323
24access_token = os.environ.get('ANILIST_ACCESS_TOKEN')
24mark_episode_as_completed_at = 85
2525
26access_token = os.environ.get('ANILIST_ACCESS_TOKEN')
2627user_id, user_name = get_anilist_user_id(access_token)
2728# user_id = os.environ.get('ANILIST_USER_ID')
2829
@@ -37,9 +38,41 @@ def get_contents_of(tmp_file_name):
3738 with open(f"scripts/tmp/{tmp_file_name}", "r") as temp_file:
3839 return temp_file.read()
3940
40def run_script(script):
41def run_script(script: str):
4142 os.system(f"./scripts/{script}.sh")
4243
44def write_to_tmp(tmp_filename:str, content:str):
45 try:
46 with open(f"scripts/tmp/{tmp_filename}", "w") as _:
47 _.write(content)
48 return True
49 except:
50 return False
51
52def read_tmp(tmp_filename:str):
53 try:
54 with open(f"scripts/tmp/{tmp_filename}", "r") as _:
55 content = _.read()
56 return content
57 except:
58 return False
59
60def download_anilist_data(access_token, user_id):
61 ''' dowlnoad anilist user data'''
62 print("downloading user data")
63 anilist_user_data = get_user_data(access_token, user_id)
64 with open("response.json", "w") as response:
65 response.write(str(anilist_user_data))
66 try:
67 if anilist_user_data['data'] == None:
68 print("Cannot process user data.")
69 print(anilist_user_data)
70 exit()
71 except:
72 pass
73
74 return anilist_user_data
75
4376def load_config():
4477 command = """echo $(xdg-user-dir CONFIG)"""
4578
@@ -112,51 +145,25 @@ presence_script_path="curddiscordpresence.py"
112145 # with open(config_file_path, "r") as config_file:
113146 # return config_file.read()
114147
115user_config = load_config() # python dictionary containing all the configs as key value pairs
116
117print("downloading user data")
118anilist_user_data = get_user_data(access_token, user_id)
119with open("response.json", "w") as response:
120 response.write(str(anilist_user_data))
121try:
122 if anilist_user_data['data'] == None:
123 print("Cannot process user data.")
124 print(anilist_user_data)
125 exit()
126except:
127 pass
128
129# Searching for anime
130
131# with open("scripts/tmp/query", "w") as file:
132# file.write(input("Enter the anime you want:\n"))
148# START OF SCRIPT
133149
134# os.system("./scripts/anime_list.sh")
135
136# with open('response.json', 'r') as file:
137 # data = json.load(file)
150user_config = load_config() # python dictionary containing all the configs as key value pairs
138151
139# print(data)
140# print(type(data['data']))
152anilist_user_data = download_anilist_data(access_token, user_id)
141153
142154anime_dict = extract_anime_info(anilist_user_data)[0]
143# print(anime_dict)
144# anime_dict = load_anime_data("scripts/tmp/anime_list")
145# print(anime_dict)
146# print(f"ANIME DICT = {anime_dict}")
147155
148156select_anime(anime_dict)
149157
150with open("scripts/tmp/anime", "r") as anime:
151 anime_name = anime.read()
158anime_name = read_tmp("anime")
152159
153with open("scripts/tmp/query", "w") as query_file:
154 query_file.write(anime_name)
160write_to_tmp("query", anime_name)
155161
156162run_script("anime_list")
157163
158164anime_dict = load_anime_data("scripts/tmp/anime_list")
159165
166#clean anime name
160167cleaned_text = re.sub(r'\(.*$', '', anime_name).strip()
161168
162169try:
@@ -166,6 +173,10 @@ try:
166173 progress = int(result['progress'])
167174 title = result['english_title']
168175 total_episodes = result['episodes']
176 duration = result['duration']
177except KeyboardInterrupt:
178 print("bye")
179 exit(0)
169180except:
170181 print("fucked up")
171182 anime_id = 98460
@@ -176,16 +187,15 @@ try:
176187 print(finding_anime)
177188 if finding_anime:
178189 print("AUTOMATICALLY BABY")
179 with open("scripts/tmp/id", "w") as id_file:
180 id_file.write(finding_anime['allanime_id'])
181 with open("scripts/tmp/anime", "w") as anime_name_file:
182 anime_name_file.write(finding_anime['name'])
190 write_to_tmp("id", finding_anime['allanime_id'])
191 write_to_tmp("anime", finding_anime['name'])
183192 else:
184193 print("Trying to automate")
185 with open("scripts/tmp/id", "w") as id_file:
186 id_file.write(anime_dict[anime_name+f" ({total_episodes} episodes)"])
187 with open("scripts/tmp/anime", "w") as anime_name_file:
188 anime_name_file.write(anime_name)
194 write_to_tmp("id", anime_dict[anime_name+f" ({total_episodes} episodes)"])
195 write_to_tmp("anime", anime_name)
196except KeyboardInterrupt:
197 print("bye")
198 exit(0)
189199except:
190200 print("Cannot automate")
191201 select_anime(anime_dict)
@@ -200,80 +210,56 @@ run_script("episode_list")
200210
201211binge_watching = False
202212
203while True:
204
205 mpv_args = []
206
207 with open("scripts/tmp/episode_list") as ep_list:
208 temp = ep_list.read()
209 temp = temp.split()
210 last_episode = int(temp[-1])
211
212 anime_watch_history = get_all_anime(user_config['history_file'])
213
214 # anime_watch_history[]
215 anime_history = find_anime(anime_watch_history, anilist_id=anime_id, allanime_id=get_contents_of("id"))
216
217 if anime_history: # if it exists and if the progress is not ahead
218 print(f"came in history {str(progress)}")
219 if int(anime_history['episode']) != progress+1:
220 with open("scripts/tmp/ep_no", "w") as ep_no_file_2:
221 ep_no_file_2.write(str(int(progress)+1))
222 print(f"Starting anime from upstream {str(progress + 1)}")
223
224 watching_ep = progress + 1
225
226 elif int(anime_history['episode']) == int(progress)+1:
227 mpv_args.append(f"--start={anime_history['time']}")
228 with open("scripts/tmp/ep_no", "w") as ep_no_file_2:
229 ep_no_file_2.write(anime_history['episode'])
230 print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
231
232 watching_ep = anime_history['episode']
233 # if : # if upstream is ahead
234 # pass
235 else: # if there is no history
236 print("no history found")
237 if binge_watching:
238 print("binge watching")
239 with open("scripts/tmp/ep_no", "r") as ep_no_file_1:
240 current_ep = int(ep_no_file_1.read())
241 if current_ep == last_episode:
242 print("completed anime.")
243 # TODO: Add way to rate the anime
244 delete_anime(user_config['history_file'], anime_id, get_contents_of("id"))
245 exit(0)
246
247 else:
248 print(f"Next episode is here, goshujin sama progress: {current_ep} {type(current_ep)}")
249 with open("scripts/tmp/ep_no", "w") as ep_no_file:
250 ep_no_file.write(str(int(current_ep)+1))
251
252 watching_ep = current_ep+1
213mpv_args = []
214
215last_episode = int(read_tmp("episode_list").split()[-1])
216
217anime_watch_history = get_all_anime(user_config['history_file'])
218# anime_watch_history[]
219anime_history = find_anime(anime_watch_history, anilist_id=anime_id, allanime_id=get_contents_of("id"))
220episode_completed = False
221if anime_history: # if it exists in local history
222 print(f"came in history {str(progress)}")
223 if int(anime_history['episode']) != progress+1: # if the upstream progress is ahead
224 write_to_tmp("ep_no", str(int(progress)+1))
225 print(f"Starting anime from upstream {str(progress + 1)}")
226
227 watching_ep = progress + 1
228
229 elif int(anime_history['episode']) == int(progress)+1: # if the upstream progress is NOT ahead
230 mpv_args.append(f"--start={anime_history['time']}")
231 write_to_tmp("ep_no", anime_history['episode'])
232 print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
233
234 watching_ep = int(anime_history['episode'])
235else: # if there is no history
236 print("no history found")
237
238 print("First time watch")
239
240 if progress == last_episode:
241 user_input = input("Do you want to start this anime from beginning? (y/n):")
242 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
243 progress = 0
253244 else:
254 print("First time watch")
255 with open("scripts/tmp/ep_no", "w") as ep_no_file:
245 print("Starting last episode of anime")
246 progress = last_episode - 1
256247
257 if progress == last_episode:
258 user_input = input("Do you want to start this anime from beginning? (y/n):")
259 if user_input.lower() == "yes" or user_input.lower() == "y" or user_input.lower() == "":
260 progress = 0
261 else:
262 print("Starting last episode of anime")
263 progress = last_episode - 1
248 watching_ep = int(progress)+1
249 write_to_tmp("ep_no", str(watching_ep))
264250
265 watching_ep = progress+1
266 ep_no_file.write(str(watching_ep))
251# os.system("./scripts/episode_url.sh")
252run_script("episode_url")
267253
268 os.system("./scripts/episode_url.sh")
254# Print the result
255if anime_id:
256 print(f"Anime ID: {anime_id}")
257else:
258 print("Anime not found.")
269259
270 # Print the result
271 if anime_id:
272 print(f"Anime ID: {anime_id}")
273 else:
274 print("Anime not found.")
260links = load_links("scripts/tmp/links")
275261
276 links = load_links("scripts/tmp/links")
262while True:
277263
278264 try:
279265 salt = random.randint(0,1500)
@@ -288,7 +274,6 @@ while True:
288274
289275 mpv_duration_command = """echo '{ "command": ["get_property", "duration"] }' | socat - """+mpv_socket_path
290276
291
292277 while True:
293278 time.sleep(2)
294279
@@ -302,42 +287,120 @@ while True:
302287 try:
303288 data = json.loads(output)
304289 if data["error"] == "success":
305 playback_time = round(int(data["data"]))
290 playback_time = round(int(data["data"]), 2)
306291
307 print(user_config['history_file'])
292 # print(user_config['history_file'])
308293
309 update_anime(user_config['history_file'], str(anime_id), str(get_contents_of("id")), str(watching_ep), str(playback_time), str(title))
310 print("Playback time:", playback_time)
294 update_anime(user_config['history_file'], str(anime_id), str(get_contents_of("id")), str(watching_ep), str(playback_time), str(duration), str(title))
295 # print("Playback time:", playback_time)
311296
312297 watched_percentage = get_percentage_watched(mpv_socket_path)
313 print(watched_percentage)
314 if watched_percentage > 85:
315 print("Completed")
298 print("watched percentage", watched_percentage)
299 if watched_percentage > mark_episode_as_completed_at:
300
301 episode_completed = True
302 binge_watching = True
303 else:
304 print(f"Episode not done: {watched_percentage} {mark_episode_as_completed_at}")
316305 # video_duration = subprocess.run(mpv_duration_command, shell=True, capture_output=True, text=True)
317
306
318307 else:
319 if data['error'] == "property unavailable":
308 if data['error'] == "property unavailable": # Stream has not started yet
320309 pass
321310 else:
322 print("Error:", data["error"])
311 print("Error (330):", data["error"])
323312 break
324313 except json.decoder.JSONDecodeError as e:
325314 print("Error decoding JSON:", e)
326315 break # Exit the loop on unexpected JSON error
316 except KeyboardInterrupt:
317 print("bye")
318 exit(0)
319 except Exception as e:
320 print("some error fucked everything up:\n", e)
327321 else:
328322 killing_error = str(result.stderr)
329323 if killing_error == "property unavailable": # mpv is not started yet
330324 print("passing")
331325 pass
332 else:
333 print("Error:", killing_error)
326 else: # Stream has ended (maybe)
327 print("Error (346):", killing_error)
328 # try:
329
330 # except Exception as e:
331 # print("fuck")
332 # print(f"Exception: {e}")
334333 break
335334 except ConnectionRefusedError:
336335 print("Player Closed")
336 except KeyboardInterrupt:
337 if watched_percentage > mark_episode_as_completed_at:
338 watching_ep = int(watching_ep)+1
339
340 update_anime(user_config['history_file'], str(anime_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title))
341
342 print("bye")
343 exit(0)
337344 finally:
338 to_continue_or_not_to_continue = input("Continue? (y/n)\n")
339 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 == "":
340 binge_watching = True
345 binge_watching=True
346
347 print("binge watching")
348 current_ep = int(read_tmp("ep_no"))
349
350 if current_ep == last_episode:
351 print("completed anime.")
352 # TODO: Add way to rate the anime
353 delete_anime(user_config['history_file'], anime_id, get_contents_of("id"))
354 exit(0)
355
356 else:
357 print(f"Next episode is here, goshujin sama progress: {current_ep} {type(current_ep)}")
358 # write_to_tmp("ep_no", str(int(current_ep)+1))
359
360 if watched_percentage > mark_episode_as_completed_at:
361 last_episode = int(read_tmp("episode_list").split()[-1])
362
363 watching_ep = int(watching_ep)+1
364 write_to_tmp("ep_no", str(watching_ep))
365 print("here")
366 update_anime(user_config['history_file'], str(anime_id), str(get_contents_of("id")), str(watching_ep), "0", str(duration), str(title))
367 print("inside")
368 print(f"Episode done: {type(watching_ep)}")
369 print(f"Episode done: {int(watching_ep)}")
370
371 anime_watch_history = get_all_anime(user_config['history_file'])
372 # anime_watch_history[]
373 anime_history = find_anime(anime_watch_history, anilist_id=anime_id, allanime_id=get_contents_of("id"))
374 episode_completed = False
375 if anime_history: # if it exists in local history
376 print(f"came in history {str(anime_history['episode'])}")
377 print("is ahead")
378 # write_to_tmp("ep_no", str(int(progress)+1))
379 # print(f"Starting anime from upstream {str(progress + 1)}")
380
381 # watching_ep = progress + 1
382
383 # elif int(anime_history['episode']) == int(progress)+1: # if the upstream progress is NOT ahead
384 # print("is equal")
385 mpv_args.append(f"--start={anime_history['time']}")
386 # write_to_tmp("ep_no", watching_ep)
387 print(f"STARTING ANIME FROM EPISODE {anime_history['episode']} {anime_history['time']}")
388 watching_ep = int(anime_history['episode'])
389
390 print("watching ep", watching_ep)
391
392 run_script("episode_url")
393 links = load_links("scripts/tmp/links")
394 mpv_args = []
395 # watching_ep = current_ep+1
396
397 # to_continue_or_not_to_continue = input("Continue? (y/n)\n")
398 # try:
399 # # print("percentage watched",percentage_watched(playback_time, duration), "%")
400 # except:
401 # pass
402 # 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 == "":
403 # binge_watching = True
341404 # ep_no_file
342 else:
343 break
405 # else:
406 # break