This repository was archived by the owner on Feb 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathKMPDownloader.py
More file actions
2339 lines (2000 loc) · 115 KB
/
KMPDownloader.py
File metadata and controls
2339 lines (2000 loc) · 115 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
from queue import Queue
import shutil
import sqlite3
from threading import Lock, Semaphore
import traceback
import requests
from bs4 import BeautifulSoup, ResultSet
import os
import re
import time
import sys
import cfscrape
from tqdm import tqdm
import logging
import requests.adapters
from datetime import datetime, timezone
#import webbrowser
from ssl import SSLError
import threading
from Threadpool import tname
from DiscordtoJson import DiscordToJson
from HashTable import HashTable
from HashTable import KVPair
from datetime import timedelta
from Threadpool import ThreadPool
import zipextracter
import alive_progress
from PersistentCounter import PersistentCounter
import jutils
from DB import DB
"""
Simple kemono.party downloader relying on html parsing and download by url
Using multithreading
@author Jeff Chen
@version 0.6.2.3
@last modified 9/10/2023
"""
request_headers = {} # Headers to be used for python requests, modified later on since is constantly changing
LOG_PATH = os.path.abspath(".") + "\\logs\\" # Directory for logging
LOG_NAME = LOG_PATH + "LOG - " + datetime.now(tz = timezone.utc).strftime('%a %b %d %H-%M-%S %Z %Y') + ".txt" # Name for log file to use
LOG_MUTEX = Lock() # Mutex for log file
download_format_types = ["image", "audio", "video", "plain", "stream", "application", "7z", "audio"] # Download types for file attachments, can be modified by the user with switches
class Error(Exception):
"""Base class for other exceptions"""
pass
class UnknownURLTypeException(Error):
"""Raised when url type cannot be determined"""
pass
class UnspecifiedDownloadPathException(Error):
"""Raised when download path is not given"""
pass
class DeadThreadPoolException(Error):
"""Raised when download threads are nonexistant or dead"""
pass
class KMP:
"""
Kemono.party downloader class, contains everything needed to download
all of Kemono parties resources
"""
__folder: str # Folder to download files to
__unzip: bool # Unzipping flag
__tcount: int # Thread count
__chunksz: int # Size of chunks to download in
__threads:ThreadPool # Threadpool with tcount threads
__sessions:list # requests sessions for threads
__session:requests.Session # request session for main thread
__unpacked:bool # Unpacked download type flag
__http_codes:list[int] # list of HTTP codes to retry on
__container_prefix:str # Prefix of kemono website
__register:HashTable # Registers a directory, combats multiple posts using the same name
__register_mutex:Lock # Lock for the register
__fcount:int # Number of downloaded files
__fcount_mutex:Lock # Mutex for fcount
__failed:int # Number of downloaded files
__failed_mutex:Lock # Mutex for fcount
__post_name_exclusion:list[str] # Keywords in excluded posts
__link_name_exclusion:list[str] # Keywords in excluded posts
__ext_blacklist:HashTable # Stores excluded extensions
__timeout:int # Timeout for network issues
__post_process:list # Directories that require post processing when they contain text only
__download_server_name_type:bool # Switch to use server hashed names instead of custom names
__progress:Semaphore # Semaphore for progress bar, one release means 1 file downloaded
__progress_mutex:Lock # Mutex for semaphore
__dir_lock:Lock # Mutex for when a directory is being created
__wait:float # Wait time between downloads in seconds
__db:DB # Name of database
__update:bool # True for update mode, false for download mode
__exclcomments:bool # Exclude comments switch
__exclcontents:bool # Exclude contents switch
__minsize:bool # Minimum downloadable file size
__existing_file_register:HashTable # Existing files and their size
__existing_file_register_lock:Lock # Lock for existing file table
__predupe:bool # True to prepend () in cases of dupe, false to postpend ()
__urls:list[str] # List of downloaded artist urls
__latest_urls:list[str] # List of downloaded artist's latest urls
__override_paths:list[str] # List of file paths to override old file paths if they exists in db
__config:tuple # Download configuration
__artist:list[str] # Downloaded artist name
__reupdate:bool # True to reupdate, false to not
__date:bool # True to append date to files/folder, false to not
__id:bool # True to prepend id to files/folder, false to not
__rename:bool # True to rename tracked artist files (nothing is downloaded), false for regular operation.
__tempextr:bool # True to extract to temp folder then move to dir, false to extract within dir only
__root:str # Root directory
__scount:int # Number of files skipped
__scount_mutex:Lock # lock for scount
__connection_timeout:int # Timeout used for general connection issues
#__wait_browser_cond:threading.Condition # Conditional used for blocking when waiting on CAPTCHA to be completed
#__browser_active:bool # True if browser for captcha has been open, false if not
#__browser_active_mutex:Lock # Mutex used for browser_active
def __init__(self, folder: str, unzip:bool, tcount: int | None, chunksz: int | None, ext_blacklist:list[str]|None = None , timeout:int = 30, http_codes:list[int] = None, post_name_exclusion:list[str]=[], download_server_name_type:bool = False,\
link_name_exclusion:list[str] = [], wait:float = 0, db_name:str = "KMP.db", track:bool = False, update:bool = False, exclcomments:bool = False, exclcontents:bool = False, minsize:float = 0, predupe:bool = False, prefix:str = "https://kemono.party",
disableprescan:bool = False, date:bool = False, id:bool = False, rename:bool = False, tempextr:bool = True, root:str = os.path.dirname(os.path.realpath(__file__)), connect_timeout:int = 10, **kwargs) -> None:
"""
Initializes all variables. Does not run the program
Param:
folder: Folder to download to, cannot be None
unzip: True to automatically unzip files, false to not
tcount: Number of threads to use, max thread count is 12, default is 6
chunksz: Download chunk size, default is 1024 * 1024 * 64
ext_blacklist: List of file extensions to skips, does not contain '.' and no spaces
timeout: Max retries, default is infinite (-1)
http_codes: Codes to retry downloads for
post_name_exclusion: keywords in excluded posts, must be all lowercase to be case insensitive
download_server_name_type: True to download server file name, false to use a program defined naming scheme instead
link_name_exclusion: keyword in excluded link. The link is the plaintext, not the link pointer, must be all lowercase to be case insensitive.
wait: time in seconds to wait in between downloads.
db_name: database name, this object creates or extends upon 2 tables named Parent & Child
track: true to add entries to database, false otherwise
update: Routines update instead of downloading artists
predupe: True to prepend () in cases of dupe, false to postpend ()
prefix: Prefix of kemono URL. Must include https and any other relevant parts of the URL and does not end in slash.
disableprescan: True to disable prescan used to build temp dupe file database.
date: True to use date info for file names, False to not
id: True to use id info for file names, False to not
rename: True to rename and/or delete local files if a online version was found during archiving. NOTE: makes sure directory looks identical to online copy
tempextr: True to extract to a temp directory then move to dest directory, false to extract to the dest directory
root: Root directory for files, default is where KMPDownloader.py is located
connect_timeout: Timeout in seconds when a general connectivity error has occured.
kwargs: not in use for now
"""
self.__connection_timeout = connect_timeout
#self.__wait_browser_cond = threading.Condition()
#self.__browser_active = Lock()
self.__root = root
tname.id = None
if folder:
self.__folder = folder
elif not update and not kwargs["reupdate"]:
raise UnspecifiedDownloadPathException
self.__scount = 0
self.__scount_mutex = Lock()
self.__dir_lock = Lock()
self.__progress_mutex = Lock()
self.__progress = Semaphore(value=0)
self.__register = HashTable(10)
self.__fcount = 0
self.__unzip = unzip
self.__fcount_mutex = Lock()
self.__timeout = timeout
self.__failed = 0
self.__failed_mutex = Lock()
self.__post_process = []
self.__post_name_exclusion = post_name_exclusion
self.__download_server_name_type = download_server_name_type
self.__link_name_exclusion = link_name_exclusion
self.__register_mutex = Lock()
self.__db = DB(os.path.join(root, db_name))
self.__update = update
self.__exclcomments = exclcomments
self.__exclcontents = exclcontents
self.__urls = []
self.__latest_urls = []
self.__override_paths = []
self.__config = locals()
self.__artist = []
self.__container_prefix = prefix
self.__date = date
self.__tempextr = tempextr
self.__id = id
if minsize < 0:
self.__minsize = 0
else:
self.__minsize = minsize
if not http_codes or len(http_codes) == 0:
self.__http_codes = [429, 403, 502]
else:
self.__http_codes = http_codes
if not tcount or tcount <= 0:
self.__tcount = 1
else:
self.__tcount = min(5, tcount)
if wait < 2:
self.__wait = 2
else:
self.__wait = wait
if chunksz and chunksz > 0 and chunksz <= 12:
self.__chunksz = chunksz
else:
self.__chunksz = 1024 * 1024 * 64
self.__unpacked = 0
if ext_blacklist:
self.__ext_blacklist = HashTable(len(ext_blacklist) * 2)
for ext in ext_blacklist:
self.__ext_blacklist.hashtable_add(KVPair(ext, ext))
else:
self.__ext_blacklist = None
self.__reupdate = kwargs["reupdate"]
self.__rename = rename
# Create database #############
if track or update or kwargs["reupdate"]:
# Check if database exists
if os.path.exists(os.path.join(self.__root, db_name)):
# If exists, create a backup
if(not os.path.exists(os.path.join(self.__root, "Data_Backup"))):
os.makedirs(os.path.join(self.__root, "Data_Backup"))
# Copy db file to backup location
db_part_name = db_name.rpartition('.')
shutil.copyfile(os.path.join(self.__root, db_name), os.path.join(self.__root, "Data_Backup/", db_part_name[0] + "-" + datetime.now(tz = timezone.utc).strftime('%a %b %d %H-%M-%S %Z %Y') + "." + db_part_name[2]))
# Create a new table
self.__db.executeNCommit("CREATE TABLE IF NOT EXISTS Parent2 (url TEXT, artist TEXT, type TEXT, latest TEXT, destination TEXT, config TEXT)")
# Update older databases
legacy_table:sqlite3.Cursor = self.__db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='Parent'").fetchall()
if (len(legacy_table) == 1):
cursor = self.__db.execute("SELECT * from Parent")
col_names = [description[0] for description in cursor.description]
# Version 6.0's db
if len(col_names) == 4:
# Get all column data
urls = [item[0] for item in self.__db.execute("SELECT url FROM Parent").fetchall()]
latest = [item[0] for item in self.__db.execute("SELECT latest FROM Parent").fetchall()]
dfolder = [item[0] for item in self.__db.execute("SELECT destination FROM Parent").fetchall()]
# Add to the new table
for i in range(0, len(urls)):
self.__db.execute(("INSERT INTO Parent2 VALUES (?, ?, 'Kemono', ?, ?, ?)", (urls[i], None, latest[i], dfolder[i], None),))
# Remove old table
self.__db.executeNCommit("DROP TABLE Parent")
else:
self.__db = None
# Create session ###########################
self.__sessions = []
for _ in range(0, max(self.__tcount, self.__tcount)):
session = cfscrape.create_scraper(requests.Session())
session.max_redirects = 5
adapter = requests.adapters.HTTPAdapter(pool_connections=self.__tcount, pool_maxsize=self.__tcount, max_retries=0, pool_block=True)
session.mount('http://', adapter)
self.__sessions.append(session)
self.__session = cfscrape.create_scraper(requests.Session())
self.__session.max_redirects = 5
adapter = requests.adapters.HTTPAdapter(pool_connections=self.__tcount, pool_maxsize=self.__tcount, max_retries=0, pool_block=True)
self.__session.mount('http://', adapter)
# TODO choose better number
self.__existing_file_register = HashTable(10000000)
self.__existing_file_register_lock = Lock()
# File prescan
if not disableprescan:
# If update is selected, read in all update paths
if update or kwargs["reupdate"]:
# Use a set to skip ignore duplicate paths
update_path_set = {item[0] for item in self.__db.execute("SELECT destination FROM Parent2").fetchall()}
for path in update_path_set:
self.__fregister_preload(path, self.__existing_file_register, self.__existing_file_register_lock)
# If update is not selected, read from download folder
else:
self.__fregister_preload(folder, self.__existing_file_register, self.__existing_file_register_lock)
logging.info("Finished scanning directory")
self.__predupe = predupe
def __fregister_preload(self, dir:str, fregister:HashTable, mutex:Lock) -> None:
"""
Registers all files and directories within a path to a Hashtable with multithreading
Args:
path (str): Directory path to walk
fregister (HashTable): If provided, appends to the hashtable
mutex (Lock): Mutex to be used with fregister
Pre: path ends with '/' and uses '/'
Returns:
HashTable: Hashtable with all file records if register is None
"""
# If path does not exists, skip
logging.info(f"Please wait, scanning {dir}")
if not os.path.exists(dir):
logging.warning("{} does not exists, preload skipped".format(dir))
return None
# Pull up current directory information
contents = os.scandir(dir)
# Generate thread pool
file_pool = ThreadPool(100)
file_pool.start_threads()
# Iterate through all elements
for file in contents:
# If is a directory, recursive call into directory and append result
if file.is_dir():
file_pool.enqueue((self.__fregister_preload_helper, (file_pool, file.path + '\\', fregister, mutex,)))
# TODO sort values by radix sort and implement binary search
file_pool.join_queue()
file_pool.kill_threads()
def __basename_generator(self, name:str)->tuple:
"""
Given a file or dir name (not path), return a basename
Args:
name (str): name of a file or directory
Returns:
tuple (str): Size 1 or 2 tuple. Size 1 has basename of file while size 2 has basename
in first position and an alternate basename in second position if it is impossible
to derive just one basename from a name.
"""
basename = name
ext = name.rpartition('.')[2]
# Predupe case
if name[0] == "(":
basename = name.rpartition(") ")[2]
# Postdupe case
else:
# 2 types of '(' checked for since previous versions <=0.6 don't have spacing between filename and ()
if ' (' in name:
basename = name.partition(" (")[0] + (("." + ext) if ext != name else "")
elif '(' in name:
basename = name.partition("(")[0] + ext
# Probably unecessary trim but to be safe
basename = basename.strip()
basename_tokens = basename.split(" ")
secondpath = None
if len(basename_tokens) >= 3: # Skips files with inadequent tokens
# Date case
if basename_tokens[len(basename_tokens) - (3 if ext != name else 1)].isnumeric():
# Check if new keyword is used for date
if basename_tokens[len(basename_tokens) - (5 if ext != name else 3)] == "Published":
basename = " ".join(basename_tokens[0:len(basename_tokens) - (5 if ext != name else 3)]) + ((" " + " ".join(basename_tokens[len(basename_tokens) - 2:]) if ext != name else ""))
# If no keyword is used for date
else:
basename = " ".join(basename_tokens[0:len(basename_tokens) - (4 if ext != name else 2)]) + ((" " + " ".join(basename_tokens[len(basename_tokens) - 2:]) if ext != name else ""))
# ID Case
basename_tokens = basename.split(" ")
if basename_tokens[0].isnumeric():
secondpath = basename # Is impossible to know if first token references id or something else
basename = (" ".join(basename_tokens[1:]))
return (basename, secondpath) if secondpath else (basename,)
def __fregister_preload_helper(self, pool:ThreadPool, dir:str, fregister:HashTable, mutex:Lock) -> None:
"""
Helper function for __fregister_preload. Performs the operation of assigning thread task and recursively
visiting each directory and registering each file.
Data registered to fregtister in the following format:
KVPair(base_name, [file1_name, file1_identifier, file2_name, file2_identifier...])
Where basename is the key which should be used when searching the hash table and the array
contains the values where each even position is the actual filename and odd position is the
file's unique identifier which includes file size, file content, and etc.
Note that there may be multiple basenames for a single file depending on the format of the file
and the format of its parent directory.
Args:
path (str): Workers to be used for the registering of files and folders
dir (str): directory to have the worker threads examine
fregister (HashTable): Table to register data to
mutex (Lock): Mutex for fregister
Pre: path ends with '/' and uses '/'
Returns:
HashTable: Hashtable with all file records if register is None
"""
# Pull up current directory information
contents = os.scandir(dir)
# Iterate through all elements
for file in contents:
# If is a directory, recursive call into directory and append result
if file.is_dir():
pool.enqueue((self.__fregister_preload_helper, (pool, file.path + '\\', fregister, mutex,)))
# If not directory, get file size and remove any ()
elif file.stat().st_size > 0:
# Get directory name by itself
dir_partition = os.path.dirname(dir).rpartition("\\")
dir_name = dir_partition[2]
# Generate basename of dir_name
base_dir_names = self.__basename_generator(dir_name)
# Generate basename of file
base_file_names = self.__basename_generator(file.name)
# Get file size
fsize = os.stat(file.path).st_size
# Recreate fullpath
dir_paths = [os.path.join(dir_partition[0], n) for n in base_dir_names] # Reconstruct dirpath
file_paths = []
for dir_path in dir_paths:
for base_file_name in base_file_names:
file_paths.append(os.path.join(dir_path, base_file_name))
for fullpath in file_paths:
# Check if is text file and is a file written by the program (contains __)
if(file.name.endswith("txt") and "__" in file.name):
# Add file contents to register
try:
with open(file.path, 'r', encoding="utf-") as fd:
# Text content of file
contents = fd.read()
mutex.acquire()
# fullpath
data = fregister.hashtable_lookup_value(fullpath)
# If entry does not exists, add it
if not data:
fregister.hashtable_add(KVPair(fullpath, [hash(contents), file.path]))
# Else append data to currently existing entry if not already included in the entry
elif(file.path not in data):
data.append(hash(contents))
data.append(file.path)
fregister.hashtable_edit_value(fullpath, data)
mutex.release()
except(UnicodeDecodeError):
logging.warning("UnicodeDecodeError in {}, skipping file".format(file.path))
#os.remove(file.path)
except Exception as e:
logging.error("Handled an unknown exception, skipping file: {}".format(e.__class__.__name__))
else:
# Add size value to register
mutex.acquire()
data = fregister.hashtable_lookup_value(fullpath)
# If entry does not exists, add it
if not data:
fregister.hashtable_add(KVPair(fullpath, [fsize, file.path]))
# Else append data to currently existing entry
elif(file.path not in data):
data.append(fsize)
data.append(file.path)
fregister.hashtable_edit_value(fullpath, data)
mutex.release()
# TODO sort values by radix sort and implement binary search
def reset(self) -> None:
"""
Resets register and download count, should be called if the KMP
object will be reused; otherwise, downloaded url data will persist
and file download and failed count will persist.
TODO DEPRECATED, needs to be updated
"""
self. __register = HashTable(10)
self.__fcount = 0
self.__failed = 0
def close(self) -> None:
"""
Closes KMP download session, cannot be reopened, must be called to prevent
unclosed socket warnings. Database is processed and closed here as well.
"""
[session.close() for session in self.__sessions]
self.__session.close()
# Update db
if self.__db:
done = False
while not done:
try:
for i in range(0, len(self.__urls)):
# Check if db entry already exists
entry = self.__db.execute(("SELECT * FROM Parent2 WHERE url LIKE '%'||?", (self.__urls[i].rpartition(".")[2].partition('/')[2],),))
old_config = None
entries = entry.fetchall()
# If it already exists, remove the entry
if len(entries) > 0:
# Save any old data
old_config = entries[0][5]
# Remove old entry
self.__db.execute(("DELETE FROM Parent2 WHERE url LIKE '%'||?", (self.__urls[i].rpartition(".")[2].partition('/')[2],),))
# Insert updated entry
self.__db.execute(("INSERT INTO Parent2 VALUES (?, ?, 'Kemono', ?, ?, ?)", (self.__urls[i], self.__artist[i], self.__latest_urls[i], self.__override_paths[i], str(self.__config) if not old_config else old_config),))
done = True
except sqlite3.OperationalError:
logging.warning("Database is locked, waiting 10s before trying again".format(self.__db))
time.sleep(10)
self.__db.commit()
self.__db.close()
def __submit_failure(self, msg:str|None) -> None:
"""
Called when a file related failure occurs
Param:
msg: Message to write to LOG_NAME, skip step if None
"""
jutils.write_to_file(LOG_NAME, msg, LOG_MUTEX) if msg else None
self.__failed_mutex.acquire()
self.__failed += 1
self.__failed_mutex.release()
def __submit_progress(self) -> None:
"""
Called when progress is made on files
"""
self.__progress_mutex.acquire()
self.__progress.release()
self.__progress_mutex.release()
def __submit_downloaded(self) -> None:
"""
Called when a file is successfully downloaded
"""
self.__fcount_mutex.acquire()
self.__fcount += 1
self.__fcount_mutex.release()
def __submit_skipped(self)->None:
"""
Called when a file download is skipped
"""
self.__scount_mutex.acquire()
self.__scount += 1
self.__scount_mutex.release()
def __download_file(self, src: str, fname: str, org_fname: str, display_bar:bool = True) -> None:
"""
Downloads file at src. Skips if
(1) a file already exists sharing the same fname and size
(2) Contains blacklisted extensions
(3) File's name and size matches a locally downloaded file
However, if self.__rename is true, file will be renamed according to self's vars if src file matches a local copy
Param:
src: src of image to download
fname: what to name the file to download, with extensions. Absolute path
org_fname: fname but the base version of it. Used for file name collision checks.
display_bar: Whether to display download progress bar or not. If False, display bar is not displayed and self.__progress
is incremented instead.
Pre: If program is called with a thread, it will use a unique session, if called by main, it will use a newly
generated session that is closed before function terminates
"""
close = False
# Configure tname and session #######################################################################################################
if not tname.name:
tname.name = "default thread name"
session = cfscrape.create_scraper(requests.Session())
session.max_redirects = 5
adapter = requests.adapters.HTTPAdapter(pool_connections=self.__tcount, pool_maxsize=self.__tcount, max_retries=0, pool_block=True)
session.mount('http://', adapter)
close = True
else:
session = self.__sessions[tname.id]
logging.debug("Downloading " + fname + " from " + src)
r = None
timeout = 0
notifcation = 0
# Grabbing content length ###########################################################################################################
while not r:
try:
r = session.request('HEAD', src, timeout=10)
if r.status_code >= 400:
if r.status_code in self.__http_codes and 'kemono' in src:
if timeout == self.__timeout:
logging.critical("Reached maximum timeout, writing error to log")
self.__submit_failure("TIMEOUT -> SRC: {src}, FNAME: {fname}\n".format(src=src, fname=fname))
if not display_bar:
self.__submit_progress()
return
else:
timeout += 1
logging.warning(f"Kemono party is rate limiting this download, download restarted in {self.__connection_timeout} seconds:\nCode: " + str(r.status_code) + "\nSrc: " + src + "\nFname: " + fname)
time.sleep(self.__connection_timeout)
else:
logging.critical("(" + str(r.status_code) + ")" + "Link provided cannot be downloaded from, likely a dead link. Check HTTP code and src: \nSrc: " + src + "\nFname: " + fname)
self.__submit_failure("{code} UNREGISTERED TIMEOUT AND NONKEMONO LINK -> SRC: {src}, FNAME: {fname}\n".format(code=str(r.status_code), src=src, fname=fname))
if not display_bar:
self.__submit_progress()
return
except requests.exceptions.Timeout:
logging.warning("Connection timed out, this may be due to CAPTCHA, please open Kemono and solve the captcha, program will sleep for 20 seconds")
time.sleep(20)
except(requests.exceptions.RequestException) as e:
logging.warning(f"{e.__class__.__name__} has occured for {src} ({notifcation}), thread sleeping for {self.__connection_timeout} seconds.")
notifcation+=1
time.sleep(self.__connection_timeout)
if(notifcation % 10 == 0):
logging.warning("Connection has been retried multiple times on {url} for {f}, if problem persists, check https://status.kemono.party/".format(url=src, f=fname))
logging.debug("Connection request unanswered, retrying -> URL: {url}, FNAME: {f}".format(url=src, f=fname))
# Checking if file has a correct download format
format = r.headers["content-type"]
found = False
for f in download_format_types:
if f in format:
found = True
break
if not found:
logging.warning("{} has nontracked MIME type {}, skipping".format(src, format))
if not display_bar:
self.__submit_progress()
return
fullsize = r.headers.get('Content-Length')
f = fname.split('\\')[len(fname.split('\\')) - 1] # File name only, used for bar display
# If file does not have a length, it is most likely an invalid file
if fullsize == None:
logging.critical("Download was attempted on an undownloadable file, details describe\nSrc: " + src + "\nFname: " + fname)
self.__submit_failure("UNDOWNLOADABLE -> SRC: {src}, FNAME: {fname}\n".format(code=str(r.status_code), src=src, fname=fname))
else:
# Convert fullsize
fullsize = int(fullsize)
# Check to see if file exists in the file register
self.__existing_file_register_lock.acquire()
if self.__existing_file_register.hashtable_exist_by_key(org_fname) == -1:
# If does not exists, add an entry
self.__existing_file_register.hashtable_add(KVPair(org_fname, []))
# Check 3 conditions when renaming
download = self.__dupe_file_procedure(fname, org_fname, fullsize, True)
# Otherwise, download files that are greater than minimum size and whose extension is not blacklisted
if download and fullsize > self.__minsize and (not self.__ext_blacklist or self.__ext_blacklist.hashtable_exist_by_key(f.partition('.')[2]) == -1):
headers = request_headers
mode = 'wb'
done = False
downloaded = 0 # Used for updating the bar
failed = False
# Make a new file name according to number of matching fname entries
download_fname = fname
# Make sure that file does not already exists
i = 0
while(os.path.exists(download_fname)):
# Starts at 0 due to backward compatibility with previous dupe naming scheme
# predupe case
if self.__predupe:
ftokens = fname.rpartition('\\')
download_fname = ftokens[0] + "\\(" + str(i) + ") " + ftokens[2]
# postdupe case
else:
ftokens = fname.rpartition('.')
download_fname = ftokens[0] + " (" + str(i) + ")." + ftokens[2]
i += 1
self.__existing_file_register_lock.release()
while(not done):
try:
# Get the session
data = None
while not data:
try:
data = session.get(src, stream=True, timeout=10, headers=headers)
except requests.exceptions.Timeout:
logging.warning("Connection timed out, this may be due to CAPTCHA, please open Kemono and solve the captcha, program will sleep for 20 seconds")
time.sleep(20)
except(requests.exceptions.RequestException) as e:
logging.warning(f"{e.__class__.__name__} has occured for {src}, thread sleeping for {self.__connection_timeout} seconds.")
time.sleep(self.__connection_timeout)
# Download the file with visual bars
if display_bar:
with open(download_fname, mode) as fd, tqdm(
desc=download_fname,
total=fullsize - downloaded,
unit='iB',
unit_scale=True,
leave=False,
bar_format= tname.name + ": (" + str(self.__threads.get_qsize()) + ")->" + f + '[{bar}{r_bar}]',
unit_divisor=int(1024)) as bar:
for chunk in data.iter_content(chunk_size=self.__chunksz):
sz = fd.write(chunk)
fd.flush()
bar.update(sz)
downloaded += sz
time.sleep(self.__wait)
bar.clear()
else:
with open(download_fname, 'wb') as fd:
try:
for chunk in data.iter_content(chunk_size=self.__chunksz):
if chunk:
sz = fd.write(chunk)
fd.flush()
downloaded += sz
else:
logging.error("Chunk not received")
except(SSLError):
logging.error("SSL read error has occured on URL: {}".format(src))
jutils.write_to_file(LOG_NAME, "SSL read error -> SRC: {src}, FNAME: {fname}\n".format(code=str(r.status_code), src=src, fname=download_fname), LOG_MUTEX)
failed = True
except requests.exceptions.Timeout:
logging.warning("Connection timed out, this may be due to CAPTCHA, please open Kemono and solve the captcha, program will sleep for 20 seconds")
time.sleep(20)
except(requests.exceptions.RequestException) as e:
logging.warning(f"{e.__class__.__name__} has occured for {src}, thread sleeping for {self.__connection_timeout} seconds.")
time.sleep(self.__connection_timeout)
except(Exception) as e:
logging.error("Handled an unknown exception: {}".format(e.__class__.__name__))
jutils.write_to_file(LOG_NAME, "Unknown Exception {exc} -> SRC: {src}, FNAME: {fname}\n".format(exc=e.__class__.__name__, code=str(r.status_code), src=src, fname=download_fname), LOG_MUTEX)
failed = True
# Checks if unrecoverable error as occured
if failed:
done = True
self.__submit_failure(None)
# Checks if the file is correctly downloaded, if so, we are done
elif(os.stat(download_fname).st_size == fullsize):
done = True
logging.debug("Downloaded Size (" + download_fname + ") -> " + str(fullsize))
# Increment file download count, file is downloaded at this point
self.__submit_downloaded()
# Unzip file if specified
if self.__unzip and zipextracter.supported_zip_type(download_fname):
p = download_fname.rpartition('\\')[0] + "\\" + re.sub(r'[^\w\-_\. ]|[\.]$', '',
download_fname.rpartition('\\')[2]).rpartition(" by")[0].strip() + "\\"
self.__dir_lock.acquire()
if not os.path.exists(p):
os.mkdir(p)
self.__dir_lock.release()
if not zipextracter.extract_zip(download_fname, p, temp=self.__tempextr):
self.__submit_failure("Extraction Failure -> FILE: {fname}\n".format(fname=download_fname))
else:
logging.warning("File not downloaded correctly, will be restarted!\nSrc: " + src + "\nFname: " + download_fname)
time.sleep(self.__connection_timeout)
#headers = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
# 'Range': 'bytes=' + str(downloaded) + '-' + str(fullsize)}
#mode = 'ab'
except(requests.exceptions.RequestException) as e:
logging.warning(f"{e.__class__.__name__} has occured for {src}, thread sleeping for {self.__connection_timeout} seconds.")
time.sleep(self.__connection_timeout)
except FileNotFoundError:
logging.debug("Cannot be downloaded, file likely a link, not a file ->" + download_fname)
done = True
else:
self.__submit_skipped()
self.__existing_file_register_lock.release()
# Increment progress mutex
if not display_bar:
self.__progress_mutex.acquire()
self.__progress.release()
self.__progress_mutex.release()
# Closes session if session was created within this function
if close:
session.close()
# Sleep before exiting
logging.debug(f"Thread sleeping for {self.__wait} seconds after completing download")
time.sleep(self.__wait)
def __trim_fname(self, fname: str) -> str:
"""
Trims fname, returns result. Extensions are kept:
For example
When ext length of ?<filename>.ext token is <= 6:
"/data/2f/33/2f33425e67b99de681eb7638ef2c7ca133d7377641cff1c14ba4c4f133b9f4d6.txt?f=File.txt"
-> File.txt
Or
When ext length of ?<filename>.ext token is > 6:
"/data/2f/33/2f33425e67b99de681eb7638ef2c7ca133d7377641cff1c14ba4c4f133b9f4d6.jpg?f=File.jpe%3Ftoken-time%3D1570752000..."
->2f33425e67b99de681eb7638ef2c7ca133d7377641cff1c14ba4c4f133b9f4d6.jpg
Or
When ' ' exists
'Download まとめDL用.zip'
-> まとめDL用.zip
Param:
fname: file name
Pre: fname follows above conventions
Return: trimmed filename with extension
"""
# Case 3, space
case3 = fname.partition(' ')[2]
if case3 != fname and len(case3) > 0:
return re.sub(r'[^\w\-_\. ]|[\.]$', '',
case3)
case1 = fname.rpartition('=')[2]
# Case 2, bad extension provided
if len(case1.rpartition('.')[2]) > 6:
first = fname.rpartition('?')[0]
return re.sub(r'[^\w\-_\. ]|[\.]$', '',
first.rpartition('/')[2])
# Case 1, good extension
return re.sub(r'[^\w\-_\. ]|[\.]$', '',
case1)
def __queue_download_files(self, imgLinks: ResultSet, dir: str, org_dir: str, base_name:str | None, org_base_name:str | None, task_list:Queue|None, counter:PersistentCounter, postcounter:int|None = None) -> Queue:
"""
Puts all urls in imgLinks in threadpool download queue. If task_list is not None, then
all urls will be added to task_list instead of being added to download queue.
Param:
imgLinks: all image links within a Kemono container
dir: where to save the images
base_name: Prefix to name files, None for just a counter
task_list: list to store tasks into instead of directly processing them, None to directly process them
counter: a counter to increment for each file and used to rename files
org_base_name: base name without any additions
postcounter: counter added to the end of the file name, None to not have one
Raise: DeadThreadPoolException when no download threads are available, ignored if enqueue is false
Return modified tasklist, is None if task_list param is None
"""
if not self.__threads.get_status():
raise DeadThreadPoolException
if not base_name:
base_name = ""
if not org_base_name:
org_base_name = ""
for link in imgLinks:
href = link.get('href')
# Type 1 image - Image in Files section
if href:
src = href if "http" in href else self.__container_prefix + href
# Type 2 image - Image in Content section
else:
target = link.get('src')
# Polluted link check, Fanbox is notorious for this
# Curiously, src can be None as a string
if "downloads.fanbox" not in target and target != "None":
# Hosted on non KMP server
if 'http' in target:
src = target
# Hosted on KMP server
else:
src = target if "http" in target else self.__container_prefix + target
else:
src = None
# If a src is detected, it is added to the download queue/task list
if src:
logging.debug("Extracted content link: " + src)
# Select the correct download name based on switch
if self.__download_server_name_type:
fname = dir + base_name + self.__trim_fname(src)
org_fname = org_dir + base_name + self.__trim_fname(src)
else:
if not postcounter:
fname = dir + base_name + str(counter.get()) + '.' + self.__trim_fname(src).rpartition('.')[2]
org_fname = org_dir + org_base_name + str(counter.get()) + '.' + self.__trim_fname(src).rpartition('.')[2]
else:
fname = dir + base_name + str(counter.get()) + ' (' + str(postcounter) +').' + self.__trim_fname(src).rpartition('.')[2]
org_fname = org_dir + org_base_name + str(counter.get()) + '.' + self.__trim_fname(src).rpartition('.')[2]
if not task_list:
self.__threads.enqueue((self.__download_file, (src, fname, org_fname)))
else:
task_list.put((self.__download_file, (src, fname, org_fname, False)))
counter.toggle()
return task_list
def __download_file_text(self, textLinks:ResultSet, dir:str, base_dir:str) -> None:
"""
Scrapes all text and their links in textLink and saves it to
in dir
Param:
textLink: Set of links and their text in Files segment
dir: Where to save the text and links to. Must be a .txt file
base_dir: dir without any additions
"""
frontOffset = 5
endOffset = 4
currOffset = 0
listSz = len(textLinks)
strBuilder = []
# No work to be done if the file already exists
if os.path.exists(base_dir) or listSz <= 9:
logging.debug(f"File already exists, skipping: {dir}")
return
# Record data
for txtlink in textLinks:
if frontOffset > 0:
frontOffset -= 1
elif(endOffset < listSz - currOffset):
text = txtlink.get('href').strip()
if not text.isnumeric():
strBuilder.append(txtlink.text.strip() + '\n')
strBuilder.append(text + '\n')
strBuilder.append("____________________________________________________________\n")
currOffset += 1
# Write to file if data exists
if len(strBuilder) > 0:
jutils.write_utf8("".join(strBuilder), dir, 'w')
def __dupe_file_check(self, org_fname:str, value)->bool:
"""
Check if dupe file exists
Args:
org_fname (str): base name of file
value: Characteristic of the file
Return true if dupe file exists, false if does not
Pre: elf.__existing_file_register_lock is already acquired (will not be released)
"""
values = self.__existing_file_register.hashtable_lookup_value(org_fname)
for i in values[0::2]:
if i == value:
return True
return False
def __clear_empty(self, dir:str)->None:
"""
Deletes a directory if it is empty
Args:
dir (str): directory to check
Pre: Handler for exceptions
"""
if len(os.listdir(dir)) == 0: