-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitchApi.js
225 lines (214 loc) · 6.7 KB
/
twitchApi.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
import * as fs from "fs";
const VALIDATE_ENDPOINT = "https://id.twitch.tv/oauth2/validate";
const SCOPES = encodeURIComponent(["moderator:read:followers"].join(" "));
var tokens = {
access_token: null,
refresh_token: null,
device_code: null,
user_code: null,
verification_uri: null,
};
async function handleDcfLogin(loopCallback) {
if (fs.existsSync("./.tokens.json")) {
tokens = JSON.parse(
fs.readFileSync("./.tokens.json", { encoding: "utf8", flag: "r" }),
);
let validated = await validate();
if (validated) {
console.log("Validated Tokens and started polling loop");
await loopCallback();
return;
}
}
let dcf = await fetch(
`https://id.twitch.tv/oauth2/device?client_id=${process.env.TWITCH_CLIENT_ID}&scopes=${SCOPES}`,
{
method: "POST",
},
);
if (dcf.status >= 200 && dcf.status < 300) {
// Successfully got DCF data
let dcfJson = await dcf.json();
tokens.device_code = dcfJson.device_code;
tokens.user_code = dcfJson.user_code;
tokens.verification_uri = dcfJson.verification_uri;
console.log(
`Open ${tokens.verification_uri} in a browser and enter ${tokens.user_code} there!`,
);
}
let dcf_interval = setInterval(async () => {
let tokenPair = await fetch(
`https://id.twitch.tv/oauth2/token?client_id=${process.env.TWITCH_CLIENT_ID}&scopes=${SCOPES}&device_code=${tokens.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`,
{
method: "POST",
},
);
if (tokenPair.status == 400) return; // Probably authorization pending
if (tokenPair.status >= 200 && tokenPair.status < 300) {
// Successfully got token pair
let tokenJson = await tokenPair.json();
tokens.access_token = tokenJson.access_token;
tokens.refresh_token = tokenJson.refresh_token;
fs.writeFileSync("./.tokens.json", JSON.stringify(tokens));
clearInterval(dcf_interval);
console.log("Got Device Code Flow Tokens and started polling loop");
await loopCallback();
}
}, 1000);
}
function getStatusResponse(res, json) {
switch (res.status) {
case 400:
return `Bad Request: ${json.message}`;
case 401:
return `Unauthorized: ${json.message}`;
case 404:
return `Not Found: ${json.message}`;
case 429:
return `Too Many Requests: ${json.message}`;
case 500:
return `Internal Server Error: ${json.message}`;
default:
return `${json.error} (${res.status}): ${json.message}`;
}
}
async function getUser(url) {
return (
await fetch(url, {
headers: {
"Client-ID": process.env.TWITCH_CLIENT_ID,
Authorization: `Bearer ${tokens.access_token}`,
},
})
.then((res) => res.json())
.catch((err) => console.error)
).data[0];
}
async function getUserByLogin(login) {
if (login) {
return getUser(`https://api.twitch.tv/helix/users?login=${login}`);
} else {
return getUser(`https://api.twitch.tv/helix/users`);
}
}
async function getUserById(id) {
if (id) {
return getUser(`https://api.twitch.tv/helix/users?id=${id}`);
} else {
return getUser(`https://api.twitch.tv/helix/users`);
}
}
// https://dev.twitch.tv/docs/api/reference/#get-channel-followers
async function getChannelFollowers(broadcasterId, paginationCursor = null) {
let apiUrl;
if (paginationCursor) {
apiUrl = `https://api.twitch.tv/helix/channels/followers?broadcaster_id=${broadcasterId}&first=100&after=${paginationCursor}`;
} else {
apiUrl = `https://api.twitch.tv/helix/channels/followers?broadcaster_id=${broadcasterId}&first=100`;
}
const res = await fetch(apiUrl, {
method: "GET",
headers: {
"Client-ID": process.env.TWITCH_CLIENT_ID,
Authorization: `Bearer ${tokens.access_token}`,
"Content-Type": "application/json",
},
});
const json = await res.json();
if (res.status == 401) {
console.log("Status 401");
let refreshed = await refresh();
if (!refreshed) throw new Error("Token refresh failed");
return await getChannelFollowers(broadcasterId, paginationCursor);
}
if (!res.ok) {
console.log("!res.ok: " + res.status);
throw new Error(getStatusResponse(res, json));
}
if (json.error) {
throw new Error(`Error: ${json.error}\nError-Message: ${json.message}`);
} else {
let result = {
total: json.total,
followers: [],
};
if (json.data) {
result.followers = json.data;
}
let pagination = json.pagination;
if (pagination.cursor) {
let followers = await getChannelFollowers(
broadcasterId,
pagination.cursor,
);
if (followers.followers) {
for (let follower of followers.followers) {
result.followers.push(follower);
}
}
}
return result;
}
}
async function refresh() {
console.log("Refreshing tokens...");
let refreshResult = await fetch(
`https://id.twitch.tv/oauth2/token?grant_type=refresh_token&refresh_token=${encodeURIComponent(
tokens.refresh_token,
)}&client_id=${process.env.TWITCH_CLIENT_ID}&client_secret=${
process.env.TWITCH_CLIENT_SECRET
}`,
{
method: "POST",
headers: {
"Client-ID": process.env.TWITCH_CLIENT_ID,
Authorization: `Bearer ${tokens.access_token}`,
},
},
);
let refreshJson = await refreshResult.json();
if (refreshResult.status >= 200 && refreshResult.status < 300) {
// Successfully refreshed
tokens.access_token = refreshJson.access_token;
tokens.refresh_token = refreshJson.refresh_token;
fs.writeFileSync("./.tokens.json", JSON.stringify(tokens));
console.log("Successfully refreshed tokens!");
return true;
} else {
// Refreshing failed
console.log(`Failed refreshing tokens: ${JSON.stringify(refreshJson)}`);
return false;
}
}
async function validate() {
tokens = JSON.parse(
fs.readFileSync(".tokens.json", { encoding: "utf8", flag: "r" }),
);
return await fetch("https://id.twitch.tv/oauth2/validate", {
method: "GET",
headers: {
"Client-ID": process.env.TWITCH_CLIENT_ID,
Authorization: `Bearer ${tokens.access_token}`,
},
}).then(async (res) => {
if (res.status) {
if (res.status == 401) {
return await refresh();
} else if (res.status >= 200 && res.status < 300) {
console.log("Successfully validated tokens!");
return true;
} else {
console.error(
`Unhandled validation error: ${JSON.stringify(await res.json())}`,
);
return false;
}
} else {
console.error(
`Unhandled network error! res.status is undefined or null! ${res}`,
);
return false;
}
});
}
export { handleDcfLogin, getUserByLogin, getUserById, getChannelFollowers };