forked from Nandaka/PixivUtil2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPixivUtil2.py
1921 lines (1660 loc) · 81.5 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
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os
import re
import traceback
import gc
import time
import datetime
import urllib2
import getpass
import httplib
import codecs
from BeautifulSoup import BeautifulSoup
if os.name == 'nt':
# enable unicode support on windows console.
import win_unicode_console
win_unicode_console.enable()
import PixivConstant
import PixivConfig
import PixivDBManager
import PixivHelper
from PixivModel import PixivArtist, PixivImage, PixivListItem, PixivBookmark, PixivTags
from PixivModel import PixivNewIllustBookmark, PixivGroup
from PixivException import PixivException
import PixivBrowserFactory
from optparse import OptionParser
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()
# 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+)')
# -T04------For download file
def download_image(url, filename, referer, overwrite, max_retry, backup_old_file=False, image_id=None, page=None):
global ERROR_CODE
tempErrorCode = None
retry_count = 0
while retry_count <= max_retry:
res = None
req = None
try:
try:
if not overwrite and not __config__.alwaysCheckFileSize:
print 'Checking local filename...',
if os.path.exists(filename) and os.path.isfile(filename):
PixivHelper.printAndLog('info', "File exists: {0}".format(filename.encode('utf-8')))
return PixivConstant.PIXIVUTIL_SKIP_DUPLICATE
print 'Getting remote filesize...'
# open with HEAD method
req = PixivHelper.createCustomRequest(url, __config__, referer, head=True)
res = __br__.open_novisit(req)
# get file size
file_size = -1
try:
file_size = int(res.info()['Content-Length'])
except KeyError:
file_size = -1
PixivHelper.printAndLog('info', "\tNo file size information!")
print "Remote filesize = {0} ({1} Bytes)".format(PixivHelper.sizeInStr(file_size), file_size)
# check if existing file exists
if os.path.exists(filename) and os.path.isfile(filename) and not filename.endswith(".zip"):
old_size = os.path.getsize(filename)
checkResult = PixivHelper.checkFileExists(overwrite, filename, file_size, old_size, backup_old_file)
if checkResult != 1:
return checkResult
# check for ugoira file
if filename.endswith(".zip"):
ugoName = filename[:-4] + ".ugoira"
gifName = filename[:-4] + ".gif"
apngName = filename[:-4] + ".png"
# 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(ugoName) and os.path.isfile(ugoName):
old_size = PixivHelper.getUgoiraSize(ugoName)
checkResult = PixivHelper.checkFileExists(overwrite, ugoName, file_size, old_size, backup_old_file)
if checkResult != 1:
# try to convert existing file.
if __config__.createGif and not os.path.exists(gifName):
PixivHelper.ugoira2gif(ugoName, gifName)
if __config__.createApng and not os.path.exists(apngName):
PixivHelper.ugoira2apng(ugoName, apngName)
return checkResult
# 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)
checkResult = PixivHelper.checkFileExists(overwrite, db_filename, file_size, old_size, backup_old_file)
if checkResult != 1:
ugoName = None
if db_filename.endswith(".zip"):
ugoName = db_filename[:-4] + ".ugoira"
gifName = db_filename[:-4] + ".gif"
apngName = db_filename[:-4] + ".png"
if db_filename.endswith(".ugoira"):
ugoName = db_filename
gifName = db_filename[:-7] + ".gif"
apngName = db_filename[:-7] + ".png"
if ugoName is not None and os.path.exists(ugoName) and os.path.isfile(ugoName):
# try to convert existing file.
if __config__.createGif and not os.path.exists(gifName):
PixivHelper.ugoira2gif(ugoName, gifName)
if __config__.createApng and not os.path.exists(apngName):
PixivHelper.ugoira2apng(ugoName, apngName)
return checkResult
# actual download
print 'Start downloading...',
req = PixivHelper.createCustomRequest(url, __config__, referer)
res = __br__.open_novisit(req)
downloadedSize = PixivHelper.downloadImage(url, filename, res, file_size, overwrite)
# 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.printAndLog('info', ' Image verified.')
except:
if fp is not None:
fp.close()
PixivHelper.printAndLog('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.printAndLog('info', ' Image verified.')
except:
if fp is not None:
fp.close()
PixivHelper.printAndLog('info', ' Image invalid, deleting...')
os.remove(filename)
raise
else:
PixivHelper.printAndLog('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
except urllib2.HTTPError as httpError:
PixivHelper.printAndLog('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
tempErrorCode = PixivException.DOWNLOAD_FAILED_NETWORK
raise
except urllib2.URLError as urlError:
PixivHelper.printAndLog('error', '[download_image()] URL Error: {0} at {1}'.format(str(urlError), url))
tempErrorCode = PixivException.DOWNLOAD_FAILED_NETWORK
raise
except IOError as ioex:
if ioex.errno == 28:
PixivHelper.printAndLog('error', ioex.message)
raw_input("Press Enter to retry.")
return PixivConstant.PIXIVUTIL_NOT_OK
tempErrorCode = PixivException.DOWNLOAD_FAILED_IO
raise
except KeyboardInterrupt:
PixivHelper.printAndLog('info', 'Aborted by user request => Ctrl-C')
return PixivConstant.PIXIVUTIL_ABORTED
finally:
if res is not None:
del res
if req is not None:
del req
except:
if tempErrorCode is None:
tempErrorCode = PixivException.DOWNLOAD_FAILED_OTHER
ERROR_CODE = tempErrorCode
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.printAndLog('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 "Retrying [{0}]...".format(retry_count)
PixivHelper.printDelay(__config__.retryWait)
else:
raise
# Start of main processing logic
def process_list(mode, list_file_name=None, tags=None):
global ERROR_CODE
result = None
try:
# Getting the list
if __config__.processFromDb:
PixivHelper.printAndLog('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.printAndLog('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.printAndLog('info', 'Processing ignore list for member: {0}'.format("ignore_list.txt"))
ignoreList = PixivListItem.parseList("ignore_list.txt", __config__.rootDirectory)
for ignore in ignoreList:
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(mode, item.memberId, item.path, tags=tags)
break
except KeyboardInterrupt:
raise
except:
if retry_count > __config__.retry:
PixivHelper.printAndLog('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)
print 'Error at process_list():', sys.exc_info()
print 'Failed'
__log__.exception('Error at process_list(): ' + str(sys.exc_info()))
raise
def process_member(mode, member_id, user_dir='', page=1, end_page=0, bookmark=False, tags=None):
global __errorList
global ERROR_CODE
list_page = None
PixivHelper.printAndLog('info', 'Processing Member Id: ' + str(member_id))
if page != 1:
PixivHelper.printAndLog('info', 'Start Page: ' + str(page))
if end_page != 0:
PixivHelper.printAndLog('info', 'End Page: ' + str(end_page))
if __config__.numberOfPage != 0:
PixivHelper.printAndLog('info', 'Number of page setting will be ignored')
elif np != 0:
PixivHelper.printAndLog('info', 'End Page from command line: ' + str(np))
elif __config__.numberOfPage != 0:
PixivHelper.printAndLog('info', 'End Page from config: ' + str(__config__.numberOfPage))
__config__.loadConfig(path=configfile)
# calculate the offset for display properties
offset = 20
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.printAndLog('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.printAndLog('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.printAndLog('error', 'Error at processing Artist Info: ' + str(sys.exc_info()))
__log__.exception('Error at processing Artist Info: ' + str(member_id))
PixivHelper.safePrint('Member Name : ' + artist.artistName)
print 'Member Avatar:', artist.artistAvatar
print 'Member Token :', artist.artistToken
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 = 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)
is_avatar_downloaded = True
__dbManager__.updateMemberName(member_id, artist.artistName)
if not artist.haveImages:
PixivHelper.printAndLog('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 mode == PixivConstant.PIXIVUTIL_MODE_UPDATE_ONLY:
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:
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(mode, artist, image_id, user_dir, bookmark, title_prefix=title_prefix) # Yavos added dir-argument to pass
break
except KeyboardInterrupt:
result = PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT
break
except:
if retry_count > __config__.retry:
PixivHelper.printAndLog('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.printAndLog("info", "Member: " + str(member_id) + ", processing aborted")
flag = False
break
else:
continue
# return code from process image
if result == PixivConstant.PIXIVUTIL_SKIP_OLDER:
PixivHelper.printAndLog("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:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
PixivHelper.printAndLog('error', 'Error at process_member(): ' + str(sys.exc_info()))
__log__.exception('Error at process_member(): ' + str(member_id))
try:
if list_page is not None:
dump_filename = 'Error page for member ' + str(member_id) + '.html'
PixivHelper.dumpHtml(dump_filename, list_page)
PixivHelper.printAndLog('error', "Dumping html to: " + dump_filename)
except:
PixivHelper.printAndLog('error', 'Cannot dump page for member_id:' + str(member_id))
raise
def process_image(mode, 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)
try:
filename = 'N/A'
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)
if r is not None and not __config__.alwaysCheckFileSize:
if mode == PixivConstant.PIXIVUTIL_MODE_UPDATE_ONLY:
print 'Already downloaded:', image_id
gc.collect()
return
# get the medium page
try:
(image, parse_medium_page) = PixivBrowserFactory.getBrowser().getImagePage(imageId=image_id,
parent=artist,
fromBookmark=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.printAndLog('error', 'Giving up image_id (medium): ' + str(image_id))
elif ex.errorCode > 2000:
PixivHelper.printAndLog('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.printAndLog('error', 'Dumping html to: ' + dump_filename)
else:
PixivHelper.printAndLog('info', 'Image ID (' + str(image_id) + '): ' + str(ex))
return PixivConstant.PIXIVUTIL_NOT_OK
except Exception as ex:
PixivHelper.printAndLog('info', '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.printAndLog('error', 'Dumping html to: ' + dump_filename)
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):
if image.worksDateDateTime < datetime.datetime.today() - datetime.timedelta(__config__.dateDiff):
PixivHelper.printAndLog('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.printAndLog('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.printAndLog('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:
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",
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.printAndLog('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.printAndLog('error', 'Dumping html to: ' + dump_filename)
except:
PixivHelper.printAndLog('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 = user_dir
result = PixivConstant.PIXIVUTIL_OK
mangaFiles = dict()
page = 0
for img in image.imageUrls:
print 'Image URL :', img
url = os.path.basename(img)
splitted_url = url.split('.')
if splitted_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.safePrint('Filename : ' + filename)
result = PixivConstant.PIXIVUTIL_NOT_OK
try:
overwrite = False
if mode == PixivConstant.PIXIVUTIL_MODE_OVERWRITE:
overwrite = True
result = download_image(img, filename, referer, overwrite, __config__.retry, __config__.backupOldFile, image_id, page)
mangaFiles[page] = filename
page = page + 1
if result == PixivConstant.PIXIVUTIL_NOT_OK:
PixivHelper.printAndLog('error', 'Image url not found/failed to download: ' + str(image.imageId))
elif result == PixivConstant.PIXIVUTIL_ABORTED:
raise KeyboardInterrupt()
except urllib2.URLError:
PixivHelper.printAndLog('error', 'Giving up url: ' + str(img))
__log__.exception('Error when download_image(): ' + str(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('_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.printAndLog('info', "Creating ugoira archive => " + ugo_name)
image.CreateUgoira(filename)
if __config__.deleteZipFile:
PixivHelper.printAndLog('info', "Deleting zip file => " + filename)
os.remove(filename)
if __config__.createGif:
gif_filename = ugo_name[:-7] + ".gif"
PixivHelper.ugoira2gif(ugo_name, gif_filename)
if __config__.createApng:
gif_filename = ugo_name[:-7] + ".png"
PixivHelper.ugoira2apng(ugo_name, gif_filename)
if __config__.writeUrlInDescription:
PixivHelper.writeUrlInDescription(image, __config__.urlBlacklistRegex, __config__.urlDumpFilename)
# 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:
pass
__dbManager__.updateImage(image.imageId, image.imageTitle, filename, image.imageMode)
if image.imageMode == 'manga':
for page in mangaFiles:
__dbManager__.insertMangaImage(image_id, page, mangaFiles[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.printAndLog('error', 'Error at process_image(): ' + str(sys.exc_info()))
__log__.exception('Error at process_image(): ' + str(image_id))
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.printAndLog('error', 'Dumping html to: ' + dump_filename)
raise
def process_tags(mode, 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
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)
i = page
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.printAndLog('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.printAndLog('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(mode, None, item.imageId, search_tags=search_tags, title_prefix=title_prefix, bookmark_count=item.bookmarkCount, image_response_count=item.imageResponse)
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.printAndLog("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.printAndLog('info', "End Page reached: " + str(end_page))
flag = False
if t.isLastPage:
PixivHelper.printAndLog('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
PixivHelper.printAndLog('info', "Hit page 1000, trying to get workdate for last image id: " + str(last_image_id))
referer = 'https://www.pixiv.net/member_illust.php?mode=medium&illust_id=' + str(last_image_id)
parse_medium_page = PixivBrowserFactory.getBrowser().getPixivPage(referer)
image = PixivImage(iid=last_image_id, page=parse_medium_page, dateFormat=__config__.dateFormat)
_last_date = image.worksDateDateTime.strftime("%Y-%m-%d")
# hit the last page
PixivHelper.printAndLog('info', "Hit page 1000, looping back to page 1 with ecd: " + str(_last_date))
i = 1
end_date = _last_date
flag = True
last_image_id = -1
else:
PixivHelper.printAndLog('info', "No more image in the list.")
flag = False
print 'done'
except KeyboardInterrupt:
raise
except:
print 'Error at process_tags():', sys.exc_info()
__log__.exception('Error at process_tags(): ' + str(sys.exc_info()))
try:
if search_page is not None:
dump_filename = 'Error page for search tags ' + tags + '.html'
PixivHelper.dumpHtml(dump_filename, search_page)
PixivHelper.printAndLog('error', "Dumping html to: " + dump_filename)
except:
PixivHelper.printAndLog('error', 'Cannot dump page for search tags:' + search_tags)
raise
def process_tags_list(mode, filename, page=1, end_page=0, wild_card=True,
oldest_first=False, bookmark_count=None,
start_date=None, end_date=None):
global ERROR_CODE
try:
print "Reading:", filename
l = PixivTags.parseTagsList(filename)
for tag in l:
process_tags(mode, tag, page=page, end_page=end_page, wild_card=wild_card,
use_tags_as_dir=__config__.useTagsAsDir, oldest_first=oldest_first,
bookmark_count=bookmark_count, start_date=start_date, end_date=end_date)
except KeyboardInterrupt:
raise
except Exception as ex:
ERROR_CODE = getattr(ex, 'errorCode', -1)
print 'Error at process_tags_list():', sys.exc_info()
__log__.exception('Error at process_tags_list(): ' + str(sys.exc_info()))
raise
def process_image_bookmark(mode, hide='n', start_page=1, end_page=0, tag=''):
global np_is_valid
global np
try:
print "Importing image bookmarks..."
totalList = list()
image_count = 1
if hide == 'n':
totalList.extend(get_image_bookmark(False, start_page, end_page, tag))
elif hide == 'y':
# public and private image bookmarks
totalList.extend(get_image_bookmark(False, start_page, end_page, tag))
totalList.extend(get_image_bookmark(True, start_page, end_page, tag))
else:
totalList.extend(get_image_bookmark(True, start_page, end_page, tag))
PixivHelper.printAndLog('info', "Found " + str(len(totalList)) + " image(s).")
for item in totalList:
print "Image #" + str(image_count)
process_image(mode, artist=None, image_id=item)
image_count = image_count + 1
print "Done.\n"
except KeyboardInterrupt:
raise
except:
print 'Error at process_image_bookmark():', sys.exc_info()
__log__.exception('Error at process_image_bookmark(): ' + str(sys.exc_info()))
raise
def get_image_bookmark(hide, start_page=1, end_page=0, tag=''):
"""Get user's image bookmark"""
total_list = list()
i = start_page
while True:
if end_page != 0 and i > end_page:
print "Page Limit reached: " + str(end_page)
break
url = 'https://www.pixiv.net/bookmark.php?p=' + str(i)
if hide:
url = url + "&rest=hide"
if tag is not None and len(tag) > 0:
url = url + '&tag=' + PixivHelper.encode_tags(tag)
PixivHelper.printAndLog('info', "Importing user's bookmarked image from page " + str(i))
PixivHelper.printAndLog('info', "Source URL: " + url)
page = __br__.open(url)
parse_page = BeautifulSoup(page.read())
l = PixivBookmark.parseImageBookmark(parse_page)
total_list.extend(l)
if len(l) == 0:
print "No more images."
break
else:
print " found " + str(len(l)) + " images."
i = i + 1
parse_page.decompose()
del parse_page
return total_list