-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreams.class.js
219 lines (176 loc) · 6.87 KB
/
Streams.class.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
require('dotenv').config();
const axios = require('axios');
const colors = require('colors');
class Streams {
constructor() {
this.streams = [];
this.gamesList = [];
this.fetchStreams = [];
this.fetchStreamsIDs = [];
this.fetchEvery = 60 * 1000;
this.bearer = '';
this.canFetch = true;
axios.post(`https://id.twitch.tv/oauth2/token?client_id=${process.env.TWITCH_CLIENT_ID}&client_secret=${process.env.TWITCH_CLIENT_SECRET}&grant_type=client_credentials`)
.then(({data}) => {
this.bearer = data.access_token;
this.startFetchStreams();
setTimeout(() => this.refreshToken(), (data.expires_in * 60));
});
this.events = {
'fetchFinished': () => ({}),
};
}
refreshToken() {
axios.post(`https://id.twitch.tv/oauth2/token?client_id=${process.env.TWITCH_CLIENT_ID}&client_secret=${process.env.TWITCH_CLIENT_SECRET}&grant_type=client_credentials`)
.then(({data}) => {
this.bearer = data.access_token;
setTimeout(() => this.refreshToken(), (data.expires_in * 60));
});
}
/// GETTER FUNCTIONS
pickRandomStream(games) {
if (!games || games.length < 1) return this.streams[Math.floor(Math.random() * this.streams.length)];
else {
let selectedStreams = this.streams.filter(s => games.includes(parseInt(s.game_id)));
return selectedStreams[Math.floor(Math.random() * selectedStreams.length)];
}
}
getStreamsCount(games) {
if (!games || games.length < 1) return this.streams.length;
else {
return this.streams.filter(s => games.includes(parseInt(s.game_id))).length;
}
}
getTotalViewersCount() {
let viewersCount = 0;
this.streams.forEach(s => viewersCount += s.viewer_count);
return viewersCount;
}
getTop10ViewerCount() {
let viewersCount = 0;
this.streams.slice(0, 9).forEach(s => viewersCount += s.viewer_count);
return viewersCount;
}
streamsCount() {
return this.streams.length;
}
getGames() {
return this.gamesList;
}
/// EVENT FUNCTIONS
onFetchFinished(event) {
this.events.fetchFinished = event;
}
/// FETCHING FUNCTIONS
startFetchStreams() {
if (this.canFetch) {
this.canFetch = false;
console.log('NEXT FETCH'.yellow, (new Date(Date.now() + this.fetchEvery)).toLocaleTimeString('fr-FR').magenta);
this.startGetStreams();
}
setTimeout(() => {
this.startFetchStreams();
}, this.fetchEvery);
}
tryAddStream(stream) {
if (!this.fetchStreamsIDs.includes(stream.id) && stream.type === 'live') {
this.fetchStreams.push(stream);
this.fetchStreamsIDs.push(stream.id);
}
}
startGetStreams() {
console.log('FETCHING STREAMS'.cyan);
this.fetchStreams = [];
this.fetchStreamsIDs = [];
axios.get('https://api.twitch.tv/helix/streams?language=fr&first=100', {
headers: {
'Client-ID': process.env.TWITCH_CLIENT_ID,
'Authorization': `Bearer ${this.bearer}`,
},
}).then(r => {
this.firstFetchedViewerCount = r.data.data[0].viewer_count;
r.data.data.forEach(e => {
this.tryAddStream(e);
});
this.getNextPage(r.data.pagination.cursor);
});
}
getNextPage(cursor) {
axios.get(`https://api.twitch.tv/helix/streams?language=fr&first=100&after=${cursor}`, {
headers: {
'Client-ID': process.env.TWITCH_CLIENT_ID,
'Authorization': `Bearer ${this.bearer}`,
},
}).then(r => {
r.data.data.forEach(e => {
this.tryAddStream(e);
});
if (r.data.data[0] && r.data.data[0].viewer_count < this.firstFetchedViewerCount && r.data.pagination.cursor)
this.getNextPage(r.data.pagination.cursor);
else {
this.streams = this.fetchStreams;
this.streams.sort((a, b) => {
if (a.viewer_count < b.viewer_count) return 1;
if (a.viewer_count > b.viewer_count) return -1;
else return 0;
});
console.log('STEAMS FETCHED'.cyan, `(${this.streams.length} total)`.yellow);
this.events.fetchFinished(this.streams);
this.fetchGames().then(() => this.canFetch = true);
}
}).catch(e => {
let resetTimeStamp = parseInt(e.response.headers['ratelimit-reset']);
let RateLimit = e.response.headers['ratelimit-limit'];
let RateLimitRemaining = e.response.headers['ratelimit-remaining'];
let resetIn = (resetTimeStamp * 1000) - Date.now() + 500;
console.error('ERROR | Retry in:'.red, `${resetIn / 1000} s`.magenta, `RPM: ${RateLimit} - RPMR: ${RateLimitRemaining}`.yellow);
this.refreshToken();
if (e.response.status) setTimeout(() => {
this.getNextPage(cursor);
}, resetIn);
});
}
async fetchGames() {
return new Promise(async (resolve, reject) => {
console.log('FETCHING GAMES'.blue)
let gamesIds = [];
let games = {};
this.streams.forEach(s => {
if (!gamesIds.includes(s.game_id)) gamesIds.push(s.game_id);
});
for (let i = 0; i < Math.ceil(gamesIds.length / 100); i++) {
let isLastPart = (i === Math.ceil(gamesIds.length / 100));
let idList = [];
for (let j = i * 100; j < i * 100 + 100; j++) {
idList.push(`id=${gamesIds[j]}`);
}
await axios.get(`https://api.twitch.tv/helix/games?${idList.join('&')}`, {
headers: {
'Client-ID': process.env.TWITCH_CLIENT_ID,
'Authorization': `Bearer ${this.bearer}`,
},
}).then(d => {
d.data.data.forEach(g => {
games[g.id] = {
name: g.name,
imgUrl: g.box_art_url,
streamCount: 0,
};
})
});
}
this.streams.forEach(s => {
if (games[s.game_id]) games[s.game_id].streamCount++;
});
this.gamesList = {
games,
length: Object.keys(games).length,
};
console.log('GAMES FETCHED'.blue)
resolve();
});
}
}
module.exports = () => {
return new Streams;
};