twitch-manager/public/app.js

126 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-11-20 21:51:10 +00:00
Vue.config.devtools = true
const app = new Vue({
computed: {
clock() {
return moment(this.time).format('HH:mm:ss')
},
icons() {
const icons = []
if (!this.conn.avail) {
icons.push({ class: 'fas fa-ethernet text-warning' })
}
return icons
},
nextFollowers() {
return Math.ceil((this.store.followers.count + 1) / 25) * 25
},
nextSubs() {
return Math.ceil((this.store.subs.count + 1) / 5) * 5
},
},
created() {
window.setInterval(() => { this.time = new Date() }, 1000)
this.startSocket()
2020-11-23 10:08:57 +00:00
this.sound = new Audio()
this.sound.addEventListener('load', () => this.sound.play(), true)
this.sound.autoplay = true
2020-11-20 21:51:10 +00:00
},
data: {
conn: {
avail: false,
backoff: 100,
},
2020-11-23 10:08:57 +00:00
sound: null,
2020-11-20 21:51:10 +00:00
store: {},
socket: null,
time: new Date(),
2020-11-20 23:33:02 +00:00
version: null,
2020-11-20 21:51:10 +00:00
},
el: '#app',
methods: {
2020-11-23 10:08:57 +00:00
playSound(soundUrl) {
this.sound.src = soundUrl
},
2020-11-23 10:34:08 +00:00
showAlert(title, text, variant) {
2020-11-20 21:51:10 +00:00
this.$bvToast.toast(text, {
title,
toaster: 'b-toaster-top-right',
2020-11-23 10:34:08 +00:00
variant: variant || 'primary',
2020-11-20 21:51:10 +00:00
})
},
startSocket() {
if (this.socket) {
// Dispose old socket
this.socket.close()
this.socket = null
}
let socketAddr = `${window.location.origin.replace(/^http/, 'ws')}/api/subscribe`
this.socket = new WebSocket(socketAddr)
this.socket.onclose = () => {
this.conn.avail = false
this.conn.backoff = Math.min(this.conn.backoff * 1.25, 10000)
window.setTimeout(this.startSocket, this.conn.backoff) // Restart socket
}
this.socket.onmessage = evt => {
const data = JSON.parse(evt.data)
2020-11-20 23:01:55 +00:00
2020-11-20 23:33:02 +00:00
if (data.version) {
this.version = data.version
}
2020-11-20 23:01:55 +00:00
switch (data.type) {
2020-11-23 10:34:08 +00:00
case 'alert':
this.showAlert(data.payload.title, data.payload.text, data.payload.variant)
if (data.payload.sound) {
this.playSound(data.payload.sound)
}
break
2020-11-20 23:01:55 +00:00
case 'store':
2020-11-20 23:33:02 +00:00
this.store = data.payload
2020-11-20 23:01:55 +00:00
break
default:
console.log(`Unhandled message type ${data.type}`, data)
}
2020-11-20 21:51:10 +00:00
}
this.socket.onopen = evt => {
this.conn.avail = true
this.conn.backoff = 100
}
},
},
watch: {
'store.followers.last'(to, from) {
if (!from || !to) {
// Initial load
return
}
this.showAlert('New Follower', `${to} just followed`)
2020-11-23 10:08:57 +00:00
this.playSound('/public/doorbell.webm')
2020-11-20 21:51:10 +00:00
},
2020-11-20 23:33:02 +00:00
version(to, from) {
if (!from || !to || from === to) {
return
}
window.location.reload()
},
2020-11-20 21:51:10 +00:00
},
})