twitch-bot/route/index.js

104 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-02-12 15:08:42 +00:00
const Router = require('koa-router')
const r = new Router()
const config = require('../config')
const qs = require('querystring')
const request = require('request')
r.get('/', async (c, n) => {
await c.render('index')
})
r.get('/chat_login', async (c, n) => {
let url = config.twitch.auth_url
let qsObj = {
client_id: config.twitch.client_id,
redirect_uri: config.twitch.redirect_uri,
response_type: 'code',
scope: 'chat_login'
}
let qsStr = qs.stringify(qsObj)
let toUrl = `${url}?${qsStr}`
c.redirect(toUrl)
})
r.get('/login', async (c, n) => {
let url = config.twitch.auth_url
let qsObj = {
client_id: config.twitch.client_id,
redirect_uri: config.twitch.redirect_uri,
response_type: 'code',
scope: 'user_read'
}
let qsStr = qs.stringify(qsObj)
let toUrl = `${url}?${qsStr}`
c.redirect(toUrl)
})
r.get('/twitch/oauth', async (c, n) => {
let code = c.query.code || ''
if (!code) {
await c.render('test', {
data: {
msg: 'code not found'
}
})
return
}
let url = config.twitch.token_url
let qsObj = {
client_id: config.twitch.client_id,
client_secret: config.twitch.secret,
code,
grant_type: 'authorization_code',
redirect_uri: config.twitch.redirect_uri
}
let qsStr = qs.stringify(qsObj)
let toUrl = `${url}?${qsStr}`
let body = await new Promise((resolve, reject) => {
request.post(toUrl, (err, res, body) => {
if (err) {
reject(err)
return
}
try {
resolve(JSON.parse(body))
} catch (err) {
resolve(body)
}
})
})
let opts = {
url: 'https://api.twitch.tv/kraken/user',
headers: {
'Client-ID': config.twitch.client_id,
'Authorization': 'OAuth ' + body.access_token
},
method: 'get'
}
let userProfile = await new Promise((resolve) => {
request(opts, (err, res, body) => {
console.log('get profile', body)
if (err) {
resolve(null)
return
}
2018-02-21 06:14:31 +00:00
try {
body = JSON.parse(body)
}catch (err){}
2018-02-12 15:08:42 +00:00
resolve(body)
})
})
await c.render('test', { data: { body, userProfile } })
})
module.exports = r