-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
503 lines (468 loc) · 14.8 KB
/
index.js
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
const QS = require('querystring')
const {URL} = require('url')
const https = require('https')
const Events = require('events')
const Hosts = require('./hosts.js')
const searchData = require('./search')
const BASE_URL = 'https://app-api.pixiv.net'
const CLIENT_ID = 'KzEZED7aC0vird8jWyHM38mXjNTY'
const CLIENT_SECRET = 'W9JZoJe00qPvJsiyCGT3CCtC6ZUtdpKpzMbNlUGP'
function catcher(error) {
if (error.response) {
throw error.response.data
} else {
throw error.message
}
}
function toKebab(source) {
if (typeof source === 'string') {
return source.replace(/-/g, '_')
.replace(/[A-Z]/g, char => '_' + char.toLowerCase())
} else {
const result = {}
for (const key in source) {
result[toKebab(key)] = toKebab(source[key])
}
return result
}
}
function _wrap(source) {
if (!(source instanceof Promise)) return source
return new Proxy(source, {
get(target, property) {
if (property in Promise.prototype) {
return (...args) => {
return _wrap(target[property].apply(target, args))
}
} else {
return (...args) => _wrap(target.then((result) => {
return result[property](...args)
}))
}
}
})
}
const AsyncWrapper = new Proxy(Promise, {
construct: (_, args) => _wrap(new Promise(...args)),
get: (target, property) => _wrap(target[property])
})
const supportedLanguages = ['zh', 'zh-TW', 'en', 'ja']
class PixivAPI {
constructor({
hosts = Hosts.default,
allowCache = true,
timeout = 20000,
language = 'en-US',
} = {}) {
/** Host map */
this.hosts = new Hosts(hosts)
/** Default headers */
this.headers = {
'App-OS': 'ios',
'App-OS-Version': '9.3.3',
'App-Version': '7.1.11',
'User-Agent': 'PixivIOSApp/7.1.11 (iOS 9.0; iPhone8,2)',
}
/** Whether to allow cache */
this.allowCache = allowCache
/** Socket timeout */
this.timeout = timeout
/** Set language */
this.language = language
/** Event emitter */
this.events = new Events()
}
get user() {
return Object.assign({}, this.auth.user)
}
get language() {
return this.headers['Accept-Language']
}
set language(value) {
this.headers['Accept-Language'] = value
}
authorize(auth) {
if (!auth) return
this.auth = auth
this.headers.Authorization = `Bearer ${auth.access_token}`
}
on(event, listener) {
this.events.on(event, listener)
}
once(event, listener) {
this.events.once(event, listener)
}
/**
* @private Request without authorization
* @param {string|URL} url URL
* @param {string} method Method
* @param {object} headers Headers
* @param {string|object} postdata Data
**/
request({url, method, headers, postdata}) {
if (!(url instanceof URL)) {
url = new URL(url, BASE_URL)
}
return new AsyncWrapper((resolve, reject) => {
let data = ''
const request = https.request({
method: method || 'GET',
headers: Object.assign({
Host: url.hostname
}, this.headers, headers),
hostname: this.hosts.getHostName(url.hostname),
servername: url.hostname,
path: url.pathname + url.search,
}, (response) => {
response.on('data', chunk => data += chunk)
response.on('end', () => {
try {
return resolve(JSON.parse(data))
} catch (err) {
return reject(new Error(`An error is encounted in ${data}\n${err}`))
}
})
})
request.on('error', error => reject(error))
if (postdata instanceof Object) {
request.write(QS.stringify(postdata))
} else if (typeof postdata === 'string') {
request.write(postdata)
}
request.end()
setTimeout(() => {
request.abort()
}, this.timeout)
}).then((result) => {
if (result.error) {
throw result.error
} else {
return result
}
})
}
/**
* Log in your pixiv account
* @param {string} username User Name
* @param {string} password Password
* @param {boolean} remember Whether to remember password
*/
login(username, password, remember = true) {
if (!username) return AsyncWrapper.reject(new TypeError('username required'))
if (!password) return AsyncWrapper.reject(new TypeError('password required'))
return this.request({
url: 'https://oauth.secure.pixiv.net/auth/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
postdata: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
get_secure_url: 1,
grant_type: 'password',
username,
password,
}
}).then((data) => {
if (data.response) {
this.events.emit('auth', data.response)
/** Authorization Information */
this.authorize(data.response)
/** Whether to remember password */
this.remember = !!remember
if (remember) {
/** User name */
this.username = username
/** Password */
this.password = password
}
return data.response
} else if (data.has_error) {
throw data.errors.system
} else {
console.error('An unknown error was encounted.')
throw data
}
}).catch(catcher)
}
/** Log out your pixiv account */
logout() {
this.auth = null
this.username = null
this.password = null
this._user_state = null
delete this.headers.Authorization
}
/** Refresh access token (authorization required) */
refreshAccessToken() {
if (!this.auth) return AsyncWrapper.reject(new Error('Authorization required'))
return this.request({
url: 'https://oauth.secure.pixiv.net/auth/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
postdata: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
get_secure_url: 1,
grant_type: 'refresh_token',
refresh_token: this.auth.refresh_token,
}
}).then((data) => {
this.authorize(data.response)
this.events.emit('auth', data.response)
return data.response
}).catch(catcher)
}
/**
* Create provisional account
* @param {string} nickname Nickname
*/
createProvisionalAccount(nickname) {
if (!nickname) return AsyncWrapper.reject(new TypeError('nickname required'))
return this.request({
url: 'https://accounts.pixiv.net/api/provisional-accounts/create',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer WHDWCGnwWA2C8PRfQSdXJxjXp0G6ULRaRkkd6t5B6h8',
},
postdata: {
ref: 'pixiv_ios_app_provisional_account',
user_name: nickname,
}
}).then(data => data.body).catch(catcher)
}
/**
* @private Request with authorization
* @param {URL} url URL
* @param {object} options Options
* @param {string} options.method Method
* @param {object} options.headers Headers
* @param {object} options.postdata Postdata
*/
authRequest(url, options = {}, callback = arg => arg) {
if (!url) return AsyncWrapper.reject(new TypeError('Url cannot be empty'))
if (!this.auth) return AsyncWrapper.reject(new Error('Authorization required'))
options.url = url
options.headers = options.headers || {}
return this.request(options).then(
result => callback(result, this),
error => this.refreshAccessToken().then(() => {
return this.request(options).then(result => callback(result, this))
})
)
}
/**
* @private Post request with authorization
* @param {URL} url URL
* @param {string|object} postdata Postdata
*/
postRequest(url, postdata) {
return this.authRequest(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
postdata
})
}
/** Get pixiv user state (authorization required) */
userState() {
if (this.allowCache && this._user_state) {
return AsyncWrapper.resolve(this._user_state)
}
return this.authRequest('/v1/user/me/state').then((data) => {
if (data.user_state) {
this._user_state = data.user_state
return data.user_state
} else {
throw data
}
})
}
/**
* Edit user account (authorization required)
* @param {object} info Information
* @param {string} info.password Current password
* @param {string} info.pixivId New pixiv account
* @param {string} info.newPassword New password
* @param {string} info.email New mail address
*/
editUserAccount(info) {
if (!info) return AsyncWrapper.reject(new TypeError('info required'))
const postdata = {}
if (info.password) postdata.current_password = info.password
if (info.pixivId) postdata.new_user_account = info.pixivId
if (info.newPassword) postdata.new_password = info.newPassword
if (info.email) postdata.new_mail_address = info.email
return this.postRequest('https://accounts.pixiv.net/api/account/edit', postdata)
}
/** Send account verification email (authorization required) */
sendAccountVerificationEmail() {
return this.postRequest('/v1/mail-authentication/send')
}
/**
* @private Search (authorization required)
* @param {string} category Search category
* @param {string} key Search key
* @param {string} type Search type
* @param {object} options Search options
* @param {Function} callback Callback
*/
search(category, key, type, options, callback) {
if (!searchData[category][type]) {
return AsyncWrapper.reject(new RangeError(`"${type}" is not a supported type.`))
} else {
const search = searchData[category][type]
const query = {filter: 'for_ios'}
if (searchData[category]._key) {
if (!key) return AsyncWrapper.reject(new TypeError('key required'))
query[searchData[category]._key] = key
}
if (search.options instanceof Function) {
Object.assign(query, search.options.call(this))
} else if (search.options instanceof Object) {
Object.assign(query, search.options)
}
return this.authRequest(`${search.url}?${
QS.stringify(Object.assign(query, toKebab(options)))
}`, {}, callback || search.then)
}
}
/**
* Search by word (authorization required)
* @param {string} word Search keyword
* @param {string} type Search type
* @param {object} options Search options
*
* - Supported types: `illust`, `illustPopularPreview`, `illustBookmarkRanges`,
* `novel`, `novelPopularPreview`, `novelBookmarkRanges`, `user`, `autoComplete`.
* - Supported options: `searchTarget`, `sort`.
* - Supported search target: `partialMatchForTags`, `exactMatchForTags`, `titleAndCaption`.
* - Supported sorting method: `dateDesc`, `dateAsc`,
* `popularDesc`(only available for pixiv premium member).
*
* All options can be in either kebab-cases or snake-cases.
*/
searchWord(word, type, options = {}) {
return this.search('word', word, type, options)
}
/**
* Search by user (authorization required)
* @param {number} id User id
* @param {string} type Search type
* @param {object} options Search options
*
* - Supported types: `detail`(default), `myPixiv`,
* `illusts`, `bookmarkIllusts`, `bookmarkIllustTags`,
* `novels`, `bookmarkNovels`, `bookmarkNovelTags`,
* `following`, `follower`, `followDetail`.
* - Supported options: `restrict`.
* - Supported restrictions: `all`, `public`, `private`.
*
* All options can be in either kebab-cases or snake-cases.
*/
searchUser(id, type, options = {}) {
return this.search('user', id, type, options)
}
/**
* Search by illustration (authorization required)
* @param {number} id Illustration id
* @param {string} type Search type
*
* - Supported types: `detail`(default), `bookmarkDetail`,
* `comments`, `related`, `metadata`.
*/
searchIllust(id, type = 'detail') {
return this.search('illust', id, type)
}
/**
* Search by novel (authorization required)
* @param {number} id Novel id
* @param {string} type Search type
*
* - Supported types: `detail`(default), `text`, `bookmarkDetail`, `comments`.
*/
searchNovel(id, type = 'detail') {
return this.search('novel', id, type)
}
/**
* Search by comment (authorization required)
* @param {number} id Comment id
* @param {string} type Search type
*
* - Supported types: `replies`(default).
*/
searchComment(id, type = 'replies') {
return this.search('comment', id, type)
}
/**
* Search by series (authorization required)
* @param {number} id Series id
* @param {string} type Search type
*
* - Supported types: `detail`(default).
*/
searchSeries(id, type = 'detail') {
return this.search('series', id, type)
}
/**
* Get users
* @param {string} type Search type
*
* - Supported types: `recommended`(default), `new`.
*/
getUsers(type = 'recommended', options = {}) {
return this.search('get_users', null, type, options)
}
/**
* Get illustrations
* @param {string} type Illustration type
* @param {object} options Search options
*
* - Supported types: `recommended`(default), `new`, `follow`,
* `walkthrough`, `ranking`, `myPixiv`, `trendingTags`.
* - Supported options: `restrict`, `mode`.
* - Supported restrictions: `all`, `public`, `private`.
* - Supported modes: `day`, `week`, `month`, `day_male`, `day_female`,
* `week_original`, `week_rookie`, `day_r18`, `day_male_r18`, `day_female_r18`,
* `week_r18`, `week_r18g`, `day_manga`, `week_manga`, `month_manga`,
* `week_rookie_manga`, `day_r18_manga`, `week_r18_manga`, `week_r18g_manga`.
*
* All options can be in either kebab-cases or snake-cases.
*/
getIllusts(type = 'recommended', options = {}) {
return this.search('get_illusts', null, type, options)
}
/**
* Get novels
* @param {string} type Novel type
* @param {object} options Search options
*
* - Supported types: `recommended`(default), `new`, `follow`,
* `ranking`, `myPixiv`, `trendingTags`.
* - Supported options: `mode`.
* - Supported modes: `day`, `week`, `month`, `day_male`, `day_female`,
* `week_original`, `week_rookie`, `day_r18`, `day_male_r18`, `day_female_r18`,
* `week_r18`, `week_r18g`, `day_manga`, `week_manga`, `month_manga`,
* `week_rookie_manga`, `day_r18_manga`, `week_r18_manga`, `week_r18g_manga`.
*
* All options can be in either kebab-cases or snake-cases.
*/
getNovels(type = 'recommended', options = {}) {
return this.search('get_novels', null, type, options)
}
/**
* Get mangas
* @param {string} type Search type
*
* - Supported types: `recommended`(default), `new`.
*/
getMangas(type = 'recommended') {
return this.search('get_mangas', null, type)
}
}
module.exports = PixivAPI