forked from Nandaka/PixivUtil2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPixivUtil2.py
More file actions
executable file
·1580 lines (1359 loc) · 60.2 KB
/
PixivUtil2.py
File metadata and controls
executable file
·1580 lines (1359 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# flake8: noqa:E501,E128,E127
import codecs
import datetime
import gc
import getpass
import os
import re
import subprocess
import sys
import time
import traceback
from optparse import OptionParser
from bs4 import BeautifulSoup
import colorama
from colorama import Fore, Back, Style
import PixivArtistHandler
import PixivBatchHandler
import PixivBrowserFactory
import PixivConfig
import PixivConstant
import PixivDownloadHandler
import PixivFanboxHandler
import PixivHelper
import PixivImageHandler
import PixivModelFanbox
import PixivSketchHandler
import PixivTagsHandler
from PixivBookmark import PixivBookmark, PixivNewIllustBookmark
from PixivDBManager import PixivDBManager
from PixivException import PixivException
from PixivGroup import PixivGroup
from PixivListItem import PixivListItem
from PixivTags import PixivTags
colorama.init()
DEBUG_SKIP_PROCESS_IMAGE = False
DEBUG_SKIP_DOWNLOAD_IMAGE = False
if os.name == 'nt':
# patch getpass.getpass() for windows to show '*'
def win_getpass_with_mask(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return getpass.fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putch(c.encode())
pw = ""
while 1:
c = msvcrt.getch().decode()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
print("\b \b", end="")
else:
pw = pw + c
print("*", end="")
msvcrt.putch('\r'.encode())
msvcrt.putch('\n'.encode())
return pw
getpass.getpass = win_getpass_with_mask
script_path = PixivHelper.module_path()
np_is_valid = False
np = 0
op = ''
ERROR_CODE = 0
UTF8_FS = None
__config__ = PixivConfig.PixivConfig()
configfile = "config.ini"
__dbManager__ = None
__br__ = None
__blacklistTags = list()
__suppressTags = list()
__log__ = PixivHelper.get_logger()
__errorList = list()
__blacklistMembers = list()
__blacklistTitles = list()
__valid_options = ()
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+)')
# -T04------For download file
def download_image(url, filename, referer, overwrite, max_retry, backup_old_file=False, image=None, page=None):
return PixivDownloadHandler.download_image(sys.modules[__name__],
url,
filename,
referer,
overwrite,
max_retry,
backup_old_file=backup_old_file,
image=image,
page=page)
# 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
PixivHelper.print_and_log('info', f"Found {len(result)} items.")
current_member = 1
for item in result:
retry_count = 0
while True:
try:
prefix = "[{0} of {1}] ".format(current_member, len(result))
process_member(item.memberId, item.path, tags=tags, title_prefix=prefix)
current_member = current_member + 1
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 Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
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, title_prefix=""):
PixivArtistHandler.process_member(sys.modules[__name__],
__config__,
member_id,
user_dir=user_dir,
page=page,
end_page=end_page,
bookmark=bookmark,
tags=tags,
title_prefix=title_prefix)
def process_image(artist=None, image_id=None, user_dir='', bookmark=False, search_tags='', title_prefix="", bookmark_count=-1, image_response_count=-1):
return PixivImageHandler.process_image(sys.modules[__name__],
__config__,
artist=artist,
image_id=image_id,
user_dir=user_dir,
bookmark=bookmark,
search_tags=search_tags,
title_prefix=title_prefix,
bookmark_count=bookmark_count,
image_response_count=image_response_count)
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, type_mode=None):
PixivTagsHandler.process_tags(sys.modules[__name__],
tags,
page=page,
end_page=end_page,
wild_card=wild_card,
title_caption=title_caption,
start_date=start_date,
end_date=end_date,
use_tags_as_dir=use_tags_as_dir,
member_id=member_id,
bookmark_count=bookmark_count,
oldest_first=oldest_first,
type_mode=type_mode)
def process_tags_list(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)
tags = PixivTags.parseTagsList(filename)
for tag in tags:
process_tags(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 Exception as ex:
if isinstance(ex, KeyboardInterrupt):
raise
ERROR_CODE = getattr(ex, 'errorCode', -1)
PixivHelper.print_and_log('error', 'Error at process_tags_list(): {0}'.format(sys.exc_info()))
raise
def process_image_bookmark(hide='n', start_page=1, end_page=0, tag=None, sorting=None):
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, sorting))
elif hide == 'y':
# public and private image bookmarks
totalList.extend(get_image_bookmark(False, start_page, end_page, tag, sorting))
totalList.extend(get_image_bookmark(True, start_page, end_page, tag, sorting))
else:
totalList.extend(get_image_bookmark(True, start_page, end_page, tag, sorting))
PixivHelper.print_and_log('info', "Found " + str(len(totalList)) + " image(s).")
for item in totalList:
print("Image #" + str(image_count))
result = process_image(artist=None, image_id=item, search_tags=tag)
image_count = image_count + 1
PixivHelper.wait(result, __config__)
print("Done.\n")
except KeyboardInterrupt:
raise
except BaseException:
PixivHelper.print_and_log('error', 'Error at process_image_bookmark(): {0}'.format(sys.exc_info()))
raise
def get_image_bookmark(hide, start_page=1, end_page=0, tag=None, sorting=None):
"""Get user's image bookmark"""
total_list = list()
i = start_page
offset = 0
limit = 48
member_id = __br__._myId
while True:
if end_page != 0 and i > end_page:
print("Page Limit reached: " + str(end_page))
break
# https://www.pixiv.net/ajax/user/189816/illusts/bookmarks?tag=&offset=0&limit=48&rest=show
show = "show"
if hide:
show = "hide"
# # Implement #468 default is desc, only for your own bookmark.
# not available in current api
# if sorting in ('asc', 'date_d', 'date'):
# url = url + "&order=" + sorting
if tag is not None and len(tag) > 0:
tag = PixivHelper.encode_tags(tag)
offset = limit * (i - 1)
url = f"https://www.pixiv.net/ajax/user/{member_id}/illusts/bookmarks?tag={tag}&offset={offset}&limit={limit}&rest={show}"
PixivHelper.print_and_log('info', f"Importing user's bookmarked image from page {i}")
PixivHelper.print_and_log('info', f"Source URL: {url}")
page = __br__.open(url)
page_str = page.read().decode('utf8')
page.close()
bookmarks = PixivBookmark.parseImageBookmark(page_str)
total_list.extend(bookmarks)
if len(bookmarks) == 0:
print("No more images.")
break
else:
print(" found " + str(len(bookmarks)) + " images.")
i = i + 1
# Issue#569
PixivHelper.wait(config=__config__)
return total_list
def get_bookmarks(hide, start_page=1, end_page=0, member_id=None):
"""Get User's bookmarked artists """
total_list = list()
i = start_page
limit = 24
offset = 0
is_json = False
while True:
if end_page != 0 and i > end_page:
print('Limit reached')
break
PixivHelper.print_and_log('info', f'Exporting page {i}')
if member_id:
is_json = True
offset = limit * (i - 1)
url = f'https://www.pixiv.net/ajax/user/{member_id}/following?offset={offset}&limit={limit}'
else:
url = f'https://www.pixiv.net/bookmark.php?type=user&p={i}'
if hide:
url = url + "&rest=hide"
else:
url = url + "&rest=show"
PixivHelper.print_and_log('info', f"Source URL: {url}")
page = __br__.open_with_retry(url)
page_str = page.read().decode('utf8')
page.close()
bookmarks = PixivBookmark.parseBookmark(page_str,
root_directory=__config__.rootDirectory,
db_path=__config__.dbPath,
locale=__br__._locale,
is_json=is_json)
if len(bookmarks) == 0:
print('No more data')
break
total_list.extend(bookmarks)
i = i + 1
print(str(len(bookmarks)), 'items')
PixivHelper.wait(config=__config__)
return total_list
def process_bookmark(hide='n', start_page=1, end_page=0):
try:
total_list = list()
print(f"My Member Id = {__br__._myId}")
if hide != 'o':
print("Importing Bookmarks...")
total_list.extend(get_bookmarks(False, start_page, end_page, __br__._myId))
if hide != 'n':
print("Importing Private Bookmarks...")
total_list.extend(get_bookmarks(True, start_page, end_page, __br__._myId))
print(f"Result: {str(len(total_list))} items.")
i = 0
current_member = 1
for item in total_list:
print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list))))
i += 1
prefix = "[{0} of {1}]".format(current_member, len(total_list))
process_member(item.memberId, item.path, title_prefix=prefix)
current_member = current_member + 1
if len(total_list) > 0:
print("%d/%d\t%f %%" % (i, len(total_list), 100.0 * i / float(len(total_list))))
else:
print("Cannot find any followed member.")
except KeyboardInterrupt:
raise
except BaseException:
PixivHelper.print_and_log('error', 'Error at process_bookmark(): {0}'.format(sys.exc_info()))
raise
def export_bookmark(filename, hide='n', start_page=1, end_page=0, member_id=None):
try:
total_list = list()
if hide != 'o':
print("Importing Bookmarks...")
total_list.extend(get_bookmarks(False, start_page, end_page, member_id))
if hide != 'n':
print("Importing Private Bookmarks...")
total_list.extend(get_bookmarks(True, start_page, end_page, member_id))
print("Result: ", str(len(total_list)), "items.")
PixivBookmark.exportList(total_list, filename)
except KeyboardInterrupt:
raise
except BaseException:
PixivHelper.print_and_log('error', 'Error at export_bookmark(): {0}'.format(sys.exc_info()))
raise
def process_new_illust_from_bookmark(page_num=1, end_page_num=0):
try:
print("Processing New Illust from bookmark")
i = page_num
image_count = 1
flag = True
while flag:
print("Page #" + str(i))
url = 'https://www.pixiv.net/bookmark_new_illust.php?p=' + str(i)
if __config__.r18mode:
url = 'https://www.pixiv.net/bookmark_new_illust_r18.php?p=' + str(i)
PixivHelper.print_and_log('info', "Source URL: " + url)
page = __br__.open(url)
parsed_page = BeautifulSoup(page.read().decode("utf-8"), features="html5lib")
pb = PixivNewIllustBookmark(parsed_page)
if not pb.haveImages:
print("No images!")
break
for image_id in pb.imageList:
print("Image #" + str(image_count))
result = process_image(artist=None, image_id=int(image_id))
image_count = image_count + 1
if result == PixivConstant.PIXIVUTIL_SKIP_OLDER:
flag = False
break
PixivHelper.wait(result, __config__)
i = i + 1
page.close()
parsed_page.decompose()
del parsed_page
# Non premium is only limited to 100 page
# Premium user might be limited to 5000, refer to issue #112
if (end_page_num != 0 and i > end_page_num) or i > 5000 or pb.isLastPage:
print("Limit or last page reached.")
flag = False
print("Done.")
except KeyboardInterrupt:
raise
except BaseException:
PixivHelper.print_and_log('error', 'Error at process_new_illust_from_bookmark(): {0}'.format(sys.exc_info()))
raise
def process_from_group(group_id, limit=0, process_external=True):
try:
print("Download by Group Id")
if limit != 0:
print("Limit: {0}".format(limit))
if process_external:
print("Include External Image: {0}".format(process_external))
max_id = 0
image_count = 0
flag = True
while flag:
url = "https://www.pixiv.net/group/images.php?format=json&max_id={0}&id={1}".format(max_id, group_id)
PixivHelper.print_and_log('info', "Getting images from: {0}".format(url))
json_response = __br__.open(url)
group_data = PixivGroup(json_response)
json_response.close()
max_id = group_data.maxId
if group_data.imageList is not None and len(group_data.imageList) > 0:
for image in group_data.imageList:
if image_count > limit and limit != 0:
flag = False
break
print("Image #{0}".format(image_count))
print("ImageId: {0}".format(image))
result = process_image(image_id=image)
image_count = image_count + 1
PixivHelper.wait(result, __config__)
if process_external and group_data.externalImageList is not None and len(group_data.externalImageList) > 0:
for image_data in group_data.externalImageList:
if image_count > limit and limit != 0:
flag = False
break
print("Image #{0}".format(image_count))
print("Member Id : {0}".format(image_data.artist.artistId))
PixivHelper.safePrint("Member Name : " + image_data.artist.artistName)
print("Member Token : {0}".format(image_data.artist.artistToken))
print("Image Url : {0}".format(image_data.imageUrls[0]))
filename = PixivHelper.make_filename(__config__.filenameFormat,
imageInfo=image_data,
tagsSeparator=__config__.tagsSeparator,
tagsLimit=__config__.tagsLimit,
fileUrl=image_data.imageUrls[0],
useTranslatedTag=__config__.useTranslatedTag,
tagTranslationLocale=__config__.tagTranslationLocale)
filename = PixivHelper.sanitize_filename(filename, __config__.rootDirectory)
PixivHelper.safePrint("Filename : " + filename)
(result, filename) = download_image(image_data.imageUrls[0], filename, url, __config__.overwrite, __config__.retry, __config__.backupOldFile)
PixivHelper.get_logger().debug("Download %s result: %s", filename, result)
if __config__.setLastModified and filename is not None and os.path.isfile(filename):
ts = time.mktime(image_data.worksDateDateTime.timetuple())
os.utime(filename, (ts, ts))
image_count = image_count + 1
if (group_data.imageList is None or len(group_data.imageList) == 0) and \
(group_data.externalImageList is None or len(group_data.externalImageList) == 0):
flag = False
print("")
except BaseException:
PixivHelper.print_and_log('error', 'Error at process_from_group(): {0}'.format(sys.exc_info()))
raise
def header():
print(Fore.YELLOW + Back.BLACK + Style.BRIGHT + f"PixivDownloader2 version {PixivConstant.PIXIVUTIL_VERSION}" + Style.RESET_ALL)
print(Fore.CYAN + Back.BLACK + Style.BRIGHT + PixivConstant.PIXIVUTIL_LINK + Style.RESET_ALL)
print(Fore.YELLOW + Back.BLACK + Style.BRIGHT + f"Donate at {Fore.CYAN}{Style.BRIGHT}{PixivConstant.PIXIVUTIL_DONATE}" + Style.RESET_ALL)
def get_start_and_end_number_from_args(args, offset=0, start_only=False):
global np_is_valid
global np
page_num = 1
if len(args) > 0 + offset:
try:
page_num = int(args[0 + offset])
print("Start Page =", str(page_num))
except BaseException:
print("Invalid page number:", args[0 + offset])
raise
end_page_num = 0
if np_is_valid:
end_page_num = np
else:
end_page_num = __config__.numberOfPage
if not start_only:
if len(args) > 1 + offset:
try:
end_page_num = int(args[1 + offset])
if page_num > end_page_num and end_page_num != 0:
print("page_num is bigger than end_page_num, assuming as page count.")
end_page_num = page_num + end_page_num
print("End Page =", str(end_page_num))
except BaseException:
print("Invalid end page number:", args[1 + offset])
raise
return page_num, end_page_num
def menu():
PADDING = 40
set_console_title()
header()
print('--Pixiv'.ljust(PADDING, "-"))
print('1. Download by member_id')
print('2. Download by image_id')
print('3. Download by tags')
print('4. Download from list')
print('5. Download from bookmarked artists (/bookmark.php?type=user)')
print('6. Download from bookmarked images (/bookmark.php)')
print('7. Download from tags list')
print('8. Download new illust from bookmarked members (/bookmark_new_illust.php)')
print('9. Download by Title/Caption')
print('10. Download by Tag and Member Id')
print('11. Download Member Bookmark (/bookmark.php?id=)')
print('12. Download by Group Id')
print('--FANBOX'.ljust(PADDING, "-"))
print('f1. Download from supporting list (FANBOX)')
print('f2. Download by artist/creator id (FANBOX)')
print('f3. Download by post id (FANBOX)')
print('f4. Download from following list (FANBOX)')
print('--Sketch'.ljust(PADDING, "-"))
print('s1. Download by creator id (Sketch)')
print('s2. Download by post id (Sketch)')
print('--Batch Download'.ljust(PADDING, "-"))
print('b. Batch Download from batch_job.json (experimental)')
print('--Others'.ljust(PADDING, "-"))
print('d. Manage database')
print('e. Export online bookmark')
print('m. Export online user bookmark')
print('i. Import list file')
print('r. Reload config.ini')
print('p. Print config.ini')
print('x. Exit')
sel = input('Input: ').rstrip("\r")
return sel
def menu_download_by_member_id(opisvalid, args):
__log__.info('Member id mode.')
current_member = 1
page = 1
end_page = 0
if opisvalid and len(args) > 0:
for member_id in args:
try:
prefix = "[{0} of {1}] ".format(current_member, len(args))
test_id = int(member_id)
process_member(test_id, title_prefix=prefix)
current_member = current_member + 1
except BaseException:
PixivHelper.print_and_log('error', "Member ID: {0} is not valid".format(member_id))
global ERROR_CODE
ERROR_CODE = -1
continue
else:
member_ids = input('Member ids: ').rstrip("\r")
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
member_ids = PixivHelper.get_ids_from_csv(member_ids, sep=" ")
PixivHelper.print_and_log('info', "Member IDs: {0}".format(member_ids))
for member_id in member_ids:
try:
prefix = "[{0} of {1}] ".format(current_member, len(member_ids))
process_member(member_id, page=page, end_page=end_page, title_prefix=prefix)
current_member = current_member + 1
except PixivException as ex:
print(ex)
def menu_download_by_member_bookmark(opisvalid, args):
__log__.info('Member Bookmark mode.')
page = 1
end_page = 0
i = 0
current_member = 1
if opisvalid and len(args) > 0:
valid_ids = list()
for member_id in args:
print("%d/%d\t%f %%" % (i, len(args), 100.0 * i / float(len(args))))
i += 1
try:
test_id = int(member_id)
valid_ids.append(test_id)
except BaseException:
PixivHelper.print_and_log('error', "Member ID: {0} is not valid".format(member_id))
global ERROR_CODE
ERROR_CODE = -1
continue
if __br__._myId in valid_ids:
PixivHelper.print_and_log('error', "Member ID: {0} is your own id, use option 6 instead.".format(__br__._myId))
for mid in valid_ids:
prefix = "[{0} of {1}] ".format(current_member, len(valid_ids))
process_member(mid, bookmark=True, tags=None, title_prefix=prefix)
current_member = current_member + 1
else:
member_id = input('Member id: ').rstrip("\r")
tags = input('Filter Tags: ').rstrip("\r")
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
if __br__._myId == int(member_id):
PixivHelper.print_and_log('error', "Member ID: {0} is your own id, use option 6 instead.".format(member_id))
else:
process_member(member_id.strip(), page=page, end_page=end_page, bookmark=True, tags=tags)
def menu_download_by_image_id(opisvalid, args):
__log__.info('Image id mode.')
if opisvalid and len(args) > 0:
for image_id in args:
try:
test_id = int(image_id)
process_image(None, test_id)
except BaseException:
PixivHelper.print_and_log('error', "Image ID: {0} is not valid".format(image_id))
global ERROR_CODE
ERROR_CODE = -1
continue
else:
image_ids = input('Image ids: ').rstrip("\r")
image_ids = PixivHelper.get_ids_from_csv(image_ids, sep=" ")
for image_id in image_ids:
process_image(None, int(image_id))
def menu_download_by_tags(opisvalid, args):
__log__.info('tags mode.')
page = 1
end_page = 0
start_date = None
end_date = None
bookmark_count = None
oldest_first = False
wildcard = True
type_mode = "a"
if opisvalid and len(args) > 0:
wildcard = args[0]
if wildcard.lower() == 'y':
wildcard = True
else:
wildcard = False
(page, end_page) = get_start_and_end_number_from_args(args, 1)
tags = " ".join(args[3:])
else:
tags = input('Tags: ')
bookmark_count = input('Bookmark Count: ').rstrip("\r") or None
wildcard = input('Use Partial Match (s_tag) [y/n]: ').rstrip("\r") or 'n'
if wildcard.lower() == 'y':
wildcard = True
else:
wildcard = False
oldest_first = input('Oldest first[y/n]: ').rstrip("\r") or 'n'
if oldest_first.lower() == 'y':
oldest_first = True
else:
oldest_first = False
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
(start_date, end_date) = PixivHelper.get_start_and_end_date()
while True:
type_mode = input("Search type [a-all|i-Illustration and Ugoira|m-manga: ").rstrip("\r") or "a"
if type_mode in {'a', 'i', 'm'}:
break
else:
print("Valid values are 'a', 'i', or 'm'.")
if bookmark_count is not None:
bookmark_count = bookmark_count.strip()
if len(bookmark_count) > 0:
bookmark_count = int(bookmark_count)
process_tags(tags.strip(),
page, end_page,
wildcard,
start_date=start_date,
end_date=end_date,
use_tags_as_dir=__config__.useTagsAsDir,
bookmark_count=bookmark_count,
oldest_first=oldest_first,
type_mode=type_mode)
def menu_download_by_title_caption(opisvalid, args):
__log__.info('Title/Caption mode.')
page = 1
end_page = 0
start_date = None
end_date = None
if opisvalid and len(args) > 0:
(page, end_page) = get_start_and_end_number_from_args(args)
tags = " ".join(args[2:])
else:
tags = input('Title/Caption: ')
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
(start_date, end_date) = PixivHelper.get_start_and_end_date()
process_tags(tags.strip(),
page,
end_page,
wild_card=False,
title_caption=True,
start_date=start_date,
end_date=end_date,
use_tags_as_dir=__config__.useTagsAsDir)
def menu_download_by_tag_and_member_id(opisvalid, args):
__log__.info('Tag and MemberId mode.')
member_id = 0
tags = None
page = 1
end_page = 0
if opisvalid and len(args) >= 2:
try:
member_id = int(args[0])
except BaseException:
PixivHelper.print_and_log('error', "Member ID: {0} is not valid".format(member_id))
global ERROR_CODE
ERROR_CODE = -1
return
(page, end_page) = get_start_and_end_number_from_args(args, 1)
tags = " ".join(args[3:])
PixivHelper.safePrint("Looking tags: " + tags + " from memberId: " + str(member_id))
else:
member_id = input('Member Id: ').rstrip("\r")
tags = input('Tag : ')
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
process_tags(tags.strip(),
page,
end_page,
member_id=int(member_id),
use_tags_as_dir=__config__.useTagsAsDir)
def menu_download_from_list(opisvalid, args):
__log__.info('Batch mode.')
global op
global __config__
list_file_name = __config__.downloadListDirectory + os.sep + 'list.txt'
tags = None
if opisvalid and op == '4' and len(args) > 0:
test_file_name = __config__.downloadListDirectory + os.sep + args[0]
if os.path.exists(test_file_name):
list_file_name = test_file_name
if len(args) > 1:
tags = args[1]
else:
test_tags = input('Tag : ')
if len(test_tags) > 0:
tags = test_tags
# if tags is not None and len(tags) > 0:
# PixivHelper.safePrint(u"Processing member id from {0} for tags: {1}".format(list_file_name, tags))
# else:
# PixivHelper.safePrint("Processing member id from {0}".format(list_file_name))
process_list(list_file_name, tags)
def menu_download_from_online_user_bookmark(opisvalid, args):
__log__.info('User Bookmarked Artist mode.')
start_page = 1
end_page = 0
hide = 'n'
if opisvalid:
if len(args) > 0:
arg = args[0].lower()
if arg == 'y' or arg == 'n' or arg == 'o':
hide = arg
else:
print("Invalid args: ", args)
return
(start_page, end_page) = get_start_and_end_number_from_args(args, offset=1)
else:
arg = input("Include Private bookmarks [y/n/o]: ").rstrip("\r") or 'n'
arg = arg.lower()
if arg == 'y' or arg == 'n' or arg == 'o':
hide = arg
else:
print("Invalid args: ", arg)
return
(start_page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
process_bookmark(hide, start_page, end_page)
def menu_download_from_online_image_bookmark(opisvalid, args):
__log__.info("User's Image Bookmark mode.")
start_page = 1
end_page = 0
hide = 'n'
tag = ''
sorting = 'desc'
if opisvalid and len(args) > 0:
hide = args[0].lower()
if hide not in ('y', 'n', 'o'):
print("Invalid args: ", args)
return
(start_page, end_page) = get_start_and_end_number_from_args(args, offset=1)
if len(args) > 3:
tag = args[3]
if len(args) > 4:
sorting = args[4].lower()
if sorting not in ('asc', 'desc', 'date', 'date_d'):
print("Invalid sorting order: ", sorting)
return
else:
hide = input("Include Private bookmarks [y/n/o]: ").rstrip("\r") or 'n'
hide = hide.lower()
if hide not in ('y', 'n', 'o'):
print("Invalid args: ", hide)
return
tag = input("Tag (press enter for all images): ").rstrip("\r") or ''
(start_page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
# sorting = input("Sort Order [asc/desc/date/date_d]: ").rstrip("\r") or 'desc'
# sorting = sorting.lower()
# if sorting not in ('asc', 'desc', 'date', 'date_d'):
# print("Invalid sorting order: ", sorting)
# return
process_image_bookmark(hide, start_page, end_page, tag, sorting)
def menu_download_from_tags_list(opisvalid, args):
__log__.info('Taglist mode.')
page = 1
end_page = 0
oldest_first = False
wildcard = True
bookmark_count = None
start_date = None
end_date = None
if opisvalid and len(args) > 0:
filename = args[0]
(page, end_page) = get_start_and_end_number_from_args(args, offset=1)
else:
filename = input("Tags list filename [tags.txt]: ").rstrip("\r") or './tags.txt'
wildcard = input('Use Wildcard[y/n]: ').rstrip("\r") or 'n'
if wildcard.lower() == 'y':
wildcard = True
else:
wildcard = False
oldest_first = input('Oldest first[y/n]: ').rstrip("\r") or 'n'
if oldest_first.lower() == 'y':
oldest_first = True
else:
oldest_first = False
bookmark_count = input('Bookmark Count: ').rstrip("\r") or None
(page, end_page) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
(start_date, end_date) = PixivHelper.get_start_and_end_date()
if bookmark_count is not None:
bookmark_count = int(bookmark_count)
process_tags_list(filename, page, end_page, wild_card=wildcard, oldest_first=oldest_first,
bookmark_count=bookmark_count, start_date=start_date, end_date=end_date)
def menu_download_new_illust_from_bookmark(opisvalid, args):
__log__.info('New Illust from Bookmark mode.')
if opisvalid:
(page_num, end_page_num) = get_start_and_end_number_from_args(args, offset=0)
else:
(page_num, end_page_num) = PixivHelper.get_start_and_end_number(np_is_valid=np_is_valid, np=np)
process_new_illust_from_bookmark(page_num, end_page_num)
def menu_download_by_group_id(opisvalid, args):
__log__.info('Group mode.')
process_external = False
limit = 0
if opisvalid and len(args) > 0:
group_id = args[0]
limit = int(args[1])
if args[2].lower() == 'y':
process_external = True
else:
group_id = input("Group Id: ").rstrip("\r")
limit = int(input("Limit: ").rstrip("\r"))
arg = input("Process External Image [y/n]: ").rstrip("\r") or 'n'
arg = arg.lower()
if arg == 'y':
process_external = True
process_from_group(group_id, limit, process_external)
def menu_export_online_bookmark(opisvalid, args):
__log__.info('Export Bookmark mode.')
hide = "y" # y|n|o
filename = "export.txt"
if opisvalid and len(args) > 0:
arg = args[0]
if len(args) > 1:
filename = args[1]
else:
filename = input("Filename: ").rstrip("\r")
arg = input("Include Private bookmarks [y/n/o]: ").rstrip("\r") or 'n'
arg = arg.lower()
if arg == 'y' or arg == 'n' or arg == 'o':
hide = arg
else:
print("Invalid args: ", arg)
export_bookmark(filename, hide)
def menu_export_online_user_bookmark(opisvalid, args):
__log__.info('Export Bookmark mode.')
member_id = ''
filename = "export-user.txt"
if opisvalid and len(args) > 0:
arg = args[0]
if len(args) > 1: