Dj_Expo
5
"use strict";
const callAJAX = (props) => {
const url = props.url,
method = props.method || "GET",
type = props.type || "JSON",
header = props.header
;
return new Promise(waitForResult => {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
type === "text"
? waitForResult(this.response)
: waitForResult(JSON.parse(this.response))
;
}
};
if (method === "GET") {
xhttp.open("GET", url, true);
for (const key in props.header) {
xhttp.setRequestHeader(key, header[key]);
}
xhttp.send();
}
});
};
const AJAXProps = {
url: "https://api.twitch.tv/helix/streams?first=20",
header: {"client-ID": "2qyh8p71ip7wb5duz7s7j4ctujehqn"} //Api key
};
//Array of users (channels)
var users = ["helanyah", "exbc", "rajobostv", "zorro", "esl_sc2"];
let names = "";
for (let i = 0; i < users.length; i++) {
let name = users[i];
!(names)
? names += name
: names += `&login=${name}`
;
};
// Create Twitch iframe
var actualStream = "";
// Embed stream
var options = {
width: 1280,
height: 720,
channel: actualStream
};
var player = new Twitch.Player("twitchEmbed", options);
document.getElementsByTagName("iframe")[0].setAttribute("sandbox", "allow-scripts allow-top-navigation allow-same-origin");
// Get users:
function updateStreams() {
AJAXProps.url = `https://api.twitch.tv/helix/users?login=${names}`;
callAJAX(AJAXProps).then(allUser => {
AJAXProps.url = `https://api.twitch.tv/helix/streams?first=20&login=${names}`.replace(/login/g, "user_login"); // Check if users now streaming
// The names inconsistent, so have to work with user_id
users.forEach((user, i) => {
users[i] = allUser.data[i].id;
});
callAJAX(AJAXProps).then(onlineUsers => {
console.log("Check if the given users now streaming", onlineUsers);
var numberOnline = onlineUsers.data.length;
if (numberOnline > 0) {
var actualStream = onlineUsers.data[0].user_name;
}
player.setChannel(actualStream);
});
});
} setInterval(updateStreams, 6000);
updateStreams();