curd.py
343 lines · 11787 bytes · executable
1
2# search (anime_list.sh) -> tmp/anime_list
3# anime_id -> episode_list.sh
4# episode_number -> episdoe_url.sh -> tmp/links
5
6import re
7import os
8import json
9import socket
10import random
11import subprocess
12import time
13
14from anilist import search_anime_by_title
15from anilist import get_user_data, get_anilist_user_id
16from select_link import load_links
17from start_video import start_video, send_command, get_percentage_watched
18from select_anime import load_anime_data
19from select_anime import extract_anime_info
20from select_anime import select_anime
21
22from track_anime import add_anime, update_anime, get_all_anime, delete_anime, find_anime
23
24access_token = os.environ.get('ANILIST_ACCESS_TOKEN')
25
26user_id, user_name = get_anilist_user_id(access_token)
27# user_id = os.environ.get('ANILIST_USER_ID')
28
29if access_token == None:
30 print("No Access_token provided.")
31 exit(1)
32
33# print(access_token)
34# print(user_id)
35
36def get_contents_of(tmp_file_name):
37 with open(f"scripts/tmp/{tmp_file_name}", "r") as temp_file:
38 return temp_file.read()
39
40def run_script(script):
41 os.system(f"./scripts/{script}.sh")
42
43def load_config():
44 command = """echo $(xdg-user-dir CONFIG)"""
45
46 result = subprocess.run(command, shell=True, capture_output=True, text=True)
47 output = result.stdout.strip()
48
49 folder_name = f"{output}/.config/curd"
50 file_name = "curd.conf"
51
52 config_file_path = os.path.join(folder_name, file_name)
53
54 print(config_file_path)
55 if not os.path.exists(os.path.join(config_file_path)):
56 print("Creating config")
57
58 try:
59 print("making folder")
60 os.makedirs(folder_name)
61 except:
62 print("error making folder")
63 pass
64
65 with open(config_file_path, 'w') as file:
66 file.write(r"""player="mpv"
67show_adult_content=false
68history_file="$HOME/.local/share/curd/curd_history.txt"
69subs_language="english"
70sub_or_dub="sub"
71score_on_completion=true
72discord_presence=true
73presence_script_path="curddiscordpresence.py"
74""")
75
76 config_dict = {}
77
78 with open(config_file_path, 'r') as file:
79 for line in file:
80 # Strip whitespace and ignore comments or empty lines
81 line = line.strip()
82 if line and not line.startswith("#"):
83 # Split the line into key and value
84 key, value = line.split("=", 1)
85 key = key.strip()
86 value = value.strip().strip('"')
87
88 # Handle environment variables in the value
89 value = os.path.expandvars(value)
90
91 # Convert boolean strings to actual booleans
92 if value.lower() == "true":
93 value = True
94 elif value.lower() == "false":
95 value = False
96
97 # Store in the dictionary
98 config_dict[key] = value
99
100 if not os.path.exists(config_dict['history_file']):
101 try:
102 os.makedirs(os.path.dirname(config_dict['history_file']))
103 except:
104 pass
105 print("creating history file")
106 with open(config_dict["history_file"], "w") as history_file:
107 history_file.write("")
108
109 return config_dict
110
111 # else:
112 # with open(config_file_path, "r") as config_file:
113 # return config_file.read()
114
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"))
133
134# os.system("./scripts/anime_list.sh")
135
136# with open('response.json', 'r') as file:
137 # data = json.load(file)
138
139# print(data)
140# print(type(data['data']))
141
142anime_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}")
147
148select_anime(anime_dict)
149
150with open("scripts/tmp/anime", "r") as anime:
151 anime_name = anime.read()
152
153with open("scripts/tmp/query", "w") as query_file:
154 query_file.write(anime_name)
155
156run_script("anime_list")
157
158anime_dict = load_anime_data("scripts/tmp/anime_list")
159
160cleaned_text = re.sub(r'\(.*$', '', anime_name).strip()
161
162try:
163 result = search_anime_by_title(anilist_user_data, cleaned_text)[0]
164 print(result)
165 anime_id = result['id']
166 progress = int(result['progress'])
167 title = result['english_title']
168 total_episodes = result['episodes']
169except:
170 print("fucked up")
171 anime_id = 98460
172 progress = 0
173
174try:
175 finding_anime = find_anime(get_all_anime(user_config["history_file"]), anilist_id=str(anime_id))
176 print(finding_anime)
177 if finding_anime:
178 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'])
183 else:
184 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)
189except:
190 print("Cannot automate")
191 select_anime(anime_dict)
192
193run_script("episode_list")
194
195# with open("scripts/tmp/episode_list") as ep_list:
196# temp = ep_list.read()
197# temp = temp.split()
198# last_episode = temp[-1]
199# ep_no = input(f"Enter episode number: (number of episodes: {last_episode})\n")
200
201binge_watching = False
202
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
253 else:
254 print("First time watch")
255 with open("scripts/tmp/ep_no", "w") as ep_no_file:
256
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
264
265 watching_ep = progress+1
266 ep_no_file.write(str(watching_ep))
267
268 os.system("./scripts/episode_url.sh")
269
270 # Print the result
271 if anime_id:
272 print(f"Anime ID: {anime_id}")
273 else:
274 print("Anime not found.")
275
276 links = load_links("scripts/tmp/links")
277
278 try:
279 salt = random.randint(0,1500)
280 print("SALT IS:"+str(salt))
281 start_video(links[0][1], salt, mpv_args)
282
283 mpv_socket_path = "/tmp/mpvsocket"+str(salt)
284
285 connect_mpv_command = """echo '{ "command": ["get_property", "playback-time"] }' | socat - """+mpv_socket_path
286
287 mpv_pos_command = """echo '{ "command": ["get_property", "time-pos"] }' | socat - """+mpv_socket_path
288
289 mpv_duration_command = """echo '{ "command": ["get_property", "duration"] }' | socat - """+mpv_socket_path
290
291
292 while True:
293 time.sleep(2)
294
295 result = subprocess.run(connect_mpv_command, shell=True, capture_output=True, text=True)
296 # print(result)
297 if result.returncode == 0:
298 output = result.stdout.strip()
299
300 if not output: # Check if output is empty
301 print("No data received. Retrying...")
302 try:
303 data = json.loads(output)
304 if data["error"] == "success":
305 playback_time = round(int(data["data"]))
306
307 print(user_config['history_file'])
308
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)
311
312 watched_percentage = get_percentage_watched(mpv_socket_path)
313 print(watched_percentage)
314 if watched_percentage > 85:
315 print("Completed")
316 # video_duration = subprocess.run(mpv_duration_command, shell=True, capture_output=True, text=True)
317
318 else:
319 if data['error'] == "property unavailable":
320 pass
321 else:
322 print("Error:", data["error"])
323 break
324 except json.decoder.JSONDecodeError as e:
325 print("Error decoding JSON:", e)
326 break # Exit the loop on unexpected JSON error
327 else:
328 killing_error = str(result.stderr)
329 if killing_error == "property unavailable": # mpv is not started yet
330 print("passing")
331 pass
332 else:
333 print("Error:", killing_error)
334 break
335 except ConnectionRefusedError:
336 print("Player Closed")
337 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
341 # ep_no_file
342 else:
343 break