-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAPI.ts
More file actions
150 lines (140 loc) · 5.97 KB
/
API.ts
File metadata and controls
150 lines (140 loc) · 5.97 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
import {ParsedUrlQueryInput, stringify} from "querystring"
import {URLSearchParams} from "url"
import {PixivAPIResponse} from "./types/ApiTypes"
import {PixivAuthData, PixivAuthHeaders, PixivParams, PixivWebParams} from "./types/index"
import * as crypto from "crypto"
const oauthURL = "https://oauth.secure.pixiv.net/auth/token"
const appURL = "https://app-api.pixiv.net/"
const webURL = "https://www.pixiv.net/"
const hashSecret = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"
export default class API {
private readonly headers = {"user-agent": "PixivIOSApp/7.7.5 (iOS 13.2.0; iPhone XR)", "referer": "https://www.pixiv.net/", "accept-language": "English"}
public constructor(private readonly data: PixivAuthData,
private readonly authHeaders: PixivAuthHeaders,
public refreshToken: string,
public accessToken: string,
private readonly loginTime: number,
private readonly expirationTime: number) {}
/**
* Gets a new access token if the refresh token expires.
*/
public refreshAccessToken = async (refreshToken?: string) => {
if (refreshToken) this.refreshToken = refreshToken
const expired = (Date.now() - this.loginTime) > (this.expirationTime * 900)
if (expired) {
this.data.grant_type = "refresh_token"
const clientTime = new Date().toISOString().slice(0, -5) + "+00:00"
const clientHash = crypto.createHash("md5").update(String(clientTime + hashSecret)).digest("hex")
this.authHeaders["x-client-time"] = clientTime
this.authHeaders["x-client-hash"] = clientHash
const result = await fetch(oauthURL, {method: "POST",
body: stringify(this.data as unknown as ParsedUrlQueryInput),
headers: this.authHeaders as any
}).then((r) => r.json()) as PixivAPIResponse
this.accessToken = result.response.access_token
this.refreshToken = result.response.refresh_token
this.authHeaders.authorization = `Bearer ${this.accessToken}`
}
return this.refreshToken
}
/**
* Fetches an endpoint from the API and returns the response.
*/
public get = async (endpoint: string, params?: PixivParams) => {
await this.refreshAccessToken()
if (!params) params = {}
params.filter = "for_ios"
let headersWithAuth = Object.assign(this.headers, {
authorization: `Bearer ${this.accessToken}`
})
if (endpoint.startsWith("/")) endpoint = endpoint.slice(1)
const url = new URL(appURL + endpoint)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
}
const response = await fetch(url.toString(), {headers: headersWithAuth}).then((r) => r.json())
return response
}
/**
* Post with the API and returns the response.
*/
public post = async (endpoint: string, params?: PixivParams) => {
await this.refreshAccessToken()
if (!params) params = {}
if (endpoint.startsWith("/")) endpoint = endpoint.slice(1)
const url = appURL + endpoint
const response = await fetch(url, {method: "POST",
headers: {Authorization:this.authHeaders.authorization,...this.headers},
body: stringify(params as any)
}).then((r) => r.json())
return response
}
/**
* Fetches from web url and returns the response.
*/
public getWeb = async (endpoint: string, params?: PixivWebParams) => {
if (endpoint.startsWith("/")) endpoint = endpoint.slice(1)
const url = new URL(webURL + endpoint)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
}
const response = await fetch(url.toString(), {headers: this.headers}).then((r) => r.json())
return response as Promise<any>
}
/**
* Fetches the url in the nextUrl() property of search responses.
*/
public next = async (nextUrl: string) => {
await this.refreshAccessToken()
const {baseUrl, params} = this.destructureParams(nextUrl)
let headersWithAuth = Object.assign(this.headers, {
authorization: `Bearer ${this.accessToken}`
})
const url = new URL(baseUrl)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
}
const response = await fetch(url.toString(), { headers: headersWithAuth}).then((r) => r.json())
return response
}
/**
* Destructures a URL to get all of the search parameters and values.
*/
public destructureParams = (nextUrl: string) => {
const paramUrl = nextUrl.split("?")
const baseUrl = paramUrl[0]
paramUrl.shift()
const searchParams = new URLSearchParams(paramUrl.join(""))
const params: PixivParams = {}
for (const [key, value] of searchParams) {
params[key] = value
}
return {baseUrl, params}
}
/**
* Fetches any url.
*/
public request = async (baseUrl: string, params?: any) => {
const url = new URL(baseUrl)
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
}
return fetch(url.toString(), params).then((r) => r.json())
}
}