tmp_air.js 13.6 KB
Newer Older
limingzhe's avatar
limingzhe committed
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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
// 刷新CDN路径
// https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js
// https://teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js

const commonPostMessage = function (messageObj) {
  const obj = {...messageObj, urlParams: window.location.search}
  window.parent.postMessage(obj, '*');
};

const commonPostMessageWithCallback = function (messageObj, callback) {
  const onMessage = (e) => {
    let msgData = e.data;
    if(msgData && msgData.action === messageObj.action){
      window.removeEventListener("message", onMessage);
      callback && callback(msgData.data);
    }
  };
  window.addEventListener("message", onMessage);
  commonPostMessage(messageObj);
};

const realAir = {
  uploadUrl: null,
  uploadData: null,
  getDataCallback: null,
  setDataCallback: null,
  getUploadCallback: null,
  pageLoaded: false,
  isCourseInScreen: false,
  hideAirClassLoading: function(templateName,loadData){
    // 隐藏页面加载时候的loading
    if (deleteHistory && typeof (deleteHistory) == 'function') {
      deleteHistory();
    }
    window.parent.postMessage({ action: "course-ready", data: {template:templateName,loadData:loadData,urlParams: window.location.search}, urlParams: window.location.search}, '*');
    window.air.pageLoaded = true; 
    window.courseware.next(); 

    var cc = window.cc;

    if (cc && cc.director && cc.director._scene) {
      try {
        const canvas = cc.find("Canvas");
        canvas.on("mousemove", function () {});
        cc.director._scene.on("mousemove", function () {
          window.parent.postMessage({ action: "mousemove" }, "*");
        });
        cc.director._scene.on("touchmove", function () {
          window.parent.postMessage({ action: "mousemove" }, "*");
        });

        if (cc.systemEvent && cc.SystemEvent) {
          cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (event) => {
            switch (event.keyCode) {
              case cc.KEY.left:
                window.parent.postMessage({ action: "ArrowLeft" }, "*");
                break;
              case cc.KEY.right:
                window.parent.postMessage({ action: "ArrowRight" }, "*");
                break;
            }
          });
        }
      } catch (e) {
        console.log("====cc.director._scene绑定事件====");
      }
    }
  },
};

const uploadCallbackQueue = [];

try{
  window.air = new Proxy(realAir, {
    set: function (target, key, value, receiver) {
      if (key=="getUploadCallback") {
				uploadCallbackQueue.push(value);
			}
      return Reflect.set(target, key, value, receiver); 
    },
    get: function (target, key, receiver) {
			return Reflect.get(target, key, receiver);
    },
    deleteProperty: function(target, key){
			return Reflect.deleteProperty(target, key);
		}
  });
}catch(e){
  console.error("浏览器不支持ES6新特性Proxy/Reflect,请使用谷歌浏览器!");
}

function deleteHistory() {
  const disableBack = () => {
    window.history.pushState(null, "", document.URL);
    window.addEventListener("popstate", () => {
      window.history.pushState(null, "", document.URL);
    });
  }
  disableBack();
  window.addEventListener("load", disableBack);
}
deleteHistory();

if (window.self !== window.top) {
  window.addEventListener("message", function (e) {
    let msgData = e.data;
    // console.log("子页面接收到了消息", msgData);
    if(msgData.type === "webpackWarnings" || msgData.type === "webpackOk") {
      return;
    }
    if(msgData.action==="airEvents"){
      return;
    } 
    if (msgData.action === "getUpload" && msgData.uploadUrl) {
      window.air.uploadUrl = msgData.uploadUrl;
      window.air.uploadData = msgData.uploadData;
      for (let i = 0; i < uploadCallbackQueue.length; i++) {
        uploadCallbackQueue[i](msgData.uploadUrl, msgData.uploadData);
      }
      return;
    }
    if (msgData.action === "pauseCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.game.pause();
        console.log('pause了');
      }
      return;
    }
    if (msgData.action === "resumeCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.game.resume();
        console.log('resume了');
      }
      return;
    }
    if (msgData.action === "restartCocos") {
      let cc = window.cc;
      if (cc && cc.game) {
        cc.audioEngine.stopAll();
        // cc.game.restart();
        console.log('restart了');
      }
      return;
    }
    if (msgData.action === "setData") {
      window.air.setDataCallback && window.air.setDataCallback();
      return;
    }
    if (msgData.action === "getData") {
      try {
        const res = JSON.parse(msgData.data);
        if (res.msg !== "success") {
          console.log('数据加载失败!');
          return;
        }
        if (res.data && res.data != 'null') {
          window.air.callData = JSON.parse(res.data);
        }
        window.air.callDataFlag = true;
        return;
      } catch (e) {
        console.log('数据加载失败!');
      }
    }
  });
  window.parent.postMessage({ action: "getUpload" }, '*');

  document.onmousemove = function(){
    window.parent.postMessage({ action: "mousemove" }, '*');
  };
  document.ontouchmove = function(){
    window.parent.postMessage({ action: "mousemove" }, '*');
  };

  document.onkeydown = (event) => {
    switch(event.key) {
      case "ArrowLeft":
        window.parent.postMessage({ action: "ArrowLeft" }, '*');
        break;
      case "ArrowRight": 
        window.parent.postMessage({ action: "ArrowRight" }, '*');
        break;
    }
  }

  document.oncontextmenu = function(){
    return false;
  }
}


