forked from Nandaka/PixivUtil2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PixivUtil2.py
1597 lines (1421 loc) · 63.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 -*-
import sys
import os
import re
import traceback
import logging
import logging.handlers
import gc
import time
import xml.sax.saxutils as saxutils
import datetime
from mechanize import Browser
import mechanize
from BeautifulSoup import BeautifulSoup, Tag
import urllib2
import urllib
import getpass
import socket
import httplib
import cookielib
import PixivConstant
import PixivConfig
import PixivDBManager
import PixivHelper
from PixivModel import PixivArtist, PixivImage, PixivListItem, PixivBookmark, PixivTags, PixivNewIllustBookmark
from PixivException import PixivException
import PixivBrowserFactory
script_path = PixivHelper.module_path()
Yavos = True
npisvalid = False
np = 0
opisvalid = False
op = ''
from optparse import OptionParser
import datetime
import codecs
import subprocess
gc.enable()
##gc.set_debug(gc.DEBUG_LEAK)
__dbManager__ = PixivDBManager.PixivDBManager()
__config__ = PixivConfig.PixivConfig()
__br__ = PixivBrowserFactory.getBrowser(config=__config__)
__blacklistTags = list()
__suppressTags = list()
__log__ = PixivHelper.GetLogger()
## 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('(\d+(_big)?_p\d+)')
### Utilities function ###
def clearall():
all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__") and var != "clearall"]
for var in all:
del globals()[var]
def dumpHtml(filename, html):
try:
dump = file(filename, 'wb')
dump.write(html)
dump.close()
except :
pass
def printAndLog(level, msg):
PixivHelper.safePrint(msg)
if level == 'info':
__log__.info(msg)
elif level == 'error':
__log__.error(msg)
def customRequest(url):
if __config__.useProxy:
proxy = urllib2.ProxyHandler(__config__.proxy)
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
req = urllib2.Request(url)
return req
#-T04------For download file
def downloadImage(url, filename, referer, overwrite, retry, backupOldFile=False):
try:
try:
req = customRequest(url)
if referer != None:
req.add_header('Referer', referer)
else :
req.add_header('Referer', 'http://www.pixiv.net')
print "Using Referer:", str(referer)
filesize = -1
print 'Start downloading...',
startTime = datetime.datetime.now()
res = __br__.open_novisit(req)
try:
filesize = int(res.info()['Content-Length'])
except KeyError:
filesize = -1
print "\tNo file size information!"
except:
raise
if os.path.exists(filename) and os.path.isfile(filename) :
oldSize = os.path.getsize(filename)
if not overwrite and int(filesize) == oldSize :
print "\tFile exist! (Identical Size)"
return 0 #Yavos: added 0 -> updateImage() will be executed
else :
if backupOldFile:
import time
splitName = filename.rsplit(".", 1)
newName = filename + "." + str(int(time.time()))
if len(splitName) == 2:
newName = splitName[0] + "." + str(int(time.time())) + "." + splitName[1]
PixivHelper.safePrint("\t Found file with different filesize, backing up to: " + newName)
__log__.info("Found file with different filesize, backing up to: " + newName)
os.rename(filename, newName)
else:
print "\t Found file with different filesize, removing..."
__log__.info("Found file with different filesize, removing old file (old: " + str(oldSize) + " vs new: " + str(filesize) + ")")
os.remove(filename)
directory = os.path.dirname(filename)
if not os.path.exists(directory):
__log__.info('Creating directory: '+directory)
os.makedirs(directory)
try:
save = file(filename + '.pixiv', 'wb+', 4096)
except IOError:
msg = 'Error at downloadImage(): Cannot save ' + url +' to ' + filename + ' ' + str(sys.exc_info())
PixivHelper.safePrint(msg)
__log__.error(unicode(msg))
filename = os.path.split(url)[1]
filename = filename.split("?")[0]
filename = PixivHelper.sanitizeFilename(filename)
save = file(filename + '.pixiv', 'wb+', 4096)
msg2 = 'File is saved to ' + filename
__log__.info(msg2)
prev = 0
curr = 0
print '{0:22} Bytes'.format(prev),
try:
while 1:
save.write(res.read(PixivConstant.BUFFER_SIZE))
curr = save.tell()
print '\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b',
print '{0:9} of {1:9} Bytes'.format(curr, filesize),
## check if downloaded file is complete
if filesize > 0 and curr == filesize:
totalTime = (datetime.datetime.now() - startTime).total_seconds()
print ' Completed in ' + str(totalTime) + 's (' + PixivHelper.speedInStr(filesize, totalTime) + ')'
break
elif curr == prev: ## no filesize info
totalTime = (datetime.datetime.now() - startTime).total_seconds()
print ' Completed in ' + str(totalTime) + 's (' + PixivHelper.speedInStr(curr, totalTime) + ')'
break
prev = curr
if iv == True or __config__.createDownloadLists == True:
dfile = codecs.open(dfilename, 'a+', encoding='utf-8')
dfile.write(filename + "\n")
dfile.close()
except:
if filesize > 0 and curr < filesize:
printAndLog('error', 'Downloaded file incomplete! {0:9} of {1:9} Bytes'.format(curr, filesize))
printAndLog('error', 'Filename = ' + unicode(filename))
printAndLog('error', 'URL = {0}'.format(url))
raise
finally:
save.close()
if overwrite and os.path.exists(filename):
os.remove(filename)
os.rename(filename + '.pixiv', filename)
del save
del req
del res
except urllib2.HTTPError as httpError:
printAndLog('error', '[downloadImage()] ' + str(httpError) + ' (' + url + ')')
if httpError.code == 404:
return -1
if httpError.code == 502:
return -1
raise
except urllib2.URLError as urlError:
printAndLog('error', '[downloadImage()] ' + str(urlError) + ' (' + url + ')')
raise
except IOError as ioex:
if ioex.errno == 28:
printAndLog('error', ioex.message)
raw_input("Press Enter to retry.");
return -1
raise
except KeyboardInterrupt:
printAndLog('info', 'Aborted by user request => Ctrl-C')
raise
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
__log__.exception('Error at downloadImage(): ' + str(sys.exc_info()) + '(' + url + ')')
raise
except KeyboardInterrupt:
raise
except:
if retry > 0:
repeat = range(1,__config__.retryWait)
for t in repeat:
print t,
time.sleep(1)
print ''
return downloadImage(url, filename, referer, overwrite, retry - 1)
else :
raise
print ' done.'
return 0
def loadCookie(cookieValue):
'''Load cookie to the Browser instance'''
ck = cookielib.Cookie(version=0, name='PHPSESSID', value=cookieValue, port=None, port_specified=False, domain='pixiv.net', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
PixivBrowserFactory.addCookie(ck)
### Pixiv related function ###
def pixivLoginCookie():
'''Log in to Pixiv using saved cookie, return True if success'''
printAndLog('info','logging in with saved cookie')
cookieValue = __config__.cookie
if len(cookieValue) > 0:
printAndLog('info','Trying to log with saved cookie')
loadCookie(cookieValue);
req = customRequest('http://www.pixiv.net/mypage.php')
__br__.open(req)
resUrl = __br__.response().geturl()
if resUrl == 'http://www.pixiv.net/mypage.php' :
print 'done.'
__log__.info('Logged in using cookie')
return True
else :
__log__.info('Failed to login using cookie, returned page: ' + resUrl)
printAndLog('info','Cookie already expired/invalid.')
return False
def pixivLogin(username, password):
'''Log in to Pixiv, return 0 if success'''
try:
printAndLog('info','Log in using form.')
req = customRequest(PixivConstant.PIXIV_URL+PixivConstant.PIXIV_LOGIN_URL)
__br__.open(req)
form = __br__.select_form(nr=PixivConstant.PIXIV_FORM_NUMBER)
__br__['pixiv_id'] = username
__br__['pass'] = password
if __config__.keepSignedIn:
__br__.find_control('skip').items[0].selected = True
response = __br__.submit()
return pixivProcessLogin(response)
except:
print 'Error at pixivLogin():',sys.exc_info()
print 'failed'
__log__.exception('Error at pixivLogin(): ' + str(sys.exc_info()))
raise
def pixivProcessLogin(response):
__log__.info('Logging in, return url: ' + response.geturl())
## failed login will return to either of these page:
## http://www.pixiv.net/login.php
## https://www.secure.pixiv.net/login.php
if response.geturl().find('pixiv.net/login.php') == -1:
print 'done.'
__log__.info('Logged in')
## write back the new cookie value
for cookie in __br__._ua_handlers['_cookies'].cookiejar:
if cookie.name == 'PHPSESSID':
print 'new cookie value:', cookie.value
__config__.cookie = cookie.value
__config__.writeConfig()
break
return True
else :
errors = parseLoginError(response)
if len(errors)>0:
for error in errors:
printAndLog('error','Server Reply: ' + error.string)
else:
printAndLog('info','Wrong username or password.')
return False
def pixivLoginSSL(username, password):
try:
printAndLog('info','Log in using secure form.')
req = customRequest(PixivConstant.PIXIV_URL_SSL)
__br__.open(req)
form = __br__.select_form(nr=PixivConstant.PIXIV_FORM_NUMBER_SSL)
__br__['pixiv_id'] = username
__br__['pass'] = password
if __config__.keepSignedIn:
__br__.find_control('skip').items[0].selected = True
response = __br__.submit()
return pixivProcessLogin(response)
except:
print 'Error at pixivLoginSSL():',sys.exc_info()
__log__.exception('Error at pixivLoginSSL(): ' + str(sys.exc_info()))
raise
def parseLoginError(res):
page = BeautifulSoup(res.read())
r = page.findAll('span', attrs={'class':'error'})
return r
def processList(mode):
global args
result = None
try:
## Getting the list
if __config__.processFromDb :
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 :
printAndLog('info','Processing from list file.')
listFilename = __config__.downloadListDirectory + os.sep + 'list.txt'
if op == '4' and len(args) > 0:
testListFilename = __config__.downloadListDirectory + os.sep + args[0]
if os.path.exists(testListFilename) :
listFilename = testListFilename
result = PixivListItem.parseList(listFilename, __config__.rootDirectory)
printAndLog('info','List file used: ' + listFilename)
print "Found "+str(len(result))+" items."
## iterating the list
for item in result:
retryCount = 0
while True:
try:
processMember(mode, item.memberId, item.path)
break
except KeyboardInterrupt:
raise
except:
if retryCount > __config__.retry:
printAndLog('error','Giving up member_id: '+str(item.memberId))
break
retryCount = retryCount + 1
print 'Something wrong, retrying after 2 second (', retryCount, ')'
time.sleep(2)
__br__.clear_history()
print 'done.'
except KeyboardInterrupt:
raise
except:
print 'Error at processList():',sys.exc_info()
print 'Failed'
__log__.exception('Error at processList(): ' + str(sys.exc_info()))
raise
def processMember(mode, member_id, userDir='', page=1, endPage=0, bookmark=False): #Yavos added dir-argument which will be initialized as '' when not given
printAndLog('info','Processing Member Id: ' + str(member_id))
if page != 1:
printAndLog('info', 'Start Page: ' + str(page))
if endPage != 0:
printAndLog('info', 'End Page: ' + str(endPage))
if __config__.numberOfPage != 0:
printAndLog('info', 'Number of page setting will be ignored')
elif np != 0:
printAndLog('info', 'End Page from command line: ' + str(np))
elif __config__.numberOfPage != 0:
printAndLog('info', 'End Page from config: ' + str(__config__.numberOfPage))
__config__.loadConfig()
try:
noOfImages = 1
avatarDownloaded = False
flag = True
while flag:
print 'Page ',page
setTitle("MemberId: " + str(member_id) + " Page: " + str(page))
## Try to get the member page
while True:
try:
if bookmark:
memberUrl = 'http://www.pixiv.net/bookmark.php?id='+str(member_id)+'&p='+str(page)
else:
memberUrl = 'http://www.pixiv.net/member_illust.php?id='+str(member_id)+'&p='+str(page)
if __config__.r18mode:
memberUrl = memberUrl + '&tag=R-18'
printAndLog('info', 'R-18 Mode only.')
printAndLog('info', 'Member Url: ' + memberUrl)
listPage = __br__.open(memberUrl)
artist = PixivArtist(mid=member_id, page=BeautifulSoup(listPage.read()))
break
except PixivException as ex:
printAndLog('info', 'Member ID (' + str(member_id) + '): ' + str(ex))
if ex.errorCode == PixivException.NO_IMAGES:
pass
else:
dumpHtml("Dump for " + str(member_id) + " Error Code " + str(ex.errorCode) + ".html", listPage.get_data())
if ex.errorCode == PixivException.USER_ID_NOT_EXISTS or ex.errorCode == PixivException.USER_ID_SUSPENDED:
__dbManager__.setIsDeletedFlagForMemberId(int(member_id))
printAndLog('info', 'Set IsDeleted for MemberId: ' + str(member_id) + ' not exist.')
#__dbManager__.deleteMemberByMemberId(member_id)
#printAndLog('info', 'Deleting MemberId: ' + str(member_id) + ' not exist.')
if ex.errorCode == PixivException.OTHER_MEMBER_ERROR:
PixivHelper.safePrint(ex.message)
raw_input('New Error Message, please inform the developer. Press enter to continue.')
return
except AttributeError as aex:
# Possible layout changes, try to dump the file below
raise
except Exception as ue:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
printAndLog('error', 'Error at processing Artist Info: ' + str(sys.exc_info()))
__log__.exception('Error at processing Artist Info: '+ str(member_id))
repeat = range(1,__config__.retryWait)
for t in repeat:
print t,
time.sleep(1)
print ''
PixivHelper.safePrint('Member Name : ' + artist.artistName)
print 'Member Avatar:', artist.artistAvatar
print 'Member Token :', artist.artistToken
if artist.artistAvatar.find('no_profile') == -1 and avatarDownloaded == False and __config__.downloadAvatar :
## Download avatar as folder.jpg
filenameFormat = __config__.filenameFormat
if userDir == '':
targetDir = __config__.rootDirectory
else:
targetDir = userDir
avatarFilename = PixivHelper.CreateAvatarFilename(filenameFormat, __config__.tagsSeparator, __config__.tagsLimit, artist, targetDir)
result = downloadImage(artist.artistAvatar, avatarFilename, listPage.geturl(), __config__.overwrite, __config__.retry, __config__.backupOldFile)
avatarDownloaded = True
__dbManager__.updateMemberName(member_id, artist.artistName)
updatedLimitCount = 0
if not artist.haveImages:
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(noOfImages)
if mode == PixivConstant.PIXIVUTIL_MODE_UPDATE_ONLY:
r = __dbManager__.selectImageByMemberIdAndImageId(member_id, image_id)
if r != None and not(__config__.alwaysCheckFileSize):
print 'Already downloaded:', image_id
updatedLimitCount = updatedLimitCount + 1
if updatedLimitCount > __config__.checkUpdatedLimit and __config__.checkUpdatedLimit != 0 :
print 'Skipping member:', member_id
__dbManager__.updateLastDownloadedImage(member_id, image_id)
del listPage
__br__.clear_history()
return
gc.collect()
continue
retryCount = 0
while True :
try:
result = processImage(mode, artist, image_id, userDir, bookmark) #Yavos added dir-argument to pass
__dbManager__.insertImage(member_id, image_id)
break
except KeyboardInterrupt:
result = PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT
break
except:
if retryCount > __config__.retry:
printAndLog('error', "Giving up image_id: "+str(image_id))
return
retryCount = retryCount + 1
print "Stuff happened, trying again after 2 second (", retryCount,")"
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
__log__.exception('Error at processMember(): ' + str(sys.exc_info()) + ' Member Id: ' + str(member_id))
time.sleep(2)
noOfImages = noOfImages + 1
if result == PixivConstant.PIXIVUTIL_KEYBOARD_INTERRUPT:
choice = raw_input("Keyboard Interrupt detected, continue to next image (Y/N)")
if choice.upper() == 'N':
printAndLog("info", "Member: " + str(member_id) + ", processing aborted")
flag = False
break
else :
continue
## return code from process image
if result == PixivConstant.PIXIVUTIL_SKIP_OLDER:
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 endPage > 0 and page > endPage:
print "Page limit reached (from endPage limit =" + str(endPage) + ")"
flag = False
else:
if npisvalid == True: #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 listPage
__br__.clear_history()
gc.collect()
__dbManager__.updateLastDownloadedImage(member_id, image_id)
print 'Done.\n'
__log__.info('Member_id: ' + str(member_id) + ' complete, last image_id: ' + str(image_id))
except KeyboardInterrupt:
raise
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
printAndLog('error', 'Error at processMember(): ' + str(sys.exc_info()))
__log__.exception('Error at processMember(): '+ str(member_id))
try:
if listPage != None :
dumpFilename = 'Error page for member ' + str(member_id) + '.html'
dumpHtml(dumpFilename, listPage.get_data())
printAndLog('error', "Dumping html to: " + dumpFilename)
except:
printAndLog('error', 'Cannot dump page for member_id:'+str(member_id))
raise
def processImage(mode, artist=None, image_id=None, userDir='', bookmark=False, searchTags=''):
#Yavos added dir-argument which will be initialized as '' when not given
parseBigImage = None
mediumPage = None
viewPage = None
image = None
try:
filename = 'N/A'
print 'Processing Image Id:', image_id
## check if already downloaded. images won't be downloaded twice - needed in processImage to catch any download
r = __dbManager__.selectImageByImageId(image_id)
if r != None and not __config__.alwaysCheckFileSize:
if mode == PixivConstant.PIXIVUTIL_MODE_UPDATE_ONLY:
print 'Already downloaded:', image_id
gc.collect()
return
retryCount = 0
while 1:
try :
mediumPage = __br__.open('http://www.pixiv.net/member_illust.php?mode=medium&illust_id='+str(image_id))
parseMediumPage = BeautifulSoup(mediumPage.read())
image = PixivImage(iid=image_id, page=parseMediumPage, parent=artist, fromBookmark=bookmark)
setTitle('MemberId: ' + str(image.artist.artistId) + ' ImageId: ' + str(image.imageId))
parseMediumPage.decompose()
del parseMediumPage
break
except PixivException as ex:
if ex.errorCode == PixivException.UNKNOWN_IMAGE_ERROR:
PixivHelper.safePrint(ex.message)
raw_input('New Error Message, please inform the developer. Press enter to continue.')
else:
printAndLog('info', 'Image ID (' + str(image_id) +'): ' + str(ex))
return
except urllib2.URLError as ue:
print ue
repeat = range(1,__config__.retryWait)
for t in repeat:
print t,
time.sleep(1)
print ''
++retryCount
if retryCount > __config__.retry:
printAndLog('error', 'Giving up image_id (medium): ' + str(image_id))
if mediumPage != None:
dumpFilename = 'Error medium page for image ' + str(image_id) + '.html'
dumpHtml(dumpFilename , mediumPage.get_data())
printAndLog('error', 'Dumping html to: ' + dumpFilename);
return
downloadImageFlag = True
if __config__.dateDiff > 0:
if image.worksDateDateTime != datetime.datetime.fromordinal(1):
if image.worksDateDateTime < datetime.datetime.today() - datetime.timedelta(__config__.dateDiff):
printAndLog('info', 'Skipping image_id: ' + str(image_id) + ' because contains older than: ' + str(__config__.dateDiff) + ' day(s).');
downloadImageFlag = False
result = PixivConstant.PIXIVUTIL_SKIP_OLDER
if __config__.useBlacklistTags:
for item in __blacklistTags:
if item in image.imageTags:
printAndLog('info', 'Skipping image_id: ' + str(image_id) + ' because contains blacklisted tags: ' + item);
downloadImageFlag = False
result = PixivConstant.PIXIVUTIL_SKIP_BLACKLIST
break
if downloadImageFlag:
PixivHelper.safePrint("Title: " + image.imageTitle)
PixivHelper.safePrint("Tags : " + ', '.join(image.imageTags))
PixivHelper.safePrint("Date : " + str(image.worksDateDateTime))
print "Mode :", image.imageMode
if __config__.useSuppressTags:
for item in __suppressTags:
if item in image.imageTags:
image.imageTags.remove(item)
errorCount = 0
while True:
try :
bigUrl = 'http://www.pixiv.net/member_illust.php?mode='+image.imageMode+'&illust_id='+str(image_id)
viewPage = __br__.follow_link(url_regex='mode='+image.imageMode+'&illust_id='+str(image_id))
parseBigImage = BeautifulSoup(viewPage.read())
if parseBigImage != None:
image.ParseImages(page=parseBigImage)
parseBigImage.decompose()
del parseBigImage
break
except PixivException as ex:
printAndLog('info', 'Image ID (' + str(image_id) +'): ' + str(ex))
return
except urllib2.URLError as ue:
if errorCount > __config__.retry:
printAndLog('error', 'Giving up image_id: '+str(image_id))
return
errorCount = errorCount + 1
print ue
repeat = range(1,__config__.retryWait)
for t in repeat:
print t,
time.sleep(1)
print ''
if image.imageMode == 'manga':
print "Page Count :", image.imageCount
result = PixivConstant.PIXIVUTIL_OK
skipOne = False
for img in image.imageUrls:
if skipOne:
skipOne = False
continue
print 'Image URL :', img
url = os.path.basename(img)
splittedUrl = url.split('.')
if splittedUrl[0].startswith(str(image_id)):
#Yavos: filename will be added here if given in list
filenameFormat = __config__.filenameFormat
if image.imageMode == 'manga':
filenameFormat = __config__.filenameMangaFormat
if userDir == '': #Yavos: use config-options
targetDir = __config__.rootDirectory
else: #Yavos: use filename from list
targetDir = userDir
filename = PixivHelper.makeFilename(filenameFormat, image, tagsSeparator=__config__.tagsSeparator, tagsLimit=__config__.tagsLimit, fileUrl=url, bookmark=bookmark, searchTags=searchTags)
filename = PixivHelper.sanitizeFilename(filename, targetDir)
if image.imageMode == 'manga' and __config__.createMangaDir :
mangaPage = __re_manga_page.findall(filename)
if len(mangaPage) > 0:
splittedFilename = filename.split(mangaPage[0][0],1)
splittedMangaPage = mangaPage[0][0].split("_p",1)
filename = splittedFilename[0] + splittedMangaPage[0] + os.sep + "_p" + splittedMangaPage[1] + splittedFilename[1]
PixivHelper.safePrint('Filename : ' + filename)
result = PixivConstant.PIXIVUTIL_NOT_OK
try:
overwrite = False
if mode == PixivConstant.PIXIVUTIL_MODE_OVERWRITE:
overwrite = True
result = downloadImage(img, filename, viewPage.geturl(), overwrite, __config__.retry, __config__.backupOldFile)
if result == PixivConstant.PIXIVUTIL_NOT_OK and image.imageMode == 'manga' and img.find('_big') > -1:
print 'No big manga image available, try the small one'
elif result == PixivConstant.PIXIVUTIL_OK and image.imageMode == 'manga' and img.find('_big') > -1:
skipOne = True
elif result == PixivConstant.PIXIVUTIL_NOT_OK:
printAndLog('error', 'Image url not found: '+str(image.imageId))
except urllib2.URLError as ue:
printAndLog('error', 'Giving up url: '+str(img))
__log__.exception('Error when downloadImage(): ' +str(img))
print ''
if __config__.writeImageInfo:
image.WriteInfo(filename + ".txt")
## Only save to db if all images is downloaded completely
if result == PixivConstant.PIXIVUTIL_OK :
try:
__dbManager__.insertImage(image.artist.artistId, image.imageId)
except:
pass
__dbManager__.updateImage(image.imageId, image.imageTitle, filename)
if mediumPage != None:
del mediumPage
if viewPage != None:
del viewPage
if image != None:
del image
gc.collect()
##clearall()
print '\n'
return result
except KeyboardInterrupt:
raise
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
printAndLog('error', 'Error at processImage(): ' + str(sys.exc_info()))
__log__.exception('Error at processImage(): ' +str(image_id))
try:
if viewPage != None:
dumpFilename = 'Error Big Page for image ' + str(image_id) + '.html'
dumpHtml(dumpFilename , viewPage.get_data())
printAndLog('error', 'Dumping html to: ' + dumpFilename);
except:
printAndLog('error', 'Cannot dump big page for image_id: '+str(image_id))
try:
if mediumPage != None:
dumpFilename = 'Error Medium Page for image ' + str(image_id) + '.html'
dumpHtml(dumpFilename , mediumPage.get_data())
printAndLog('error', 'Dumping html to: ' + dumpFilename);
except:
printAndLog('error', 'Cannot medium dump page for image_id: '+str(image_id))
raise
def processTags(mode, tags, page=1, endPage=0, wildCard=True, titleCaption=False, startDate=None, endDate=None, useTagsAsDir=False, member_id=None, bookmarkCount=None):
try:
__config__.loadConfig() ## Reset the config for root directory
try:
if tags.startswith("%") :
searchTags = PixivHelper.toUnicode(urllib.unquote_plus(tags))
else:
searchTags = PixivHelper.toUnicode(tags)
except UnicodeDecodeError as ex:
## From command prompt
searchTags = tags.decode(sys.stdout.encoding).encode("utf8")
searchTags = PixivHelper.toUnicode(searchTags)
if useTagsAsDir:
print "Save to each directory using query tags."
__config__.rootDirectory += os.sep + PixivHelper.sanitizeFilename(searchTags)
if not tags.startswith("%") :
try:
## Encode the tags
tags = tags.encode('utf-8')
tags = urllib.quote_plus(tags)
except UnicodeDecodeError as ex:
try:
## from command prompt
tags = urllib.quote_plus(tags.decode(sys.stdout.encoding).encode("utf8"))
except UnicodeDecodeError as ex:
printAndLog('error', 'Cannot decode the tags, you can use URL Encoder (http://meyerweb.com/eric/tools/dencoder/) and paste the encoded tag.')
__log__.exception('decodeTags()')
i = page
images = 1
dateParam = ""
if startDate != None:
dateParam = dateParam + "&scd=" + startDate
if endDate != None:
dateParam = dateParam + "&ecd=" + endDate
printAndLog('info', 'Searching for: ('+ searchTags + ") " + tags + dateParam)
flag = True
while flag:
if not member_id == None:
url = 'http://www.pixiv.net/member_illust.php?id=' + str(member_id) + '&tag=' + tags + '&p='+str(i)
else :
if titleCaption:
url = 'http://www.pixiv.net/search.php?s_mode=s_tc&p='+str(i)+'&word='+tags + dateParam
else:
if wildCard:
url = 'http://www.pixiv.net/search.php?s_mode=s_tag&p='+str(i)+'&word='+tags + dateParam
print "Using Wildcard (search.php)"
else:
url = 'http://www.pixiv.net/search.php?s_mode=s_tag_full&word='+tags+'&p='+str(i) + dateParam
if __config__.r18mode:
url = url + '&r18=1'
printAndLog('info', 'Looping... for '+ url)
searchPage = __br__.open(url)
parseSearchPage = BeautifulSoup(searchPage.read())
t = PixivTags()
l = list()
if not member_id == None:
l = t.parseMemberTags(parseSearchPage)
else :
l = t.parseTags(parseSearchPage)
if len(l) == 0 :
print 'No more images'
flag = False
else:
#for image_id in l:
for item in t.itemList:
print 'Image #' + str(images)
print 'Image Id:', str(item.imageId)
print 'Bookmark Count:', str(item.bookmarkCount)
if bookmarkCount != None and bookmarkCount > item.bookmarkCount:
printAndLog('info', 'Skipping imageId='+str(item.imageId)+' because less than bookmark count limit ('+ str(bookmarkCount) + ' > ' + str(item.bookmarkCount) + ')')
continue
result = 0
while True:
try:
processImage(mode, None, item.imageId, searchTags=searchTags)
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':
printAndLog("info", "Tags: " + tags + ", processing aborted")
flag = False
break
else :
continue
__br__.clear_history()
i = i + 1
parseSearchPage.decompose()
del parseSearchPage
del searchPage
if endPage != 0 and endPage < i:
print 'End Page reached.'
flag = False
if t.isLastPage:
print 'Last page'
flag = False
print 'done'
except KeyboardInterrupt:
raise
except:
print 'Error at processTags():',sys.exc_info()
__log__.exception('Error at processTags(): ' + str(sys.exc_info()))
raise
def processTagsList(mode, filename, page=1, endPage=0):
try:
print "Reading:",filename
l = PixivTags.parseTagsList(filename)
for tag in l:
processTags(mode, tag, page=page, endPage=endPage, useTagsAsDir=__config__.useTagsAsDir)
except KeyboardInterrupt:
raise
except:
print 'Error at processTagsList():',sys.exc_info()
__log__.exception('Error at processTagsList(): ' + str(sys.exc_info()))
raise
def processImageBookmark(mode, hide='n', startPage = 1, endPage = 0):
try:
print "Importing image bookmarks..."
#totalList = list()
i = startPage
imageCount = 1
while True:
if endPage != 0 and i > endPage:
print "Page Limit reached: " + str(endPage)
break
print "Importing user's bookmarked image from page", str(i),
url = 'http://www.pixiv.net/bookmark.php?p='+str(i)
if hide == 'y':
url = url + "&rest=hide"
page = __br__.open(url)
parsePage = BeautifulSoup(page.read())
l = PixivBookmark.parseImageBookmark(parsePage)
if len(l) == 0:
print "No more images."
break
else :
print " found " + str(len(l)) + " images."
for item in l:
print "Image #" + str(imageCount)
processImage(mode, artist=None, image_id=item)
imageCount = imageCount + 1
i = i + 1
parsePage.decompose()
del parsePage
if npisvalid == True: #Yavos: overwrite config-data
if i > np and np != 0:
break
elif i > __config__.numberOfPage and __config__.numberOfPage != 0 :
break
print "Done.\n"
except KeyboardInterrupt:
raise
except :
print 'Error at processImageBookmark():',sys.exc_info()
__log__.exception('Error at processImageBookmark(): ' + str(sys.exc_info()))
raise
def getBookmarks(hide, startPage = 1, endPage = 0):
'''Get user/artists bookmark'''
totalList = list()
i = startPage
while True:
if endPage != 0 and i > endPage:
print 'Limit reached'
break
print 'Exporting page', str(i),
url = 'http://www.pixiv.net/bookmark.php?type=user&p='+str(i)
if hide:
url = url + "&rest=hide"
page = __br__.open(url)
parsePage = BeautifulSoup(page.read())
l = PixivBookmark.parseBookmark(parsePage)
if len(l) == 0:
print 'No more data'
break
totalList.extend(l)
i = i + 1
print str(len(l)), 'items'
return totalList
def processBookmark(mode, hide='n', startPage = 1, endPage = 0):
try:
totalList = list()
if hide != 'o':
print "Importing Bookmarks..."
totalList.extend(getBookmarks(False, startPage, endPage))
if hide != 'n':
print "Importing Private Bookmarks..."
totalList.extend(getBookmarks(True, startPage, endPage))
print "Result: ", str(len(totalList)), "items."
for item in totalList:
processMember(mode, item.memberId, item.path)
except KeyboardInterrupt:
raise
except :
print 'Error at processBookmark():',sys.exc_info()
__log__.exception('Error at processBookmark(): ' + str(sys.exc_info()))
raise
def exportBookmark(filename, hide='n', startPage = 1, endPage = 0):
try:
totalList = list()
if hide != 'o':
print "Importing Bookmarks..."
totalList.extend(getBookmarks(False, startPage, endPage))
if hide != 'n':
print "Importing Private Bookmarks..."
totalList.extend(getBookmarks(True, startPage, endPage))