RecordInfoMatch.js 14.1 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 407 408 409
import Emiter from 'Emiter';
import MessageTypes from 'MessageTypes';
import Loger from 'Loger';

import MediaModule from "apes/MediaModule";

import Base64 from 'base64-js';
import GlobalConfig from 'GlobalConfig';
import EngineUtils from 'EngineUtils';


// 日志对象
const loger = Loger.getLoger('RecordInfoMatch');
class RecordInfoMatch extends Emiter {
  constructor() {
    super();
    this.recordMessages = {};
    this.jsonPathList = {};
    this.m3u8jsonDataList = {};
    this.streamInfoLen = 0;
    this.filePath = "";
    this.matchStreams = {};//记录匹配完成的数据
    this.unMatchStreams = {};//记录匹配完成的数据
    this.unMatchUid = {};//没有匹配到的uid
  }

  start(_recordMessagesList) {
    this.recordMessagesList=_recordMessagesList;
    let serverIp = GlobalConfig.recordFileSever || "playbak.xuedianyun.com:8080";
    this.filePath = `${GlobalConfig.locationProtocol + serverIp}`;

    if(GlobalConfig.locationProtocol=="https://"){
      this.filePath=this.filePath.replace(":8080","");
    }

    //this.getRecordInfo(()=> {
    this.parseRecordMessage(_recordMessagesList,()=> {
      console.log("JSON数据列表",this.jsonPathList);
      let requestLen = Object.keys(this.jsonPathList).length;
      let currentLen = 0;
      let fileNameArr;
      for (let i in this.jsonPathList) {
        this.getRecordFileJSON(this.jsonPathList [i], (data)=> {
          currentLen++;
          console.log(i, "getRecordFileJSON请求返回", currentLen);
          if (data) {
            for (let k in data) {
              let arr = data[k];
              let indexStr = ".m3u8";
              //"694537045_20171103073546522.m3u8" //522.m3u8是需要截取掉的内容
              for (let j of arr) {
                if (j && j.indexOf(indexStr) >= 0) {
                  //console.log("视频地址:"+i+"/"+k+"/"+j);
                  fileNameArr = j.split("_");
                  if (fileNameArr && fileNameArr.length > 0) {
                    let stream = fileNameArr[1];
                    //20171106102811807  -->20171106102811
                    stream = stream.substr(0, 14);
                    if (!this.m3u8jsonDataList[fileNameArr[0]]) {
                      this.m3u8jsonDataList[fileNameArr[0]] = {}
                    }
                    //筛除一些重复流地址,会出现多录制的情况,保留一个即可
                    this.m3u8jsonDataList[fileNameArr[0]][stream] = {
                      video_url: this.filePath + "/samples/" + i + "/" + k + "/" + j,
                      creatDate: i,
                      folder: k,
                      stream: j,
                      createTimeUTC: stream
                    };
                  }

                }
              }
            }
          }
          if (currentLen >= requestLen) {
            console.log("视频数据获取完成", this.m3u8jsonDataList);
            this.matchRecordFile(this.recordMessages, this.m3u8jsonDataList);
          }
        });
      }
    });
  }

  getRecordInfo(_callback) {
    //获取课堂录制信息   get  localhost:3000/recordInfo/getRecordInfo/7d72365eb9834353397e3e3f9d460bdda
    //localhost:3000/recordInfo/getRecordInfo/ 后面直接添加课堂号 channel
    if (!GlobalConfig.getRecordInfoInterfaces) {
      loger.log("AG-获取媒体录制信息->失败->接口地址无效");
      if (_callback) {
        _callback();
      }
      return;
    }
    let url = `${GlobalConfig.locationProtocol + GlobalConfig.getRecordInfoInterfaces}/${GlobalConfig.channelId}`;
    loger.log('AG-获取媒体录制信息.', url);
    fetch(url, {
      timeout: 15000
    })
      .then(ret => {
        if (ret.ok) {
          return ret.json();
        } else {
          loger.error(`AG-获取媒体录制信息-网络异常.状态码:${ret}`);
          if (_callback) {
            _callback();
          }
          throw '';
        }
      })
      .then(ret => {
        loger.log('AG-获取媒体录制信息-完成');
        this.parseRecordMessage(ret.returnData.data,_callback);
    /*    for (let i = 0; i < ret.returnData.data.length; i++) {
          let item = ret.returnData.data[i];
          if (item.status == 1) {
            this.streamInfoLen++;
            //console.log(JSON.stringify(item));
            delete item.appId;
            delete  item.id;
            let time = parseInt(item.createTime);
            let timeInfo = this.timestampToUTCTime(time);
            //return {yymmddhhmmss:yymmddhhmmss,yymmdd:yymmdd}
            item.seek = 0;
            item.createTimeUTC = timeInfo.yymmddhhmmss;
            item.creatDate = timeInfo.yymmdd;
            this.jsonPathList [timeInfo.yymmdd] = this.filePath + "/" + timeInfo.yymmdd + "/json/" + item.channel + ".json";
            item.stream_id = item.channel + "_" + item.userId + "_" + item.timestamp;

            if (!this.recordMessages[item.uid]) {
              this.recordMessages[item.uid] = {};
            }
            this.recordMessages[item.uid][item.timestamp] = item;
          }
        }
        if (_callback) {
          _callback();
        }*/
      })
      .catch(err => {
        loger.error(`AG-获取媒体录制信息-异常.状态码:${err}`);
        if (_callback) {
          _callback();
        }
      });
  }

