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
|
diff --git a/pixivpy3/api.py b/pixivpy3/api.py
index 8a246b6..473c620 100644
--- a/pixivpy3/api.py
+++ b/pixivpy3/api.py
@@ -24,6 +24,7 @@ class BasePixivAPI:
self.user_id: int | str = 0
self.access_token: str | None = None
self.refresh_token: str | None = None
+ self.token_expiration: int | None = None
self.hosts = "https://app-api.pixiv.net"
# self.requests = requests.Session()
@@ -63,6 +64,11 @@ class BasePixivAPI:
stream: bool = False,
) -> Response:
"""Requests http/https call for Pixiv API"""
+ if self.token_expiration and datetime.now().timestamp() >= self.token_expiration:
+ # Token expired refresh auth.
+ print("Token expired, refreshing auth.")
+ self.token_expiration = None
+ self.auth()
merged_headers = self.additional_headers.copy()
if headers:
# Use the headers in the parameter to override the
@@ -123,11 +129,12 @@ class BasePixivAPI:
headers: ParamDict = None,
) -> ParsedJson:
"""Login with password, or use the refresh_token to acquire a new bearer token"""
- local_time = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
+ local_time = datetime.now()
+ local_time_str = local_time.strftime("%Y-%m-%dT%H:%M:%S+00:00")
headers_ = CaseInsensitiveDict(headers or {})
- headers_["x-client-time"] = local_time
+ headers_["x-client-time"] = local_time_str
headers_["x-client-hash"] = hashlib.md5(
- (local_time + self.hash_secret).encode("utf-8")
+ (local_time_str + self.hash_secret).encode("utf-8")
).hexdigest()
# Allow mock UA due to #171: https://github.com/upbit/pixivpy/issues/171
if "user-agent" not in headers_:
@@ -156,6 +163,8 @@ class BasePixivAPI:
elif refresh_token or self.refresh_token:
data["grant_type"] = "refresh_token"
data["refresh_token"] = refresh_token or self.refresh_token
+ if self.access_token:
+ data["access_token"] = self.access_token
else:
msg = "[ERROR] auth() but no password or refresh_token is set."
raise PixivError(msg)
@@ -183,6 +192,7 @@ class BasePixivAPI:
self.user_id = token.response.user.id
self.access_token = token.response.access_token
self.refresh_token = token.response.refresh_token
+ self.token_expiration = local_time.timestamp() + token.response.expires_in
except json.JSONDecodeError:
msg = f"Get access_token error! Response: {token}"
raise PixivError(
|