forked from Nandaka/PixivUtil2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPixivUtil2.py
executable file
·2255 lines (1947 loc) · 98.1 KB
/
PixivUtil2.py
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=I0011, C, C0302, W0602, W0603, W0703, R0102, R1702, R0912, R0915
from __future__ import print_function
import sys
try:
stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
reload(sys)
sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
sys.setdefaultencoding("utf-8")
except Exception as e:
pass # swallow the exception
import os
import re
import traceback
import gc
import time
import datetime
import datetime_z
import urllib2
import getpass
import httplib
import codecs
import subprocess
from BeautifulSoup import BeautifulSoup
if os.name == 'nt':
# enable unicode support on windows console.
import win_unicode_console
# monkey patch for #305
from ctypes import byref, c_ulong
from win_unicode_console.streams import set_last_error, ERROR_SUCCESS, ReadConsoleW, get_last_error, ERROR_OPERATION_ABORTED, WinError
from win_unicode_console.buffer import get_buffer
EOF = b"\x1a\x00"
def readinto_patch(self, b):
bytes_to_be_read = len(b)
if not bytes_to_be_read:
return 0
elif bytes_to_be_read % 2:
raise ValueError("cannot read odd number of bytes from UTF-16-LE encoded console")
buffers = get_buffer(b, writable=True)
code_units_to_be_read = bytes_to_be_read // 2
code_units_read = c_ulong()
set_last_error(ERROR_SUCCESS)
ReadConsoleW(self.handle, buffers, code_units_to_be_read, byref(code_units_read), None)
last_error = get_last_error()
if last_error == ERROR_OPERATION_ABORTED:
time.sleep(0.1) # wait for KeyboardInterrupt
if last_error != ERROR_SUCCESS:
raise WinError(last_error)
if buffers[:len(EOF)] == EOF:
return 0
else:
return 2 * code_units_read.value # bytes read
win_unicode_console.streams.WindowsConsoleRawReader.readinto = readinto_patch
win_unicode_console.enable()
import PixivConstant
import PixivConfig
import PixivDBManager
import PixivHelper
from PixivModel import PixivImage, PixivListItem, PixivBookmark, PixivTags
from PixivModel import PixivNewIllustBookmark, PixivGroup
from PixivException import PixivException
import PixivBrowserFactory
from optparse import OptionParser
import random
script_path = PixivHelper.module_path()
np_is_valid = False
np = 0
op = ''
DEBUG_SKIP_PROCESS_IMAGE = False
ERROR_CODE = 0
gc.enable()
# gc.set_debug(gc.DEBUG_LEAK)
import mechanize
# replace unenscape_charref implementation with our implementation due to bug.
mechanize._html.unescape_charref = PixivHelper.unescape_charref
__config__ = PixivConfig.PixivConfig()
configfile = "config.ini"
__dbManager__ = None
__br__ = None
__blacklistTags = list()
__suppressTags = list()
__log__ = PixivHelper.GetLogger()
__errorList = list()
__blacklistMembers = list()
start_iv = False
dfilename = ""
# http://www.pixiv.net/member_illust.php?mode=medium&illust_id=18830248
__re_illust = re.compile(r'member_illust.*illust_id=(\d*)')
__re_manga_page = re.compile(r'(\d+(_big)?_p\d+)')
# issue #299
def get_remote_filesize(url, referer):
print('Getting remote filesize...')
# open with HEAD method, might be expensive
req = PixivHelper.create_custom_request(url, __config__, referer, head=True)
res = __br__.open_novisit(req)
try:
file_size = int(res.info()['Content-Length'])
except KeyError:
file_size = -1
PixivHelper.print_and_log('info', "\tNo file size information!")
print("Remote filesize = {0} ({1} Bytes)".format(PixivHelper.sizeInStr(file_size), file_size))
return file_size
# -T04------For download file
def download_image(url, filename, referer, overwrite, max_retry, backup_old_file=False, image_id=None, page=None):
'''return download result and filename if ok'''
global ERROR_CODE
temp_error_code = None
retry_count = 0
while retry_count <= max_retry:
res = None
req = None
try:
try:
if not overwrite and not __config__.alwaysCheckFileSize:
print('\rChecking local filename...', end=' ')
if os.path.exists(filename) and os.path.isfile(filename):
PixivHelper.print_and_log('info', "\rLocal file exists: {0}".format(filename.encode('utf-8')))
return (PixivConstant.PIXIVUTIL_SKIP_DUPLICATE, filename)
file_size = -1
# check if existing ugoira file exists
if filename.endswith(".zip"):
ugo_name = filename[:-4] + ".ugoira"
gif_name = filename[:-4] + ".gif"
apng_name = filename[:-4] + ".png"
webm_name = filename[:-4] + ".webm"
# non-converted zip (no animation.json)
if os.path.exists(filename) and os.path.isfile(filename):
# not sure what is the proper handling, currently it will throw error after download due to file already exists.
pass
# converted to ugoira (has animation.json)
if os.path.exists(ugo_name) and os.path.isfile(ugo_name):
old_size = PixivHelper.getUgoiraSize(ugo_name)
if file_size < 0:
file_size = get_remote_filesize(url, referer)
check_result = PixivHelper.checkFileExists(overwrite, ugo_name, file_size, old_size, backup_old_file)
if check_result != PixivConstant.PIXIVUTIL_OK:
# try to convert existing file.
if __config__.createGif and not os.path.exists(gif_name):
PixivHelper.ugoira2gif(ugo_name, gif_name, __config__.deleteUgoira)
if __config__.createApng and not os.path.exists(apng_name):
PixivHelper.ugoira2apng(ugo_name, apng_name, __config__.deleteUgoira)
if __config__.createWebm and not os.path.exists(webm_name):
PixivHelper.ugoira2webm(ugo_name,
webm_name,
__config__.deleteUgoira,
__config__.ffmpeg,
__config__.ffmpegCodec,
__config__.ffmpegParam)
return (check_result, filename)
elif os.path.exists(filename) and os.path.isfile(filename):
# other image? files
old_size = os.path.getsize(filename)
if file_size < 0:
file_size = get_remote_filesize(url, referer)
check_result = PixivHelper.checkFileExists(overwrite, filename, file_size, old_size, backup_old_file)
if check_result != PixivConstant.PIXIVUTIL_OK:
return (check_result, filename)
# check based on filename stored in DB using image id
if image_id is not None:
db_filename = None
if page is not None:
row = __dbManager__.selectImageByImageIdAndPage(image_id, page)
if row is not None:
db_filename = row[2]
else:
row = __dbManager__.selectImageByImageId(image_id)
if row is not None:
db_filename = row[3]
if db_filename is not None and os.path.exists(db_filename) and os.path.isfile(db_filename):
old_size = os.path.getsize(db_filename)
if file_size < 0:
file_size = get_remote_filesize(url, referer)
check_result = PixivHelper.checkFileExists(overwrite, db_filename, file_size, old_size, backup_old_file)
if check_result != PixivConstant.PIXIVUTIL_OK:
ugo_name = None
if db_filename.endswith(".zip"):
ugo_name = db_filename[:-4] + ".ugoira"
gif_name = db_filename[:-4] + ".gif"
apng_name = db_filename[:-4] + ".png"
webm_name = db_filename[:-4] + ".webm"
if db_filename.endswith(".ugoira"):
ugo_name = db_filename
gif_name = db_filename[:-7] + ".gif"
apng_name = db_filename[:-7] + ".png"
webm_name = db_filename[:-7] + ".webm"
if ugo_name is not None and os.path.exists(ugo_name) and os.path.isfile(ugo_name):
# try to convert existing file.
if __config__.createGif and not os.path.exists(gif_name):
PixivHelper.ugoira2gif(ugo_name, gif_name, __config__.deleteUgoira)
if __config__.createApng and not os.path.exists(apng_name):
PixivHelper.ugoira2apng(ugo_name, apng_name, __config__.deleteUgoira)
if __config__.createWebm and not os.path.exists(webm_name):
PixivHelper.ugoira2webm(ugo_name,
webm_name,
__config__.deleteUgoira,
__config__.ffmpeg,
__config__.ffmpegCodec,
__config__.ffmpegParam)
return (check_result, filename)
# actual download
(downloadedSize, filename) = perform_download(url, file_size, filename, overwrite, referer)
# check the downloaded file size again
if file_size > 0 and downloadedSize != file_size:
raise PixivException("Incomplete Downloaded for {0}".format(url), PixivException.DOWNLOAD_FAILED_OTHER)
elif __config__.verifyImage and (filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".gif")):
fp = None
try:
from PIL import Image, ImageFile
fp = open(filename, "rb")
# Fix Issue #269, refer to https://stackoverflow.com/a/42682508
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open(fp)
img.load()
fp.close()
PixivHelper.print_and_log('info', ' Image verified.')
except BaseException:
if fp is not None:
fp.close()
PixivHelper.print_and_log('info', ' Image invalid, deleting...')
os.remove(filename)
raise
elif __config__.verifyImage and (filename.endswith(".ugoira") or filename.endswith(".zip")):
fp = None
try:
import zipfile
fp = open(filename, "rb")
zf = zipfile.ZipFile(fp)
zf.testzip()
fp.close()
PixivHelper.print_and_log('info', ' Image verified.')
except BaseException:
if fp is not None:
fp.close()
PixivHelper.print_and_log('info', ' Image invalid, deleting...')
os.remove(filename)
raise
else:
PixivHelper.print_and_log('info', ' done.')
# write to downloaded lists
if start_iv or __config__.createDownloadLists:
dfile = codecs.open(dfilename, 'a+', encoding='utf-8')
dfile.write(filename + "\n")
dfile.close()
return (PixivConstant.PIXIVUTIL_OK, filename)
except urllib2.HTTPError as httpError:
PixivHelper.print_and_log('error', '[download_image()] HTTP Error: {0} at {1}'.format(str(httpError), url))
if httpError.code == 404 or httpError.code == 502:
return (PixivConstant.PIXIVUTIL_NOT_OK, None)
temp_error_code = PixivException.DOWNLOAD_FAILED_NETWORK
raise
except urllib2.URLError as urlError:
PixivHelper.print_and_log('error', '[download_image()] URL Error: {0} at {1}'.format(str(urlError), url))
temp_error_code = PixivException.DOWNLOAD_FAILED_NETWORK
raise
except IOError as ioex:
if ioex.errno == 28:
PixivHelper.print_and_log('error', ioex.message)
raw_input("Press Enter to retry.")
return (PixivConstant.PIXIVUTIL_NOT_OK, None)
temp_error_code = PixivException.DOWNLOAD_FAILED_IO
raise
except KeyboardInterrupt:
PixivHelper.print_and_log('info', 'Aborted by user request => Ctrl-C')
return (PixivConstant.PIXIVUTIL_ABORTED, None)
finally:
if res is not None:
del res
if req is not None:
del req
except BaseException:
if temp_error_code is None:
temp_error_code = PixivException.DOWNLOAD_FAILED_OTHER
ERROR_CODE = temp_error_code
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', 'Error at download_image(): {0} at {1} ({2})'.format(str(sys.exc_info()), url, ERROR_CODE))
if retry_count < max_retry:
retry_count = retry_count + 1
print("\rRetrying [{0}]...".format(retry_count), end=' ')
PixivHelper.printDelay(__config__.retryWait)
else:
raise
def perform_download(url, file_size, filename, overwrite, referer=None):
if referer is None:
referer = __config__, referer
# actual download
print('\rStart downloading...', end=' ')
# fetch filesize
req = PixivHelper.create_custom_request(url, __config__, referer)
res = __br__.open_novisit(req)
if file_size < 0:
try:
file_size = int(res.info()['Content-Length'])
except KeyError:
file_size = -1
PixivHelper.print_and_log('info', "\tNo file size information!")
(downloadedSize, filename) = PixivHelper.downloadImage(url, filename, res, file_size, overwrite)
return (downloadedSize, filename)
# Start of main processing logic
def process_list(list_file_name=None, tags=None):
global ERROR_CODE
result = None
try:
# Getting the list
if __config__.processFromDb:
PixivHelper.print_and_log('info', 'Processing from database.')
if __config__.dayLastUpdated == 0:
result = __dbManager__.selectAllMember()
else:
print('Select only last', __config__.dayLastUpdated, 'days.')
result = __dbManager__.selectMembersByLastDownloadDate(__config__.dayLastUpdated)
else:
PixivHelper.print_and_log('info', 'Processing from list file: {0}'.format(list_file_name))
result = PixivListItem.parseList(list_file_name, __config__.rootDirectory)
if os.path.exists("ignore_list.txt"):
PixivHelper.print_and_log('info', 'Processing ignore list for member: {0}'.format("ignore_list.txt"))
ignore_list = PixivListItem.parseList("ignore_list.txt", __config__.rootDirectory)
for ignore in ignore_list:
for item in result:
if item.memberId == ignore.memberId:
result.remove(item)
break
print("Found " + str(len(result)) + " items.")
for item in result:
retry_count = 0
while True:
try:
process_member(item.memberId, item.path, tags=tags)
break
except KeyboardInterrupt:
raise
except BaseException:
if retry_count > __config__.retry:
PixivHelper.print_and_log('error', 'Giving up member_id: ' + str(item.memberId))
break
retry_count = retry_count + 1
print('Something wrong, retrying after 2 second (', retry_count, ')')
time.sleep(2)
__br__.clear_history()
print('done.')
except KeyboardInterrupt:
raise
except Exception as ex:
ERROR_CODE = getattr(ex, 'errorCode', -1)
PixivHelper.print_and_log('error', 'Error at process_list(): {0}'.format(sys.exc_info()))
print('Failed')
raise
def process_member(member_id, user_dir='', page=1, end_page=0, bookmark=False, tags=None):
global __errorList
global ERROR_CODE
list_page = None
PixivHelper.print_and_log('info', 'Processing Member Id: ' + str(member_id))
if page != 1:
PixivHelper.print_and_log('info', 'Start Page: ' + str(page))
if end_page != 0:
PixivHelper.print_and_log('info', 'End Page: ' + str(end_page))
if __config__.numberOfPage != 0:
PixivHelper.print_and_log('info', 'Number of page setting will be ignored')
elif np != 0:
PixivHelper.print_and_log('info', 'End Page from command line: ' + str(np))
elif __config__.numberOfPage != 0:
PixivHelper.print_and_log('info', 'End Page from config: ' + str(__config__.numberOfPage))
__config__.loadConfig(path=configfile)
# calculate the offset for display properties
offset = 24 # new offset for AJAX call
if __br__._isWhitecube:
offset = 50
offset_start = (page - 1) * offset
offset_stop = end_page * offset
try:
no_of_images = 1
is_avatar_downloaded = False
flag = True
updated_limit_count = 0
image_id = -1
while flag:
print('Page ', page)
set_console_title("MemberId: " + str(member_id) + " Page: " + str(page))
# Try to get the member page
while True:
try:
(artist, list_page) = PixivBrowserFactory.getBrowser().getMemberPage(member_id, page, bookmark, tags)
break
except PixivException as ex:
ERROR_CODE = ex.errorCode
PixivHelper.print_and_log('info', 'Member ID (' + str(member_id) + '): ' + str(ex))
if ex.errorCode == PixivException.NO_IMAGES:
pass
else:
if list_page is None:
list_page = ex.htmlPage
if list_page is not None:
PixivHelper.dumpHtml("Dump for " + str(member_id) + " Error Code " + str(ex.errorCode) + ".html", list_page)
if ex.errorCode == PixivException.USER_ID_NOT_EXISTS or ex.errorCode == PixivException.USER_ID_SUSPENDED:
__dbManager__.setIsDeletedFlagForMemberId(int(member_id))
PixivHelper.print_and_log('info', 'Set IsDeleted for MemberId: ' + str(member_id) + ' not exist.')
# __dbManager__.deleteMemberByMemberId(member_id)
# PixivHelper.printAndLog('info', 'Deleting MemberId: ' + str(member_id) + ' not exist.')
if ex.errorCode == PixivException.OTHER_MEMBER_ERROR:
PixivHelper.safePrint(ex.message)
__errorList.append(dict(type="Member", id=str(member_id), message=ex.message, exception=ex))
return
except AttributeError:
# Possible layout changes, try to dump the file below
raise
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', 'Error at processing Artist Info: {0}'.format(sys.exc_info()))
PixivHelper.safePrint('Member Name : ' + artist.artistName)
print('Member Avatar:', artist.artistAvatar)
print('Member Token :', artist.artistToken)
print('Member Background :', artist.artistBackground)
print_offset_stop = offset_stop if offset_stop < artist.totalImages and offset_stop != 0 else artist.totalImages
print('Processing images from {0} to {1} of {2}'.format(offset_start + 1, print_offset_stop, artist.totalImages))
if artist.artistAvatar.find('no_profile') == -1 and not is_avatar_downloaded and __config__.downloadAvatar:
if user_dir == '':
target_dir = __config__.rootDirectory
else:
target_dir = unicode(user_dir)
avatar_filename = PixivHelper.createAvatarFilename(artist, target_dir)
if not DEBUG_SKIP_PROCESS_IMAGE:
# hardcode the referer to pixiv main site
download_image(artist.artistAvatar, avatar_filename, "https://www.pixiv.net/", __config__.overwrite,
__config__.retry, __config__.backupOldFile)
if artist.artistBackground is not None and artist.artistBackground.startswith("http"):
bg_name = PixivHelper.createBackgroundFilenameFromAvatarFilename(avatar_filename)
download_image(artist.artistBackground, bg_name, "https://www.pixiv.net/", __config__.overwrite,
__config__.retry, __config__.backupOldFile)
is_avatar_downloaded = True
__dbManager__.updateMemberName(member_id, artist.artistName)
if not artist.haveImages:
PixivHelper.print_and_log('info', "No image found for: " + str(member_id))
flag = False
continue
result = PixivConstant.PIXIVUTIL_NOT_OK
for image_id in artist.imageList:
print('#' + str(no_of_images))
if not __config__.overwrite:
r = __dbManager__.selectImageByMemberIdAndImageId(member_id, image_id)
if r is not None and not __config__.alwaysCheckFileSize:
print('Already downloaded:', image_id)
updated_limit_count = updated_limit_count + 1
if updated_limit_count > __config__.checkUpdatedLimit:
if __config__.checkUpdatedLimit != 0 and not __config__.alwaysCheckFileExists:
print('Skipping member:', member_id)
__dbManager__.updateLastDownloadedImage(member_id, image_id)
del list_page
__br__.clear_history()
return
gc.collect()
continue
retry_count = 0
while True:
try:
if artist.totalImages > 0:
# PixivHelper.safePrint("Total Images = " + str(artist.totalImages))
total_image_page_count = artist.totalImages
if(offset_stop > 0 and offset_stop < total_image_page_count):
total_image_page_count = offset_stop
total_image_page_count = total_image_page_count - offset_start
# PixivHelper.safePrint("Total Images Offset = " + str(total_image_page_count))
else:
total_image_page_count = ((page - 1) * 20) + len(artist.imageList)
title_prefix = "MemberId: {0} Page: {1} Image {2}+{3} of {4}".format(member_id,
page,
no_of_images,
updated_limit_count,
total_image_page_count)
if not DEBUG_SKIP_PROCESS_IMAGE:
result = process_image(artist, image_id, user_dir, bookmark, title_prefix=title_prefix) # Yavos added dir-argument to pass
wait()
break
except KeyboardInterrupt:
result = PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT
break
except BaseException:
if retry_count > __config__.retry:
PixivHelper.print_and_log('error', "Giving up image_id: " + str(image_id))
return
retry_count = retry_count + 1
print("Stuff happened, trying again after 2 second (", retry_count, ")")
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
__log__.exception('Error at process_member(): ' + str(sys.exc_info()) + ' Member Id: ' + str(member_id))
time.sleep(2)
no_of_images = no_of_images + 1
if result == PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT:
choice = raw_input("Keyboard Interrupt detected, continue to next image (Y/N)")
if choice.upper() == 'N':
PixivHelper.print_and_log("info", "Member: " + str(member_id) + ", processing aborted")
flag = False
break
else:
continue
# return code from process image
if result == PixivConstant.PIXIVUTIL_SKIP_OLDER:
PixivHelper.print_and_log("info", "Reached older images, skippin to next member.")
flag = False
break
if artist.isLastPage:
print("Last Page")
flag = False
page = page + 1
# page limit checking
if end_page > 0 and page > end_page:
print("Page limit reached (from endPage limit =" + str(end_page) + ")")
flag = False
else:
if np_is_valid: # Yavos: overwriting config-data
if page > np and np > 0:
print("Page limit reached (from command line =" + str(np) + ")")
flag = False
elif page > __config__.numberOfPage and __config__.numberOfPage > 0:
print("Page limit reached (from config =" + str(__config__.numberOfPage) + ")")
flag = False
del artist
del list_page
__br__.clear_history()
gc.collect()
if image_id > 0:
__dbManager__.updateLastDownloadedImage(member_id, image_id)
log_message = 'last image_id: ' + str(image_id)
else:
log_message = 'no images were found'
print('Done.\n')
__log__.info('Member_id: ' + str(member_id) + ' complete, ' + log_message)
except KeyboardInterrupt:
raise
except BaseException:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', 'Error at process_member(): {0}'.format(sys.exc_info()))
try:
if list_page is not None:
dump_filename = 'Error page for member {0} at page {1}.html'.format(member_id, page)
PixivHelper.dumpHtml(dump_filename, list_page)
PixivHelper.print_and_log('error', "Dumping html to: {0}".format(dump_filename))
except BaseException:
PixivHelper.print_and_log('error', 'Cannot dump page for member_id: {0}'.format(member_id))
raise
def process_image(artist=None, image_id=None, user_dir='', bookmark=False, search_tags='', title_prefix=None, bookmark_count=-1, image_response_count=-1):
global __errorList
global ERROR_CODE
parse_big_image = None
parse_medium_page = None
image = None
result = None
referer = 'https://www.pixiv.net/member_illust.php?mode=medium&illust_id=' + str(image_id)
filename = u'no-filename-{0}.tmp'.format(image_id)
try:
print('Processing Image Id:', image_id)
# check if already downloaded. images won't be downloaded twice - needed in process_image to catch any download
r = __dbManager__.selectImageByImageId(image_id, cols='save_name')
exists = False
in_db = False
if r is not None:
exists = True
in_db = True
if r is not None and __config__.alwaysCheckFileExists:
exists = __dbManager__.cleanupFileExists(r[0])
if r is not None and not __config__.alwaysCheckFileSize and exists:
if not __config__.overwrite and exists:
print('Already downloaded:', image_id)
gc.collect()
return PixivConstant.PIXIVUTIL_SKIP_DUPLICATE
# get the medium page
try:
(image, parse_medium_page) = PixivBrowserFactory.getBrowser().getImagePage(image_id=image_id,
parent=artist,
from_bookmark=bookmark,
bookmark_count=bookmark_count)
if title_prefix is not None:
set_console_title(title_prefix + " ImageId: {0}".format(image.imageId))
else:
set_console_title('MemberId: ' + str(image.artist.artistId) + ' ImageId: ' + str(image.imageId))
except PixivException as ex:
ERROR_CODE = ex.errorCode
__errorList.append(dict(type="Image", id=str(image_id), message=ex.message, exception=ex))
if ex.errorCode == PixivException.UNKNOWN_IMAGE_ERROR:
PixivHelper.safePrint(ex.message)
elif ex.errorCode == PixivException.SERVER_ERROR:
PixivHelper.print_and_log('error', 'Giving up image_id (medium): ' + str(image_id))
elif ex.errorCode > 2000:
PixivHelper.print_and_log('error', 'Image Error for ' + str(image_id) + ': ' + ex.message)
if parse_medium_page is not None:
dump_filename = 'Error medium page for image ' + str(image_id) + '.html'
PixivHelper.dumpHtml(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', 'Dumping html to: ' + dump_filename)
else:
PixivHelper.print_and_log('error', 'Image ID (' + str(image_id) + '): ' + str(ex))
PixivHelper.print_and_log('error', 'Stack Trace: {0}'.format(str(sys.exc_info())))
return PixivConstant.PIXIVUTIL_NOT_OK
except Exception as ex:
PixivHelper.print_and_log('error', 'Image ID (' + str(image_id) + '): ' + str(ex))
if parse_medium_page is not None:
dump_filename = 'Error medium page for image ' + str(image_id) + '.html'
PixivHelper.dumpHtml(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', 'Dumping html to: ' + dump_filename)
PixivHelper.print_and_log('error', 'Stack Trace: {0}'.format(str(sys.exc_info())))
return PixivConstant.PIXIVUTIL_NOT_OK
download_image_flag = True
# date validation and blacklist tag validation
if __config__.dateDiff > 0:
if image.worksDateDateTime != datetime.datetime.fromordinal(1).replace(tzinfo=datetime_z.utc):
if image.worksDateDateTime < (datetime.datetime.today() - datetime.timedelta(__config__.dateDiff)).replace(tzinfo=datetime_z.utc):
PixivHelper.print_and_log('info', 'Skipping image_id: ' + str(image_id) + ' because contains older than: ' + str(__config__.dateDiff) + ' day(s).')
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_OLDER
if __config__.useBlacklistTags:
for item in __blacklistTags:
if item in image.imageTags:
PixivHelper.print_and_log('info', 'Skipping image_id: ' + str(image_id) + ' because contains blacklisted tags: ' + item)
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
if __config__.useBlacklistMembers:
if str(image.originalArtist.artistId) in __blacklistMembers:
PixivHelper.print_and_log('info', 'Skipping image_id: ' + str(image_id) + ' because contains blacklisted member id: ' + str(image.originalArtist.artistId))
download_image_flag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
if download_image_flag:
if artist is None:
PixivHelper.safePrint('Member Name : ' + image.artist.artistName)
print('Member Avatar:', image.artist.artistAvatar)
print('Member Token :', image.artist.artistToken)
print('Member Background :', image.artist.artistBackground)
PixivHelper.safePrint("Title: " + image.imageTitle)
PixivHelper.safePrint("Tags : " + ', '.join(image.imageTags))
PixivHelper.safePrint("Date : " + str(image.worksDateDateTime))
print("Mode :", image.imageMode)
# get bookmark count
if ("%bookmark_count%" in __config__.filenameFormat or "%image_response_count%" in __config__.filenameFormat) and image.bookmark_count == -1:
print("Parsing bookmark page", end=' ')
bookmark_url = 'https://www.pixiv.net/bookmark_detail.php?illust_id=' + str(image_id)
parse_bookmark_page = PixivBrowserFactory.getBrowser().getPixivPage(bookmark_url)
image.ParseBookmarkDetails(parse_bookmark_page)
parse_bookmark_page.decompose()
del parse_bookmark_page
print("Bookmark Count :", str(image.bookmark_count))
__br__.back()
if __config__.useSuppressTags:
for item in __suppressTags:
if item in image.imageTags:
image.imageTags.remove(item)
# get manga page
if image.imageMode == 'manga' or image.imageMode == 'big':
while True:
try:
big_url = 'https://www.pixiv.net/member_illust.php?mode={0}&illust_id={1}'.format(image.imageMode, image_id)
parse_big_image = PixivBrowserFactory.getBrowser().getPixivPage(big_url, referer)
if parse_big_image is not None:
image.ParseImages(page=parse_big_image, _br=PixivBrowserFactory.getExistingBrowser())
parse_big_image.decompose()
del parse_big_image
break
except Exception as ex:
__errorList.append(dict(type="Image", id=str(image_id), message=ex.message, exception=ex))
PixivHelper.print_and_log('info', 'Image ID (' + str(image_id) + '): ' + str(traceback.format_exc()))
try:
if parse_big_image is not None:
dump_filename = 'Error Big Page for image ' + str(image_id) + '.html'
PixivHelper.dumpHtml(dump_filename, parse_big_image)
PixivHelper.print_and_log('error', 'Dumping html to: ' + dump_filename)
except BaseException:
PixivHelper.print_and_log('error', 'Cannot dump big page for image_id: ' + str(image_id))
return PixivConstant.PIXIVUTIL_NOT_OK
if image.imageMode == 'manga':
print("Page Count :", image.imageCount)
if user_dir == '': # Yavos: use config-options
target_dir = __config__.rootDirectory
else: # Yavos: use filename from list
target_dir = unicode(user_dir)
result = PixivConstant.PIXIVUTIL_OK
manga_files = dict()
page = 0
for img in image.imageUrls:
print('Image URL :', img)
url = os.path.basename(img)
split_url = url.split('.')
if split_url[0].startswith(str(image_id)):
# Yavos: filename will be added here if given in list
filename_format = __config__.filenameFormat
if image.imageMode == 'manga':
filename_format = __config__.filenameMangaFormat
filename = PixivHelper.makeFilename(filename_format, image, tagsSeparator=__config__.tagsSeparator, tagsLimit=__config__.tagsLimit, fileUrl=url, bookmark=bookmark, searchTags=search_tags)
filename = PixivHelper.sanitizeFilename(filename, target_dir)
if image.imageMode == 'manga' and __config__.createMangaDir:
manga_page = __re_manga_page.findall(filename)
if len(manga_page) > 0:
splitted_filename = filename.split(manga_page[0][0], 1)
splitted_manga_page = manga_page[0][0].split("_p", 1)
filename = splitted_filename[0] + splitted_manga_page[0] + os.sep + "_p" + splitted_manga_page[1] + splitted_filename[1]
PixivHelper.print_and_log('info', u'Filename : {0}'.format(filename))
result = PixivConstant.PIXIVUTIL_NOT_OK
try:
(result, filename) = download_image(img, filename, referer, __config__.overwrite, __config__.retry, __config__.backupOldFile, image_id, page)
# set last-modified and last-accessed timestamp
if __config__.setLastModified and filename is not None and os.path.isfile(filename):
ts = time.mktime(image.worksDateDateTime.timetuple())
os.utime(filename, (ts, ts))
if result == PixivConstant.PIXIVUTIL_NOT_OK:
PixivHelper.print_and_log('error', 'Image url not found/failed to download: ' + str(image.imageId))
elif result == PixivConstant.PIXIVUTIL_ABORTED:
raise KeyboardInterrupt()
manga_files[page] = filename
page = page + 1
except urllib2.URLError:
PixivHelper.print_and_log('error', 'Error when download_image(), giving up url: {0}'.format(img))
print('')
if __config__.writeImageInfo or __config__.writeImageJSON:
filename_info_format = __config__.filenameInfoFormat
info_filename = PixivHelper.makeFilename(filename_info_format, image, tagsSeparator=__config__.tagsSeparator,
tagsLimit=__config__.tagsLimit, fileUrl=url, appendExtension=False, bookmark=bookmark,
searchTags=search_tags)
info_filename = PixivHelper.sanitizeFilename(info_filename, target_dir)
# trim _pXXX
info_filename = re.sub(r'_p?\d+$', '', info_filename)
if __config__.writeImageInfo:
image.WriteInfo(info_filename + ".txt")
if __config__.writeImageJSON:
image.WriteJSON(info_filename + ".json")
if image.imageMode == 'ugoira_view':
if __config__.writeUgoiraInfo:
image.WriteUgoiraData(filename + ".js")
if __config__.createUgoira and result == PixivConstant.PIXIVUTIL_OK:
ugo_name = filename[:-4] + ".ugoira"
PixivHelper.print_and_log('info', "Creating ugoira archive => " + ugo_name)
image.CreateUgoira(filename)
if __config__.deleteZipFile:
PixivHelper.print_and_log('info', "Deleting zip file => " + filename)
os.remove(filename)
if __config__.createGif:
gif_filename = ugo_name[:-7] + ".gif"
PixivHelper.ugoira2gif(ugo_name, gif_filename, __config__.deleteUgoira)
if __config__.createApng:
gif_filename = ugo_name[:-7] + ".png"
PixivHelper.ugoira2apng(ugo_name, gif_filename, __config__.deleteUgoira)
if __config__.createWebm:
gif_filename = ugo_name[:-7] + ".webm"
PixivHelper.ugoira2webm(ugo_name,
gif_filename,
__config__.deleteUgoira,
__config__.ffmpeg,
__config__.ffmpegCodec,
__config__.ffmpegParam)
if __config__.writeUrlInDescription:
PixivHelper.writeUrlInDescription(image, __config__.urlBlacklistRegex, __config__.urlDumpFilename)
if in_db and not exists:
result = PixivConstant.PIXIVUTIL_CHECK_DOWNLOAD # There was something in the database which had not been downloaded
# Only save to db if all images is downloaded completely
if result == PixivConstant.PIXIVUTIL_OK or result == PixivConstant.PIXIVUTIL_SKIP_DUPLICATE or result == PixivConstant.PIXIVUTIL_SKIP_LOCAL_LARGER:
try:
__dbManager__.insertImage(image.artist.artistId, image.imageId, image.imageMode)
except BaseException:
PixivHelper.print_and_log('error', 'Failed to insert image id:{0} to DB'.format(image.imageId))
__dbManager__.updateImage(image.imageId, image.imageTitle, filename, image.imageMode)
if len(manga_files) > 0:
for page in manga_files:
__dbManager__.insertMangaImage(image_id, page, manga_files[page])
# map back to PIXIVUTIL_OK (because of ugoira file check)
result = 0
if image is not None:
del image
gc.collect()
# clearall()
print('\n')
return result
except KeyboardInterrupt:
raise
except Exception as ex:
ERROR_CODE = getattr(ex, 'errorCode', -1)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.print_and_log('error', 'Error at process_image(): {0}'.format(image_id))
PixivHelper.print_and_log('error', 'Exception: {0}'.format(sys.exc_info()))
if parse_medium_page is not None:
dump_filename = 'Error medium page for image ' + str(image_id) + '.html'
PixivHelper.dumpHtml(dump_filename, parse_medium_page)
PixivHelper.print_and_log('error', 'Dumping html to: {0}'.format(dump_filename))
raise
def process_tags(tags, page=1, end_page=0, wild_card=True, title_caption=False,
start_date=None, end_date=None, use_tags_as_dir=False, member_id=None,
bookmark_count=None, oldest_first=False):
search_page = None
i = page
try:
__config__.loadConfig(path=configfile) # Reset the config for root directory
search_tags = PixivHelper.decode_tags(tags)
if use_tags_as_dir:
print("Save to each directory using query tags.")
__config__.rootDirectory += os.sep + PixivHelper.sanitizeFilename(search_tags)
tags = PixivHelper.encode_tags(tags)
images = 1
last_image_id = -1
skipped_count = 0
offset = 20
if __br__._isWhitecube:
offset = 50
start_offset = (page - 1) * offset
stop_offset = end_page * offset
PixivHelper.print_and_log('info', 'Searching for: (' + search_tags + ") " + tags)
flag = True
while flag:
(t, search_page) = __br__.getSearchTagPage(tags, i,
wild_card,
title_caption,
start_date,
end_date,
member_id,
oldest_first,
page)
if len(t.itemList) == 0:
print('No more images')
flag = False
else:
for item in t.itemList:
last_image_id = item.imageId
print('Image #' + str(images))
print('Image Id:', str(item.imageId))
print('Bookmark Count:', str(item.bookmarkCount))
if bookmark_count is not None and bookmark_count > item.bookmarkCount:
PixivHelper.print_and_log('info', 'Skipping imageId= {0} because less than bookmark count limit ({1} > {2}).'.format(item.imageId, bookmark_count, item.bookmarkCount))
skipped_count = skipped_count + 1
continue
result = 0
while True:
try:
if t.availableImages > 0:
# PixivHelper.safePrint("Total Images: " + str(t.availableImages))
total_image = t.availableImages
if(stop_offset > 0 and stop_offset < total_image):
total_image = stop_offset
total_image = total_image - start_offset
# PixivHelper.safePrint("Total Images Offset: " + str(total_image))
else:
total_image = ((i - 1) * 20) + len(t.itemList)
title_prefix = "Tags:{0} Page:{1} Image {2}+{3} of {4}".format(tags, i, images, skipped_count, total_image)
if member_id is not None:
title_prefix = "MemberId: {0} Tags:{1} Page:{2} Image {3}+{4} of {5}".format(member_id,
tags, i,
images,
skipped_count,
total_image)
if not DEBUG_SKIP_PROCESS_IMAGE:
process_image(None, item.imageId, search_tags=search_tags, title_prefix=title_prefix, bookmark_count=item.bookmarkCount, image_response_count=item.imageResponse)
wait()
break
except KeyboardInterrupt:
result = PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT
break
except httplib.BadStatusLine:
print("Stuff happened, trying again after 2 second...")
time.sleep(2)
images = images + 1
if result == PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT:
choice = raw_input("Keyboard Interrupt detected, continue to next image (Y/N)")
if choice.upper() == 'N':
PixivHelper.print_and_log("info", "Tags: " + tags + ", processing aborted")
flag = False
break
else:
continue
__br__.clear_history()
i = i + 1
del search_page
if end_page != 0 and end_page < i:
PixivHelper.print_and_log('info', "End Page reached: " + str(end_page))
flag = False
if t.isLastPage:
PixivHelper.print_and_log('info', "Last page: " + str(i - 1))
flag = False
if __config__.enableInfiniteLoop and i == 1001 and not oldest_first:
if last_image_id > 0:
# get the last date