99 lines
2.3 KiB
JavaScript
99 lines
2.3 KiB
JavaScript
const axios = require('axios')
|
|
const config = require('@config/index')
|
|
const client = axios.create({
|
|
baseURL: 'https://api.twitch.tv/helix',
|
|
headers: {
|
|
'Client-ID': config.twitch.clientid
|
|
}
|
|
})
|
|
const querystring = require('querystring')
|
|
|
|
/**
|
|
* get twitch user id by login name
|
|
* @param {string} name login name
|
|
*/
|
|
const getUserIDByName = async (name = '') => {
|
|
if (typeof name !== 'string' || name.trim().length === 0) return null
|
|
name = name.trim()
|
|
let url = '/users'
|
|
let params = {
|
|
login: name
|
|
}
|
|
let res = await client({
|
|
url,
|
|
method: 'get',
|
|
params
|
|
})
|
|
if (!('data' in res) || !('data' in res.data) || !Array.isArray(res.data.data) || res.data.data.length === 0) return null
|
|
let userInfo = res.data.data[0]
|
|
if (!('id' in userInfo) || !('login' in userInfo)) return null
|
|
return {
|
|
id: userInfo.id,
|
|
login: userInfo.login
|
|
}
|
|
}
|
|
|
|
const registerWebHook = async (uid = '', type = null) => {
|
|
if (!typeof uid === 'string' || uid.trim().length === 0) return null
|
|
uid = uid.trim()
|
|
let topic = null
|
|
switch (type) {
|
|
case 'live':
|
|
topic = `https://api.twitch.tv/helix/streams?user_id=${encodeURIComponent(uid)}`
|
|
break
|
|
}
|
|
if (topic === null) return null
|
|
let url = '/webhooks/hub'
|
|
let data = {
|
|
'hub.mode': 'subscribe',
|
|
'hub.topic': topic,
|
|
'hub.callback': `${config.url.replace(/\/$/, '')}/twitch/webhook?uid=${encodeURIComponent(uid)}&type=${encodeURIComponent(type)}`,
|
|
'hub.lease_seconds': 864000,
|
|
'hub.secret': config.twitch.subsecret
|
|
}
|
|
try {
|
|
await client({
|
|
method: 'post',
|
|
data,
|
|
url
|
|
})
|
|
} catch (err) {
|
|
console.log(err)
|
|
}
|
|
return null
|
|
}
|
|
|
|
const getUserStream = async (uids = []) => {
|
|
if (!uids || !Array.isArray(uids) || uids.length === 0) return null
|
|
let res = []
|
|
while (uids.length > 0) {
|
|
let tmp = uids.splice(0, 50)
|
|
let url = '/streams'
|
|
let params = {
|
|
user_id: [...tmp]
|
|
}
|
|
try {
|
|
let result = await client({
|
|
method: 'get',
|
|
url,
|
|
params,
|
|
paramsSerializer: function (params) {
|
|
return querystring.stringify(params)
|
|
}
|
|
})
|
|
if (!('data' in result) || !('data' in result.data)) continue
|
|
res = [...result.data.data]
|
|
} catch (err) {
|
|
console.log(err)
|
|
}
|
|
}
|
|
|
|
return res
|
|
}
|
|
|
|
module.exports = {
|
|
registerWebHook,
|
|
getUserIDByName,
|
|
getUserStream
|
|
}
|