  parseRecordMessage(_data,_callback){
    if(!_data||_data.length<1){
      console.log("录制消息数据无效",_data)
      return;
    }
    for (let i = 0; i <_data.length; i++) {
      let item =_data[i];
      if (item.status == 1) {
        this.streamInfoLen++;
        //console.log(JSON.stringify(item));
        delete item.appId;
        delete  item.id;
        let time = parseInt(item.createTime);
        let timeInfo = this.timestampToUTCTime(time);
        //return {yymmddhhmmss:yymmddhhmmss,yymmdd:yymmdd}
        item.seek = 0;
        item.createTimeUTC = timeInfo.yymmddhhmmss;
        item.creatDate = timeInfo.yymmdd;
        this.jsonPathList [timeInfo.yymmdd] = this.filePath + "/samples/" + timeInfo.yymmdd + "/json/" + item.channel + ".json";
        item.stream_id = item.channel + "_" + item.userId + "_" + item.timestamp;

        if (!this.recordMessages[item.uid]) {
          this.recordMessages[item.uid] = {};
        }
        this.recordMessages[item.uid][item.timestamp] = item;
      }
    }
    if (_callback) {
      _callback();
    }
  }

  getRecordFileJSON(path, _callback) {
    let url = path + "?t=" + new Date().getTime();
    /* $.ajax(
     {
     type: "GET",
     url: location,
     dataType: 'json',
     success: function (data) {
     console.log("getRecordFileJSON success", data);
     if (_callback) {
     _callback(data);
     }
     },
     error: function (data) {
     //alert(data.code);
     console.log("getRecordFileJSON error", data);
     if (_callback) {
     _callback(null);
     }
     }
     }
     );*/
    fetch(url, {
      timeout: 5000,
      method: 'GET',
    })
      .then(ret => {
        if (ret.ok) {
          return ret.json();
        } else {
          loger.error(`AG-getRecordFileJSON-网络异常.状态码:${ret}`);
          if (_callback) {
            _callback();
          }
          throw '';
        }
      })
      .then(ret => {
        loger.log('AG-getRecordFileJSON-完成');
        if (_callback) {
          _callback(ret);
        }
      })
      .catch(err => {
        loger.error(`AG-getRecordFileJSON-异常.状态码:${err}`);
        if (_callback) {
          _callback();
        }
      });
  }

  matchRecordFile(_messages, _m3u8List) {
    let _recordMessages = _messages;
    let _m3u8jsonDataList = _m3u8List;
    console.log("匹配之前的消息集合", _recordMessages);
    console.log("匹配之前的视频地址集合", _m3u8jsonDataList);
    let matchStreams = {};
    let uidRecordInfo;
    let uidRecordFile;

    for (let k in _recordMessages) {
      this.matchForUid(k, _recordMessages[k], _m3u8jsonDataList[k]);
    }

    console.log("unMatchUid", this.matchStreams);
    console.log("_recordMessages", _recordMessages);
    console.log("_m3u8jsonDataList", _m3u8jsonDataList);
    console.log("最终匹配完成的数量为->" + Object.keys(this.matchStreams).length, "未匹配成功的数量为->" + (this.streamInfoLen - parseInt(Object.keys(this.matchStreams).length)));
    console.log("没有录制文件的用户", this.unMatchUid);
    this._emit(RecordInfoMatch.RECORD_INFO_MATCH_COMPLETE, this.matchStreams);
  }

