-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
141 lines (127 loc) · 3.95 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
const fs = require("fs");
const util = require("util");
const fetch = require("node-fetch");
const fsWriteFile = util.promisify(fs.writeFile);
const sessionFileLocation = "./twitch-session.json";
let twitchSession = {};
async function createSessionFile() {
try {
const sessionFile = fs.readFileSync(sessionFileLocation, "utf8");
session = JSON.parse(sessionFile);
} catch (err) {
console.debug("Session file doesn't exist. Creating...");
try {
await fsWriteFile(sessionFileLocation, JSON.stringify({ twitch: {} }));
} catch (err) {
throw new Error("Failed to create twitch-session.json file");
}
console.debug("Created new session.json file!");
}
}
async function twitchAuthCode(settings) {
const { clientId, clientSecret, scope } = settings;
const readlineSync = require("readline-sync");
const scopeStr = scope ? `&scope=${scope}` : "";
const url = `https://id.twitch.tv/oauth2/authorize?client_id=${clientId}&client_secret=${clientSecret}&response_type=code&redirect_uri=${redirectUri}${scopeStr}`;
console.log(url);
let authCode = readlineSync.question("Enter your authorization code: ");
return authCode;
}
async function twitchAuthToken(settings, code) {
const url = "https://id.twitch.tv/oauth2/token";
const options = {
method: "POST",
json: true,
};
let params = {
client_id: settings.clientId,
client_secret: settings.clientSecret,
};
if (code) {
console.debug("Getting a new Twitch token");
params = {
...params,
code,
grant_type: "authorization_code",
redirect_uri: settings.redirectUri,
};
} else if (twitchSession.refreshToken) {
console.debug("Refreshing Twitch token");
params = {
...params,
grant_type: "refresh_token",
refresh_token: twitchSession.refreshToken,
};
} else {
throw new Error("Either auth code or refresh token are needed");
}
params = new URLSearchParams(params);
const res = await fetch(`${url}?${params}`, options);
if (res.ok) {
return res.json();
} else {
throw new Error(res.statusText);
}
}
async function updateSessionStorage(newSession) {
try {
await fsWriteFile(sessionFileLocation, JSON.stringify(newSession));
console.debug("Successfully updated session!");
} catch (err) {
console.error("ERR updateSessionStorage:", err);
}
twitchSession = newSession;
return newSession;
}
async function refreshTwitchToken(settings) {
let authCode = undefined;
if (!twitchSession.refreshToken) {
authCode = await twitchAuthCode(settings);
}
// Update the twitch portion of our sessions storage
const response = await twitchAuthToken(settings, authCode);
console.debug("New Twitch Auth token gotten!", response);
const newSession = {
clientId: settings.clientId,
accessToken: response.access_token,
refreshToken: response.refresh_token,
expires: new Date(new Date().getTime() + response.expires_in * 1000),
};
return newSession;
}
async function getTwitchSession(settings, forceRefresh = false) {
settings.redirectUri = settings.redirectUri
? settings.redirectUri
: "http://localhost";
const { clientId } = settings;
twitchSession = {
clientId,
...twitchSession,
};
try {
const sessionFile = fs.readFileSync(sessionFileLocation, "utf8");
twitchSession = JSON.parse(sessionFile);
} catch (err) {
await createSessionFile();
}
// Loads a default session storage
let currentSession = {
clientId: clientId || twitchSession.clientId,
accessToken: "",
expires: undefined,
...twitchSession,
};
// check if twitch token is valid
if (
forceRefresh ||
!currentSession.accessToken ||
!currentSession.expires ||
new Date(currentSession.expires) <=
new Date(new Date().getTime() + 5 * 60000)
) {
const newSession = await refreshTwitchToken(settings);
currentSession = await updateSessionStorage(newSession);
}
return currentSession;
}
module.exports = getTwitchSession;