index.js 16.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
const express = require('express');
const router = express.Router();
const { spawn, exec } = require('child_process');
const fs = require("fs");
var path = require('path')
const OSS = require('ali-oss');
require('dotenv').config(); // 加载环境变量

const method = require("../config/method")
const config = require("../config/config")
const {
    highlightRecordingService,
    HighlightValidationError,
    HighlightUpstreamError
} = require('../services/highlightRecordingService');
const version ='v1.2.0.20251208';
// const { GETCLASSURL, GETCLASSURLPARAMETER, PROJECTCATALOG, PROJECTWINCATALOG, BACKMEDIACONFIG } = config
const { YesterdayTime,getDayTime, getRequestClassIds, dayTimeYMD } = method

let siteIds = []

let classid = []
let classidPost = []
let classTasks=[];
let parentData = {}
var classobj = {};
let className = ""
let yesterday = "" // get写入课堂的时间

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

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

    // 取出所有数据
    async allData() {
        // const { startTime, endTime } = YesterdayTime()
        let yesterday=YesterdayTime();
        let startTime = yesterday.startTime
        let endTime = yesterday.endTime

        let fileConfig = new MediaCreat().getConfigFileJson()
        if (!fileConfig) return false
        className = siteIds.shift()
        const { GETCLASSURL, GETCLASSURLPARAMETER, classLastNumber } = JSON.parse(fileConfig)
        let page = 1
        if (className) {
            if(GETCLASSURLPARAMETER.recordDateYYMMDD){
                let dateInfo = getDayTime(GETCLASSURLPARAMETER.recordDateYYMMDD)
                if(dateInfo.startTime){
                    startTime = dateInfo.startTime
                    endTime = dateInfo.endTime
                }
            }

            let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime, page)
            // parentData[result.data.data.siteId] = new Set()
            let resultList = result.data.data.list
            for (let j = 0; j < resultList.length; j++) {
                let item = resultList[j]
                let classId = item['classId']
                let number = classId.substr(classId.length - 1, 1)
                if (classLastNumber.includes(number)){
                    classid.push(item)
                    // parentData[result.data.data.siteId].add(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)
                let resultList = result.data.data.list
                for (let j = 0; j < resultList.length; j++) {
                    let item = resultList[j]
                    let classId = item['classId']
                    let number = classId.substr(classId.length - 1, 1)
                    if (classLastNumber.includes(number)) {
                        classid.push(item)
                        // parentData[result.data.data.siteId].add(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');
    }

    recordingCreat(id, siteId, type,yymmdd="") {
        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 = null
        if (type == 'post') {
            ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" + dayTimeYMD().ymd
        } else {
            // get 的目录创建为上一天日期
            ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" + yesterday
        }
        //如果指定了时间就按指定时间处理
        if(yymmdd){
            ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" +yymmdd;
        }

        if (!fs.existsSync(mediaDir)) {
            fs.mkdirSync(mediaDir);
        }
        if (!fs.existsSync(classDir)) {
            fs.mkdirSync(classDir);
        }
        if (!fs.existsSync(ymdDir)) {
            fs.mkdirSync(ymdDir);
        }
        let files = fs.readdirSync(ymdDir);
        // let interValGetFile = setInterval(()=>{
        this.wrieLog("ymdDir" + ymdDir)
	this.wrieLog("files:" + files)
        if (files.indexOf(id + ".mp4") != -1) {
            this.wrieLog("已存在:" + id + "课堂号,停止继续录制")
            if (type == 'post') {
                if (classidPost.length) {
                    let shiftData = classidPost.shift()
                    this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                    this.recordingCreat(shiftData['classId'], shiftData['siteId'], type)
                }
            } else {
                if (classid.length) {
                    let shiftData = classid.shift()
                    this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                    this.recordingCreat(shiftData['classId'], shiftData['siteId'], type)
                }
            }
            return
        }
        // 目前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}&language=zh-cn" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa} -k=${BACKMEDIACONFIG.k} -w=${BACKMEDIACONFIG.w} -h=${BACKMEDIACONFIG.h} -ar=44100`
        this.wrieLog(" 启动url " + url)
	exec(url, { maxBuffer: 1073741824 }, (err, stdout, stderr) => {
            if (err != null) {
                this.wrieLog(" 错误" + id + ":" + err)
                this.wrieLog(" 错误 stdout" + id + ":" + stdout)
                this.wrieLog(" 错误 stderr" + id + ":" + stderr)
                return
            }
            let files = fs.readdirSync(ymdDir);
            // let interValGetFile = setInterval(()=>{
            if (files.indexOf(id + ".mp4") == -1) {
                this.wrieLog(" 课堂录制未发现该" + id + "课堂号")
            } else {
                if (type == 'get') {
                    if (classid.length) {
                        let shiftData = classid.shift()
                        this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                        this.recordingCreat(shiftData['classId'], shiftData['siteId'], type)
                    } else {
                        this.wrieLog("录制结束:------>")
                        fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
                            if (err) {
                                console.log(err);
                            }
                        });
                    }
                } else {
                    if (classidPost.length) {
                        let shiftData = classidPost.shift()
                        this.wrieLog(" 录制下一节课 课堂号:" + shiftData['classId'])
                        this.recordingCreat(shiftData['classId'], shiftData['siteId'], type)
                    } 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('/recording', 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 parsedConfig = JSON.parse(fileConfig)
    if (parsedConfig.HIGHLIGHTCONFIG && parsedConfig.HIGHLIGHTCONFIG.enabled === true) {
        try {
            const data = await highlightRecordingService.runScheduledRecording()
            res.send({ code: "0", message: data.received ? "success" : "无高光数据", data })
        } catch (error) {
            new MediaCreat().wrieLog("高光录制任务读取失败:------>" + (error.message || error))
            if (error instanceof HighlightValidationError) {
                res.status(400).send({ code: "1", message: error.message })
            } else if (error instanceof HighlightUpstreamError) {
                res.status(502).send({ code: String(error.upstreamCode), message: error.message })
            } else {
                res.status(500).send({ code: "-1", message: "高光录制任务读取失败" })
            }
        }
        return
    }

    const { GETCLASSURLPARAMETER } = parsedConfig
    siteIds = GETCLASSURLPARAMETER.siteId
    if (siteIds.length == 0) {
        new MediaCreat().wrieLog("脚本录制,未配置siteId:------>" + siteIds)
        res.send({ code: "1", message: "未配置siteId", data: siteIds });
        return
    }
    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) {
                    yesterday = YesterdayTime().ymd
                    new MediaCreat().recordingCreat(shiftData['classId'], shiftData['siteId'], 'get')
                } else {
                    return false
                }
            }
            res.send({ code: "0" });
        } else {
            res.send({ code: "1", message: "无录制数据" });
        }
    } 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 (classidPost.length > 0) {
        // 有正在录制中的课堂,禁止重复
        res.send({ code: "1", message: "有正在录制中的课堂", data: classidPost });
        return
    }
    if (classId && classId.length) {
        classidPost = classId
        if (!maxMedia || maxMedia == undefined) {
            maxMedia = 1
        }
        for (let i = 0; i < maxMedia; i++) {
            let shiftData = classidPost.shift()
            if (shiftData) {
                new MediaCreat().recordingCreat(shiftData['classId'], shiftData['siteId'], 'post')
            } else {
                return false
            }
        }
        res.send({ code: "0" });
    } else {
        res.send({ code: "1", message: "无录制数据" });
    }

})

// 判断该视频文件是否存在
router.post('/fileExists', async (req, res) => {
    const { siteId, classId, classStartTime } = req.body;

    // 检查输入参数
    if (!siteId) {
        return res.status(400).send({ code: 2, message: "机构编码无效" });
    }
    if (!classId) {
        return res.status(400).send({ code: 3, message: "课堂号无效" });
    }

    try {
        // 检查环境变量是否设置
        if (!process.env.ALIBABA_CLOUD_ACCESS_KEY_ID || !process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET) {
            throw new Error('Environment variables are not set correctly.');
        }

        // 创建OSS客户端实例
        const client = new OSS({
            region: 'oss-cn-beijing',
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
            authorizationV4: true,
            bucket: 'xdymp4'
        });

        // 构建文件前缀
        let prefix = '';
        if (classStartTime) {
            prefix = `oss/${siteId}/${classStartTime}/${classId}.mp4`;
        } else {
            // 如果没有提供classStartTime,默认返回文件未生成
            let classUrl = `https://pclive.xuedianyun.com/pcBase/pclive2/release/index.html?portalIP=saas.xuedianyun.com&portalPort=80&classId=${classId}&channels=2&playRecord=1#/`;
            return res.send({ code: 1, message: "文件未生成", classUrl });
        }

        // 使用 await 处理异步操作
        const result = await client.list({ prefix });
        console.log('OSS list result:', JSON.stringify(result, null, 2)); // 日志记录详细结果

        // 检查是否有匹配的文件
        let isVideo = false;
        let url = "";
        if (result.res.status === 200 && result.objects && result.objects.length > 0) {
            for (let item of result.objects) {
                // 更精确的匹配逻辑,确保找到的是目标文件
                if (item.name === `${prefix}`) {
                    isVideo = true;
                    url = item.name;
                    break;
                }
            }
        }

        // 根据结果发送响应
        if (!isVideo) {
            let classUrl = `https://pclive.xuedianyun.com/pcBase/pclive2/release/index.html?portalIP=saas.xuedianyun.com&portalPort=80&classId=${classId}&channels=2&playRecord=1#/`;
            res.send({ code: 1, message: "文件未生成", classUrl });
        } else {
            let classUrl = `https://xdymp4.xuedianyun.com/${url}`;
            res.send({ code: 0, message: "文件已生成", classUrl });
        }

    } catch (err) {
        console.error('Error checking file existence:', err);
        res.status(500).send({ code: -1, message: "服务器内部错误", error: err.message });
    }
});
router.post('/recordingTask', async function (req, res, next) {
    new MediaCreat().wrieLog("录制启动:------>")
    let fileConfig = new MediaCreat().getConfigFileJson()
    if (!fileConfig){
        res.send({ code: "1", message: "无效的fileConfig", data:[] ,v:version});
       return ;
    } 
    let { list, maxMedia } = req.body;

    if (!list||list.length <= 0) {
        // 有正在录制中的课堂,禁止重复
        res.send({ code: "1", message: "无效的数据", data: list ,v:version});
        return
    }
    if(maxMedia&&list.length>maxMedia){
        res.send({ code: "1", message: "数组长度超过设置的最大值", data: list,v:version });
        return
    }
    for (let i = 0; i < list.length; i++) {
        let classInfo =list[i];
        if (classInfo&&classInfo.classId&&classInfo.siteId) {
            new MediaCreat().recordingCreat(classInfo['classId'], classInfo['siteId'], 'post',classInfo['yymmdd']||"")
        }
    }
    res.send({ code: "0",message:"success",v:version });
})

module.exports = router