-
Notifications
You must be signed in to change notification settings - Fork 11
/
api.go
220 lines (192 loc) · 5.53 KB
/
api.go
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
package pixiv
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"github.com/dghubble/sling"
"github.com/pkg/errors"
)
const (
clientID = "MOBrBDS8blbauoSck0ZfDbtuzpyT"
clientSecret = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"
clientHashSecret = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"
)
var (
_token, _refreshToken string
_tokenDeadline time.Time
authHook func(string, string, time.Time) error
)
type AccountProfileImages struct {
Px16 string `json:"px_16x16"`
Px50 string `json:"px_50x50"`
Px170 string `json:"px_170x170"`
}
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Account string `json:"account"`
MailAddress string `json:"mail_address"`
IsPremium bool `json:"is_premium"`
XRestrict int `json:"x_restrict"`
IsMailAuthorized bool `json:"is_mail_authorized"`
ProfileImage AccountProfileImages `json:"profile_image_urls"`
}
type authInfo struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
RefreshToken string `json:"refresh_token"`
User *Account `json:"user"`
DeviceToken string `json:"device_token"`
}
type authParams struct {
GetSecureURL int `url:"get_secure_url,omitempty"`
ClientID string `url:"client_id,omitempty"`
ClientSecret string `url:"client_secret,omitempty"`
GrantType string `url:"grant_type,omitempty"`
Username string `url:"username,omitempty"`
Password string `url:"password,omitempty"`
RefreshToken string `url:"refresh_token,omitempty"`
}
type loginResponse struct {
Response *authInfo `json:"response"`
}
type loginError struct {
HasError bool `json:"has_error"`
Errors map[string]Perror `json:"errors"`
}
type Perror struct {
Message string `json:"message"`
Code int `json:"code"`
}
func genClientHash(clientTime string) string {
h := md5.New()
io.WriteString(h, clientTime)
io.WriteString(h, clientHashSecret)
return hex.EncodeToString(h.Sum(nil))
}
func auth(params *authParams) (*authInfo, error) {
clientTime := time.Now().Format(time.RFC3339)
s := sling.New().Base("https://oauth.secure.pixiv.net/").Set("User-Agent", "PixivAndroidApp/5.0.115 (Android 6.0)").Set("X-Client-Time", clientTime).Set("X-Client-Hash", genClientHash(clientTime))
res := &loginResponse{
Response: &authInfo{
User: &Account{},
},
}
loginErr := &loginError{
Errors: map[string]Perror{},
}
_, err := s.New().Post("auth/token").BodyForm(params).Receive(res, loginErr)
if err != nil {
return nil, errors.Wrap(err, "auth request failed")
}
if loginErr.HasError {
for k, v := range loginErr.Errors {
return nil, fmt.Errorf("Login %s error: %s", k, v.Message)
}
}
_token = res.Response.AccessToken
_refreshToken = res.Response.RefreshToken
_tokenDeadline = time.Now().Add(time.Duration(res.Response.ExpiresIn) * time.Second)
if authHook != nil {
err = authHook(_token, _refreshToken, _tokenDeadline)
}
return res.Response, err
}
// HookAuth add a hook with (token, refreshToken, tokenDeadline) after a successful auth.
// Prividing a way to store the latest token.
func HookAuth(f func(string, string, time.Time) error) {
authHook = f
}
func Login(username, password string) (*Account, error) {
params := &authParams{
GetSecureURL: 1,
ClientID: clientID,
ClientSecret: clientSecret,
GrantType: "password",
Username: username,
Password: password,
}
a, err := auth(params)
if err != nil {
return nil, errors.Wrap(err, "login failed")
}
return a.User, nil
}
func LoadAuth(token, refreshToken string, tokenDeadline time.Time) (*Account, error) {
_token = token
_refreshToken = refreshToken
_tokenDeadline = tokenDeadline
return refreshAuth(true)
}
func refreshAuth(force bool) (*Account, error) {
if !force && time.Now().Before(_tokenDeadline) {
return nil, nil
}
if _refreshToken == "" {
return nil, fmt.Errorf("missing refresh token")
}
params := &authParams{
GetSecureURL: 1,
ClientID: clientID,
ClientSecret: clientSecret,
GrantType: "refresh_token",
RefreshToken: _refreshToken,
}
a, err := auth(params)
if err != nil {
return nil, errors.Wrap(err, "refresh token")
}
return a.User, nil
}
// download image to file (use 6.0 app-api)
func download(client *http.Client, url, path, name, tmpdir string, replace bool) (int64, error) {
if path == "" {
return 0, fmt.Errorf("download path needed")
}
if name == "" {
name = filepath.Base(url)
}
fullPath := filepath.Join(path, name)
if !replace {
if _, err := os.Stat(fullPath); err == nil {
return 0, nil
}
}
tmpFile, err := os.CreateTemp(tmpdir, "pixiv-*")
if err != nil {
return 0, errors.Wrap(err, "create temp file failed")
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 0, errors.Wrap(err, "create request failed")
}
req.Header.Add("Referer", apiBase)
resp, err := client.Do(req)
if err != nil {
return 0, errors.Wrap(err, "request failed")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("download failed: %s", resp.Status)
}
n, err := io.Copy(tmpFile, resp.Body)
if err != nil {
return 0, errors.Wrap(err, "download failed")
}
err = tmpFile.Close()
if err != nil {
return 0, errors.Wrap(err, "close temp file failed")
}
err = os.Rename(tmpFile.Name(), fullPath)
if err != nil {
return 0, errors.Wrap(err, "rename temp file failed")
}
return n, nil
}