'use strict'; const moment = require('moment') module.exports = function (app, opts) { async function token4yingshi ({ key, secret, token, expire } = {}) { const { models } = app.fs.dc if (!key || !secret) { throw '参数 { key, secret } 缺一不可' } if (token && expire && moment().isBefore(moment(expire))) { return token } else { const secretRes = await models.SecretYingshi.findOne({ where: { key, secret } }) if (secretRes && secretRes.expire && secretRes.token && moment().isBefore(moment(secretRes.expire))) { return secretRes.token } } // 也可以做基于 redis 的缓存 const tokenRes = await app.fs.yingshiRequest.post(`lapp/token/get`, { query: { appKey: key, appSecret: secret } }) if (tokenRes.code == 200) { const { accessToken, expireTime } = tokenRes.data await models.SecretYingshi.update({ token: accessToken, expire: expireTime }, { where: { key, secret } }) return accessToken } else { throw tokenRes } } async function varifyYingshiBelongSecretBySerialNo (serialNo) { const { models } = app.fs.dc const serialNo_ = String(serialNo).toUpperCase() const secretRes = await models.SecretYingshi.findAll() let beloneSecret = null for (let s of secretRes) { const tokenYingshi = await token4yingshi(s.dataValues) // 检测设备所属 const cameraState = await app.fs.yingshiRequest.post('lapp/device/info', { query: { accessToken: tokenYingshi, deviceSerial: serialNo_ } }) if (cameraState.code == 200) { beloneSecret = { ...s.dataValues, token: tokenYingshi } break } } return beloneSecret } const getYingshiPlayUrl = async ({ deviceSerial, token }) => { const protocolMap = { ezopen: 1, hls: 2, rtmp: 3, flv: 4, } const qualityMap = { hd: 1, sd: 2, } const typeMap = { // live: 1, local: 2, cloud: 3 } let playUrl = { liveUrl: {// 直播 hd: {// 高清 rtmp: '', hls: '', flv: '', ezopen: '', }, sd: {// 标清 rtmp: '', hls: '', flv: '', ezopen: '', } }, replayUrl: {// 回放 cloud: '', local: '', } } for (let protocol in protocolMap) { for (let quality in qualityMap) { const playUrlRes = await app.fs.yingshiRequest.post('lapp/v2/live/address/get', { query: { accessToken: token, deviceSerial: deviceSerial, protocol: protocolMap[protocol], quality: qualityMap[quality], } }) if (playUrlRes.code == 200) { playUrl.liveUrl[quality][protocol] = playUrlRes.data.url } else { // return null } } } for (let type in typeMap) { try { const playUrlRes = await app.fs.yingshiRequest.post('lapp/v2/live/address/get', { query: { accessToken: token, deviceSerial: deviceSerial, type: typeMap[type], } }) if (playUrlRes.code == 200) { playUrl.replayUrl[type] = playUrlRes.data.url } else { // return null } } catch (error) { app.fs.logger.error(`sechedule: freshYingshiPlayUrl, error: ${error}`); } } return playUrl } return { token4yingshi, varifyYingshiBelongSecretBySerialNo, getYingshiPlayUrl, } }