-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1478 lines (1126 loc) · 58.1 KB
/
main.py
File metadata and controls
1478 lines (1126 loc) · 58.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import requests
import json
import asyncio
import time
import threading
from tabulate import tabulate
from yaspin import yaspin
from yaspin.spinners import Spinners
from pprint import pprint
from prompt_toolkit import PromptSession
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from scripts import webscraper
from prompt_toolkit.completion import Completer, Completion
# Check if the 'scripts' directory exists; if not, raise an error
if not os.path.exists("scripts"):
raise FileNotFoundError("The 'scripts' directory is missing. It seems the cloning/copying/installing of this project failed.")
# Check if config.json file exists in the current directory
if not os.path.exists("config.json"):
raise FileNotFoundError("The 'config.json' file is missing.\n--- Important data is lost.\n\n--> Please run 'createJSONS.py' to create a new JSON file.\n")
# Check if the 'scripts/bookmark.json' file is missing
if not os.path.exists("scripts/bookmark.json"):
raise FileNotFoundError("The 'scripts/bookmark.json' file is missing.\n--- Important data is lost.\n\n--> Please run 'createJSONS.py' to create a new JSON file.\n")
# Check if the 'saves/asura' directory exists and the 'asura.json' file is missing
if os.path.exists("saves/asura") and not os.path.exists("saves/asura/asura.json"):
raise FileNotFoundError("The 'asura.json' file is missing in the 'saves/asura' directory.\n--- Important bookmark and URL data for 'asura' is lost!\n\n--> Please run 'createJSONS.py' to create a new JSON file in 'saves/asura'.\n")
# Check if the 'saves/reaper' directory exists and the 'reaper.json' file is missing
if os.path.exists("saves/reaper") and not os.path.exists("saves/reaper/reaper.json"):
raise FileNotFoundError("The 'reaper.json' file is missing in the 'saves/reaper' directory.\n--- Important bookmark and URL data for 'reaper' is lost!\n\n--> Please run 'createJSONS.py' to create a new JSON file in 'saves/reaper'\n.")
# Import necessary modules
from scripts import webscraper
from scripts import bookmarks
try:
from scripts import download
except:
...
with open("config.json", "r", encoding='utf-8') as file:
config = json.load(file)
# Create necessary directories for saving data
os.makedirs("saves/asura", exist_ok=True)
os.makedirs("saves/reaper", exist_ok=True)
os.makedirs(config["backup"]["asura"], exist_ok=True)
os.makedirs(config["backup"]["reaper"], exist_ok=True)
os.makedirs(config["restore"]["reaper"], exist_ok=True)
os.makedirs(config["restore"]["asura"], exist_ok=True)
os.makedirs(config["export"], exist_ok=True)
os.makedirs(config["import"]+"done/asura", exist_ok=True)
os.makedirs(config["import"]+"done/reaper", exist_ok=True)
# Read JSON files data
with open("saves/asura/asura.json", 'r', encoding="utf-8") as json_file:
data_asura = json.load(json_file)
with open("saves/reaper/reaper.json", 'r', encoding="utf-8") as json_file:
data_reaper = json.load(json_file)
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
OLIVE_GREEN = "\033[33m"
def print_dict_dict_dict(dic):
keys = [k for k, i in dic.items()]
for key in keys:
print()
print()
print(f"{CYAN}{key}:{WHITE}")
print()
for k, i in dic[key].items():
print()
print(f"{BLUE}'{k}':{WHITE}")
for kk, ii in dic[key][k].items():
print(f"{GREEN}{kk}:{WHITE}")
print(f"{OLIVE_GREEN}* {ii}:{WHITE}")
def if_dict_dict_dict(dic):
if not isinstance(dic, dict):
return False
boole = []
for key, value in dic.items():
boole.append(isinstance(value, dict))
try:
for kkey, vvalue in value.items():
boole.append(isinstance(vvalue, dict))
except:
return False
if all (boole):
return True
return False
def print_dict_dict(dic):
keys = [k for k, i in dic.items()]
for key in keys:
print()
print()
print(f"{CYAN}{key}:{WHITE}")
print()
for k, i in dic[key].items():
print(f"{BLUE}'{k}':{WHITE}")
print(f"{GREEN}* {i}{WHITE}")
def print_dict(dic):
for k,i in dic.items():
print(f"{BLUE}{k}:{WHITE}")
print(f"{GREEN}{i}{WHITE}")
# Creaete list with the urls from the JSON files
scans = [data_asura["url"], data_reaper["url"]]
# Get header from config.json
with open('config.json', 'r', encoding="utf-8") as config_file:
config = json.load(config_file)
# Extract the headers from the configuration
headers = config.get("headers", {})
does_not_work = []
# Iterate through the scan URLs in the dictionary
for index, i in enumerate(scans):
if index == 0:
k = "Asura"
elif index == 1:
k = "Reaper"
temp = i
# Create a spinner
spinner = yaspin(text=f"Checking {k}scan URL...", color="yellow")
with spinner as sp:
try:
# Check if the URL is accessible
requests.get(i, headers=headers)
scans[index] = i
sp.text = ""
sp.ok(f"✅ '{k}Scans' URL works!")
except Exception as e:
sp.text = ""
sp.fail(f"💥 '{k}Scans' URL does not work!")
print()
# Create a spinner
spinner2 = yaspin(text=f"Searching new URL...", color="yellow")
with spinner2 as sp:
try:
test = search.google_search(f"{k}Scans")
test = test[0]
requests.get(test,headers=headers)
sp.text = ""
sp.ok(f"✅ Found new URL for '{k}Scans'!")
user = input(f"Is {test} the right URL for '{k}Scans?' [Y/n] ").strip().lower()
if user == "y":
scans[index] = test # Update the URL in the dictionary
else:
raise Exception
except Exception:
sp.text = ""
sp.fail(f"💥 URL for '{k}Scans' not found!")
print(f"\nPlease search the current/right URL for {k}.")
while True:
# Prompt the user to enter a new URL for the scan
test = input(f"If you do not want to enter a new URL, enter N\nEnter the URL here for '{k}' (e.g., https://reaperscans.com/): ")
if test.lower() == "n":
does_not_work.append(k)
sp.text = ""
sp.ok(f"URL will not be changed. This could lead to errors!")
break
# Create a spinner
spinner3 = yaspin(text=f"Testing new URL '{test}'...", color="yellow")
with spinner3 as sp:
try:
# Check if the entered URL is valid
requests.get(test,headers=headers)
scans[index] = test # Update the URL in the dictionary
sp.text = ""
sp.ok(f"✅ New URL '{test}' works!")
break
except Exception:
sp.text = ""
sp.fail("💥 Invalid URL!")
# Adds / at the end of URL if needed
if not scans[index].endswith("/"):
scans[index] += "/"
# If there is a new URL
if temp != scans[index]:
webscraper.url_update(index)
# Save the updated url back to the JSON file
if index == 0:
data_asura["url"] = scans[index]
with open("saves/asura/asura.json", 'w', encoding="utf-8") as json_file:
json.dump(data_asura, json_file, ensure_ascii=False, indent=4)
elif index == 1:
data_reaper["url"] = scans[index]
with open("saves/reaper/reaper.json", 'w', encoding="utf-8") as json_file:
json.dump(data_reaper, json_file, ensure_ascii=False, indent=4)
# If there is a new URL
if temp != scans[index]:
webscraper.url_update(index)
# Asynchronous function to update the ReaperScans cache
async def return_cache_reaper():
webscraper.update_reaper_cache()
await asyncio.sleep(1) # Simulated asynchronous work
# Asynchronous function to update the AsuraScans cache
async def return_cache_asura():
webscraper.update_asura_cache()
await asyncio.sleep(2) # Simulated asynchronous work
# Asynchronous function to update the cache with a given name
async def update_cache(name, func, sp):
await func() # Execute the cache update function asynchronously
sp.write(f"> '{name}Scans' cache created / updated!") # Provide feedback
# Main function to initiate and execute the cache update tasks
async def main_update_cache(does_not_work):
spinner = yaspin(text=f"Creating / Updating cache...", color="yellow")
with spinner as sp:
# Define the tasks for updating Reaper and Asura caches concurrently
tasks = []
if not "Asura" in does_not_work:
tasks.append(update_cache("Asura", return_cache_asura, sp))
if not "Reaper" in does_not_work:
tasks.append(update_cache("Reaper", return_cache_reaper, sp))
# Execute cache update tasks concurrently
await asyncio.gather(*tasks)
sp.text = ""
sp.ok("✅ Cache created / updated!")
# Run the main cache update function
asyncio.run(main_update_cache(does_not_work))
spinner = yaspin(text=f"Setting bookmark URLs up to date...", color="yellow")
with spinner as sp:
webscraper.up_to_date_asura()
webscraper.up_to_date_reaper()
sp.text = ""
sp.ok("✅ bookmark URLs are up to date!")
# -------------------------------------- UI start --------------------------------------
def checking_updates(does_not_work):
bool_asura = False
bool_reaper = False
spinner = yaspin(text=f"Checking for updates...", color="yellow")
asura_download_dict = {}
reaper_download_dict = {}
with spinner as sp:
if not "Asura" in does_not_work:
with open("saves/asura/asura.json", "r", encoding='utf-8') as file:
bookmarks_updates = json.load(file)["bookmarks"]
asura_check, asura_download_dict = webscraper.check_asura()
if len(bookmarks_updates) > 0 and len(asura_check) > 0:
bool_asura = True
if not "Reaper" in does_not_work:
with open("saves/reaper/reaper.json", "r", encoding='utf-8') as file:
bookmarks_updates = json.load(file)["bookmarks"]
reaper_check, reaper_download_dict = webscraper.check_reaper()
if len(bookmarks_updates) > 0 and len(reaper_check) > 0:
bool_reaper = True
# Display the tables
if bool_asura or bool_reaper:
headers = ["Update", "URL"]
table_data = []
if bool_asura:
table_data.append(("AsuraScans","AsuraScans"))
for key, value in asura_check.items():
table_data.append((key,value["next_to_read"]["url"]))
if bool_reaper:
table_data.append(("ReaperScans","ReaperScans"))
for key, value in reaper_check.items():
table_data.append((key,value["next_to_read"]["url"]))
table = tabulate(table_data, headers, tablefmt="pretty")
sp.text = ""
sp.ok("✅ Updates found!")
print()
print()
print(table)
else:
sp.text = ""
sp.fail("No updates for AsuraScans and ReaperScans!")
return (asura_download_dict, reaper_download_dict)
asura_download_dict, reaper_download_dict = checking_updates(does_not_work)
man = {
"System": {
"cls": "clear the termninal.",
"clear": "clear the termninal.",
"man": "show this page.",
"exit": "exit.",
"q": "exit.",
"update_cache": "update the cache of AsuraScans and ReaperScans.",
"update_cache --reaper": "update the cache of ReaperScans.",
"update_cache --asura": "update the cache of AsuraScans."
},
"Search": {
"search --asura ": "to search only mangas from AsuraScans.",
"search --reaper ": "to search only mangas from ReaperScans.",
"search ": "to search from both."
},
"Bookmarks": {
"bookmark --help": "to show all bookmark related commands."
},
"Checking": {
"check": "check for updates"
} ,
"Download": {
"download -all -scan (asura/reaper) -name (name of the manga)": "downloads all chapters of the manga",
"download -current -scan (asura/reaper) -name (name of the manga)": "downloads the current chapter of the manga",
"download -next -scan (asura/reaper) -name (name of the manga)": "downloads the next chapter of the manga"
}
}
# --------------------------------- Auto complete start ---------------------------------
# Load data from JSON files
with open("scripts/bookmark.json", "r", encoding='utf-8') as file:
bookmarkJson = json.load(file)
with open("auto_complete_asura.json", "r", encoding='utf-8') as file:
auto_complete_asura = json.load(file)
with open("auto_complete_reaper.json", "r", encoding='utf-8') as file:
auto_complete_reaper = json.load(file)
auto_search_combine = auto_complete_asura.copy()
auto_search_combine.update(auto_complete_reaper)
# Create an empty auto_complete_bookmark dictionary
auto_complete_bookmark = {key: None for key, value in bookmarkJson.items()}
# Populate auto_complete_bookmark with options from the JSON file
for key, value in auto_complete_bookmark.items():
if key == "--help":
continue
auto_complete_bookmark[key] = [key for key, value in bookmarkJson[key]["suffix"].items()]
# Save the auto_complete_bookmark dictionary to a JSON file
with open("auto_complete_bookmark.json", "w", encoding="utf-8") as file:
json.dump(auto_complete_bookmark, file, ensure_ascii=False, indent=4)
# Load data from JSON files (part 2)
with open("scripts/bookmark.json", "r", encoding='utf-8') as file:
bookmarkJson = json.load(file)
with open("auto_complete_asura.json", "r", encoding='utf-8') as file:
auto_complete_asura = json.load(file)["list"]
with open("auto_complete_reaper.json", "r", encoding='utf-8') as file:
auto_complete_reaper = json.load(file)["list"]
# Combine auto_complete_asura and auto_complete_reaper lists
auto_search_combine = auto_complete_asura.copy()
auto_search_combine.extend(auto_complete_reaper)
# Define options for different commands
search_options = ["--asura", "--reaper"]
update_cache_options = ["--asura", "--reaper"]
bookmark_options = [key for key, value in bookmarkJson.items()]
# Define a custom AutoCompleter class
class AutoCompleter(Completer):
def get_completions(self, document, complete_event):
text = document.text_before_cursor.lower()
not_text_lower = document.text_before_cursor
default = ['exit', 'q', 'man', 'manual', 'cls', 'clear', 'check', 'download', 'search', 'bookmark', 'update_cache', 'sirmrmanuel0']
completions = []
# Add default completions
for option in default:
if option.startswith(text) or text == "":
completions.extend([Completion(option, start_position=-len(option))])
# Handle command-specific completions
if text.startswith("search "):
# Suggest search-specific options
try:
startposition = -len(text.split()[1])
except:
startposition = 0
completions = [Completion("--asura", start_position=startposition), Completion("--reaper", start_position=startposition)]
elif text.startswith("download "):
try:
if len(text.split()) > 6:
completions = [Completion("", start_position=startposition)]
return
except:
...
# Suggest search-specific options
try:
startposition = -len(text.split()[1])
except:
startposition = 0
completions = [Completion("-all", start_position=startposition), Completion("-current", start_position=startposition), Completion("-next", start_position=startposition)]
if text.startswith("download -all "):
try:
startposition = -len(text.split()[2])
except:
startposition = 0
completions = [Completion("-scan", start_position=startposition)]
if text.startswith("download -all -scan "):
try:
startposition = -len(text.split()[3])
except:
startposition = 0
completions = [Completion("AsuraScan", start_position=startposition), Completion("ReaperScan", start_position=startposition)]
if text.startswith("download -all -scan ") and \
(len(text.split()) >= 4 and text.split()[3].lower() in ['asura', 'reaper', 'reaperscan', 'asurascan']) or \
(len(text.split()) >= 5 and text.endswith(" ")):
try:
startposition = -len(text.split()[5])
except:
startposition = 0
completions = [Completion("-name", start_position=startposition)]
if text.find("-name") > 0 and text.index("-name") > text.index("-scan"):
try:
startposition = -len(text.split()[6])
except:
startposition = 0
completions = []
for name in auto_search_combine:
startposition = 0
try:
name_ends_at = text.find("-name") + 6
startposition = -len(text[name_ends_at:])
except Exception as e:
startposition = -5
if name.lower().startswith(text[text.find("-name") + 6:]):
completions.extend([Completion(name, start_position=startposition)])
if text.startswith("download -current "):
try:
startposition = -len(text.split()[2])
except:
startposition = 0
completions = [Completion("-scan", start_position=startposition)]
if text.startswith("download -current -scan "):
try:
startposition = -len(text.split()[3])
except:
startposition = 0
completions = [Completion("AsuraScan", start_position=startposition), Completion("ReaperScan", start_position=startposition)]
if text.startswith("download -current -scan ") and \
(len(text.split()) >= 4 and text.split()[3].lower() in ['asura', 'reaper', 'reaperscan', 'asurascan']) or \
(len(text.split()) >= 5 and text.endswith(" ")):
try:
startposition = -len(text.split()[5])
except:
startposition = 0
completions = [Completion("-name", start_position=startposition)]
if text.find("-name") > 0 and text.index("-name") > text.index("-scan"):
try:
startposition = -len(text.split()[6])
except:
startposition = 0
completions = []
for name in auto_search_combine:
startposition = 0
try:
name_ends_at = text.find("-name") + 6
startposition = -len(text[name_ends_at:])
except Exception as e:
startposition = -5
if name.lower().startswith(text[text.find("-name") + 6:]):
completions.extend([Completion(name, start_position=startposition)])
if text.startswith("download -next "):
try:
startposition = -len(text.split()[2])
except:
startposition = 0
completions = [Completion("-scan", start_position=startposition)]
if text.startswith("download -next -scan "):
try:
startposition = -len(text.split()[3])
except:
startposition = 0
completions = [Completion("AsuraScan", start_position=startposition), Completion("ReaperScan", start_position=startposition)]
if text.startswith("download -next -scan ") and \
(len(text.split()) >= 4 and text.split()[3].lower() in ['asura', 'reaper', 'reaperscan', 'asurascan']) or \
(len(text.split()) >= 5 and text.endswith(" ")):
try:
startposition = -len(text.split()[5])
except:
startposition = 0
completions = [Completion("-name", start_position=startposition)]
if text.find("-name") > 0 and text.index("-name") > text.index("-scan"):
try:
startposition = -len(text.split()[6])
except:
startposition = 0
completions = []
for name in auto_search_combine:
startposition = 0
try:
name_ends_at = text.find("-name") + 6
startposition = -len(text[name_ends_at:])
except Exception as e:
startposition = -5
if name.lower().startswith(text[text.find("-name") + 6:]):
completions.extend([Completion(name, start_position=startposition)])
elif text.startswith("update_cache "):
# Suggest update_cache-specific options
try:
startposition = -len(text.split()[1])
except:
startposition = 0
completions = [Completion("--asura", start_position=startposition), Completion("--reaper", start_position=startposition)]
elif text.startswith("bookmark "):
completions = []
if text.startswith("bookmark --help"):
#completions.extend(Completion("/"))
return completions
# Handle bookmark-specific completions
temp_text = text.split()
if 3 > len(temp_text) >= 1:
for option in bookmark_options:
if option.startswith(text[9:]) :#or text in ["bookmark", "bookmark "]:
try:
startposition = -len(text.split()[1])
except:
startposition = 0
completions.extend([Completion(option, start_position=startposition)])
if len(temp_text) > 1 and temp_text[1] in bookmark_options:
with open("auto_complete_bookmark.json", "r", encoding='utf-8') as file:
bookmark_completer = json.load(file)
boole_name = []
# Handle name completions
try:
name_ends_at_url = not_text_lower.find("-name") + 6 if not_text_lower.find("-name") > -1 else "e"
for name in auto_search_combine:
boole_name.append(name.lower().startswith(text[name_ends_at_url:]))
except:
boole_name = []
boole_name.append(False)
poss_urls = []
# Handle URL completions
try:
name_ends_at_url = not_text_lower.find("-name") + 6 if not_text_lower.find("-name") > -1 and \
not_text_lower.find("-url") > -1 and temp_text[len(temp_text)-1] == "-url" else "e"
subtract = -1
bool_break = False
save = ""
#for i in range(len(text[name_ends_at:])):
# for name in auto_search_combine:
# if name == text[name_ends_at:subtract]:
# bool_break = True
# save = name
# break
# if bool_break:
# break
# subtract -= 1
# Handle URL completion logic
with open("scripts/search_asura_cache.json", "r", encoding='utf-8') as file:
search_asura = json.load(file)
with open("scripts/search_reaper_cache.json", "r", encoding='utf-8') as file:
search_reaper = json.load(file)
while True:
try:
poss_urls.append(search_asura[not_text_lower[name_ends_at_url:subtract]]["url"])
break
except:
subtract -= 1
if not_text_lower[name_ends_at_url:subtract] == "":
break
subtract = 0
while True:
try:
poss_urls.append(search_reaper[not_text_lower[name_ends_at_url:subtract]]["url"])
break
except:
subtract -= 1
if not_text_lower[name_ends_at_url:subtract] == "":
break
except Exception as e:
poss_urls = []
# Suggest completions based on name or URL
if not any(boole_name) and len(poss_urls) <= 0:
for option in bookmark_completer[temp_text[1]]:
try:
if not text.endswith(" "):
startposition = -len(text.split()[2])
else:
startposition = 0
except:
startposition = 0
if option not in text:
if text.endswith(" ") or option.startswith(temp_text[len(temp_text)-1].lower()):
completions.extend([Completion(option, start_position=startposition)])
else:
completions.extend([Completion(" "+option, start_position=startposition)])
elif any(boole_name):
for name in auto_search_combine:
startposition = 0
try:
name_ends_at = text.find("-name") + 6
startposition = -len(text[name_ends_at:])
except Exception as e:
startposition = -5
if name.lower().startswith(text[text.find("-name") + 6:]):
completions.extend([Completion(name, start_position=startposition)])
elif len(poss_urls) > 0:
if not text.endswith(" "):
startposition = -len(text.split()[len(temp_text)-1])
else:
startposition = 0
for url in poss_urls:
completions.extend([Completion(url, start_position=startposition)])
return completions
# Create a PromptSession with the custom AutoCompleter
session = PromptSession()
completer = AutoCompleter()
# --------------------------------- Auto complete end ---------------------------------
# --------------------------------- Download start ---------------------------------
#
# The following download commands will not work due to legal and ethical uncertainties.
# For more information, refer to download_py.md.
# Keep coding ethically and responsibly! 🌱✨
#
print()
print()
print()
spinner = yaspin(text=f"Downloading Chapter...", color="yellow")
downloaded_asura = {}
downloaded_reaper = {}
fail = False
down_least_1 = False
asura_down = False
reaper_down = False
with spinner as sp:
# ---- AsuraScan
if len(asura_download_dict.items()) > 0:
with open("saves/asura/asura.json", "r", encoding='utf-8') as file:
asura_json = json.load(file)["bookmarks"]
keys = [key for key, value in asura_json.items() if asura_json[key]["to_download"]]
try:
for key, value in asura_download_dict.items():
if key in keys:
down_least_1 = True
asura_down = True
downloaded_asura[key] = download.save(key, download.ASURA, asura_download_dict[key])
sp.write("> Downloaded AsuraScans: '" + key + "'!")
if asura_down:
sp.write("> Download AsuraScans done!")
except:
fail = True
sp.write(f"{RED}Download does not work. Check out download_py.md.{WHITE}")
# ---- ReaperScan
if len(reaper_download_dict.items()) > 0:
with open("saves/reaper/reaper.json", "r", encoding='utf-8') as file:
reaper_json = json.load(file)["bookmarks"]
keys = [key for key, value in reaper_json.items() if reaper_json[key]["to_download"]]
try:
for key, value in reaper_download_dict.items():
if key in keys:
down_least_1 = True
reaper_down = True
downloaded_reaper[key] = download.save(key, download.REAPER, reaper_download_dict[key])
sp.write("> Downloaded ReaperScans: '" + key + "'!")
if reaper_down:
sp.write("> Download ReaperScans done!")
except:
fail = True
sp.write(f"{RED}Download does not work. Check out download_py.md.{WHITE}")
sp.text = ""
if not fail and (len(asura_download_dict.items()) > 0 or len(reaper_download_dict.items()) > 0) and down_least_1:
sp.ok("✅ Downloads are done!")
elif fail and (len(asura_download_dict.items()) > 0 or len(reaper_download_dict.items()) > 0) and down_least_1:
sp.fail("💥 Downloads cannot be done!")
else:
sp.ok("✅ Nothing to download!")
print()
print()
if len(downloaded_asura.items()) > 0:
print("AsuraScans:")
print()
for key, value in downloaded_asura.items():
if value:
print(f"{GREEN}Downloaded '{key}' successfully!{WHITE}")
# Get the directory of the current script
script_directory = os.path.dirname(os.path.abspath(__file__))
# Specify the relative path
relative_path = "saves/asura/"
manga_path = f"saves/asura/{key}/"
# Construct the full path
full_path = os.path.join(script_directory, relative_path)
manga_path = os.path.join(script_directory, manga_path)
try:
# Open File Explorer
os.startfile(manga_path)
except:
# Open File Explorer
os.startfile(full_path)
else:
print(f"{RED}Download for '{key}' failed!{WHITE}")
print()
print()
if len(downloaded_reaper.items()) > 0:
print()
print()
print("ReaperScans:")
print()
for key, value in downloaded_reaper.items():
if value:
print(f"{GREEN}Downloaded '{key}' successfully!{WHITE}")
else:
print(f"{RED}Download for '{key}' failed!{WHITE}")
# Get the directory of the current script
script_directory = os.path.dirname(os.path.abspath(__file__))
# Specify the relative path
relative_path = "saves/reaper/"
# Construct the full path
full_path = os.path.join(script_directory, relative_path)
# Open File Explorer
os.startfile(full_path)
print()
# ---------------------------------- Download end ----------------------------------
# ---------------------------------- autoUpdate start -------------------------------
class autoUpdateThread(threading.Thread):
listInAction = []
does_not_work = []
stop_working = False
def __init__(self, does_not_work, listInAction):
super().__init__()
self._stop_event = threading.Event()
self.listInAction = listInAction
self.does_not_work = does_not_work
def run(self):
try:
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
OLIVE_GREEN = "\033[33m"
while True:
table = None
for i in range(3601):
if self.stop_working:
raise Exception()
time.sleep(1)
webscraper.update_asura_cache()
webscraper.update_reaper_cache()
webscraper.up_to_date_asura()
webscraper.up_to_date_reaper()
bool_asura = False
bool_reaper = False
asura_download_dict = {}
reaper_download_dict = {}
if not "Asura" in does_not_work:
with open("saves/asura/asura.json", "r", encoding='utf-8') as file:
bookmarks_updates = json.load(file)["bookmarks"]
asura_check, asura_download_dict = webscraper.check_asura()
if len(bookmarks_updates) > 0 and len(asura_check) > 0:
bool_asura = True
if not "Reaper" in does_not_work:
with open("saves/reaper/reaper.json", "r", encoding='utf-8') as file:
bookmarks_updates = json.load(file)["bookmarks"]
reaper_check, reaper_download_dict = webscraper.check_reaper()
if len(bookmarks_updates) > 0 and len(reaper_check) > 0:
bool_reaper = True
# Create the tables
if bool_asura or bool_reaper:
headers = ["Update", "URL"]
table_data = []
if bool_asura:
table_data.append(("AsuraScans","AsuraScans"))
for key, value in asura_check.items():
table_data.append((key,value["next_to_read"]["url"]))
if bool_reaper:
table_data.append(("ReaperScans","ReaperScans"))
for key, value in reaper_check.items():
table_data.append((key,value["next_to_read"]["url"]))
table = tabulate(table_data, headers, tablefmt="pretty")
downloaded_asura = {}
downloaded_reaper = {}
fail = False
down_least_1 = False
asura_down = False
reaper_down = False
downloadsFail = False
nothingToDownload = False
# ---- AsuraScan
if len(asura_download_dict.items()) > 0:
with open("saves/asura/asura.json", "r", encoding='utf-8') as file:
asura_json = json.load(file)["bookmarks"]
keys = [key for key, value in asura_json.items() if asura_json[key]["to_download"]]
try:
for key, value in asura_download_dict.items():
if key in keys:
down_least_1 = True
asura_down = True
downloaded_asura[key] = False
downloaded_asura[key] = download.save(key, download.ASURA, asura_download_dict[key])
# "> Downloaded AsuraScans: '" + key + "'!"
if asura_down:
# "> Download AsuraScans done!"
...
except:
fail = True
# f"{RED}Download does not work. Check out download_py.md.{WHITE}"
# ---- ReaperScan