Advertisement
kyroskoh

twitch.js

Jun 29th, 2017
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict'
  2.  
  3. var constants = require('./constants')
  4. var moment = require('moment')
  5. var request = require('request-promise')
  6. var _ = require('lodash')
  7. require('moment-precise-range-plugin')
  8.  
  9. function Twitch () {
  10.   this.isOnline = false
  11.  
  12.   this.currentViewers = 0
  13.   this.currentFollowers = 0
  14.   this.currentViews = 0
  15.   this.currentHosts = 0
  16.   this.maxViewers = 0
  17.   this.chatMessagesAtStart = global.parser.linesParsed
  18.   this.maxRetries = 12
  19.   this.curRetries = 0
  20.   this.newChatters = 0
  21.   this.currentStatus = ''
  22.   this.currentGame = ''
  23.  
  24.   this.cached = {
  25.     followers: [],
  26.     subscribers: []
  27.   }
  28.  
  29.   this.when = {
  30.     online: null,
  31.     offline: null
  32.   }
  33.  
  34.   this.cGamesTitles = {} // cached Games and Titles
  35.   global.watcher.watch(this, 'cGamesTitles', this._save)
  36.   global.watcher.watch(this, 'when', this._save)
  37.   global.watcher.watch(this, 'cached', this._save)
  38.   this._load(this)
  39.  
  40.   var self = this
  41.   setInterval(function () {
  42.     let options = {
  43.       url: 'https://api.twitch.tv/kraken/streams/' + global.channelId,
  44.       headers: {
  45.         Accept: 'application/vnd.twitchtv.v5+json',
  46.         'Client-ID': global.configuration.get().twitch.clientId
  47.       }
  48.     }
  49.  
  50.     if (global.configuration.get().bot.debug) {
  51.       global.log.debug('Get current stream data from twitch', options)
  52.     }
  53.     global.client.api(options, function (err, res, body) {
  54.       if (err) {
  55.         if (err.code !== 'ETIMEDOUT' && err.code !== 'ECONNRESET') global.log.error(err, { fnc: 'Twitch#1' })
  56.         return
  57.       }
  58.  
  59.       if (global.configuration.get().bot.debug) {
  60.         global.log.debug('Response: Get current stream data from twitch', body)
  61.       }
  62.  
  63.       if (res.statusCode === 200 && !_.isNull(body.stream)) {
  64.         self.curRetries = 0
  65.         if (!self.isOnline) { // if we are switching from offline - bots restarts? We want refresh to correct data for start as well
  66.           self.chatMessagesAtStart = global.parser.linesParsed
  67.           self.currentViewers = 0
  68.           self.maxViewers = 0
  69.           self.newChatters = 0
  70.           self.chatMessagesAtStart = global.parser.linesParsed
  71.           global.events.fire('stream-started')
  72.           global.events.fire('every-x-seconds', { reset: true })
  73.         }
  74.         self.saveStream(body.stream)
  75.         self.isOnline = true
  76.         self.when.offline = null
  77.         global.events.fire('number-of-viewers-is-at-least-x')
  78.         global.events.fire('stream-is-running-x-minutes')
  79.         global.events.fire('every-x-seconds')
  80.       } else {
  81.         if (self.isOnline && self.curRetries < self.maxRetries) { self.curRetries = self.curRetries + 1; return } // we want to check if stream is _REALLY_ offline
  82.         // reset everything
  83.         self.curRetries = 0
  84.         self.isOnline = false
  85.         if (_.isNil(self.when.offline)) {
  86.           self.when.offline = new Date().getTime()
  87.           global.events.fire('stream-stopped')
  88.           global.events.fire('stream-is-running-x-minutes', { reset: true })
  89.           global.events.fire('number-of-viewers-is-at-least-x', { reset: true })
  90.         }
  91.         self.when.online = null
  92.       }
  93.     })
  94.  
  95.     options = {
  96.       url: 'https://api.twitch.tv/kraken/channels/' + global.channelId + '/follows?limit=100',
  97.       headers: {
  98.         Accept: 'application/vnd.twitchtv.v5+json',
  99.         'Client-ID': global.configuration.get().twitch.clientId
  100.       }
  101.     }
  102.     if (global.configuration.get().bot.debug) {
  103.       global.log.debug('Get last 100 followers from twitch', options)
  104.     }
  105.     global.client.api(options, function (err, res, body) {
  106.       if (err) {
  107.         if (err.code !== 'ETIMEDOUT' && err.code !== 'ECONNRESET') global.log.error(err, { fnc: 'Twitch#2' })
  108.         return
  109.       }
  110.       if (global.configuration.get().bot.debug) {
  111.         global.log.debug('Response: Get last 100 followers from twitch', body)
  112.       }
  113.       if (res.statusCode === 200 && !_.isNull(body)) {
  114.         self.currentFollowers = body._total
  115.  
  116.         self.cached.followers = []
  117.         _.each(body.follows, function (follower) {
  118.           if (!global.users.get(follower.user.name).is.follower) {
  119.             if (new Date().getTime() - moment(follower.created_at).format('X') * 1000 < 60000 * 60) global.events.fire('follow', { username: follower.user.name })
  120.           }
  121.           global.users.set(follower.user.name, { id: follower.user._id, is: { follower: true }, time: { followCheck: new Date().getTime(), follow: moment(follower.created_at).format('X') * 1000 } })
  122.           self.cached.followers.push(follower.user.name)
  123.         })
  124.       }
  125.     })
  126.  
  127.     // count watching time when stream is online
  128.     if (self.isOnline) {
  129.       const users = global.users.getAll({ is: { online: true } })
  130.       _.each(users, function (user) {
  131.         // add user as a new chatter in a stream
  132.         if (_.isUndefined(user.time.watched) || user.time.watched === 0) self.newChatters = self.newChatters + 1
  133.         const time = (!_.isUndefined(user.time.watched)) ? 15000 + user.time.watched : 15000
  134.         global.users.set(user.username, { time: { watched: time } })
  135.       })
  136.     }
  137.   }, 15000)
  138.  
  139.   setInterval(function () {
  140.     let options = {
  141.       url: 'https://api.twitch.tv/kraken/channels/' + global.channelId + '?timestamp=' + new Date().getTime(),
  142.       headers: {
  143.         Accept: 'application/vnd.twitchtv.v5+json',
  144.         'Client-ID': global.configuration.get().twitch.clientId
  145.       }
  146.     }
  147.     if (global.configuration.get().bot.debug) {
  148.       global.log.debug('Get current channel data from twitch', options)
  149.     }
  150.     global.client.api(options, function (err, res, body) {
  151.       if (err) {
  152.         if (err.code !== 'ETIMEDOUT' && err.code !== 'ECONNRESET') global.log.error(err, { fnc: 'Twitch#3' })
  153.         return
  154.       }
  155.       if (global.configuration.get().bot.debug) {
  156.         global.log.debug('Response: Get current channel data from twitch', body)
  157.       }
  158.       if (res.statusCode === 200 && !_.isNull(body)) {
  159.         self.currentGame = body.game
  160.         self.currentStatus = body.status
  161.         self.currentViews = body.views
  162.       }
  163.     })
  164.  
  165.     if (!_.isNull(global.channelId)) {
  166.       options = {
  167.         url: 'http://tmi.twitch.tv/hosts?include_logins=1&target=' + global.channelId
  168.       }
  169.       if (global.configuration.get().bot.debug) {
  170.         global.log.debug('Get current hosts', options)
  171.       }
  172.       global.client.api(options, function (err, res, body) {
  173.         if (err) {
  174.           if (err.code !== 'ETIMEDOUT' && err.code !== 'ECONNRESET') global.log.error(err, { fnc: 'Twitch#4' })
  175.           return
  176.         }
  177.         if (global.configuration.get().bot.debug) {
  178.           global.log.debug('Response: Get current hosts', body)
  179.         }
  180.         if (res.statusCode === 200 && !_.isNull(body)) {
  181.           self.currentHosts = body.hosts.length
  182.         }
  183.       })
  184.     }
  185.  
  186.     options = {
  187.       url: 'https://api.twitch.tv/kraken',
  188.       headers: {
  189.         'Client-ID': global.configuration.get().twitch.clientId
  190.       }
  191.     }
  192.     if (global.configuration.get().bot.debug) {
  193.       global.log.debug('Get API connection status', options)
  194.     }
  195.     global.client.api(options, function (err, res, body) {
  196.       if (err) {
  197.         global.status.API = constants.DISCONNECTED
  198.         return
  199.       }
  200.       if (global.configuration.get().bot.debug) {
  201.         global.log.debug('Response: Get API connection status', body)
  202.       }
  203.       global.status.API = res.statusCode === 200 ? constants.CONNECTED : constants.DISCONNECTED
  204.     })
  205.   }, 10000)
  206.  
  207.   global.parser.register(this, '!uptime', this.uptime, constants.VIEWERS)
  208.   global.parser.register(this, '!lastseen', this.lastseen, constants.VIEWERS)
  209.   global.parser.register(this, '!watched', this.watched, constants.VIEWERS)
  210.   global.parser.register(this, '!followage', this.followage, constants.VIEWERS)
  211.   global.parser.register(this, '!age', this.age, constants.VIEWERS)
  212.   global.parser.register(this, '!me', this.showMe, constants.VIEWERS)
  213.   global.parser.register(this, '!top', this.showTop, constants.OWNER_ONLY)
  214.   global.parser.register(this, '!title', this.setTitle, constants.OWNER_ONLY)
  215.   global.parser.register(this, '!game', this.setGame, constants.OWNER_ONLY)
  216.  
  217.   global.parser.registerParser(this, 'lastseen', this.lastseenUpdate, constants.VIEWERS)
  218.  
  219.   global.configuration.register('uptimeFormat', 'core.settings.uptime-format', 'string', '(days)(hours)(minutes)(seconds)')
  220.  
  221.   this.webPanel()
  222. }
  223.  
  224. Twitch.prototype._load = function (self) {
  225.   global.botDB.findOne({ _id: 'cachedGamesTitles' }, function (err, item) {
  226.     if (err) return global.log.error(err, { fnc: 'Twitch.prototype._load' })
  227.     if (_.isNull(item)) return
  228.     self.cGamesTitles = item
  229.   })
  230.   global.botDB.findOne({ _id: 'when' }, function (err, item) {
  231.     if (err) return global.log.error(err, { fnc: 'Twitch.prototype._load#2' })
  232.     if (_.isNull(item)) return
  233.     self.when = item
  234.   })
  235.   global.botDB.findOne({ _id: 'cached' }, function (err, item) {
  236.     if (err) return global.log.error(err, { fnc: 'Twitch.prototype._load#3' })
  237.     if (_.isNull(item)) return
  238.     self.cached = item
  239.   })
  240. }
  241.  
  242. Twitch.prototype._save = function (self) {
  243.   var cachedGamesTitles = self.cGamesTitles
  244.   cachedGamesTitles._id = 'cachedGamesTitles'
  245.   global.botDB.remove({ _id: cachedGamesTitles._id })
  246.   global.botDB.insert(cachedGamesTitles)
  247.   global.botDB.update({ _id: 'when' }, { $set: self.when }, { upsert: true })
  248.   global.botDB.update({ _id: 'cached' }, { $set: self.cached }, { upsert: true })
  249.   self.timestamp = new Date().getTime()
  250. }
  251.  
  252. Twitch.prototype.saveStream = function (stream) {
  253.   this.currentViewers = stream.viewers
  254.   this.when.online = stream.created_at
  255.   this.maxViewers = this.maxViewers < this.currentViewers ? this.currentViewers : this.maxViewers
  256.  
  257.   var messages = global.parser.linesParsed - this.chatMessagesAtStart
  258.   global.stats.save({
  259.     timestamp: new Date().getTime(),
  260.     whenOnline: this.when.online,
  261.     currentViewers: this.currentViewers,
  262.     chatMessages: messages,
  263.     currentFollowers: this.currentFollowers,
  264.     currentViews: this.currentViews,
  265.     maxViewers: this.maxViewers,
  266.     newChatters: this.newChatters,
  267.     game: this.currentGame,
  268.     status: this.currentStatus,
  269.     currentHosts: this.currentHosts
  270.   })
  271. }
  272.  
  273. Twitch.prototype.webPanel = function () {
  274.   global.panel.addWidget('twitch', 'widget-title-monitor', 'facetime-video')
  275.   global.panel.socketListening(this, 'getTwitchVideo', this.sendTwitchVideo)
  276.   global.panel.socketListening(this, 'getStats', this.sendStats)
  277. }
  278.  
  279. Twitch.prototype.sendStats = function (self, socket) {
  280.   var messages = self.isOnline ? global.parser.linesParsed - self.chatMessagesAtStart : 0
  281.   var data = {
  282.     uptime: self.getTime(self.when.online, false),
  283.     currentViewers: self.currentViewers,
  284.     maxViewers: self.maxViewers,
  285.     chatMessages: messages > 20000 ? (messages / 1000) + 'k' : messages,
  286.     currentFollowers: self.currentFollowers,
  287.     currentViews: self.currentViews,
  288.     newChatters: self.newChatters,
  289.     game: self.currentGame,
  290.     status: self.currentStatus,
  291.     currentHosts: self.currentHosts
  292.   }
  293.   socket.emit('stats', data)
  294. }
  295.  
  296. Twitch.prototype.sendTwitchVideo = function (self, socket) {
  297.   socket.emit('twitchVideo', global.configuration.get().twitch.channel.toLowerCase())
  298. }
  299.  
  300. Twitch.prototype.isOnline = function () {
  301.   return this.isOnline
  302. }
  303.  
  304. Twitch.prototype.getTime = function (time, isChat) {
  305.   var now, days, hours, minutes, seconds
  306.   now = _.isNull(time) || !time ? {days: 0, hours: 0, minutes: 0, seconds: 0} : moment().preciseDiff(time, true)
  307.   if (isChat) {
  308.     days = now.days > 0 ? now.days + 'd' : ''
  309.     hours = now.hours > 0 ? now.hours + 'h' : ''
  310.     minutes = now.minutes > 0 ? now.minutes + 'm' : ''
  311.     seconds = now.seconds > 0 ? now.seconds + 's' : ''
  312.     return { days: days,
  313.       hours: hours,
  314.       minutes: minutes,
  315.       seconds: seconds }
  316.   } else {
  317.     days = now.days > 0 ? now.days + 'd' : ''
  318.     hours = now.hours >= 0 && now.hours < 10 ? '0' + now.hours + ':' : now.hours + ':'
  319.     minutes = now.minutes >= 0 && now.minutes < 10 ? '0' + now.minutes + ':' : now.minutes + ':'
  320.     seconds = now.seconds >= 0 && now.seconds < 10 ? '0' + now.seconds : now.seconds
  321.     return days + hours + minutes + seconds
  322.   }
  323. }
  324.  
  325. Twitch.prototype.uptime = function (self, sender) {
  326.   const time = self.getTime(self.isOnline ? self.when.online : self.when.offline, true)
  327.   global.commons.sendMessage(global.translate(self.isOnline ? 'core.online' : 'core.offline')
  328.     .replace('(time)', global.configuration.getValue('uptimeFormat')
  329.     .replace('(days)', time.days)
  330.     .replace('(hours)', time.hours)
  331.     .replace('(minutes)', time.minutes)
  332.     .replace('(seconds)', time.seconds)), sender)
  333. }
  334.  
  335. Twitch.prototype.lastseenUpdate = function (self, id, sender, text) {
  336.   if (_.isNull(sender)) {
  337.     global.updateQueue(id, true)
  338.     return
  339.   }
  340.   global.users.set(sender.username, { time: { message: new Date().getTime() } }, true)
  341.   if (_.isUndefined(global.users.get(sender.username).is) || !global.users.get(sender.username).is.online) global.users.set(sender.username, { is: { online: true } }, true)
  342.   global.users.set(sender.username, { is: { subscriber: sender.subscriber } }, true) // save subscriber status
  343.   global.updateQueue(id, true)
  344. }
  345.  
  346. Twitch.prototype.followage = function (self, sender, text) {
  347.   let username
  348.   let parsed = text.match(/^(\S?)+$/g)
  349.   if (parsed[0].length > 0) username = parsed[0]
  350.   else username = sender.username
  351.  
  352.   global.users.isFollower(username)
  353.  
  354.   const user = global.users.get(username)
  355.   if (_.isNil(user) || _.isNil(user.time) || _.isNil(user.time.follow) || _.isNil(user.is.follower) || !user.is.follower) {
  356.     global.commons.sendMessage(global.translate('followage.success.never').replace('(username)', username), sender)
  357.   } else {
  358.     let diff = moment.preciseDiff(user.time.follow, moment(), true)
  359.     let output = []
  360.     if (diff.years) output.push(diff.years + ' ' + global.parser.getLocalizedName(diff.years, 'core.years'))
  361.     if (diff.months) output.push(diff.months + ' ' + global.parser.getLocalizedName(diff.months, 'core.months'))
  362.     if (diff.days) output.push(diff.days + ' ' + global.parser.getLocalizedName(diff.days, 'core.days'))
  363.     if (diff.hours) output.push(diff.hours + ' ' + global.parser.getLocalizedName(diff.hours, 'core.hours'))
  364.     global.commons.sendMessage(global.translate('followage.success.time')
  365.       .replace('(username)', username)
  366.       .replace('(diff)', output.join(', ')), sender)
  367.   }
  368. }
  369.  
  370. Twitch.prototype.age = function (self, sender, text) {
  371.   let username
  372.   let parsed = text.match(/^(\S?)+$/g)
  373.   if (parsed[0].length > 0) username = parsed[0].toLowerCase()
  374.   else username = sender.username
  375.  
  376.   const user = global.users.get(username)
  377.   if (_.isNil(user) || _.isNil(user.time) || _.isNil(user.time.created_at)) {
  378.     global.commons.sendMessage(global.translate('age.failed').replace('(username)', username), sender)
  379.   } else {
  380.     let diff = moment.preciseDiff(user.time.created_at, moment(), true)
  381.     let output = []
  382.     if (diff.years) output.push(diff.years + ' ' + global.parser.getLocalizedName(diff.years, 'core.years'))
  383.     if (diff.months) output.push(diff.months + ' ' + global.parser.getLocalizedName(diff.months, 'core.months'))
  384.     if (diff.days) output.push(diff.days + ' ' + global.parser.getLocalizedName(diff.days, 'core.days'))
  385.     if (diff.hours) output.push(diff.hours + ' ' + global.parser.getLocalizedName(diff.hours, 'core.hours'))
  386.     global.commons.sendMessage(global.translate(sender.username.toLowerCase() !== username.toLowerCase() ? 'age.success.withUsername' : 'age.success.withoutUsername')
  387.       .replace('(username)', username)
  388.       .replace('(diff)', output.join(', ')), sender)
  389.   }
  390. }
  391.  
  392. Twitch.prototype.lastseen = function (self, sender, text) {
  393.   try {
  394.     var parsed = text.match(/^([\u0500-\u052F\u0400-\u04FF\w]+)$/)
  395.     const user = global.users.get(parsed[0])
  396.     if (_.isNil(user) || _.isNil(user.time) || _.isNil(user.time.message)) {
  397.       global.commons.sendMessage(global.translate('lastseen.success.never').replace('(username)', parsed[0]), sender)
  398.     } else {
  399.       global.commons.sendMessage(global.translate('lastseen.success.time')
  400.         .replace('(username)', parsed[0])
  401.         .replace('(when)', moment.unix(user.time.message / 1000).format('DD-MM-YYYY HH:mm:ss')), sender)
  402.     }
  403.   } catch (e) {
  404.     global.commons.sendMessage(global.translate('lastseen.failed.parse'), sender)
  405.   }
  406. }
  407.  
  408. Twitch.prototype.watched = function (self, sender, text) {
  409.   try {
  410.     let watched, parsed
  411.     parsed = text.match(/^([\u0500-\u052F\u0400-\u04FF\w]+)$/)
  412.     const user = global.users.get(text.trim() < 1 ? sender.username : parsed[0])
  413.     watched = parseInt(!_.isNil(user) && !_.isNil(user.time) && !_.isNil(user.time.watched) ? user.time.watched : 0) / 1000 / 60 / 60
  414.  
  415.     let username = (global.configuration.getValue('atUsername') ? '@' : '') + user.username
  416.     global.commons.sendMessage(global.translate('watched.success.time')
  417.       .replace('(time)', watched.toFixed(1))
  418.       .replace('(username)', username), sender)
  419.   } catch (e) {
  420.     global.commons.sendMessage(global.translate('watched.failed.parse'), sender)
  421.   }
  422. }
  423.  
  424. Twitch.prototype.showMe = function (self, sender, text) {
  425.   try {
  426.     const user = global.users.get(sender.username)
  427.     var message = ['(sender)']
  428.     // rank
  429.     var rank = !_.isUndefined(user.rank) ? user.rank : null
  430.     rank = !_.isNil(user.custom.rank) ? user.custom.rank : null
  431.     if (global.configuration.get().systems.ranks === true && !_.isNull(rank)) message.push(rank)
  432.  
  433.     // watchTime
  434.     var watchTime = _.isFinite(parseInt(user.time.watched, 10)) && _.isNumber(parseInt(user.time.watched, 10)) ? user.time.watched : 0
  435.     message.push((watchTime / 1000 / 60 / 60).toFixed(1) + 'h')
  436.  
  437.     // points
  438.     var points = !_.isUndefined(user.points) ? user.points : 0
  439.     if (global.configuration.get().systems.points === true) message.push(points + ' ' + global.systems.points.getPointsName(points))
  440.  
  441.     // message count
  442.     var messages = !_.isUndefined(user.stats.messages) ? user.stats.messages : 0
  443.     message.push(messages + ' ' + global.parser.getLocalizedName(messages, 'core.messages'))
  444.  
  445.     global.commons.sendMessage(message.join(' | '), sender)
  446.   } catch (e) {
  447.     global.log.error(e, { fnc: 'Twitch.prototype.showMe' })
  448.   }
  449. }
  450.  
  451. Twitch.prototype.showTop = function (self, sender, text) {
  452.   try {
  453.     let sorted, message
  454.     let type = text.trim().match(/^(time|points)$/)
  455.  
  456.     if (_.isNil(type)) type = 'time'
  457.     else type = type[1]
  458.  
  459.     if (type === 'points' && global.commons.isSystemEnabled('points')) {
  460.       sorted = _.orderBy(_.filter(global.users.users, function (o) { return !_.isNil(o.points) && !global.parser.isOwner(o.username) && o.username !== global.configuration.get().twitch.username }), 'points', 'desc')
  461.     } else {
  462.       sorted = _.orderBy(_.filter(global.users.users, function (o) { return !_.isNil(o.time.watched) && !global.parser.isOwner(o.username) && o.username !== global.configuration.get().twitch.username }), 'time.watched', 'desc')
  463.     }
  464.  
  465.     sorted = _.chunk(_.map(sorted, 'username'), 10)[0]
  466.  
  467.     message = global.translate(type === 'points' ? 'top.listPoints' : 'top.listWatched').replace('(amount)', 10)
  468.     _.each(sorted, function (username, index) {
  469.       message += (index + 1) + '. ' + (global.configuration.getValue('atUsername') ? '@' : '') + username + ' - '
  470.       if (type === 'time') message += (global.users.get(username).time.watched / 1000 / 60 / 60).toFixed(1) + 'h'
  471.       else message += global.users.get(username).points + ' ' + global.systems.points.getPointsName(global.users.get(username).points)
  472.       if (index + 1 < 10) message += ', '
  473.     })
  474.     global.commons.sendMessage(message, sender)
  475.   } catch (e) {
  476.     console.log(e)
  477.     global.log.error(e)
  478.   }
  479. }
  480.  
  481. Twitch.prototype.setTitleAndGame = async function (self, sender, args) {
  482.   args = _.defaults(args, { title: null }, { game: null })
  483.  
  484.   const options = {
  485.     url: 'https://api.twitch.tv/kraken/channels/' + global.channelId,
  486.     json: true,
  487.     method: 'PUT',
  488.     body: {
  489.       channel: {
  490.         game: !_.isNull(args.game) ? args.game : self.currentGame,
  491.         status: !_.isNull(args.title) ? args.title : self.currentStatus
  492.       }
  493.     },
  494.     headers: {
  495.       Accept: 'application/vnd.twitchtv.v5+json',
  496.       Authorization: 'OAuth ' + global.configuration.get().twitch.password.split(':')[1]
  497.     }
  498.   }
  499.   if (global.configuration.get().bot.debug) {
  500.     global.log.debug('Updating game and title ', options)
  501.   }
  502.  
  503.   try {
  504.     const response = await request(options)
  505.     if (global.configuration.get().bot.debug) {
  506.       global.log.debug('Response: Updating game and title ', response)
  507.     }
  508.  
  509.     if (!_.isNull(args.game)) {
  510.       if (response.game === args.game.trim()) {
  511.         global.commons.sendMessage(global.translate('game.change.success')
  512.           .replace('(game)', response.game), sender)
  513.         self.currentGame = response.game
  514.       } else {
  515.         global.commons.sendMessage(global.translate('game.change.failed')
  516.           .replace('(game)', self.currentGame), sender)
  517.       }
  518.     }
  519.  
  520.     if (!_.isNull(args.title)) {
  521.       if (response.status === args.title.trim()) {
  522.         global.commons.sendMessage(global.translate('title.change.success')
  523.           .replace('(status)', response.status), sender)
  524.         self.currentStatus = response.status
  525.       } else {
  526.         global.commons.sendMessage(global.translate('title.change.failed')
  527.           .replace('(status)', self.currentStatus), sender)
  528.       }
  529.     }
  530.   } catch (e) {
  531.     if (global.configuration.get().bot.debug) {
  532.       global.log.debug('Response: Updating game and title ', e.message)
  533.     }
  534.   }
  535.   /*
  536.   global.client.api(options, function (err, res, body) {
  537.     if (err) { return global.log.error(err, { fnc: 'Twitch.prototype.setTitleAndGame' }) }
  538.  
  539.     if (global.configuration.get().bot.debug) {
  540.       global.log.debug('Response: Updating game and title ', body)
  541.     }
  542.  
  543.     if (!_.isNull(args.game)) {
  544.       if (body.game === args.game.trim()) {
  545.         global.commons.sendMessage(global.translate('game.change.success')
  546.           .replace('(game)', body.game), sender)
  547.         self.currentGame = body.game
  548.       } else {
  549.         global.commons.sendMessage(global.translate('game.change.failed')
  550.           .replace('(game)', self.currentGame), sender)
  551.       }
  552.     }
  553.  
  554.     if (!_.isNull(args.title)) {
  555.       if (body.status === args.title.trim()) {
  556.         global.commons.sendMessage(global.translate('title.change.success')
  557.           .replace('(status)', body.status), sender)
  558.         self.currentStatus = body.status
  559.       } else {
  560.         global.commons.sendMessage(global.translate('title.change.failed')
  561.           .replace('(status)', self.currentStatus), sender)
  562.       }
  563.     }
  564.   })
  565.   */
  566. }
  567.  
  568. Twitch.prototype.setTitle = function (self, sender, text) {
  569.   if (text.trim().length === 0) {
  570.     global.commons.sendMessage(global.translate('title.current')
  571.       .replace('(title)', self.currentStatus), sender)
  572.     return
  573.   }
  574.   self.setTitleAndGame(self, sender, { title: text })
  575. }
  576.  
  577. Twitch.prototype.setGame = function (self, sender, text) {
  578.   if (text.trim().length === 0) {
  579.     global.commons.sendMessage(global.translate('game.current')
  580.       .replace('(game)', self.currentGame), sender)
  581.     return
  582.   }
  583.   self.setTitleAndGame(self, sender, { game: text })
  584. }
  585.  
  586. Twitch.prototype.sendGameFromTwitch = function (self, socket, game) {
  587.   const options = {
  588.     url: 'https://api.twitch.tv/kraken/search/games?query=' + encodeURIComponent(game) + '&type=suggest',
  589.     json: true,
  590.     headers: {
  591.       Accept: 'application/vnd.twitchtv.v5+json',
  592.       'Client-ID': global.configuration.get().twitch.clientId
  593.     }
  594.   }
  595.  
  596.   if (global.configuration.get().bot.debug) {
  597.     global.log.debug('Search game on twitch ', options)
  598.   }
  599.  
  600.   global.client.api(options, function (err, res, body) {
  601.     if (err) { return global.log.error(err, { fnc: 'Twitch.prototype.sendGameFromTwitch' }) }
  602.  
  603.     if (global.configuration.get().bot.debug) {
  604.       global.log.debug('Response: Search game on twitch ', body)
  605.     }
  606.  
  607.     if (_.isNull(body.games)) {
  608.       socket.emit('sendGameFromTwitch', false)
  609.     } else {
  610.       socket.emit('sendGameFromTwitch', _.map(body.games, 'name'))
  611.     }
  612.   })
  613. }
  614.  
  615. Twitch.prototype.deleteUserTwitchGame = function (self, socket, game) {
  616.   delete self.cGamesTitles[game]
  617.   self.sendUserTwitchGamesAndTitles(self, socket)
  618. }
  619.  
  620. Twitch.prototype.deleteUserTwitchTitle = function (self, socket, data) {
  621.   _.remove(self.cGamesTitles[data.game], function (aTitle) {
  622.     return aTitle === data.title
  623.   })
  624.   self.sendUserTwitchGamesAndTitles(self, socket)
  625. }
  626.  
  627. Twitch.prototype.sendUserTwitchGamesAndTitles = function (self, socket) {
  628.   socket.emit('sendUserTwitchGamesAndTitles', self.cGamesTitles)
  629. }
  630.  
  631. Twitch.prototype.updateGameAndTitle = function (self, socket, data) {
  632.   self.setTitleAndGame(self, null, data)
  633.  
  634.   if (_.isUndefined(self.cGamesTitles[data.game])) { // create key if doesnt exists
  635.     self.cGamesTitles[data.game] = []
  636.   }
  637.  
  638.   if (self.cGamesTitles[data.game].indexOf(data.title) === -1) { // if unique
  639.     self.cGamesTitles[data.game].push(data.title) // also, we need to add game and title to cached property
  640.   }
  641.   self.sendStats(self, global.panel.io) // force dashboard update
  642. }
  643.  
  644. module.exports = Twitch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement