index.js 16.0 KB
var express = require('express');
var router = express.Router();
const {spawn, exec} = require('child_process');
const fs = require("fs");
var path = require('path')

const method = require("../config/method")
const config = require("../config/config")

// const { GETCLASSURL, GETCLASSURLPARAMETER, PROJECTCATALOG, PROJECTWINCATALOG, BACKMEDIACONFIG } = config
const {YesterdayTime, getRequestClassIds, dayTimeYMD} = method

let siteIds = []

let classid = []
let parentData = {}
var classobj = {};
let className = ""

// spawn("export DISPLAY=:7", { shell: true})

/**
 *
 * @param {*} id 课堂id
 */
class MediaCreat {
    constructor() {
    }

    // 取出所有数据
    async allData() {
        const {startTime, endTime} = YesterdayTime()
        let fileConfig = new MediaCreat().getConfigFileJson()
        if (!fileConfig) return false
        className = siteIds.shift()
        const {GETCLASSURL, GETCLASSURLPARAMETER} = JSON.parse(fileConfig)
        let page = 1
        if (className) {
            let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime, page)
            parentData[result.data.data.siteId] = new Set()
            for (let j = 0; j < result.data.data.list.length; j++) {
                classid.push(result.data.data.list[j])
                parentData[result.data.data.siteId].add(result.data.data.list[j]['classId'])
            }
            const {siteId, list, totalPage} = result.data.data
            for (let i = page += 1; i <= totalPage; i++) {
                let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime, i)
                for (let j = 0; j < result.data.data.list.length; j++) {
                    classid.push(result.data.data.list[j])
                    parentData[result.data.data.siteId].add(result.data.data.list[j]['classId'])
                }
            }
            parentData[result.data.data.siteId] = Array.from(parentData[result.data.data.siteId])
            if (siteIds.length) {
                return await new MediaCreat().allData()
            }
            this.wrieLog("去重前的classId:------>" + JSON.stringify(classid))
            this.wrieLog("httpData:------>" + JSON.stringify(result.data))
            return true
        } else {
            return false
        }
    }

    wrieLog(text) {
        // 写入log
        let logFile = `./log/${dayTimeYMD().ymd}.txt`
        fs.appendFileSync(logFile, new Date().toLocaleString() + " " + text + '\r\n');
    }

    // async mediaCreat(id, siteId) {
    //     const {ymd} = YesterdayTime()
    //     let fileConfig = await new MediaCreat().getConfigFileJson()
    //     if (!fileConfig) return false
    //     const {BACKMEDIACONFIG, PROJECTWINCATALOG, PROJECTCATALOG} = JSON.parse(fileConfig)
    //
    //     let mediaDir = PROJECTCATALOG + "/media/"
    //     let classDir = PROJECTCATALOG + "/media/" + siteId
    //     let ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" + ymd
    //     if (!fs.existsSync(mediaDir)) {
    //         fs.mkdirSync(mediaDir);
    //     }
    //     if (!fs.existsSync(classDir)) {
    //         fs.mkdirSync(classDir);
    //     }
    //     if (!fs.existsSync(ymdDir)) {
    //         fs.mkdirSync(ymdDir);
    //     }
    //     let url = `"${PROJECTWINCATALOG} /web_capture_c" -o=../media/${siteId}/${ymd}/${id}.mp4 -u="${BACKMEDIACONFIG.url}?classId=${id}&recordMp4=${BACKMEDIACONFIG.recordMp4}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa} -k=${BACKMEDIACONFIG.k} -w=${BACKMEDIACONFIG.w} -h=${BACKMEDIACONFIG.h}`
    //     var workerProcess = exec(url) // , {cwd: PROJECTWINCATALOG, shell: true}
    //     // workerProcess.stdout.on('data', async function (data) {
    //
    //     // });
    //
    //     workerProcess.on('close', async (code) => {
    //         let files = fs.readdirSync(ymdDir);
    //         if (files.indexOf(id + ".mp4") == -1) {
    //             //当前课堂没有写入到文件夹,进入重录
    //             new MediaCreat().mediaCreat(id, siteId)
    //             return false
    //         } else {
    //             if (parentData[siteId].indexOf(id.toString()) != -1) {
    //                 parentData[siteId].splice(parentData[siteId].indexOf(id.toString()), 1)
    //             }
    //             if (parentData[siteId].length == 0) {
    //                 //   //全部录制完毕
    //                 this.wrieLog("录制结束:------>")
    //                 fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
    //                     if (err) {
    //                         console.log(err);
    //                     }
    //                 });
    //             }
    //             if (classid.length) {
    //                 let shiftData = classid.shift()
    //                 new MediaCreat().mediaCreat(shiftData['classId'], shiftData['siteId'])
    //             }
    //         }
    //     });
    // }

    recordingCreat(id, siteId) {
        this.wrieLog(" 课堂录制开始:------>" + id)
        let fileConfig = this.getConfigFileJson()
        if (!fileConfig) return false
        const {BACKMEDIACONFIG, PROJECTWINCATALOG, PROJECTCATALOG} = JSON.parse(fileConfig)
        let mediaDir = PROJECTCATALOG + "/media/"
        let classDir = PROJECTCATALOG + "/media/" + siteId
        let ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" + dayTimeYMD().ymd
        if (!fs.existsSync(mediaDir)) {
            fs.mkdirSync(mediaDir);
        }
        if (!fs.existsSync(classDir)) {
            fs.mkdirSync(classDir);
        }
        if (!fs.existsSync(ymdDir)) {
            fs.mkdirSync(ymdDir);
        }
        // 目前url是linux的写法 win系统不支持
        // export DISPLAY=:7
        // let url = `${path.resolve(__dirname, PROJECTWINCATALOG+"/web_capture_c")} -o=${ymdDir}/${id}.mp4 -u="${BACKMEDIACONFIG.url}?classId=${id}&recordMp4=${BACKMEDIACONFIG.recordMp4}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa} -k=${BACKMEDIACONFIG.k} -w=${BACKMEDIACONFIG.w} -h=${BACKMEDIACONFIG.h}`
        // console.log("url", url)
        let url = `${PROJECTWINCATALOG}/web_capture_c -o=${ymdDir}/${id}.mp4 -u="${BACKMEDIACONFIG.url}?classId=${id}&recordMp4=${BACKMEDIACONFIG.recordMp4}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa} -k=${BACKMEDIACONFIG.k} -w=${BACKMEDIACONFIG.w} -h=${BACKMEDIACONFIG.h} -k=0`
        // console.log("url", url)
        // console.log("PROJECTWINCATALOG", PROJECTWINCATALOG)
        exec(url, {maxBuffer:1073741824},(err, stdout, stderr) => {
            // setTimeout(()=>{
                if (err != null) {
                    this.wrieLog(" 错误" + id +":" + err)
                    this.wrieLog(" 错误 stdout" + id +":" + stdout)
                    this.wrieLog(" 错误 stderr" + id +":" + stderr)
                    // if (files.indexOf(id + ".mp4") == -1) {
                    //     //     //当前课堂没有写入到文件夹,进入重录
                    //     this.wrieLog(" 课堂录制未发现该" + id + "课堂号")
                    //     this.recordingCreat(id, siteId)
                    //     //     return false
                    // }
                    // if (classid.length) {
                    //     setTimeout(()=>{
                    //         let shiftData = classid.shift()
                    //         this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                    //         this.recordingCreat(shiftData['classId'], shiftData['siteId'])
                    //     },20000)
                    //     // clearInterval(interValGetFile)
                    // }
                    return
                }
                    let files = fs.readdirSync(ymdDir);
                // let interValGetFile = setInterval(()=>{
                    if (files.indexOf(id + ".mp4") == -1) {
                        this.wrieLog(" 课堂录制未发现该" + id + "课堂号")
                    }else{
                        if (classid.length) {
                            setTimeout(()=>{
                                let shiftData = classid.shift()
                                this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                                this.recordingCreat(shiftData['classId'], shiftData['siteId'])
                            },60*1000*5)
                            // clearInterval(interValGetFile)
                        }else{
                            this.wrieLog("录制结束:------>")
                            fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
                                if (err) {
                                    console.log(err);
                                }
                            });
                            // clearInterval(interValGetFile)
                        }
                    }
                // },3000)
                // if (files.indexOf(id + ".mp4") == -1) {
                //     //     //当前课堂没有写入到文件夹,进入重录
                //     this.wrieLog(" 课堂录制未发现该" + id + "课堂号")
                //     this.recordingCreat(id, siteId)
                //     //     return false
                // } else {
                //     if (classid.length) {
                //         let shiftData = classid.shift()
                //         this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                //         this.recordingCreat(shiftData['classId'], shiftData['siteId'])
                //     } else {
                //         this.wrieLog("录制结束:------>")
                //         fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
                //             if (err) {
                //                 console.log(err);
                //             }
                //         });
                //     }
                // }
            // },20000)
        })
        // console.log("/web_capture_c",path.resolve(__dirname, PROJECTWINCATALOG+"./web_capture_c"))
        // spawnSync(path.resolve(__dirname, PROJECTWINCATALOG+"./web_capture_c"),[
        //     "-o",`${ymdDir}/${id}.mp4`,
        //     "-u",`${BACKMEDIACONFIG.url}?classId=${id}&recordMp4=${BACKMEDIACONFIG.recordMp4}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}`,
        //     "-d",`${BACKMEDIACONFIG.d}`,
        //     "-s",`${BACKMEDIACONFIG.s}`,
        //     "-fa",`${BACKMEDIACONFIG.fa}`,
        //     "-k",`${BACKMEDIACONFIG.k}`,
        //     "-w",`${BACKMEDIACONFIG.w}`,
        //     "-h",`${BACKMEDIACONFIG.h}`
        //     ])
        // workerProcess = spawnSync(url,{shell: true})// {cwd: PROJECTWINCATALOG, shell: true}
        // console.log("workerProcess",workerProcess)
        // workerProcess.stdout.on('data', function (data) {
        //         console.log("stdout",data)
        // });
        // workerProcess.stderr.on('data', (data) => {
        //     console.error(`stderr: ${data}`);
        // });
        //
        // workerProcess.on('close', (code) => {
        //     console.log("code", code)
        //     if (code == 0) {
        //         this.wrieLog(" 课堂录制结束:------>" + id)
        //         let files = fs.readdirSync(ymdDir);
        //         if (files.indexOf(id + ".mp4") == -1) {
        //             //     //当前课堂没有写入到文件夹,进入重录
        //             this.wrieLog(" 课堂录制未发现该" + id + "课堂号")
        //             new MediaCreat().recordingCreat(id, siteId)
        //             //     return false
        //         } else {
        //             if (classid.length) {
        //                 let shiftData = classid.shift()
        //                 this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
        //                 new MediaCreat().recordingCreat(shiftData['classId'], shiftData['siteId'])
        //             } else {
        //                 this.wrieLog("录制结束:------>")
        //                 fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
        //                     if (err) {
        //                         console.log(err);
        //                     }
        //                 });
        //             }
        //         }
        //     }
        // });
    }

    getConfigFileJson() {
        const buffer = fs.readFileSync(process.cwd() + "/config/config.json")
        return String(buffer)
    }
}


