const Router = require('koa-router') const koaBody = require('koa-body') const { chkObject, resObject, APIError, genError, checkSession, calPage, toInt } = require('@libs/route-utils') const DB = require('@libs/database') const r = new Router() const { comparePassword } = require('@libs/tools') r.use(async (c, n) => { c.obj = {} c.db = await DB.connect() c.chkBody = chkObject.bind(c.request) let obj = null try { await n() } catch (err) { console.log(err) obj = resObject(err instanceof APIError ? err.resKey : 'InternalError', err.apiMsg || null, err.msgCode || null) } if (Object.keys(c.obj).length > 0 && 'status' in c.obj && 'obj' in c.obj) { c.status = c.obj.status c.body = c.obj.obj } if (obj !== null) { c.status = obj.status c.body = obj.obj } c.db.release() }) r.post('/login', koaBody(), async (c, n) => { if (!c.chkBody('account', 'string') || !c.chkBody('password', 'string')) throw genError('DataFormat') let text = `select * from "public"."account" where "account" = $1 limit 1` let values = [c.request.body.account] let userAcc = await c.db.query({text, values}) if (userAcc.rowCount === 0) throw genError('NotFound', 'user not found') let matchPass = await comparePassword(c.request.body.password, userAcc.rows[0].password) if (!matchPass) throw genError('DataFormat', 'account or password error') let user = userAcc.rows[0] delete user.password c.session.user = user c.session.loginType = 'system' c.obj = resObject('Success') }) r.post('/logout', async (c, n) => { c.session = null c.obj = resObject('Success') }) r.get('/session', checkSession, async (c, n) => { c.obj = resObject('Success', { user: c.state.loginUser }) }) r.get('/line_msg', checkSession, async (c, n) => { let p = toInt(c.query.p, 1, 1) let text = `select count(*) as c from "public"."line_message_log"` let msgCount = await c.db.query({text}) if (msgCount.rowCount === 0) throw genError('InternalError', 'database query fail') if (!('c' in msgCount.rows[0])) throw genError('InternalError', 'database query fail') let page = calPage(msgCount.rows[0].c, p, 20) text = `select g.name, u.name as user, m.message, m.ctime from "public"."line_message_log" m left join "public"."line_group" g on g.id = m.group left join "public"."line_user" u on u.id = m.user order by m.ctime desc offset $1 limit $2` let values = [page.offset, page.limit] let msgData = await c.db.query({ text, values }) c.obj = resObject('Success', { messages: msgData.rows, page: { cur: page.page, total: page.totalPage } }) }) r.use('/twitch', require('./twitch').routes()) module.exports = r