-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
380 lines (337 loc) · 11.5 KB
/
app.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
const CLIENT_ID = '5rocrgu81rtj4mw65d1j78rue4dszu';
// when on PROD
const REDIRECT_URI = 'https://matthewbrandt.github.io/JustInChatters';
// when on LOCAL
// const REDIRECT_URI = 'http://localhost:5500';
const params = new URLSearchParams(window.location.search);
const hash = new URLSearchParams(document.location.hash.slice(1));
const loaderWrapper = document.getElementById('loader-wrapper');
async function preLoadBotList () {
const botList = './bot_list.txt';
const response = await fetch(botList);
return await response.text();
}
const loadedBotListPromise = preLoadBotList();
let footerState = localStorage.getItem('footer');
let tokenPromise = upsertToken(hash.get('access_token'));
tokenPromise.then(async function(twitchToken) {
if (twitchToken) {
console.log("Resolved token");
let broadcaster = JSON.parse(localStorage.getItem('broadcaster'));
getChatters(twitchToken, broadcaster);
} else {
console.log("No token resolved");
displayAuthorizationPrompt();
}
});
if(JSON.parse(footerState) === true ) {
hideFooter();
}
function upsertToken(incomingToken) {
if (incomingToken) {
console.log("New incoming token");
localStorage.setItem('access_token', incomingToken);
setUserFilter();
return fetchUserInfo(incomingToken);
}
console.log("Get cached token");
return Promise.resolve(localStorage.getItem('access_token'));
}
function fetchUserInfo(token) {
const url = 'https://id.twitch.tv/oauth2/validate';
return fetch(url, {
headers: { Authorization: 'Bearer ' + token }
}).then(async function(response) {
if (response.ok) {
return await response.json();
//return testData;
} else {
return Promise.reject(response);
}
}).then(async function (data) {
localStorage.setItem('broadcaster', JSON.stringify({ "id": data.user_id, "name": data.login }));
return token;
});
}
function displayAuthorizationPrompt() {
footer = document.getElementById('footer');
footer.style.display = 'none';
let divItem = document.createElement("div");
let params = new URLSearchParams();
params.append("client_id", CLIENT_ID);
params.append("redirect_uri", REDIRECT_URI);
params.append("response_type", "token");
params.append("scope", "moderator:read:chatters");
divItem.innerHTML = `<h3>Please login with Twitch to authorize JustInChatters to load your chatters.</h3>
<a class="button button-auth" href="https://id.twitch.tv/oauth2/authorize?${params}">Connect with Twitch</a>`;
document.getElementById('chatters').append(divItem);
}
function setUserFilter() {
if (document.getElementById("userlist")) {
let LSInput = localStorage.getItem('userlist');
// if localstorage is filled prefill the field with localstorage data
if (LSInput) {
document.getElementById("userlist").value = LSInput;
}
}
}
function hideFooter() {
footer = document.getElementById('footer');
footer.classList.toggle('main-footer--hide');
footerText = document.getElementById('footer--hide__text');
if (footer.classList.contains("main-footer--hide") == true) {
footerText.innerText = 'Show Key';
localStorage.setItem('footer', false);
} else {
footerText.innerText = 'Hide Key';
localStorage.setItem('footer', true);
}
}
function filter_results() {
var input, chatters, table, li, i, txtValue;
input = document.getElementById("username");
inputValue = input.value.toLowerCase();
chatters = document.getElementById("chatters");
li = chatters.getElementsByTagName("li");
if(inputValue != 0){
for (i = 0; i < li.length; i++) {
let element = li[i];
txtValue = element.textContent || element.innerText;
if (txtValue.includes(inputValue)) {
element.style.display = "";
} else {
element.style.display = "none";
}
}
} else {
for (i = 0; i < li.length; i++) {
let element = li[i];
element.style.display = "";
}
}
}
function apply_userlist(){
let LSInput, fieldInput, chatters, li, i, txtValue;
LSInput = localStorage.getItem('userlist');
console.log("LSInput =",LSInput);
fieldInput = document.getElementById("userlist").value.toLowerCase();
console.log("fieldInput = ",fieldInput);
if (fieldInput !== LSInput) {
if (fieldInput.length > 0) {
// write data from field to localstorage if different
localStorage.setItem('userlist', fieldInput);
}
else {
// delete localstorage key if field is emptied
localStorage.removeItem('userlist');
}
}
chatters = document.getElementById("chatters");
li = chatters.getElementsByTagName("li");
if(fieldInput != 0){
for (i = 0; i < li.length; i++) {
let element = li[i];
txtValue = element.textContent || element.innerText;
if (txtValue.includes(fieldInput)) {
element.classList.add("custom-user");
//element.style.display = "";
} else {
//element.style.display = "none";
}
}
} else {
for (i = 0; i < li.length; i++) {
let element = li[i];
element.style.display = "";
}
}
};
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function botCheck(user,botList) {
// read huge bot list from local file
// source: https://github.com/thatvoidcat/twitch_insights_bot_names
// check the full file for bots
if (botList.includes(user)) {
return user;
}
}
function serviceCheck(user) {
// preliminary list, will be added to later
const serviceBot = [
'9kmmrbot',
'amazeful',
'amazefulbot',
'buttsbot',
'commanderroot',
'creatisbot',
'dinu',
'dr3ddbot',
'fossabot',
'kikettebot',
'lattemotte',
'logiceftbot',
'logviewer',
'lolrankbot',
'mikuia',
'mirrobot',
'moobot',
'mtgbot',
'nightbot',
'overrustlelogs',
'own3d',
'p4nth3rb0t',
'playwithviewersbot',
'pokemoncommunitygame',
'pretzelrocks',
'quirkapp',
'rainmaker',
'restreambot',
'sery_bot',
'sixflagsmagicmountain',
'socialblade',
'songlistbot',
'soundalerts',
'sport_scores_bot',
'ssakdook',
'streambee_bot',
'streamcaptainbot',
'streamdeckerbot',
'streamelements',
'streamholics',
'streamjar',
'streamkit',
'streamlabs',
'streamstickers',
'tipeeebot',
'vivbot',
'vtuberplus',
'wizebot',
'wzbot'
];
return serviceBot.includes(user);
}
function customUserCheck(user) {
// read list from localstorage
let customUser = [];
if (localStorage.getItem('userlist')) {
customUser = localStorage.getItem('userlist');
}
return customUser.includes(user);
}
function getChatters(token, broadcaster) {
const requestParams = new URLSearchParams();
requestParams.append("broadcaster_id", broadcaster.id);
requestParams.append("moderator_id", broadcaster.id);
requestParams.append("first", 1000);
const url = `https://api.twitch.tv/helix/chat/chatters?${requestParams}`;
const broadcasterName = document.getElementById('broadcaster-name');
broadcasterName.textContent=broadcaster.name.toLowerCase();
[].forEach.call(document.querySelectorAll('.hide'), function (el) {
el.classList.remove('hide');
});
loaderWrapper.classList.remove('loader-hide');
fetch(url, {
headers: { Authorization: 'Bearer ' + token, 'Client-Id': CLIENT_ID }
}).then(async function (response) {
let testData = {
"_links": {},
"chatter_count": 7,
"chatters": {
"admins": [],
"broadcaster": [],
"global_mods": [],
"moderators": [
"streamelements",
"finitesingularity",
"mattythreeshoes",
"dramaman"
],
"staff": [
"zachbussey",
"slashie101"
],
"viewers": [
"anna_banana_10",
"affewfw6235325",
"bestvieweroftwitch",
"commanderroot",
"creatisbot",
"gnare",
"robohubby",
"sc0ttzen",
"scg_noisy",
"sebi_96000",
"shadoow_lol",
"silva_lindow",
"slaan",
"sophiafox21",
"streambee_bot",
"tinarif",
"standardvieweroftwitch"
],
"vips": [
"fancyperson",
"timeenjoyed"
]
}
}
if (response.ok) {
return await response.json();
//return testData;
} else {
return Promise.reject(response);
}
}).then(async function (data) {
document.getElementById('chatters').innerHTML = '';
const viewerCount = data.total - 1;
document.querySelector('#totalcount span').innerHTML = addCommas(viewerCount);
const botListRaw = await loadedBotListPromise;
const botList = botListRaw.split('\n');
console.log(botList.length + ' bots in list');
const userType = 'Chatter';
let divItem = document.createElement("div");
divItem.innerHTML = `<h3>${userType} (${addCommas(viewerCount)})</h3>`;
divItem.classList.add('row', userType);
let unorderedList = document.createElement("ul");
document.getElementById('chatters').append(divItem);
divItem.append(unorderedList);
let userArr = data.data;
function sortChatters(a,b) {
return a.user_login < b.user_login ? -1 : a.user_login > b.user_login ? 1 : 0;
}
// sort chatters alphabetically
let sortedArr = userArr.sort(sortChatters);
// remove broadcaster from chatters list
let finalArr = sortedArr.filter(name => name.user_login != broadcaster.name);
for (user of finalArr) {
let listItem = document.createElement("li");
listItem.innerHTML = `<a target="_blank" href="https://twitch.tv/${user.user_login}">${user.user_name}</a>`;
unorderedList.appendChild(listItem);
if (customUserCheck(user.user_login)) {
listItem.classList.add("custom-user");
}
else if (serviceCheck(user.user_login)) {
listItem.classList.add("service-user");
}
else if (botCheck(user.user_login, botList)) {
listItem.classList.add("bot-user");
}
};
loaderWrapper.classList.add('loader-hide');
}).catch(function (err) {
console.warn('Something went wrong!', err);
});
setTimeout(function() {
getChatters(token, broadcaster);
}, 180000); // every 3 mins
}