-
Notifications
You must be signed in to change notification settings - Fork 254
/
PixivBrowserFactory.py
1532 lines (1334 loc) · 66.1 KB
/
PixivBrowserFactory.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
# -*- coding: utf-8 -*-
# pylint: disable=W0603, C0325
import http.client
import http.cookiejar
import json
import re
import socket
import sys
import time
import traceback
import urllib
from typing import List, Tuple, Union
import demjson3
import mechanize
import socks
from bs4 import BeautifulSoup
from colorama import Fore, Style
import PixivHelper
from PixivArtist import PixivArtist
from PixivBookmark import PixivNewIllustBookmark
from PixivException import PixivException
from PixivImage import PixivImage, PixivMangaSeries
from PixivModelFanbox import FanboxArtist, FanboxPost
from PixivModelSketch import SketchArtist, SketchPost
from PixivNovel import MAX_LIMIT, NovelSeries, PixivNovel
from PixivOAuth import PixivOAuth
from PixivRanking import PixivNewIllust, PixivRanking
from PixivTags import PixivTags
defaultCookieJar = None
defaultConfig = None
_browser = None
# pylint: disable=E1101
class PixivBrowser(mechanize.Browser):
_config = None
_cache = dict()
_max_cache = 10000 # keep n-item in memory
_myId = 0
_isPremium = False
_xRestrict = 0
_username = None
_password = None
_locale = ""
_is_logged_in_to_FANBOX = False
__oauth_manager = None
@property
def _oauth_manager(self):
if self.__oauth_manager is None:
proxy = None
if self._config.useProxy:
proxy = self._config.proxy
if self._config is not None:
if self._username is None:
self._username = self._config.username
if self._password is None:
self._password = self._config.password
self.__oauth_manager = PixivOAuth(self._username,
self._password,
proxies=proxy,
refresh_token=self._config.refresh_token,
validate_ssl=self._config.enableSSLVerification)
return self.__oauth_manager
def _put_to_cache(self, key, item, expiration=3600):
expiry = time.time() + expiration
self._cache[key] = (item, expiry)
# check oldest item
oldest_expiry = expiry
oldest_item = key
if len(self._cache) > self._max_cache:
for key2 in self._cache:
curr_expiry = self._cache[key2][1]
if curr_expiry < oldest_expiry:
oldest_item = key2
oldest_expiry = curr_expiry
del self._cache[oldest_item]
def _get_from_cache(self, key, sliding_window=3600):
if key in self._cache.keys():
(item, expiry) = self._cache.pop(key)
if expiry - time.time() > 0:
self._cache[key] = (item, expiry + sliding_window)
return item
# expired data
del item
return None
def __init__(self, config, cookie_jar):
# fix #218 not applicable after upgrading to mechanize 4.x
mechanize.Browser.__init__(self)
self._configureBrowser(config)
self._configureCookie(cookie_jar)
def clear_history(self):
mechanize.Browser.clear_history(self)
return
def back(self):
mechanize.Browser.back(self)
return
def _configureBrowser(self, config):
if config is None:
PixivHelper.get_logger().info("No config given")
return
global defaultConfig
if defaultConfig is None:
defaultConfig = config
self._config = config
if config.useProxy:
if config.proxyAddress.startswith('socks'):
parseResult = urllib.parse.urlparse(config.proxyAddress)
assert parseResult.scheme and parseResult.hostname and parseResult.port
socksType = socks.PROXY_TYPE_SOCKS5 if 'socks5' in parseResult.scheme else socks.PROXY_TYPE_SOCKS4
PixivHelper.get_logger().info(f"Using SOCKS5 Proxy= {parseResult.hostname}:{parseResult.port} @ {parseResult.username}")
# https://stackoverflow.com/a/14512227
socks.setdefaultproxy(socksType, parseResult.hostname, parseResult.port,
True, parseResult.username, parseResult.password)
socket.socket = socks.socksocket
# https://stackoverflow.com/a/13214222 and
# https://github.com/Anorov/PySocks/issues/22
def getaddrinfo(*args):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
self._orig_getaddrinfo = socket.getaddrinfo
socket.getaddrinfo = getaddrinfo
else:
self.set_proxies(config.proxy)
PixivHelper.get_logger().info("Using Proxy: %s", config.proxyAddress)
# self.set_handle_equiv(True)
# self.set_handle_gzip(True)
self.set_handle_redirect(True)
self.set_handle_referer(True)
self.set_handle_robots(False)
self.set_debug_http(config.debugHttp)
if config.debugHttp:
PixivHelper.get_logger().info('Debug HTTP enabled.')
# self.visit_response
self.addheaders = [('User-agent', config.useragent)]
# # force utf-8, fix issue #184
# self.addheaders += [('Accept-Charset', 'utf-8')]
socket.setdefaulttimeout(config.timeout)
if not self._config.enableSSLVerification:
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
self.set_ca_data(context=_create_unverified_https_context())
def _configureCookie(self, cookie_jar):
if cookie_jar is not None:
self.set_cookiejar(cookie_jar)
global defaultCookieJar
if defaultCookieJar is None:
defaultCookieJar = cookie_jar
def addCookie(self, cookie):
global defaultCookieJar
if defaultCookieJar is None:
defaultCookieJar = http.cookiejar.LWPCookieJar()
defaultCookieJar.set_cookie(cookie)
def clearCookie(self):
global defaultCookieJar
if defaultCookieJar is None:
defaultCookieJar = http.cookiejar.LWPCookieJar()
defaultCookieJar.clear()
def open_with_retry(self, url, data=None, timeout=60, retry=0):
''' Return response object with retry.'''
retry_count = 0
if retry == 0 and self._config is not None:
retry = self._config.retry
while True:
res = None
try:
res = self.open(url, data, timeout)
return res
except urllib.error.HTTPError as fanboxError:
if res is not None:
print(f"Error Code: {res.code}")
print(f"Response Headers: {res.headers}")
if res.code == '302':
print(f"Redirect to {res.headers['location']}")
else:
# Issue #1342
if "challenge_basic_security_FANBOX" in str(fanboxError.get_data()) and fanboxError.getcode() == 403:
return fanboxError
raise
except BaseException:
exc_value = sys.exc_info()[1]
if retry_count < retry:
print(exc_value, end=' ')
for t in range(1, self._config.retryWait):
print(t, end=' ')
PixivHelper.print_delay(2)
print('')
retry_count = retry_count + 1
else:
temp = url
if isinstance(url, urllib.request.Request):
temp = url.full_url
PixivHelper.print_and_log('error', f'Error at open_with_retry(): {sys.exc_info()}')
raise PixivException(f"Failed to get page: {temp}, please check your internet connection/firewall/antivirus.",
errorCode=PixivException.SERVER_ERROR)
# def getPixivPage(self, url, referer="https://www.pixiv.net", returnParsed=True, enable_cache=True) -> Union[str, BeautifulSoup]:
def getPixivPage(self, url, referer="https://www.pixiv.net", enable_cache=True) -> str:
''' get page from pixiv and return as parsed BeautifulSoup object or response object.
throw PixivException as server error
'''
url = self.fixUrl(url)
retry_count = 0
while True:
req = mechanize.Request(url)
req.add_header('Referer', referer)
read_page = self._get_from_cache(url)
if read_page is None:
while True:
try:
temp = self.open_with_retry(req)
read_page = temp.read()
read_page = read_page.decode('utf8')
if enable_cache:
self._put_to_cache(url, read_page)
temp.close()
break
except urllib.error.HTTPError as ex:
if ex.code in [403, 404, 503]:
read_page = ex.read()
raise PixivException(f"Failed to get page: {url} => {ex}", errorCode=PixivException.SERVER_ERROR)
else:
PixivHelper.print_and_log('error', f'Error at getPixivPage(): {sys.exc_info()}')
raise PixivException(f"Failed to get page: {url}", errorCode=PixivException.SERVER_ERROR)
except BaseException:
exc_value = sys.exc_info()[1]
if retry_count < self._config.retry:
print(exc_value, end=' ')
for t in range(1, self._config.retryWait):
print(t, end=' ')
PixivHelper.print_delay(2)
print('')
retry_count = retry_count + 1
else:
raise PixivException(f"Failed to get page: {url}", errorCode=PixivException.SERVER_ERROR)
# if returnParsed:
# parsedPage = BeautifulSoup(read_page, features="html5lib")
# return parsedPage
return read_page
def fixUrl(self, url, useHttps=True):
# url = str(url)
if not url.startswith("http"):
if not url.startswith("/"):
url = "/" + url
if useHttps:
return "https://www.pixiv.net" + url
else:
return "http://www.pixiv.net" + url
return url
def _loadCookie(self, cookie_value, domain):
""" Load cookie to the Browser instance """
ck = None
# full cookies string
if cookie_value.find("PHPSESSID=") > -1:
cookies = cookie_value.split(";")
for cookie in cookies:
temp = cookie.split("=")
name = temp[0].strip()
value = temp[1] if len(temp) > 1 else ""
domain = ".pixiv.net"
if name in ("adr_id", "categorized_tags", "first_visit_datetime_pc", "tags_sended", "yuid_b"):
domain = "www.pixiv.net"
elif name in ("login_ever"):
domain = ".www.pixiv.net"
ck = http.cookiejar.Cookie(version=0, name=name, value=value, port=None,
port_specified=False, domain=domain, 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)
self.addCookie(ck)
else:
if "pixiv.net" in domain:
ck = http.cookiejar.Cookie(version=0, name='PHPSESSID', value=cookie_value, 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)
elif "fanbox.cc" in domain:
ck = http.cookiejar.Cookie(version=0, name='FANBOXSESSID', value=cookie_value, port=None,
port_specified=False, domain='fanbox.cc', 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)
if ck is not None:
self.addCookie(ck)
def _getInitConfig(self, page):
init_config = page.find('input', attrs={'id': 'init-config'})
js_init_config = json.loads(init_config['value'])
return js_init_config
def loginUsingCookie(self, login_cookie=None):
""" Log in to Pixiv using saved cookie, return True if success """
result = False
if login_cookie is None or len(login_cookie) == 0:
login_cookie = self._config.cookie
if len(login_cookie) > 0:
PixivHelper.print_and_log('info', 'Trying to log in with saved cookie')
self.clearCookie()
self._loadCookie(login_cookie, "pixiv.net")
res = self.open_with_retry('https://www.pixiv.net') # + self._locale)
parsed = BeautifulSoup(res, features="html5lib")
parsed_str = str(parsed.decode('utf-8'))
PixivHelper.print_and_log("info", f'Logging in, return url: {res.geturl()}')
res.close()
parsed.decompose()
del parsed
if "logout.php" in parsed_str:
result = True
if "pixiv.user.loggedIn = true" in parsed_str:
result = True
if "_gaq.push(['_setCustomVar', 1, 'login', 'yes'" in parsed_str:
result = True
if "var dataLayer = [{ login: 'yes'," in parsed_str:
result = True
if result:
PixivHelper.print_and_log('info', 'Login successful.')
PixivHelper.get_logger().info('Logged in using cookie')
self.getMyId(parsed_str)
temp_locale = str(res.geturl()).replace('https://www.pixiv.net', '').replace('/', '')
if len(temp_locale) > 0:
self._locale = '/' + temp_locale
PixivHelper.get_logger().info('Locale = %s', self._locale)
else:
PixivHelper.get_logger().info('Failed to log in using cookie')
PixivHelper.print_and_log('info', 'Cookie already expired/invalid.')
return result
def fanboxLoginUsingCookie(self, login_cookie=None):
""" Log in to Pixiv using saved cookie, return True if success """
result = False
parsed = ""
if login_cookie is None or len(login_cookie) == 0:
login_cookie = self._config.cookieFanbox
# Issue #1342
if self._config.cf_clearance != "":
ck1 = http.cookiejar.Cookie(version=0, name='cf_clearance', value=self._config.cf_clearance, port=None,
port_specified=False, domain='fanbox.cc', 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)
self.addCookie(ck1)
if self._config.cf_bm != "":
ck2 = http.cookiejar.Cookie(version=0, name='__cf_bm', value=self._config.cf_bm, port=None,
port_specified=False, domain='fanbox.cc', 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)
self.addCookie(ck2)
if len(login_cookie) > 0:
PixivHelper.print_and_log('info', 'Trying to log in FANBOX with saved cookie')
# self.clearCookie()
self._loadCookie(login_cookie, "fanbox.cc")
req = mechanize.Request("https://www.fanbox.cc")
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
req.add_header('Origin', 'https://www.fanbox.cc')
req.add_header('User-Agent', self._config.useragent)
try:
res = self.open_with_retry(req)
parsed = BeautifulSoup(res, features="html5lib")
PixivHelper.get_logger().info('Logging in with cookie to Fanbox, return url: %s', res.geturl())
res.close()
except BaseException:
PixivHelper.get_logger().error('Error at fanboxLoginUsingCookie(): %s', sys.exc_info())
self.cookiejar.clear("fanbox.cc")
if '"user":{"isLoggedIn":true' in str(parsed.decode('utf-8')):
result = True
self._is_logged_in_to_FANBOX = True
# Issue #1342
elif "challenge_basic_security_FANBOX" in str(parsed.decode('utf-8')):
fanboxErrorPage = parsed.decode('utf-8')
parsed.decompose()
del parsed
raise PixivException("Failed FANBOX Cloudflare CAPTCHA challenge, please check your cookie and user-agent settings.",
errorCode=PixivException.CANNOT_LOGIN, htmlPage=fanboxErrorPage)
parsed.decompose()
del parsed
if result:
PixivHelper.print_and_log('info', 'FANBOX Login successful.')
else:
PixivHelper.print_and_log('info', 'Not logged in to FANBOX, trying to update FANBOX cookie...')
result = self.updateFanboxCookie()
self._is_logged_in_to_FANBOX = result
return result
def fanbox_is_logged_in(self):
if not self._is_logged_in_to_FANBOX:
if not self.fanboxLoginUsingCookie(self._config.cookieFanbox):
raise Exception("Not logged in to FANBOX")
def updateFanboxCookie(self):
p_req = mechanize.Request("https://www.fanbox.cc/login?return_to=https%3A%2F%2Fwww.fanbox.cc%2F")
p_req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
p_req.add_header('Referer', 'https://www.fanbox.cc')
try:
p_res = self.open_with_retry(p_req)
page = p_res.read().decode("utf-8")
p_res.close()
except BaseException:
PixivHelper.get_logger().error('Error at updateFanboxCookie(): %s', sys.exc_info())
return False
match = re.search(r"(?<=pixivAccount\.postKey\":\").*?(?=\")", page)
if not match:
raise Exception("Could not get pixivAccount.postKey while trying to log into fanbox.cc with given pixiv.net cookie")
data = {"return_to": "https://www.fanbox.cc/auth/start",
"tt": match.group()}
p_req = mechanize.Request("https://accounts.pixiv.net/account-selected", data, method="POST")
try:
p_res = self.open_with_retry(p_req)
parsed = BeautifulSoup(p_res, features="html5lib")
p_res.close()
except BaseException:
PixivHelper.get_logger().error('Error at updateFanboxCookie(): %s', sys.exc_info())
return False
result = False
if '"user":{"isLoggedIn":true' in str(parsed.decode('utf-8')):
result = True
self._is_logged_in_to_FANBOX = True
parsed.decompose()
del parsed
if result:
for cookie in self._ua_handlers['_cookies'].cookiejar:
if cookie.name == 'FANBOXSESSID':
PixivHelper.print_and_log(
'info', 'New FANBOX cookie value: ' + str(cookie.value))
self._config.cookieFanbox = cookie.value
self._config.writeConfig(path=self._config.configFileLocation)
break
else:
PixivHelper.print_and_log('info', 'Could not update FANBOX cookie string.')
return result
def login(self, username, password):
parsed = None
try:
PixivHelper.print_and_log('info', 'Logging in...')
url = "https://accounts.pixiv.net/login"
# get the post key
res = self.open_with_retry(url)
parsed = BeautifulSoup(res, features="html5lib")
post_key = parsed.find('input', attrs={'name': 'post_key'})
# js_init_config = self._getInitConfig(parsed)
res.close()
data = {}
data['pixiv_id'] = username
data['password'] = password
# data['captcha'] = ''
# data['g_recaptcha_response'] = ''
data['return_to'] = 'https://www.pixiv.net'
data['lang'] = 'en'
data['post_key'] = post_key['value']
data['source'] = "accounts"
data['ref'] = ''
request = mechanize.Request("https://accounts.pixiv.net/api/login?lang=en", data, method='POST')
response = self.open_with_retry(request)
result = self.processLoginResult(response, username, password)
response.close()
return result
except BaseException:
traceback.print_exc()
PixivHelper.print_and_log('error', f'Error at login(): {sys.exc_info()}')
PixivHelper.dump_html("login_error.html", str(parsed))
raise
finally:
if parsed is not None:
parsed.decompose()
del parsed
def processLoginResult(self, response, username, password):
PixivHelper.get_logger().info('Logging in, return url: %s', response.geturl())
# check the returned json
js = response.read()
PixivHelper.get_logger().info(str(js))
result = json.loads(js)
# Fix Issue #181
if result["body"] is not None and "success" in result["body"]:
for cookie in self._ua_handlers['_cookies'].cookiejar:
if cookie.name == 'PHPSESSID':
PixivHelper.print_and_log(
'info', 'new cookie value: ' + str(cookie.value))
self._config.cookie = cookie.value
self._config.writeConfig(
path=self._config.configFileLocation)
break
# check whitecube
res = self.open_with_retry(result["body"]["success"]["return_to"])
parsed = BeautifulSoup(res, features="html5lib")
self.getMyId(parsed.decode('utf-8'))
res.close()
# store the username and password in memory for oAuth login
self._config.username = username
self._config.password = password
parsed.decompose()
del parsed
return True
else:
if result["body"] is not None and "validation_errors" in result["body"]:
PixivHelper.print_and_log(
'info', "Server reply: " + str(result["body"]["validation_errors"]))
if str(result["body"]["validation_errors"]).find("reCAPTCHA") > 0:
print(
"Please follow the method described in https://github.com/Nandaka/PixivUtil2/issues/505")
else:
PixivHelper.print_and_log('info', 'Unknown login issue, please use cookie login method.')
return False
def getMyId(self, parsed):
''' Assume from main page '''
temp = None
# pixiv.user.id = "189816";
temp = re.findall(r"pixiv.user.id = \"(\d+)\";", parsed)
if temp is not None and len(temp) > 0:
self._myId = int(temp[0])
PixivHelper.print_and_log('info', f'My User Id: {self._myId}.')
else:
# _gaq.push(['_setCustomVar', 6, 'user_id', "3145410", 1]);
temp = re.findall(r"_gaq.push\(\['_setCustomVar', 6, 'user_id', \"(\d+)\", 1\]\);", parsed)
if self._myId == 0 and temp is not None and len(temp) > 0:
self._myId = int(temp[0])
PixivHelper.print_and_log('info', f'My User Id: {self._myId}.')
else:
# var dataLayer = [{ login: 'yes', gender: "male", user_id: "3145410", lang: "en", illustup_flg: 'not_uploaded', premium: 'no', }];
temp = re.findall(r"var dataLayer = .*user_id: \"(\d+)\"", parsed)
if self._myId == 0 and temp is not None and len(temp) > 0:
self._myId = int(temp[0])
PixivHelper.print_and_log('info', f'My User Id: {self._myId}.')
if self._myId == 0:
PixivHelper.print_and_log('error', 'Unable to get User Id, please check your cookie.')
PixivHelper.print_and_log('error', 'Please follow the instruction in https://github.com/Nandaka/PixivUtil2/issues/814#issuecomment-711182644')
raise PixivException("Unable to get User Id, please check your cookie.", errorCode=PixivException.NOT_LOGGED_IN, htmlPage=parsed)
self._isPremium = False
# not used anymore
# temp = re.findall(r"pixiv.user.premium = (\w+);", parsed)
# if temp is not None and len(temp) > 0:
# self._isPremium = True if temp[0] == "true" else False
# else:
temp = re.findall(r"_gaq.push\(\['_setCustomVar', 3, 'plan', '(\w+)', 1\]\)", parsed)
if temp is not None and len(temp) > 0:
self._isPremium = True if temp[0] == "premium" else False
else:
temp = re.findall(r"var dataLayer = .*premium: '(\w+)'", parsed)
if temp is not None and len(temp) > 0:
self._isPremium = True if temp[0] == "yes" else False
PixivHelper.print_and_log('info', f'Premium User: {self._isPremium}.')
self._xRestrict = 0
temp = re.findall(r"\"xRestrict\":(\d+)", parsed)
if temp is not None and len(temp) > 0:
self._xRestrict = int(temp[0])
if self._xRestrict == 1:
PixivHelper.print_and_log('warn', 'R-18G is disabled from pixiv website settings.')
elif self._xRestrict == 0:
PixivHelper.print_and_log('warn', 'R-18 and R-18G are disabled from pixiv website settings.')
def parseLoginError(self, res):
page = BeautifulSoup(res, features="html5lib")
r = page.findAll('span', attrs={'class': 'error'})
page.decompose()
del page
return r
def getImagePage(self,
image_id,
parent=None,
from_bookmark=False,
bookmark_count=-1,
image_response_count=-1,
manga_series_order=-1,
manga_series_parent=None,
is_unlisted=False) -> Tuple[PixivImage, str]:
image = None
response = None
PixivHelper.get_logger().debug("Getting image page: %s", image_id)
if not is_unlisted:
# https://www.pixiv.net/en/artworks/76656661
url = f"https://www.pixiv.net{self._locale}/artworks/{image_id}"
else:
# https://www.pixiv.net/artworks/unlisted/SbliQHtJS5MMu3elqDFZ
url = f"https://www.pixiv.net{self._locale}/artworks/unlisted/{image_id}"
response = self.getPixivPage(url, enable_cache=False)
self.handleDebugMediumPage(response, image_id)
# Issue #355 new ui handler
image = None
try:
if response.find("meta-preload-data") > 0:
PixivHelper.print_and_log('debug', 'New UI Mode')
# Issue #420
_tzInfo = None
if self._config.useLocalTimezone:
_tzInfo = PixivHelper.LocalUTCOffsetTimezone()
image = PixivImage(image_id,
response,
parent,
from_bookmark,
bookmark_count,
image_response_count,
dateFormat=self._config.dateFormat,
tzInfo=_tzInfo,
manga_series_order=manga_series_order,
manga_series_parent=manga_series_parent,
writeRawJSON=self._config.writeRawJSON,
stripHTMLTagsFromCaption=self._config.stripHTMLTagsFromCaption)
if image.imageMode == "ugoira_view":
ugoira_meta_url = f"https://www.pixiv.net/ajax/illust/{image_id}/ugoira_meta"
res = self.open_with_retry(ugoira_meta_url)
meta_response = res.read()
image.ParseUgoira(meta_response)
res.close()
if parent is None:
if from_bookmark:
image.originalArtist.reference_image_id = image_id
self.getMemberInfoWhitecube(image.originalArtist.artistId, image.originalArtist)
else:
image.artist.reference_image_id = image_id
self.getMemberInfoWhitecube(image.artist.artistId, image.artist)
except BaseException:
PixivHelper.get_logger().error("Respose data: \r\n %s", response)
raise
return (image, response)
def handleDebugMediumPage(self, response, imageId):
if self._config.enableDump:
if self._config.dumpMediumPage:
dump_filename = f"Medium Page for Image Id {imageId}.html"
PixivHelper.dump_html(dump_filename, response)
PixivHelper.print_and_log('info', f'Dumping html to: {dump_filename}')
if self._config.debugHttp:
PixivHelper.safePrint(f"reply: {response}")
def getMemberInfoWhitecube(self, member_id, artist, bookmark=False):
''' get artist information using Ajax and AppAPI '''
try:
info = None
try:
image_id = int(artist.reference_image_id)
except:
image_id = -1
if image_id > 0:
url = f"https://www.pixiv.net/rpc/get_work.php?id={artist.reference_image_id}"
PixivHelper.get_logger().debug("using webrpc: %s", url)
info = self._get_from_cache(url)
if info is None:
request = mechanize.Request(url)
res = self.open_with_retry(request)
infoStr = res.read()
res.close()
info = json.loads(infoStr)
self._put_to_cache(url, info)
else:
PixivHelper.print_and_log('info', f'Using OAuth to retrieve member info for: {member_id}')
if not self._username or not self._password:
raise PixivException("Empty Username or Password, remove cookie value and relogin, or add username/password to config.ini.")
url = f'https://app-api.pixiv.net/v1/user/detail?user_id={member_id}'
info = self._get_from_cache(url)
if info is None:
PixivHelper.get_logger().debug("Getting member information: %s", member_id)
login_response = self._oauth_manager.login()
if login_response.status_code == 200:
info = json.loads(login_response.text)
if self._config.refresh_token != info["response"]["refresh_token"]:
PixivHelper.print_and_log('info', 'OAuth Refresh Token is updated, updating config.ini')
self._config.refresh_token = info["response"]["refresh_token"]
self._config.writeConfig(path=self._config.configFileLocation)
response = self._oauth_manager.get_user_info(member_id)
info = json.loads(response.text)
self._put_to_cache(url, info)
PixivHelper.get_logger().debug("reply: %s", response.text)
artist.ParseInfo(info, False, bookmark=bookmark)
# will throw HTTPError if user is suspended/not logged in.
url_ajax = f'https://www.pixiv.net/ajax/user/{member_id}'
info_ajax = self._get_from_cache(url_ajax)
if info_ajax is None:
res = self.open_with_retry(url_ajax)
info_ajax_str = res.read()
res.close()
info_ajax = json.loads(info_ajax_str)
self._put_to_cache(url_ajax, info_ajax)
# 2nd pass to get the background
artist.ParseBackground(info_ajax)
return artist
except urllib.error.HTTPError as error:
errorCode = error.getcode()
errorMessage = error.get_data()
PixivHelper.get_logger().error("Error data: \r\n %s", errorMessage)
payload = demjson3.decode(errorMessage)
# Issue #432
msg = None
if "message" in payload:
msg = payload["message"]
elif "error" in payload and payload["error"] is not None:
msgs = list()
msgs.append(payload["error"]["user_message"])
msgs.append(payload["error"]["message"])
msgs.append(payload["error"]["reason"])
msg = ",".join(msgs)
if errorCode == 401:
raise PixivException(msg, errorCode=PixivException.NOT_LOGGED_IN, htmlPage=errorMessage)
elif errorCode == 403:
raise PixivException(msg, errorCode=PixivException.USER_ID_SUSPENDED, htmlPage=errorMessage)
else:
raise PixivException(msg, errorCode=PixivException.OTHER_MEMBER_ERROR, htmlPage=errorMessage)
def getMemberPage(self, member_id, page=1, bookmark=False, tags=None, r18mode=False, throw_empty_error=False) -> Tuple[PixivArtist, str]:
artist = None
response = None
if tags is None:
tags = ''
limit = 48
offset = (page - 1) * limit
need_to_slice = False
if bookmark:
# https://www.pixiv.net/ajax/user/1039353/illusts/bookmarks?tag=&offset=0&limit=24&rest=show
url = f'https://www.pixiv.net/ajax/user/{member_id}/illusts/bookmarks?tag={tags}&offset={offset}&limit={limit}&rest=show'
else:
# https://www.pixiv.net/ajax/user/1813972/illusts/tag?tag=Fate%2FGrandOrder?offset=0&limit=24
# https://www.pixiv.net/ajax/user/1813972/manga/tag?tag=%E3%83%A1%E3%82%A4%E3%82%AD%E3%83%B3%E3%82%B0?offset=0&limit=24
# https://www.pixiv.net/ajax/user/5238/illustmanga/tag?tag=R-18&offset=0&limit=48
# https://www.pixiv.net/ajax/user/1813972/profile/all
url = None
if len(tags) > 0: # called from Download by tags
url = f'https://www.pixiv.net/ajax/user/{member_id}/illustmanga/tag?tag={tags}&offset={offset}&limit={limit}'
elif r18mode:
url = f'https://www.pixiv.net/ajax/user/{member_id}/illustmanga/tag?tag=R-18&offset={offset}&limit={limit}'
else:
url = f'https://www.pixiv.net/ajax/user/{member_id}/profile/all'
need_to_slice = True
PixivHelper.print_and_log('info', f'{Fore.LIGHTGREEN_EX}{"Member Url":14}:{Style.RESET_ALL} {url}')
if url is not None:
# cache the response
response = self._get_from_cache(url)
if response is None:
try:
res = self.open_with_retry(url)
response = res.read()
res.close()
except urllib.error.HTTPError as ex:
if ex.code == 404:
response = ex.read()
self._put_to_cache(url, response)
PixivHelper.get_logger().debug(response)
artist = PixivArtist(member_id, response, False, offset, limit)
# fix issue with member with 0 images, skip everything.
if len(artist.imageList) == 0 and throw_empty_error:
raise PixivException(f"No images for Member Id:{member_id}, from Bookmark: {bookmark}", errorCode=PixivException.NO_IMAGES, htmlPage=response)
artist.reference_image_id = artist.imageList[0] if len(artist.imageList) > 0 else 0
self.getMemberInfoWhitecube(member_id, artist, bookmark)
if artist.haveImages and need_to_slice:
artist.imageList = artist.imageList[offset:offset + limit]
return (artist, response)
def getSearchTagPage(self,
tags,
current_page,
wild_card=True,
title_caption=False,
start_date=None,
end_date=None,
member_id=None,
sort_order='date_d',
start_page=1,
use_bookmark_data=False,
bookmark_count=0,
type_mode="a",
r18mode=False) -> Tuple[PixivTags, str]:
response_page = None
result = None
url = ''
if member_id is not None:
# from member id search by tags
(artist, response_page) = self.getMemberPage(member_id, current_page, False, tags, r18mode=r18mode, throw_empty_error=True)
# convert to PixivTags
result = PixivTags()
result.parseMemberTags(artist, member_id, tags)
else:
# only premium support server-side filtering for bookmark count
if not self._isPremium:
bookmark_count = 0
# search by tags
url = PixivHelper.generate_search_tag_url(tags,
current_page,
title_caption=title_caption,
wild_card=wild_card,
sort_order=sort_order,
start_date=start_date,
end_date=end_date,
member_id=member_id,
r18mode=r18mode,
blt=bookmark_count,
type_mode=type_mode,
locale=self._locale)
PixivHelper.print_and_log('info', f'Looping... for {url}')
response_page = self.getPixivPage(url)
self.handleDebugTagSearchPage(response_page, url)
result = None
if member_id is not None:
result = PixivTags()
parse_search_page = BeautifulSoup(response_page, features="html5lib")
result.parseMemberTags(parse_search_page, member_id, tags)
parse_search_page.decompose()
del parse_search_page
else:
try:
result = PixivTags()
result.parseTags(response_page, tags, current_page)
# parse additional information
if 0: # Disabled, see #1159 #1160
idx = 0
print("Retrieving bookmark information...", end=' ')
for image in result.itemList:
idx = idx + 1
print("\r", end=' ')
print(f"Retrieving bookmark information... [{idx}] of [{len(result.itemList)}]", end=' ')
img_url = f"https://www.pixiv.net/ajax/illust/{image.imageId}"
response_page = self._get_from_cache(img_url)
if response_page is None:
try:
res = self.open_with_retry(img_url)
response_page = res.read()
res.close()
except urllib.error.HTTPError as ex:
if ex.code == 404:
response_page = ex.read()
self._put_to_cache(img_url, response_page)
image_info_js = json.loads(response_page)
image.bookmarkCount = int(
image_info_js["body"]["bookmarkCount"])
image.imageResponse = int(
image_info_js["body"]["responseCount"])
PixivHelper.wait(result, self._config)
print("")
except BaseException:
PixivHelper.dump_html(f"Dump for SearchTags {tags}.html", response_page)
raise
return (result, response_page)
def handleDebugTagSearchPage(self, response, url):
if self._config.enableDump:
if self._config.dumpTagSearchPage:
dump_filename = f"TagSearch Page for {url}.html"
PixivHelper.dump_html(dump_filename, response)
PixivHelper.print_and_log('info', f'Dumping html to: {dump_filename}')
if self._config.debugHttp:
PixivHelper.safePrint(f"reply: {response}")
def fanboxGetArtistList(self, via):
self.fanbox_is_logged_in()
url = None
referer = ""
if via == FanboxArtist.SUPPORTING:
url = 'https://api.fanbox.cc/plan.listSupporting'
PixivHelper.print_and_log('info', f'Getting supporting artists from {url}')
referer = "https://www.fanbox.cc/"
elif via == FanboxArtist.FOLLOWING:
url = 'https://api.fanbox.cc/creator.listFollowing'
PixivHelper.print_and_log('info', f'Getting following artists from {url}')
referer = "https://www.fanbox.cc/"
if url is not None:
req = mechanize.Request(url)
req.add_header('Accept', 'application/json, text/plain, */*')
req.add_header('Referer', referer)
req.add_header('Origin', 'https://www.fanbox.cc')
req.add_header('User-Agent', self._config.useragent)
res = self.open_with_retry(req)
# read the json response
response = res.read()
res.close()
ids = FanboxArtist.parseArtistIds(page=response)
return ids
else:
raise ValueError(f"Invalid via argument {via}")
def fanboxGetArtistById(self, artist_id, for_suspended=False):
self.fanbox_is_logged_in()
if re.match(r"^\d+$", artist_id):
id_type = "userId"
else:
id_type = "creatorId"
url = f'https://api.fanbox.cc/creator.get?{id_type}={artist_id}'
PixivHelper.print_and_log('info', f'Getting artist information from {url}')
referer = "https://www.fanbox.cc"
if id_type == "creatorId":
referer += f"/@{artist_id}"
req = mechanize.Request(url)
req.add_header('Accept', 'application/json, text/plain, */*')
req.add_header('Referer', referer)
req.add_header('Origin', 'https://www.fanbox.cc')
req.add_header('User-Agent', self._config.useragent)
res = self.open_with_retry(req)
# read the json response