window.courseware = (function () {
  let obj = {
    airEvents: {},
    eventQueue: [],
    eventLock: false,
    next: () => {
      let exe = obj.eventQueue.splice(0,1); 
      if(exe.length>0){
        obj.eventLock = true;
        let evtName = exe[0].evtName;
        let data = exe[0].data; 
        if(obj.airEvents[evtName]){
          if(evtName === "course-in-screen"){
            if(window.air.isCourseInScreen){
              return;
            }
            window.air.isCourseInScreen = true;
          }
          console.log(`evtName==${evtName}的方法被执行`);
          obj.airEvents[evtName](data, obj.next);
        } else {
          console.warn(`airclass教室交互事件 ${evtName} 没有被捕获,请确认监听事件的先后顺序2`);
          obj.next();
        }
      }else{
        obj.eventLock = false;
      } 
    }
  };
  if (window.self !== window.top) {
    window.addEventListener("message", function (e) {
      let msgData = e.data;
      if(msgData.action!=="airEvents"){
        return;
      } 
      let evtName = msgData.evt; 
      let res = msgData.data;
      if (evtName === "course-out-screen"){
        console.log(`evtName==${evtName}的方法被执行`);
        window.location.reload();
        return;
      }
      if (res&&evtName!='userchange') {
        //userchange事件传过来的值不需要转换
        res = JSON.parse(res); 
      }
      if(!window.air.pageLoaded){
        //如果页面还没有加载完成
        obj.eventQueue.push({"evtName": evtName, data: res});
      }else{ 
        if (obj.eventQueue.length === 0 && !obj.eventLock) {
          //如果没有消息积压并且事件锁未锁定
          obj.eventLock = true; 
          if(obj.airEvents[evtName]){
            if(evtName === "course-in-screen"){
              if(window.air.isCourseInScreen){
                return;
              }
              window.air.isCourseInScreen = true;
            }
            console.log(`evtName==${evtName}的方法被执行`);
            obj.airEvents[evtName](res, obj.next); 
          } else {
            console.warn(`airclass教室交互事件 ${evtName} 没有被捕获,请确认监听事件的先后顺序1`);
            obj.next();
          }
        } else {
          obj.eventQueue.push({"evtName": evtName, data: res});
        }
      } 
    }); 
    obj.getData = function (callback, key = '') {
      window.parent.postMessage({ action: "getData", data: window.location.search, urlParams: window.location.search }, '*');
      window.air.callDataFlag = false;
      
      const liuintval = setInterval(()=>{
        if(window.air.callDataFlag){
          console.log("========我进来了=========");
          clearInterval(liuintval);
          setTimeout(() => {
            console.log("执行回调,回调数据为:");
            console.log(window.air.callData);
            callback(window.air.callData);
          }, 100);
        }
      }, 100);
    };
    obj.setData = function (data, callback, key = '') {
      let str = JSON.stringify(data);
      console.log("==setData==", str);
      window.parent.postMessage({ action: "setData", data: str, urlParams: window.location.search }, '*');
      window.air.setDataCallback = callback;
    };
    obj.uploadUrl = function () {
      // return net.getUploadFileURL();
      return window.air.uploadUrl;
    };
    obj.uploadData = function () {
      // return net.getAjaxData("uploadFile","");
      return window.air.uploadData;
    };
    obj.beganRecording = function(){
      commonPostMessage({ action: "beganRecording" }); 
    };
    obj.endRecording = function(callback){
      commonPostMessageWithCallback({ action: "endRecording" }, callback);
    };
    obj.speakPoints = function(audioUrl, evalText, callback){
      const obj = {audioUrl, evalText};
      commonPostMessageWithCallback({ action: "speakPoints", data: JSON.stringify(obj) }, callback);
    };
    obj.startRecord = function(testText){
      commonPostMessage({ action: "startRecord", data: testText  });
    };
    obj.stopRecord = function(callback){
      commonPostMessageWithCallback({ action: "stopRecord" }, callback);
    };
    obj.startTest = function(testText){
      commonPostMessage({ action: "startTest", data: testText });
    };
    obj.stopTest = function(callback){
      commonPostMessageWithCallback({ action: "stopTest" }, callback);
    };
    obj.getTemplates = function(callback){
      commonPostMessageWithCallback({ action: "getTemplates" }, callback);
    };
    obj.getTemplateUrl = function(templateName, callback){
      commonPostMessageWithCallback({ action: "getTemplateUrl", data: templateName}, callback);
    };
    obj.sendEvent = function(evtName,data,key = ''){
      if(evtName==="reconnect"){
        console.error("reconnect是内置的断线重连事件名称,请勿使用此名称作为事件名");
        return;
      }
      if(evtName==="userchange"){
        console.error("userchange是内置的用户变更事件名称,请勿使用此名称作为事件名");
        return;
      }
      let str = null;
      if(data){
        str = JSON.stringify(data);
      } 
      window.parent.postMessage({ action: "airEvents",evt: evtName, data: str, urlParams: window.location.search }, '*'); 
    };
    obj.onEvent = function(evtName,callback){  
      obj.airEvents[evtName] = callback; 
    };
    obj.removeEvent = function(evtName){
      if(obj.airEvents[evtName]){ 
        delete obj.airEvents[evtName];
      }  
    };
    obj.sendErrorLog = function (error) { 
      // todo 这块预留后面采集模板的报错信息
      // window.parent.postMessage({ action: "errorlog", data: error.stack }, '*'); 
    };
  } else {
    obj.getData = function (callback, key = '') {
      let data = localStorage.getItem("courseware_data_" + key);
      if (data) {
        data = JSON.parse(data);
      }
      callback && callback(data);
    };
    obj.setData = function (data, callback, key = '') {
      console.log("******local********");
      localStorage.setItem("courseware_data_" + key, JSON.stringify(data));
      callback && callback();
    };
    obj.uploadUrl = function () {
      var protocolStr = document.location.protocol;
      return `${protocolStr}//staging-teach.ireadabc.com/fileUpload`;
    };
    obj.uploadData = function () {
      return {};
    };
    obj.beganRecording = function(){
      console.log("******beganRecording********");
    };
    obj.endRecording = function(callback){
      console.log("******endRecording********");
      callback&&callback("");
    };
    obj.speakPoints = function(audioUrl, evalText, callback){
      console.log("******speakPoints********");
      callback&&callback("");
    };
    obj.startRecord = function(){
      console.log("******startRecord********");
    };
    obj.stopRecord = function(callback){
      console.log("******stopRecord********");
      callback&&callback("");
    };
    obj.startTest = function(testText){
      console.log("******startTest********");
    };
    obj.stopTest = function(callback){
      console.log("******stopTest********");
      callback&&callback("");
    };
    obj.getTemplates = function(callback){
      callback&&callback("");
    };
    obj.getTemplateUrl = function(templateName, callback){
      const obj = {
        play_url: "",
        form_url: "",
      };
      callback&&callback(JSON.stringify(obj));
    };
    obj.sendEvent = function(evtName, data, key = ''){ 
      if(evtName==="reconnect"){
        console.error("reconnect是内置的断线重连事件名称,请勿使用此名称作为事件名");
        return;
      }
      if(evtName==="userchange"){
        console.error("userchange是内置的用户变更事件名称,请勿使用此名称作为事件名");
        return;
      }
      return;
    };
    obj.onEvent = function(evtName,callback){
      console.warn("==本地测试用,onEvent的监听事件会直接触发==", "事件名:"+ evtName);
      callback && callback("", function(){});
    };
    obj.removeEvent = function(evtName){
      
    };
    obj.sendErrorLog = function (error) { 

    };
  }

  return obj;
})();