router.get('/', async function (req, res, next) {
    if (classid.length > 0) {
        // 有正在录制中的课堂,禁止重复
        res.send({code: "1", message: "有正在录制中的课堂", data: classid});
        return
    }
    new MediaCreat().wrieLog("脚本录制开始:------>")
    let fileConfig = new MediaCreat().getConfigFileJson()
    if (!fileConfig) return false

    const {GETCLASSURLPARAMETER} = JSON.parse(fileConfig)
    siteIds = GETCLASSURLPARAMETER.siteId
    let result = await new MediaCreat().allData()
    if (result) {
        // 去重
        classobj = {}
        classid = classid.reduce(function (item, next) {
            classobj[next.classId] ? '' : classobj[next.classId] = true && item.push(next);
            return item;
        }, []);
        // 写入log
        new MediaCreat().wrieLog("去重后的classid:------>" + JSON.stringify(classid))
        if (classid.length) {
            for (let i = 0; i < GETCLASSURLPARAMETER.maxMedia; i++) {
                let shiftData = classid.shift()
                if (shiftData) {
                    new MediaCreat().recordingCreat(shiftData['classId'], shiftData['siteId'])
                } else {
                    return false
                }
            }
            res.send({code: "0"});
        } else {
            res.send({code: "1", message: "无录制数据"});
        }
    }
});

/**
 * {
 * "classId":[{ classId: '389675110', siteId: 'kuaikuenglish' }]
 * }
 */
router.post('/recording', async function (req, res, next) {
    new MediaCreat().wrieLog("录制启动:------>")
    let fileConfig = new MediaCreat().getConfigFileJson()
    if (!fileConfig) return false
    let {classId, maxMedia} = req.body
    if (classid.length > 0) {
        // 有正在录制中的课堂,禁止重复
        res.send({code: "1", message: "有正在录制中的课堂", data: classid});
        return
    }
    if (classId && classId.length) {
        classid = classId
        if (!maxMedia || maxMedia == undefined) {
            maxMedia = 1
        }
        console.log("maxMedia", maxMedia)
        for (let i = 0; i < maxMedia; i++) {
            let shiftData = classid.shift()
            if (shiftData) {
                new MediaCreat().recordingCreat(shiftData['classId'], shiftData['siteId'])
            } else {
                return false
            }
        }
        res.send({code: "0"});
    } else {
        res.send({code: "1", message: "无录制数据"});
    }

})


module.exports = router;