  matchForUid(k, _recordMessages, _m3u8jsonDataList) {
    let uidRecordInfo = _recordMessages;
    let uidRecordFile = _m3u8jsonDataList;
    if (!uidRecordFile) {
      console.log(k, "没有录制文件");
      this.unMatchUid[k] = uidRecordInfo;
    } else {

      let uidRecordInfoArr = Object.values(uidRecordInfo);
      let uidRecordFileArr = Object.values(uidRecordFile);
      uidRecordInfoArr = uidRecordInfoArr.sort(function (a, b) {
        return parseInt(a.createTimeUTC) - parseInt(b.createTimeUTC);
      });
      uidRecordFileArr = uidRecordFileArr.sort(function (a, b) {
        return parseInt(a.createTimeUTC) - parseInt(b.createTimeUTC);
      });

      if (uidRecordInfoArr.length == uidRecordFileArr.length && uidRecordFileArr.length > 0) {
        //1.如果文件数量和消息数量相等,直接关联即可
        console.log(k + "->数量相同->直接匹配", uidRecordInfoArr.length);
        for (let h = 0; h < uidRecordInfoArr.length; h++) {
          let item = uidRecordInfoArr[h];
          item.video_url = uidRecordFileArr[h].video_url;
          this.matchStreams[item.stream_id] = item;
        }

      } else {
        //2.通过时间戳匹配
        for (let f in uidRecordInfo) {
          let time = parseInt(uidRecordInfo[f].createTimeUTC);
          let video_url = "";
          let video_urlObj = uidRecordFile[k + "_" + time];
          if (video_urlObj && video_urlObj.video_url) {
            video_url = video_urlObj.video_url;
          }
          //模糊
          if (!video_url) {
            video_urlObj = uidRecordFile[k + "_" + (time + 1)];
            if (video_urlObj && video_urlObj.video_url) {
              video_url = video_urlObj.video_url;
            }
          }
          if (!video_url) {
            video_urlObj = uidRecordFile[k + "_" + (time - 1)];
            if (video_urlObj && video_urlObj.video_url) {
              video_url = video_urlObj.video_url;
            }
          }

          //通过时间戳匹配 结束
          if (video_url) {
            let item = uidRecordInfo[f];
            item.video_url = video_url;
            this.matchStreams[item.stream_id] = item;
          } else {
            console.log(k + "_" + time, "按时间戳没有查找到->");
          }
        }

        //3.最后一次通过间隔查找
        if (uidRecordInfoArr.length != uidRecordFileArr.length && uidRecordFileArr.length > 0 && uidRecordInfoArr.length > 0) {
          console.log(k + "->数量不同  消息数量:" + uidRecordInfoArr.length, "视频数量:" + uidRecordFileArr.length);
          //按消息的数量大于视频数量处理
          let lastFileItem;//记录最后一个
          for (let h = 0; h < uidRecordInfoArr.length; h++) {
            let infoItem = uidRecordInfoArr[h];
            let fileItem = uidRecordFileArr[h];
            if (fileItem) {
              infoItem.video_url = fileItem.video_url;

              //如果之前没有匹配到才设置
              if (!this.matchStreams[infoItem.stream_id]) {
                this.matchStreams[infoItem.stream_id] = infoItem;
              }
              lastFileItem = infoItem;//记录最后一个文件的数据
            } else {
              if (lastFileItem) {
                infoItem.video_url = lastFileItem.video_url;
                infoItem.seek = parseInt(infoItem.createTimeUTC) - parseInt(lastFileItem.createTimeUTC);
                if (!this.matchStreams[infoItem.stream_id]) {
                  this.matchStreams[infoItem.stream_id] = infoItem;
                }
              }
            }

          }
        }

        /*
         //没有查找到之后,如果两次推流的消息时间过短,只会有一个视频,需要再次匹配
         console.log("uidRecordInfoUnsearch", uidRecordInfoUnsearch, uidRecordInfo);
         if (Object.keys(uidRecordInfoUnsearch).length > 0) {
         let item;
         let item2;
         let minInterval = 10000;
         let nearItem = null;
         for (let s in uidRecordInfoUnsearch) {
         item = uidRecordInfoUnsearch[s];
         for (let h in uidRecordInfo) {
         item2 = uidRecordInfo[h];
         if (item2 && item2.video_url) {
         let interval = parseInt((item.createTime) * 0.001 - parseInt(item2.createTime) * 0.001);
         if (minInterval > interval) {
         nearItem = item2;
         minInterval = interval;
         }
         minInterval = Math.min(minInterval, interval);
         //console.log("两次推流消息的间隔",interval);
         }
         }
         }
         if (item && nearItem) {
         console.log("查找到最接近的消息", nearItem, "seek", minInterval);
         item.video_url = nearItem.video_url;
         item.seek = minInterval;
         matchStreams[item.stream_id] = item;
         }

         }*/
      }
    }

  }


  timestampToUTCTime(_timestamp) {
    let date = new Date(_timestamp - 8 * 60 * 60 * 1000);//GMT 转UTC 减8
    let y = "" + date.getFullYear();
    let month = "" + (date.getMonth() + 1);
    let d = "" + date.getDate();
    let h = "" + (date.getHours());
    let minutes = "" + date.getMinutes();
    let s = "" + date.getSeconds();
    if (month.length < 2) {
      month = "0" + month;
    }
    if (d.length < 2) {
      d = "0" + d;
    }
    if (h.length < 2) {
      h = "0" + h;
    }
    if (minutes.length < 2) {
      minutes = "0" + minutes;
    }
    if (s.length < 2) {
      s = "0" + s;
    }
    let yymmddhhmmss = "" + y + month + d + h + minutes + s;
    let yymmdd = "" + y + month + d;
    console.log(_timestamp, yymmdd, yymmddhhmmss, date);
    return {yymmddhhmmss: yymmddhhmmss, yymmdd: yymmdd}
  }
}

RecordInfoMatch.prototype.RECORD_INFO_MATCH_COMPLETE = RecordInfoMatch.RECORD_INFO_MATCH_COMPLETE = 'recordInfoMatchComplete';//录制数据匹配完成
export default new RecordInfoMatch;