Skip to content

Commit

Permalink
lib/api: Fix multiple getCurrentStreamData intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
sogehige committed Apr 5, 2018
1 parent 8a003b0 commit 2ea2bb6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 30 deletions.
40 changes: 11 additions & 29 deletions libs/api.js
Expand Up @@ -38,11 +38,10 @@ class API {

this._loadCachedStatusAndGame()
this.getChannelID()
this.getCurrentStreamData()
this.getCurrentStreamData({ interval: true })
this.getLatest100Followers(true)
this.updateChannelViews()
this.getChannelHosts()
this.updateWatchTime()

this.getChannelSubscribersOldAPI() // remove this after twitch add total subscribers
this.getChannelDataOldAPI() // remove this after twitch game and status for new API
Expand Down Expand Up @@ -70,7 +69,7 @@ class API {
try {
request = await snekfetch.get(url)
.set('Accept', 'application/vnd.twitchtv.v5+json')
.set('Authorization', 'OAuth ' + config.settings.broadcaster_oauth.split(':')[1])
.set('Authorization', 'OAuth ' + config.settings.bot_oauth.split(':')[1])
.set('Client-ID', config.settings.client_id)
global.db.engine.insert('APIStats', { timestamp: _.now(), call: 'getChannelID', api: 'kraken', endpoint: url, code: request.status })
} catch (e) {
Expand All @@ -82,11 +81,13 @@ class API {
if (timeout === 1000) setTimeout(() => this.getChannelID(), timeout)
}

if (_.isNil(request.body.users[0])) {
const user = request.body.users[0]
debug('api:getChannelID')(user)
if (_.isNil()) {
global.log.error('Channel ' + config.settings.broadcaster_username + ' not found!')
} else {
await global.cache.channelId(request.body.users[0]._id)
global.log.info('Broadcaster channel ID set to ' + request.body.users[0]._id)
await global.cache.channelId(user)
global.log.info('Broadcaster channel ID set to ' + user)
}
}

Expand Down Expand Up @@ -164,7 +165,7 @@ class API {
try {
request = await snekfetch.get(url)
.set('Accept', 'application/vnd.twitchtv.v5+json')
.set('Authorization', 'OAuth ' + config.settings.broadcaster_oauth.split(':')[1])
.set('Authorization', 'OAuth ' + config.settings.bot_oauth.split(':')[1])
.set('Client-ID', config.settings.client_id)
global.db.engine.insert('APIStats', { timestamp: _.now(), call: 'getChannelDataOldAPI', api: 'kraken', endpoint: url, code: request.status })
} catch (e) {
Expand Down Expand Up @@ -281,25 +282,6 @@ class API {
global.db.engine.update('api.current', { key: 'views' }, { value: this.current.views })
}

// TODO: this should be moved to users
async updateWatchTime () {
// count watching time when stream is online
const d = debug('api:updateWatchTime')
d('init')

if (await global.cache.isOnline()) {
let users = await global.users.getAll({ is: { online: true } })

d(users)
for (let user of users) {
// add user as a new chatter in a stream
if (_.isNil(user.time)) user.time = {}
if (_.isNil(user.time.watched) || user.time.watched === 0) this.newChatters++
global.db.engine.increment('users', { username: user.username }, { time: { watched: 60000 } })
}
}
}

async getLatest100Followers (quiet) {
const cid = await global.cache.channelId()
const url = `https://api.twitch.tv/helix/users/follows?to_id=${cid}&first=100`
Expand Down Expand Up @@ -429,7 +411,7 @@ class API {
}
}

async getCurrentStreamData () {
async getCurrentStreamData (opts) {
const cid = await global.cache.channelId()
const url = `https://api.twitch.tv/helix/streams?user_id=${cid}`

Expand All @@ -438,7 +420,7 @@ class API {
debug('api:getCurrentStreamData')(`GET ${url}\nwait: ${needToWait}\ncalls: ${this.remainingAPICalls}`)
if (needToWait || notEnoughAPICalls) {
if (notEnoughAPICalls) debug('api:getCurrentStreamData')('Waiting for rate-limit to refresh')
setTimeout(() => this.getCurrentStreamData(), 1000)
setTimeout(() => this.getCurrentStreamData(opts), 1000)
return
}

Expand All @@ -455,7 +437,7 @@ class API {
global.db.engine.insert('APIStats', { timestamp: _.now(), call: 'getCurrentStreamData', api: 'helix', endpoint: url, code: `${e.status} ${_.get(e, 'body.message', e.message)}`, remaining: this.remainingAPICalls })
return
} finally {
setTimeout(() => this.getCurrentStreamData(), timeout)
if (opts.interval) setTimeout(() => this.getCurrentStreamData(), timeout)
}

// save remaining api calls
Expand Down
20 changes: 20 additions & 0 deletions libs/users.js
Expand Up @@ -15,6 +15,7 @@ function Users () {

// set all users offline on start
this.setAll({ is: { online: false } })
setInterval(() => this.updateWatchTime(), 60000)
}

Users.prototype.commands = function () {
Expand Down Expand Up @@ -425,4 +426,23 @@ Users.prototype.delete = function (username) {
global.db.engine.remove('users', { username: username })
}

Users.prototype.updateWatchTime = async function () {
// count watching time when stream is online
debug('init')

if (await global.cache.isOnline()) {
let users = await global.users.getAll({ is: { online: true } })

debug(users)
for (let user of users) {
// add user as a new chatter in a stream
if (_.isNil(user.time)) user.time = {}
if (_.isNil(user.time.watched) || user.time.watched === 0) this.newChatters++
global.db.engine.increment('users', { username: user.username }, { time: { watched: 60000 } })
}
} else {
debug('Doing nothing, stream offline')
}
}

module.exports = Users
2 changes: 1 addition & 1 deletion libs/webhooks.js
Expand Up @@ -216,7 +216,7 @@ class Webhooks {
} else {
// stream is offline - add curRetry + 1 and call getCurrentStreamData to do retries
global.api.curRetries = global.api.curRetries + 1
global.api.getCurrentStreamData()
global.api.getCurrentStreamData(({ interval: false }))
}
}
}
Expand Down

0 comments on commit 2ea2bb6

Please sign in to comment.