convert to sugoi web services

This commit is contained in:
josephsmendoza
2023-07-14 19:05:49 -07:00
parent a88a096af8
commit aca8b21945
17 changed files with 370 additions and 1131 deletions
+330 -264
View File
@@ -1,296 +1,362 @@
const timeText = document.getElementById("timeText");
const client_id='ib2n7v7mur7ab2mcxv7rjju2ctsyoi'
const message_ids=[]
const timer=document.querySelector('#timeText')
let tba,tokens,pubsub,ping_tid,pong_tid,eventsub,sse,time_started,time_passed,time_total,config,localforage
/** @type WebSocket */
let irc
var initialHours;
var initialMinutes;
var initialSeconds;
var paused = false;
var happy_hour_active = false;
var random_hour_active = false;
let countdownEnded = false;
let countdownUpdater = null;
var initialHoursLocal = window.localStorage.getItem('initialHours')
if (initialHoursLocal !== null) {
initialHours = initialHoursLocal;
logMessage("Core", "Found initialHours in localStorage.")
} else {
initialHours = initialHoursConfig;
}
var initialMinutesLocal = window.localStorage.getItem('initialMinutes')
if (initialMinutesLocal !== null) {
initialMinutes = initialMinutesLocal;
logMessage("Core", "Found initialMinutes in localStorage.")
} else {
initialMinutes = initialMinutesConfig;
}
var initialSecondsLocal = window.localStorage.getItem('initialSeconds')
if (initialSecondsLocal !== null) {
initialSeconds = initialSecondsLocal;
logMessage("Core", "Found initialSeconds in localStorage.")
} else {
initialSeconds = initialSecondsConfig;
window.onanimationend=function(event){
event.target.remove()
}
resetBtn.addEventListener("click", function(){
if (happy_hour_active) specialHourHandler('Happy');
if (random_hour_active) specialHourHandler('Random');
countdownEnded = false;
initialHours = initialHoursConfig;
initialMinutes = initialMinutesConfig;
initialSeconds = initialSecondsConfig;
let timeNow = new Date(Date.now());
endingTime = timeFunc.addHours(timeNow, initialHours);
endingTime = timeFunc.addMinutes(timeNow, initialMinutes);
endingTime = timeFunc.addSeconds(timeNow, initialSeconds);
window.onload=async function(){
// init localforage
localforage=(await import('https://cdn.jsdelivr.net/npm/localforage/+esm')).default
localforage=localforage.createInstance({name:'sugoi-subathon-countdown'})
// init timer display
time_started=await localforage.getItem('time_started')
time_passed=await localforage.getItem('time_passed')
time_total=await localforage.getItem('time_total')
updateTime()
// init twitch api tokens
tba=await import('https://tba.sugoidogo.com/tba.mjs')
tokens=await tba.get_tokens(client_id)
// load user config
load_config()
// init event sources
init_irc()
init_pubsub()
init_eventsub()
}
window.localStorage.removeItem('initialHours');
window.localStorage.removeItem('initialMinutes');
window.localStorage.removeItem('initialSeconds');
function handle_event(event_name,event_amount=1){
if(!config[event_name+'-time-enabled']){
return false
}
add_time(parseReadableTimeIntoMilliseconds(config[event_name+'-time'])*event_amount)
return true
}
logMessage("Core", "Timer Reset.");
});
function reset(){
localforage.removeItem('time_started')
localforage.removeItem('time_passed')
time_started=null
time_passed=null
time_total=parseReadableTimeIntoMilliseconds(config['start-time'])
localforage.setItem('time_total',time_total)
}
startBtn.addEventListener("click", function(){
if (paused){
var initialHoursLocal = window.localStorage.getItem('initialHours')
if (initialHoursLocal !== null) {
initialHours = initialHoursLocal;
logMessage("Core", "Found initialHours in localStorage.")
} else {
initialHours = initialHoursConfig;
function load_config(){
return fetch('https://ts.sugoidogo.com/config.json',{headers:tokens.auth_headers})
.then(response=>response.json())
.then(json=>{
config=json
if(!time_started && !time_passed){
reset()
}
var initialMinutesLocal = window.localStorage.getItem('initialMinutes')
if (initialMinutesLocal !== null) {
initialMinutes = initialMinutesLocal;
logMessage("Core", "Found initialMinutes in localStorage.")
} else {
initialMinutes = initialMinutesConfig;
}
var initialSecondsLocal = window.localStorage.getItem('initialSeconds')
if (initialSecondsLocal !== null) {
initialSeconds = initialSecondsLocal;
logMessage("Core", "Found initialSeconds in localStorage.")
} else {
initialSeconds = initialSecondsConfig;
})
}
function add_time(time){
if(config['max-time-enabled']){
const new_time=time_total+time
const max_time=parseReadableTimeIntoMilliseconds(config['max-time'])
if(new_time>max_time){
time=max_time-time_total
}
}
let timeNow = new Date(Date.now());
document.getElementById("startPage").style.visibility = "hidden";
document.getElementById("container").style.visibility = "visible";
endingTime = timeFunc.addHours(timeNow, initialHours);
endingTime = timeFunc.addMinutes(timeNow, initialMinutes);
endingTime = timeFunc.addSeconds(timeNow, initialSeconds);
paused = false;
countdownUpdater = setInterval(() => {
getNextTime();
}, 1);
});
Mousetrap.bind(pauseShort, function(e) {
paused = true;
logMessage("Core", "Timer was paused");
document.getElementById("startPage").style.visibility = "visible";
document.getElementById("container").style.visibility = "hidden";
clearInterval(countdownUpdater);
});
Mousetrap.bind(happyHourShort, async function(e){
specialHourHandler('Happy');
});
Mousetrap.bind(randomHourShort, async function(e){
specialHourHandler('Random');
});
async function specialHourHandler(type){
if ((type === 'Happy' && happy_hour) || (type === 'Random' && random_hour)){
specialHourFunc(type)
let addedTime=document.createElement('p')
let timeString=parseMillisecondsIntoReadableTime(time)
if(time>0){
timeString='+'+timeString
}
else {
logMessage("Core", `${type} Hour is not available`)
document.getElementById("SpecialHourText").innerHTML = `${type} Hour error`;
document.getElementById("SpecialHourText").animate({opacity: [ 0, 1 ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourText").style.opacity = "1";
document.getElementById("SpecialHourHTML").animate({top: [ "-200px", "-250px" ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourHTML").style.top = "-250px";
await sleep(5000)
document.getElementById("SpecialHourText").animate({opacity: [ 1, 0 ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourText").style.opacity = "0";
if(time==0){
timeString='Timer Maxed!'
}
addedTime.innerHTML=timeString
addedTime.className='addedTime'
document.body.appendChild(addedTime);
time_total+=time
localforage.setItem('time_total',time_total)
}
async function specialHourFunc(type){
let activate = ((type === 'Happy' && !happy_hour_active) || (type === 'Random' && !random_hour_active));
let toggleText = activate ? 'Activated' : 'Deactivated';
logMessage("Core", `${type} Hour ${toggleText}`);
if (type === 'Happy') happy_hour_active = activate;
if (type === 'Random') random_hour_active = activate;
let animation = (happy_hour_active || random_hour_active) ? ', url(https://drive.google.com/uc?id=1oduFlPg84O1DliM5FsLvJJsnwZ4m1Vpm)' : '';
document.getElementById("SpecialHourText").innerHTML = `${type} Hour ${toggleText}!`;
document.getElementById("SpecialHourText").animate({opacity: [ 0, 1 ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourText").style.opacity = "1";
document.getElementById("SpecialHourHTML").animate({top: [ "-200px", "-250px" ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourHTML").style.top = "-250px";
document.getElementById("container").style.backgroundImage = `-webkit-linear-gradient(-45deg, transparent 33%, rgba(0, 0, 0, .1) 33%, rgba(0,0, 0, .1) 66%, transparent 66%), -webkit-linear-gradient(top, rgba(255, 255, 255, .25), rgba(0, 0, 0, .25))${animation}, -webkit-linear-gradient(left, #0074cc, #a700cc)`;
await sleep(activate ? 5000 : 10000);
document.getElementById("SpecialHourText").animate({opacity: [ 1, 0 ], easing: [ 'ease-in', 'ease-out' ],}, 500);
document.getElementById("SpecialHourText").style.opacity = "0";
function start(){
time_started=Date.now()
localforage.setItem('time_started',time_started)
}
let users = [];
let time;
let endingTime = new Date(Date.now());
endingTime = timeFunc.addHours(endingTime, initialHours);
endingTime = timeFunc.addMinutes(endingTime, initialMinutes);
endingTime = timeFunc.addSeconds(endingTime, initialSeconds);
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
function pause(){
time_passed+=Date.now()-time_started
time_started=null
localforage.removeItem('time_started')
localforage.setItem('time_passed',time_passed)
}
var randomHappyBool = false
var scheduleHappyBool = false
const getNextTime = () => {
let currentTime = new Date(Date.now());
let differenceTime = endingTime - currentTime;
time = `${timeFunc.getHours(differenceTime)}:${timeFunc.getMinutes(differenceTime)}:${timeFunc.getSeconds(differenceTime)}`;
if (differenceTime <= 0) {
time = "00:00:00";
if (differenceTime <= (syncTime * 1000 * -1)) {
clearInterval(countdownUpdater);
countdownEnded = true;
logMessage("Core", "Timer Ended");
}
// https://stackoverflow.com/a/33909506
function parseMillisecondsIntoReadableTime(milliseconds){
let negative=false
if(milliseconds<0){
milliseconds=Math.abs(milliseconds)
negative=true
}
if (!paused){
window.localStorage.setItem('initialHours', timeFunc.getHours(differenceTime));
window.localStorage.setItem('initialMinutes', timeFunc.getMinutes(differenceTime));
window.localStorage.setItem('initialSeconds', timeFunc.getSeconds(differenceTime));
if (randHappy && happy_hour && !randomHappyBool){
randomHappyBool = true
setTimeout(randomHappy,1000)
}
if (scheduleHappy && happy_hour && !scheduleHappyBool){
scheduleHappyBool = true
scheduleHappyFunc()
}
}
timeText.innerText = time;
};
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
function randomHappy(){
if (!happy_hour_active){
if ((getRandomInt(0,10000) == 127)){
logMessage("RandomHappy","It's not rigged!")
specialHourFunc()
setTimeout(specialHourFunc, 3600000)
}
setTimeout(randomHappy,1000)
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
let time = h + ':' + m + ':' + s;
if(negative){
time='-'+time
}
return time
}
function scheduleHappyFunc(){
let now = new Date()
if (now.getDay() == scheduleHappyDay){
if (now.getUTCHours() == scheduleHappyHour){
if (now.getUTCMinutes() == 00){
logMessage("Schedule","It's time!")
specialHourFunc()
setTimeout(specialHourFunc, 3600000)
setTimeout(scheduleHappyFunc, 36000000)
function parseReadableTimeIntoMilliseconds(readableTime){
let negative=false
if(readableTime.startsWith('-')){
negative=true
readableTime=readableTime.substring(1)
}
const [seconds,minutes,hours]=readableTime.split(':').reverse()
let time=((hours||0)*1000*60*60)+((minutes||0)*1000*60)+((seconds||0)*1000)
if(negative){
time=0-time
}
return time
}
function updateTime(){
let time_remaining=time_total
if(time_passed){
time_remaining-=time_passed
}
if(time_started){
time_remaining-=Date.now()-time_started
}
timer.innerHTML=parseMillisecondsIntoReadableTime(time_remaining)
requestAnimationFrame(updateTime)
}
function init_pubsub(){
if(pong_tid){
clearTimeout(pong_tid)
pong_tid=null
}
if(ping_tid){
clearTimeout(ping_tid)
ping_tid=null
}
if(pubsub){
pubsub.close()
}
pubsub=new WebSocket('wss://pubsub-edge.twitch.tv')
pubsub.onopen=function(){
pubsub.send(JSON.stringify({
"type":"LISTEN",
"data":{
"auth_token":tokens.access_token,
"topics":[
"channel-bits-events-v2."+tokens.user_id,
"channel-subscribe-events-v1."+tokens.user_id
]
}
}))
}
pubsub.onmessage=function(event){
let message=JSON.parse(event.data)
console.debug(message)
switch(message.type){
case 'RESPONSE':{
if(message.error){
throw message.error
}
pubsub_ping()
break
}
case 'PONG':{
clearTimeout(pong_tid)
pong_tid=null
break
}
case 'RECONNECT':{
init_pubsub()
break
}
case 'AUTH_REVOKED':{
location.reload()
break
}
case 'MESSAGE':{
message=message.data.message
if('sub_plan' in message){
handle_event('sub'+message.sub_plan)
break
}
if('bits_used' in message){
handle_bits('bit',message.bits_used)
break
}
}
}
}
}
var firstSub = true;
var endingTimeBeforeCounter;
var addedTimeCounter;
var timeoutID;
const addTime = async (time, s) => {
let addedTime = Math.floor(s);
if (!bulk_enabled) {
endingTimeBeforeCounter = time;
addedTimeCounter = addedTime;
addTimeInternal();
return;
}
if (firstSub) {
firstSub = false;
endingTimeBeforeCounter = time;
addedTimeCounter = addedTime;
} else {
addedTimeCounter += addedTime;
window.clearTimeout(timeoutID);
}
timeoutID = window.setTimeout(addTimeInternal, 1000);
};
const addTimeInternal = async () => {
let time = endingTimeBeforeCounter;
let s = addedTimeCounter;
addedTimeCounter = 0;
firstSub = true;
let addedTime = document.createElement("p");
happy_hour_active ? addedTime.classList = "gold" : addedTime.classList = "addedTime";
addedTime.innerText = `+${s}s`;
document.body.appendChild(addedTime);
addedTime.style.display = "block";
await sleep(50);
addedTime.style.left = `${randomInRange(35, 65)}%`;
addedTime.style.top = `${randomInRange(15, 40)}%`;
addedTime.style.opacity = "1";
while (s > 0){
timeStep = s > 60 ? s/30 : 2
endingTime = timeFunc.addSeconds(time, timeStep)
await sleep(50);
s -= timeStep
}
await sleep(200);
addedTime.style.opacity = "0";
await sleep(200);
addedTime.remove();
function pubsub_ping(){
pubsub.send(JSON.stringify({'type':'PING'}))
const time=Math.floor(Math.random() * (5*60*1000))
ping_tid=setTimeout(pubsub_ping,time)
pong_tid=setTimeout(init_pubsub,20000)
}
const testAddTime = (times, delay, s) => {
let addTimeInterval = setInterval(async () => {
if (times > 0) {
await sleep(randomInRange(50, delay-50));
addTime(endingTime, s);
--times;
function init_eventsub(){
eventsub=new WebSocket('wss://eventsub.wss.twitch.tv/ws')
eventsub.onmessage=function(event){
let message=JSON.parse(event.data)
console.debug(message)
if(message.metadata.message_id in message_ids){
return
}else{
message_ids.push(message.metadata.message_id)
}
else {
clearInterval(addTimeInterval);
switch(message.metadata.message_type){
case 'session_welcome':{
let session_id=message.payload.session.id
const headers={'content-type':'application/json'}
Object.assign(headers,tokens.auth_headers)
const url=new URL('https://api.twitch.tv/helix/eventsub/subscriptions')
subscriptions=[
{
"type": "channel.follow",
"version": "2",
"condition": {
"broadcaster_user_id": tokens.user_id,
"moderator_user_id": tokens.user_id
},
"transport": {
"method": "websocket",
"session_id": session_id,
}
},
{
"type": "channel.raid",
"version": "1",
"condition": {
"to_broadcaster_user_id": tokens.user_id
},
"transport": {
"method": "websocket",
"session_id": session_id,
}
},
{
"type": "channel.charity_campaign.donate",
"version": "1",
"condition": {
"broadcaster_user_id": tokens.user_id
},
"transport": {
"method": "websocket",
"session_id": session_id,
}
}
]
for(const subscription of subscriptions){
fetch(url,{
headers:headers,
method:"POST",
body:JSON.stringify(subscription)
})
}
break
}
case 'notification':{
switch(message.metadata.subscription_type){
case 'channel.follow':{
handle_event('follow')
break
}
case 'channel.raid':{
handle_event('raid')
break
}
case 'channel.charity_campaign.donate':{
handle_event('charity',message.event.amount.value)
}
}
}
}
}, delay);
};
}
}
function ircSend(message){
console.debug('< '+message)
irc.send(message)
}
async function init_irc(){
if(irc){
irc.close()
}
irc=new WebSocket('wss://irc-ws.chat.twitch.tv:443')
irc.onclose=init_irc
irc.onopen=function(){
ircSend('CAP REQ twitch.tv/tags')
ircSend('PASS oauth:'+tokens.access_token)
ircSend('NICK '+tokens.login)
ircSend('JOIN #'+tokens.login)
}
irc.onmessage=function(event){
console.log(event)
for(let data of event.data.split('\r\n')){
console.debug('> '+data)
/** @type string */
data=data.split(':')
const tags=data.shift()
const type=data.shift()
const message=data.join(':')
console.debug(tags,type,message)
if(!message){
continue
}
if(!(tags.includes('broadcaster') || tags.includes('moderator'))){
continue
}
const command=message.split(' ')
console.debug(command)
if(command.shift()!='!subathon'){
continue
}
switch(command.shift()){
case 'start':{
start()
break
}
case 'pause':{
pause()
break
}
case 'reset':{
reset()
break
}
case 'add':{
add_time(parseReadableTimeIntoMilliseconds(command.shift()))
break
}
}
}
}
}