-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
199 lines (161 loc) · 4.75 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
const readline = require("readline");
const util = require("util");
const path = require("path");
const fs = require("fs");
const axios = require("axios").default;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const question = util.promisify(rl.question).bind(rl);
let ACCESS_TOKEN;
// INITIALIZATION FUNC
(async function init() {
console.log(`>>> Hello 😃, This script will let you download all clips
of any number of streamers that are recorded in the last 24 hours
just by giving the names of the streamers!`);
const answer = await question(
">>> So, pls write the username of the streamers you want to get their clips: \n"
);
ACCESS_TOKEN = await getAccessToken();
const streamersArr = answer.toLowerCase().split(" ");
const clipsDataArr = [];
for (let i = 0; i < streamersArr.length; i++) {
const streamer = streamersArr[i];
const clipsData = await getClipsData(streamer);
if (clipsData && clipsData.length) {
clipsDataArr.push([streamer, clipsData]);
}
}
let clipsDir = path.resolve(__dirname, "twitchClips");
if (!fs.existsSync(clipsDir)) {
fs.mkdirSync(clipsDir);
}
for (let i = 0; i < clipsDataArr.length; i++) {
const currClipsData = clipsDataArr[i];
if (currClipsData[1].length) {
console.log(`⌛ Downloading ${currClipsData[0]}'s clips... ⌛`);
await downloadClips(currClipsData[0], currClipsData[1]);
console.log("✅ Done ✅");
}
}
rl.close();
})();
// Get Access Token Func
async function getAccessToken() {
const { data } = await axios({
method: "POST",
url: "https://id.twitch.tv/oauth2/token",
params: {
client_id: "d8w5m3clso0jswub03e47q1ptb77w1",
client_secret: "ohy64p1x9pq2sxsja6klpv6nd44n6m",
grant_type: "client_credentials",
},
});
return data.access_token;
}
// Get Streamer Id Func
async function getStreamerId(streamer) {
const { data } = await axios({
method: "GET",
url: "https://api.twitch.tv/helix/users",
params: {
login: streamer,
},
headers: {
"Client-Id": "d8w5m3clso0jswub03e47q1ptb77w1",
Authorization: `Bearer ${ACCESS_TOKEN}`,
},
});
return data.data[0]?.id;
}
// Get Clips Data Func
async function getClipsData(streamer) {
console.log(`⌛ Getting ${streamer}'s id... ⌛`);
const streamerId = await getStreamerId(streamer);
if (!streamerId) {
console.log(`❌ No streamer id was found for ${streamer} ❌`);
return;
}
console.log("✅ Done ✅");
console.log(`⌛ Getting ${streamer}'s clips data... ⌛`);
const { data } = await axios({
method: "GET",
url: "https://api.twitch.tv/helix/clips",
params: {
broadcaster_id: streamerId,
first: 100,
started_at: new Date(
new Date().getTime() - 24 * 60 * 60 * 1000
).toISOString(),
ended_at: new Date().toISOString(),
},
headers: {
"Client-Id": "d8w5m3clso0jswub03e47q1ptb77w1",
Authorization: `Bearer ${ACCESS_TOKEN}`,
},
});
if (!data.data.length) {
console.log(`❌ No clip was found for ${streamer} in the last 24 hours ❌`);
} else {
console.log("✅ Done ✅");
}
return data.data;
}
// Download Clips Func
async function downloadClips(folderName, clipsData) {
const parentDir = path.resolve(__dirname, "twitchClips", folderName);
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir);
}
for (let i = 0; i < clipsData.length; i++) {
const clip = clipsData[i];
const savePath = path.resolve(parentDir, `${clip.id}.mp4`);
if (fs.existsSync(savePath)) {
continue;
}
const cutIndex = clip.thumbnail_url.indexOf("-preview");
const downloadUrl = `${clip.thumbnail_url.substring(0, cutIndex)}.mp4`;
const res = await axios({
method: "GET",
url: downloadUrl,
responseType: "stream",
});
res.data.pipe(fs.createWriteStream(savePath));
await new Promise((resolve, reject) => {
res.data.on("end", () => {
resolve();
});
res.data.on("error", (err) => {
reject(err);
});
});
}
}
// Interface Close Event Handler
rl.on("close", () => {
console.log(">>> The script is terminated; Good bye!");
});
// Interface SIGINT Event Handler
rl.on("SIGINT", () => {
rl.question(
">>> Are you sure you want to exit? (Type yes to exit) ",
(answer) => {
if (answer.match(/^y(es)?$/i)) {
rl.pause();
process.exit();
}
}
);
});
// Internal Errors Handling
const UNKOWN_ERROR = `>>> Something went wrong ☹! Pls check your connection
or contact the developer;`;
process.on("unhandledRejection", (_) => {
console.log(UNKOWN_ERROR);
process.exit(1);
});
process.on("uncaughtException", (_) => {
console.log(UNKOWN_ERROR);
process.exit(1);
});