vhall-mini-sdk 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/lib/components/announcement/announ-banner/index.js +5 -0
- package/lib/components/announcement/announ-banner/index.wxml +1 -1
- package/lib/components/announcement/announ-banner/index.wxss +1 -1
- package/lib/components/announcement/index.js +8 -6
- package/lib/components/announcement/index.wxml +1 -1
- package/lib/components/chat/chat-item/chat-item.js +6 -0
- package/lib/components/chat/chat-item/chat-item.wxml +38 -0
- package/lib/components/chat/chat-item/chat-item.wxss +1 -1
- package/lib/components/chat/chat-list/chat-list.js +40 -2
- package/lib/components/chat/chat-list/chat-list.wxml +1 -1
- package/lib/components/chat/chat.js +4 -0
- package/lib/components/chat/chat.wxml +2 -3
- package/lib/components/chat/chat.wxss +1 -1
- package/lib/components/chat-recommend/index.js +113 -0
- package/lib/components/chat-recommend/index.json +4 -0
- package/lib/components/chat-recommend/index.wxml +10 -0
- package/lib/components/chat-recommend/index.wxss +1 -0
- package/lib/components/live-landscape/live-landscape.js +15 -0
- package/lib/components/live-landscape/live-landscape.json +2 -0
- package/lib/components/live-landscape/live-landscape.wxml +3 -1
- package/lib/components/live-portrait/live-portrait.js +14 -0
- package/lib/components/live-portrait/live-portrait.json +3 -1
- package/lib/components/live-portrait/live-portrait.wxml +4 -2
- package/lib/components/live-portrait/live-portrait.wxss +1 -1
- package/lib/components/lottery/lottery-shake/lottery-shake.js +6 -5
- package/lib/components/lottery/lottery-shake/lottery-shake.wxml +6 -1
- package/lib/components/lottery/lottery-slot/lottery-slot.js +9 -5
- package/lib/components/lottery/lottery-slot/lottery-slot.wxml +6 -1
- package/lib/components/lottery/lottery-wheel/lottery-wheel.js +16 -16
- package/lib/components/lottery/lottery-wheel/lottery-wheel.wxml +10 -4
- package/lib/components/lottery/lottery-wheel/lottery-wheel.wxss +1 -1
- package/lib/components/lottery/lottery.js +36 -16
- package/lib/components/lottery/lottery.wxml +5 -4
- package/lib/components/lottery/lottery.wxss +1 -1
- package/lib/components/player/components/main/index.wxml +2 -2
- package/lib/components/player/components/poster/poster.wxml +1 -1
- package/lib/components/player/components/poster/poster.wxss +1 -1
- package/lib/components/player/extensions/data.js +11 -1
- package/lib/components/player/extensions/methods.js +104 -3
- package/lib/components/player/extensions/observers.js +13 -8
- package/lib/components/player/player.wxml +16 -5
- package/lib/components/player/player.wxss +1 -1
- package/lib/components/product/product-card/product-card.js +9 -1
- package/lib/components/product/product-card/product-card.wxml +9 -16
- package/lib/components/product/product-card/product-card.wxss +1 -1
- package/lib/components/product/product-detail/product-detail.js +9 -1
- package/lib/components/product/product-item/product-item.js +14 -1
- package/lib/components/product/product-item/product-item.wxss +1 -1
- package/lib/components/product/product-list/product-list.wxml +1 -1
- package/lib/components/product/product-order/product-order.js +20 -13
- package/lib/components/product/product-order/product-order.wxss +1 -1
- package/lib/pubComponents/countdown/countdown.wxss +1 -1
- package/lib/pubComponents/popup/popup.js +1 -0
- package/lib/sdk/main/index.js +2 -2
- package/lib/sdk/player/index.js +1 -1
- package/lib/sdk/plugins/LotteryServer.js +1 -1
- package/lib/sdk/plugins/ProductServer.js +1 -1
- package/lib/shared/utils.js +1 -1
- package/package.json +3 -2
package/lib/sdk/player/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}var hasRequiredCrc32,crc32$1={};let WxHttp=function(){return _createClass(function WxHttp(store){_classCallCheck(this,WxHttp),this.store=store},[{key:"request",value:function request(url,data={},method="POST"){return new Promise((resolve,reject)=>{const config={url:url,method:method,data:data,header:{"Content-Type":"application/x-www-form-urlencoded"},success:res=>this._handleSuccess(res,resolve,reject),fail:err=>this._handleFail(err,reject)};wx.request(config)})}},{key:"_handleSuccess",value:function _handleSuccess(res,resolve,reject){if(200!==res.statusCode)return reject({code:res.statusCode,msg:"网络请求失败"});const response=res.data||{};200===+response.code?resolve(response.data):reject(response)}},{key:"_handleFail",value:function _handleFail(err,reject){reject({code:-1,msg:"网络连接失败",errMsg:err.errMsg})}}])}();const VHALL_API_LIST_PLAYER_CONFIG="/v3/interacts/union/player-config",VHALLYUN_API_LIST_INIT="/sdk/v2/init/start",VHALLYUN_API_LIST_INIT_LIVE="/sdk/v2/room/get-watch-info",VHALLYUN_API_LIST_INIT_VOD="/sdk/v2/demand/get-record-watch-info",VHALLYUN_API_LIST_DISPATCH_LIVE="/api/dispatch_play",VHALLYUN_API_LIST_DISPATCH_VOD="/api/dispatch_replay";function safeUrlJoin(baseUrl,path){return`${baseUrl.replace(/\/$/,"")}/${path.replace(/^\//,"")}`}const envConfig={production:{BASE_URL:"https://open-api.vhall.com",VHALLYUN_API_BASE:"https://api.vhallyun.com",LOG_REPORT_BASE_URL:"https://dc.e.vhall.com/login",PUBLIC_KEY:"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0eUJFtW3vryA2NXx4M4f\n1w7dg3PHwOCA6Kx7JVfD/9eBGfqLhqsp+pg4AXG4PhuQx8EsV+sncQIiQO5J2//T\n3pO8LftDtCQztLnxnhq+BjhbFeswgfez2CwV2YKLTX2zyZ69T1Vu/M4H4gWSLeiV\n1FcH6xycA2+jG+EvOxSSItCKYT9EkB9BZSKf5RU7gM+qPtzdPtJP5vlsMCa0WnpY\nI6Qrmu/w9CZkL0397gUek9nBpPHkyPYg7ZijF3Gj8EqCMCVVTYpX96k4dd/Rz1em\ns4OSPF5jDsYZi58p+LmTcc3g7W9bD3QWWxzn47ie/Dh9LbnWfCqpGjUaHd3d42vR\ncQIDAQAB\n-----END PUBLIC KEY-----"},test:{BASE_URL:"https://test01-open-api.vhou.tv",VHALLYUN_API_BASE:"https://test01-api.vhallyun.com",LOG_REPORT_BASE_URL:"https://t-dc.e.vhall.com/login",PUBLIC_KEY:"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxWGCgHz2NLdVNa91CsNX\nFfCsxfgkTx738t3yMpuPYLL/5wwuWRrX7hBfNsfC+R5BW5b13ISzD001NNt+BWGK\np3V5fdWO18j9M/AhaTV2Ao/IpdP5huvVoNFVWPUQvX70FHu0sPVTev8ycAZHUpKx\n+mm83wxOpWBN5vAMJYx75pRCQfidb73XbOm6JXLJlxN91TUTrTiblxBhRwH0AQyr\ns9dUr+IJUZ1ea2uU3fkB4uYh7V/cHuNDMsJowfLtEU2+9IqEuJY4OwqX0qdfPF72\nsGMjCgghgL0z/7kv7Qe1+tOkJTBQTzODXBheGTVbF7hH2+5XuZsK2TfgBIew0I4k\n1wIDAQAB\n-----END PUBLIC KEY-----"}};let WxApi=function(){return _createClass(function WxApi(store){_classCallCheck(this,WxApi),this.currentEnvConfig=store?.env&&envConfig[store.env]?envConfig[store.env]:envConfig.production,this.http=new WxHttp(store)},[{key:"initVhallPlayerConfig",value:function initVhallPlayerConfig(webinarId){const url=safeUrlJoin(this.currentEnvConfig.BASE_URL,VHALL_API_LIST_PLAYER_CONFIG),data={webinar_id:webinarId,tags:["basic-config","definition","screen-config","water-mark"]};return this.http.request(url,data)}},{key:"initVhallyun",value:function initVhallyun(){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT);return this.http.request(url)}},{key:"requestVhallyunLive",value:function requestVhallyunLive(data){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT_LIVE);return this.http.request(url,{...data,client:"pc_browser",package_check:"peter"})}},{key:"requestGslbLive",value:function requestGslbLive(domain,data){const url=safeUrlJoin(domain,VHALLYUN_API_LIST_DISPATCH_LIVE);return this.http.request(url,{...data,bu:1})}},{key:"requestVhallyunVod",value:function requestVhallyunVod(data){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT_VOD);return this.http.request(url,{...data,client:"pc_browser",package_check:"peter"})}},{key:"requestGslbVod",value:function requestGslbVod(domain,data){const url=safeUrlJoin(domain,VHALLYUN_API_LIST_DISPATCH_VOD);return this.http.request(url,{...data,bu:1})}}])}();const LOG_LEVEL_trace=0,LOG_LEVEL_debug=1,LOG_LEVEL_info=2,LOG_LEVEL_log=2,LOG_LEVEL_warn=3,LOG_LEVEL_error=4;let _logLevel=LOG_LEVEL_info;function formatTime(){const date=new Date,pad=(n,len=2)=>String(n).padStart(len,"0");return`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}:${pad(date.getMilliseconds(),3)}`}function createLogger(module=""){const prefix=module?`[${module}]`:"",appPrefix="VhallMiniSDK",enabled=level=>level>=_logLevel;return{trace:function trace(...args){enabled(LOG_LEVEL_trace)&&console.trace(`${appPrefix} [${formatTime()}] <TRACE> ${prefix} `,...args)},debug:function debug(...args){enabled(LOG_LEVEL_debug)&&console.debug(`${appPrefix} [${formatTime()}] <DEBUG> ${prefix} `,...args)},info:function info(...args){enabled(LOG_LEVEL_info)&&console.info(`${appPrefix} [${formatTime()}] <INFO> ${prefix}`,...args)},log:function log(...args){enabled(LOG_LEVEL_log)&&console.log(`${appPrefix} [${formatTime()}] <LOG> ${prefix}`,...args)},warn:function warn(...args){enabled(LOG_LEVEL_warn)&&console.warn(`${appPrefix} [${formatTime()}] <WARN> ${prefix}`,...args)},error:function error(...args){enabled(LOG_LEVEL_error)&&console.error(`${appPrefix} [${formatTime()}] <ERROR> ${prefix}`,...args)}}}const crc32=function requireCrc32(){return hasRequiredCrc32||(hasRequiredCrc32=1,factory=function(CRC32){CRC32.version="1.2.2";var T0=function signed_crc_table(){for(var c=0,table=new Array(256),n=0;256!=n;++n)c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=n)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1,table[n]=c;return"undefined"!=typeof Int32Array?new Int32Array(table):table}(),TT=function slice_by_16_tables(T){var c=0,v=0,n=0,table="undefined"!=typeof Int32Array?new Int32Array(4096):new Array(4096);for(n=0;256!=n;++n)table[n]=T[n];for(n=0;256!=n;++n)for(v=T[n],c=256+n;c<4096;c+=256)v=table[c]=v>>>8^T[255&v];var out=[];for(n=1;16!=n;++n)out[n-1]="undefined"!=typeof Int32Array?table.subarray(256*n,256*n+256):table.slice(256*n,256*n+256);return out}(T0),T1=TT[0],T2=TT[1],T3=TT[2],T4=TT[3],T5=TT[4],T6=TT[5],T7=TT[6],T8=TT[7],T9=TT[8],Ta=TT[9],Tb=TT[10],Tc=TT[11],Td=TT[12],Te=TT[13],Tf=TT[14];CRC32.table=T0,CRC32.bstr=function crc32_bstr(bstr,seed){for(var C=-1^seed,i=0,L=bstr.length;i<L;)C=C>>>8^T0[255&(C^bstr.charCodeAt(i++))];return~C},CRC32.buf=function crc32_buf(B,seed){for(var C=-1^seed,L=B.length-15,i=0;i<L;)C=Tf[B[i++]^255&C]^Te[B[i++]^C>>8&255]^Td[B[i++]^C>>16&255]^Tc[B[i++]^C>>>24]^Tb[B[i++]]^Ta[B[i++]]^T9[B[i++]]^T8[B[i++]]^T7[B[i++]]^T6[B[i++]]^T5[B[i++]]^T4[B[i++]]^T3[B[i++]]^T2[B[i++]]^T1[B[i++]]^T0[B[i++]];for(L+=15;i<L;)C=C>>>8^T0[255&(C^B[i++])];return~C},CRC32.str=function crc32_str(str,seed){for(var C=-1^seed,i=0,L=str.length,c=0,d=0;i<L;)(c=str.charCodeAt(i++))<128?C=C>>>8^T0[255&(C^c)]:c<2048?C=(C=C>>>8^T0[255&(C^(192|c>>6&31))])>>>8^T0[255&(C^(128|63&c))]:c>=55296&&c<57344?(c=64+(1023&c),d=1023&str.charCodeAt(i++),C=(C=(C=(C=C>>>8^T0[255&(C^(240|c>>8&7))])>>>8^T0[255&(C^(128|c>>2&63))])>>>8^T0[255&(C^(128|d>>6&15|(3&c)<<4))])>>>8^T0[255&(C^(128|63&d))]):C=(C=(C=C>>>8^T0[255&(C^(224|c>>12&15))])>>>8^T0[255&(C^(128|c>>6&63))])>>>8^T0[255&(C^(128|63&c))];return~C}},"undefined"==typeof DO_NOT_EXPORT_CRC?factory(crc32$1):factory({})),crc32$1;var factory}(),logger$2=createLogger("playerCore_scheduler"),QUALITY_SORTED_LIST=["same","origin","720p","720sp","480p","480sp","360p","360sp","a"];let Scheduler=function(){function Scheduler(option){_classCallCheck(this,Scheduler),this.option=option,this.audioMode=!1,this.hideSameQuality=!1,this.api=new WxApi(option)}return _createClass(Scheduler,[{key:"initVhallPlayerConfig",value:async function initVhallPlayerConfig(webinarId){return this.api.initVhallPlayerConfig(webinarId)}},{key:"initForLive",value:function initForLive(){return new Promise((resolve,reject)=>{this.api.requestVhallyunLive({app_id:this.option.paasAppId,room_id:this.option.paasRoomId,third_party_user_id:this.option.uid,access_token:this.option.paasAccessToken}).then(data=>{logger$2.debug("vhallyun直播接口成功: ",data);var vhallyunLiveData=(data=>{const{dispatch_server:dispatch_server,live_delay:live_delay,live_subtitle_mps:live_subtitle_mps,log_info:log_info}=data;return{log_info:log_info,uid:log_info.uid,dispatch_server:dispatch_server,subtitles:(live_subtitle_mps||"").split(",").map(s=>s.trim()).filter(s=>s.length>0),live_delay:live_delay}})(data);this.vhallyunLiveData=vhallyunLiveData,resolve(vhallyunLiveData)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initGslbLive",value:function initGslbLive(){const _parseGslbLive=data=>{const{dispatch_urls_v2:dispatch_urls_v2,token:token}=data,{stream_id:stream_id,quality:quality,multi_lang_subtitle:multi_lang_subtitle,rtmp_urls:rtmp_urls}=dispatch_urls_v2;let qualitys,httpflv_urls=dispatch_urls_v2.httpflv_urls;if(this.audioMode)qualitys=["same"];else if(qualitys=quality.sort((a,b)=>{const indexA=QUALITY_SORTED_LIST.indexOf(a),indexB=QUALITY_SORTED_LIST.indexOf(b);return-1===indexA&&-1===indexB?0:-1===indexA?1:-1===indexB?-1:indexA-indexB}),this.hideSameQuality){qualitys.some(item=>"same"!==item&&"a"!==item)&&(qualitys=qualitys.filter(item=>"same"!==item))}const subtitles=this.vhallyunLiveData.subtitles;subtitles.length>0&&(httpflv_urls=httpflv_urls.filter(item=>"tx"===item.cdn_name));const lines=[];httpflv_urls.forEach(item=>{lines.push(item.cdn_name)}),logger$2.debug("优先清晰度: ",this.option.defaultDefinition),logger$2.debug("全部清晰度: ",qualitys),logger$2.debug("全部字幕: ",subtitles),logger$2.debug("全部线路: ",lines);const defaultDefinition=this.option.defaultDefinition;let currentSubtitle=subtitles.length>0?subtitles[0]:"",currentQuality=Scheduler._decideCurrentQuality(defaultDefinition,qualitys);if(!currentQuality)return log.error("无法获取有效的直播播放地址!"),null;logger$2.debug("选择清晰度: ",currentQuality),logger$2.debug("选择字幕: ",currentSubtitle),logger$2.debug("选择线路: ",0);const newToken=Scheduler._createPlayToken(token),http_flv_domain=httpflv_urls[0].url,http_flv_app=httpflv_urls[0].app;return{httpflv_urls:httpflv_urls,stream_id:stream_id,newToken:newToken,lines:lines,currentLines:0,videoSrc:`${http_flv_domain}/${http_flv_app}/${stream_id}${""==currentSubtitle?"":`_${currentSubtitle}`}${"same"==currentQuality?"":`_${currentQuality}`}.flv?token=${newToken}`,qualitys:qualitys,currentQuality:currentQuality,subtitles:subtitles,currentSubtitle:currentSubtitle}};return new Promise((resolve,reject)=>{this.api.requestGslbLive(this.vhallyunLiveData.dispatch_server,{app_id:this.option.paasAppId,webinar_id:this.option.paasRoomId,uid:this.option.uid,rand:Scheduler._getRandom()}).then(data=>{logger$2.debug("GSLB直播接口成功: ",data);const livePlayInfo=_parseGslbLive(data);this.livePlayInfo=livePlayInfo,resolve(livePlayInfo)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initForVod",value:function initForVod(){return new Promise((resolve,reject)=>{this.api.requestVhallyunVod({app_id:this.option.paasAppId,record_id:this.option.paasVodId,third_party_user_id:this.option.uid,access_token:this.option.paasAccessToken}).then(data=>{logger$2.debug("vhallyun点播接口成功: ",data);var vhallyunVodData=(data=>{const{cue_point:cue_point,default_server:default_server,definition:definition,dispatch_server:dispatch_server,log_info:log_info,safe_server:safe_server,subtitle_info:subtitle_info,watermark:watermark}=data,vodEncrypted=safe_server.hasOwnProperty("cipher_key"),videoUri=default_server.uri,rand=default_server.rand,uid=log_info.uid;return definition.sort((a,b)=>{const indexA=QUALITY_SORTED_LIST.indexOf(a),indexB=QUALITY_SORTED_LIST.indexOf(b);return-1===indexA&&-1===indexB?0:-1===indexA?1:-1===indexB?-1:indexA-indexB}),{log_info:log_info,uid:uid,rand:rand,vodEncrypted:vodEncrypted,cue_point:cue_point,videoUri:videoUri,definition:definition,dispatch_server:dispatch_server,subtitle_info:subtitle_info,watermark:watermark}})(data);this.vhallyunVodData=vhallyunVodData,resolve(vhallyunVodData)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initGslbVod",value:function initGslbVod(){const _parseGslbVod=data=>{const{hls_domainnames:hls_domainnames,token:token}=data;let qualitys;qualitys=this.audioMode?["same"]:this.vhallyunVodData.definition;const qualitySample=qualitys.indexOf("same")>=0?"same":qualitys[0],lines=[];hls_domainnames[qualitySample].forEach(item=>{lines.push(item.cdn_name)}),logger$2.debug("优先清晰度: ",this.option.defaultDefinition),logger$2.debug("全部清晰度: ",qualitys),logger$2.debug("全部线路: ",lines);const defaultDefinition=this.option.defaultDefinition;let currentQuality=Scheduler._decideCurrentQuality(defaultDefinition,qualitys);if(!currentQuality)return log.error("无法获取有效的点播播放地址!"),null;logger$2.debug("选择清晰度: ",currentQuality),logger$2.debug("选择线路: ",0);const newToken=Scheduler._createPlayToken(token),hls_url_tmp=hls_domainnames[currentQuality][0].hls_domainname;return{hls_domainnames:hls_domainnames,newToken:newToken,lines:lines,currentLines:0,videoSrc:`${hls_url_tmp}?token=${newToken}`,qualitys:qualitys,currentQuality:currentQuality}};return new Promise((resolve,reject)=>{this.api.requestGslbVod(this.vhallyunVodData.dispatch_server,{app_id:this.option.paasAppId,webinar_id:this.option.paasVodId,uid:this.vhallyunVodData.uid,rand:this.vhallyunVodData.rand,uri:this.vhallyunVodData.videoUri,quality:`["${this.vhallyunVodData.definition.join('","')}"]`}).then(data=>{logger$2.debug("GSLB点播接口成功: ",data);const vodPlayInfo=_parseGslbVod(data);this.vodPlayInfo=vodPlayInfo,resolve(vodPlayInfo)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"getVideoSrc",value:function getVideoSrc(quality,subtitle){if("vod"==this.option.type){const newToken=this.vodPlayInfo.newToken;return`${this.vodPlayInfo.hls_domainnames[quality][this.vodPlayInfo.currentLines].hls_domainname}?token=${newToken}`}{const newToken=this.livePlayInfo.newToken,http_flv_quality="same"==quality?"":`_${quality}`,http_flv_subtitle=""==subtitle?"":`_${subtitle}`;return`${this.livePlayInfo.httpflv_urls[this.livePlayInfo.currentLines].url}/${this.livePlayInfo.httpflv_urls[this.livePlayInfo.currentLines].app}/${this.livePlayInfo.stream_id}${http_flv_subtitle}${http_flv_quality}.flv?token=${newToken}`}}}],[{key:"_getRandom",value:function _getRandom(){return 1e8+(899999999*Math.random()|0)}},{key:"_createPlayToken",value:function _createPlayToken(originToken){const pre=originToken.split("_")[0],last=originToken.split("_")[1],reverseToken=pre.split("").reverse().join("");return`${(crc32.str(reverseToken)>>>0).toString(16).toUpperCase()}_${last}`}}])}();!function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}(Scheduler,"_decideCurrentQuality",function(defaultDefinition,qualitys){let currentQuality=null;if(0==qualitys.length)log.error("调度无法获取点播播放地址!");else if(1==qualitys.length)currentQuality=qualitys[0];else if(qualitys.indexOf(defaultDefinition)>=0)currentQuality=defaultDefinition;else{let alternatives=qualitys.filter(item=>"same"!==item&&"a"!==item);currentQuality=alternatives.length>0?alternatives[0]:qualitys[0]}return currentQuality});const _hasBuffer="function"==typeof Buffer,_TE=("function"==typeof TextDecoder&&new TextDecoder,"function"==typeof TextEncoder?new TextEncoder:void 0),b64chs=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),b64tab=(()=>{let tab={};return b64chs.forEach((c,i)=>tab[c]=i),tab})(),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_mkUriSafe=("function"==typeof Uint8Array.from&&Uint8Array.from.bind(Uint8Array),src=>src.replace(/=/g,"").replace(/[+\/]/g,m0=>"+"==m0?"-":"_")),_tidyB64=s=>s.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=bin=>{let u32,c0,c1,c2,asc="";const pad=bin.length%3;for(let i=0;i<bin.length;){if((c0=bin.charCodeAt(i++))>255||(c1=bin.charCodeAt(i++))>255||(c2=bin.charCodeAt(i++))>255)throw new TypeError("invalid character found");u32=c0<<16|c1<<8|c2,asc+=b64chs[u32>>18&63]+b64chs[u32>>12&63]+b64chs[u32>>6&63]+b64chs[63&u32]}return pad?asc.slice(0,pad-3)+"===".substring(pad):asc},_btoa="function"==typeof btoa?bin=>btoa(bin):_hasBuffer?bin=>Buffer.from(bin,"binary").toString("base64"):btoaPolyfill,_fromUint8Array=_hasBuffer?u8a=>Buffer.from(u8a).toString("base64"):u8a=>{let strs=[];for(let i=0,l=u8a.length;i<l;i+=4096)strs.push(_fromCC.apply(null,u8a.subarray(i,i+4096)));return _btoa(strs.join(""))},cb_utob=c=>{if(c.length<2)return(cc=c.charCodeAt(0))<128?c:cc<2048?_fromCC(192|cc>>>6)+_fromCC(128|63&cc):_fromCC(224|cc>>>12&15)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc);var cc=65536+1024*(c.charCodeAt(0)-55296)+(c.charCodeAt(1)-56320);return _fromCC(240|cc>>>18&7)+_fromCC(128|cc>>>12&63)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=u=>u.replace(re_utob,cb_utob),_encode=_hasBuffer?s=>Buffer.from(s,"utf8").toString("base64"):_TE?s=>_fromUint8Array(_TE.encode(s)):s=>_btoa(utob(s)),encode=(src,urlsafe=!1)=>urlsafe?_mkUriSafe(_encode(src)):_encode(src),atobPolyfill=asc=>{if(asc=asc.replace(/\s+/g,""),!b64re.test(asc))throw new TypeError("malformed base64.");asc+="==".slice(2-(3&asc.length));let u24,r1,r2,bin="";for(let i=0;i<asc.length;)u24=b64tab[asc.charAt(i++)]<<18|b64tab[asc.charAt(i++)]<<12|(r1=b64tab[asc.charAt(i++)])<<6|(r2=b64tab[asc.charAt(i++)]),bin+=64===r1?_fromCC(u24>>16&255):64===r2?_fromCC(u24>>16&255,u24>>8&255):_fromCC(u24>>16&255,u24>>8&255,255&u24);return bin},gBase64_encode=encode;function guid(){return"xxxxxxxx-xxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)})}function formatTimestamp(timestamp,format="YYYY-MM-DD HH:mm:ss"){const ms=10===timestamp.toString().length?1e3*timestamp:timestamp,date=new Date(ms),year=date.getFullYear(),month=String(date.getMonth()+1).padStart(2,"0"),day=String(date.getDate()).padStart(2,"0"),hours=String(date.getHours()).padStart(2,"0"),minutes=String(date.getMinutes()).padStart(2,"0"),seconds=String(date.getSeconds()).padStart(2,"0");return format?format.replaceAll("YYYY",year).replaceAll("MM",month).replaceAll("DD",day).replaceAll("HH",hours).replaceAll("mm",minutes).replaceAll("ss",seconds):`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`}const logger$1=createLogger("playerCore_logReport"),app=getApp(),DF="wxminiprogram",LIVE_CODE_Start=102001,LIVE_CODE_Info=102002,VOD_CODE_Start=92001,VOD_CODE_Info=92005;let LogReport=function(){return _createClass(function LogReport(option){_classCallCheck(this,LogReport);const currentEnvConfig=option?.env&&envConfig[option.env]?envConfig[option.env]:envConfig.production;this.logReportBaseUrl=currentEnvConfig.LOG_REPORT_BASE_URL,this.option=option,this._infoPackInterval=void 0,this.infoPackIntervalMs=3e4,this.body={},this.uuid=void 0},[{key:"justUpdateData",value:function justUpdateData(option){this.option=option,this.initReportConfig()}},{key:"init",value:function init(){logger$1.debug("init() exec!"),!1!==this.option.enable&&(this.uuid=guid(),this.initReportConfig())}},{key:"initReportConfig",value:function initReportConfig(){const uuid=this.uuid?this.uuid:guid();this.body={ver:this.option.componetVersion,bu:1,flow_type:2,vtype:"",topic:"",webUrl:"",pf:9,df:DF,ua:DF,browser_name:DF,osv:DF,ndi:DF,uid:this.option.uid||"",_uuid:uuid,s:uuid,app_id:"",p:"",aid:"",biz_id:"",guid:"",vid:"",vfid:"",videoWidth:0,videoHeight:0,protocol:"live"===this.option.type?"flv":"hls",picture_quality:"",sd:"",fd:"",tt:this.infoPackIntervalMs,bc:0,bt:0,tf:0,errcode:0,pushTime:Date.now(),reportTime:Date.now()},Object.assign(this.body,this.option.otherOption)}},{key:"updateReportConfig",value:function updateReportConfig(obj){Object.assign(this.body,obj)}},{key:"start",value:function start(){logger$1.debug("start() exec"),this.startPack(),this.resume()}},{key:"resume",value:function resume(){logger$1.debug("resume() call"),this._clearTimer(),this._infoPackInterval=setInterval(this.infoPack.bind(this),this.infoPackIntervalMs),app.globalData?.playerReportTimer||(app.globalData.playerReportTimer=[]),app.globalData.playerReportTimer.push(this._infoPackInterval)}},{key:"startPack",value:function startPack(){if(Date.now()-app.globalData.playerReportStartTs<1e3)return void(app.globalData.playerReportStartTs=Date.now());app.globalData.playerReportStartTs=Date.now();const code="live"===this.option.type?LIVE_CODE_Start:VOD_CODE_Start;this._report(code),logger$1.debug(`startPack() call:, ${formatTimestamp(Date.now())}, ${code}: `,this.body)}},{key:"infoPack",value:function infoPack(){const code="live"===this.option.type?LIVE_CODE_Info:VOD_CODE_Info;this._report(code),logger$1.debug(`infoPack() call: timerId=${this._infoPackInterval}, ${formatTimestamp(Date.now())}, ${code}: `,this.body)}},{key:"_stringToBase64",value:function _stringToBase64(str){let arrayBuffer=function stringToUtf8ArrayBuffer(input){let utf8=[];for(let i=0;i<input.length;i++){let code=input.charCodeAt(i);code<128?utf8.push(code):code<2048?utf8.push(192|code>>6,128|63&code):code<55296||code>=57344?utf8.push(224|code>>12,128|code>>6&63,128|63&code):(i++,code=65536+((1023&code)<<10|1023&input.charCodeAt(i)),utf8.push(240|code>>18,128|code>>12&63,128|code>>6&63,128|63&code))}return new Uint8Array(utf8)}(str);return wx.arrayBufferToBase64(arrayBuffer)}},{key:"_report",value:function _report(code){this.body.reportTime=Date.now();const data={k:code,id:Date.now(),token:gBase64_encode(JSON.stringify(this.body))};wx.request({url:this.logReportBaseUrl,method:"GET",data:data,success(res){}})}},{key:"_clearTimer",value:function _clearTimer(){if(this._infoPackInterval&&(clearInterval(this._infoPackInterval),this._infoPackInterval=void 0),app.globalData?.playerReportTimer){for(const timer of app.globalData.playerReportTimer)clearInterval(timer);app.globalData.playerReportTimer=[]}}},{key:"destroy",value:function destroy(){logger$1.debug("destroy() call"),this._clearTimer()}}])}();const logger=createLogger("playerCore");let VhallPlayerCore=function(){return _createClass(function VhallPlayerCore(){_classCallCheck(this,VhallPlayerCore)},[{key:"init",value:function init(option){this.option=option,this.scheduler=new Scheduler(option),this.logReporter&&this.logReporter._infoPackInterval>0?(logger.debug("LogReport justUpdateData"),this.logReporter.justUpdateData(option)):(this.logReporter=new LogReport(option),this.logReporter.init())}},{key:"initVhallPlayer",value:async function initVhallPlayer(){try{const vhallInitData=this.option.watchInitData,webinarId=vhallInitData.webinar.id,uid=vhallInitData.join_info.third_party_user_id,nickname=vhallInitData.join_info.nickname,vhallPlayerConfig=await this.scheduler.initVhallPlayerConfig(webinarId),webinar_type=vhallInitData.webinar.type;let type="";1==webinar_type?type="live":2==webinar_type&&vhallInitData.warmup&&vhallInitData.warmup.warmup_paas_record_id||4!=webinar_type&&5!=webinar_type||(type="vod");const paasAppId=vhallInitData.interact.paas_app_id,paasRoomId=vhallInitData.interact.room_id,paasVodId=vhallInitData.paas_record_id,paasAccessToken=vhallInitData.interact.paas_access_token,audioMode=Boolean(1==parseInt(vhallInitData.webinar.mode));this.scheduler.audioMode=audioMode;const verticalMode=Boolean(0==vhallInitData.webinar.webinar_show_type),liveDelayMode=1==vhallInitData.webinar.no_delay_webinar?"RTC":"live",autoplay=1==vhallPlayerConfig["basic-config"].data.autoplay,showProgress=1==vhallPlayerConfig["basic-config"].data.progress_bar,defaultDefinition=vhallPlayerConfig.definition.data.default_definition,permission_value_obj=this.option.permissionValue,hideSameQuality=Boolean("1"==permission_value_obj?.live_hidden_same);this.scheduler.hideSameQuality=hideSameQuality;let posterUrl=vhallInitData.webinar.img_url;verticalMode&&vhallInitData.webinar.vertical_img_url&&(posterUrl=vhallInitData.webinar.vertical_img_url);let posterOption={};posterUrl.length>0&&(posterOption={enable:!0,url:posterUrl});const watermarkConfig=vhallPlayerConfig["water-mark"].data;let watermarkOption={};if(1==watermarkConfig.watermark_open&&watermarkConfig.img_url.length>0){const align=["tl","tr","bl","br"][watermarkConfig.img_position-1],size=[["12%","12%"],["10%","10%"],["8%","8%"]][watermarkConfig.img_size-1];watermarkOption={enable:!0,url:watermarkConfig.img_url,align:align,position:["20px","20px"],size:size,alpha:watermarkConfig.img_alpha}}const marqueeConfig=vhallPlayerConfig["screen-config"].data;let marqueeOption={};if(1==marqueeConfig.scrolling_open){const displayType=marqueeConfig.scroll_type-1,alpha=marqueeConfig.alpha,size=marqueeConfig.size,color=marqueeConfig.color,speed=marqueeConfig.speed,interval=marqueeConfig.interval,position=marqueeConfig.position;marqueeOption={enable:!0,displayType:displayType,text:1==marqueeConfig.text_type?marqueeConfig.text:`${uid}-${nickname}`,alpha:alpha,size:size,color:color,interval:interval,speed:speed,position:position}}return Object.assign(this.scheduler.option,{uid:uid,type:type,paasAppId:paasAppId,paasRoomId:paasRoomId,paasVodId:paasVodId,paasAccessToken:paasAccessToken,defaultDefinition:defaultDefinition}),this.logReporter.updateReportConfig(vhallInitData.report_data),this.logReporter.option.type=type,this.logReporter.updateReportConfig({app_id:paasAppId,aid:"live"==type?paasRoomId:paasVodId,p:"live"==type?paasRoomId:paasVodId,uid:uid}),{type:type,paasAppId:paasAppId,paasRoomId:paasRoomId,paasVodId:paasVodId,paasAccessToken:paasAccessToken,audioMode:audioMode,liveDelayMode:liveDelayMode,verticalMode:verticalMode,autoplay:autoplay,showProgress:showProgress,defaultDefinition:defaultDefinition,posterOption:posterOption,watermarkOption:watermarkOption,marqueeOption:marqueeOption}}catch(err){throw logger.error("初始化失败",err),err}}},{key:"initVhallyunLive",value:function initVhallyunLive(){return new Promise((resolve,reject)=>{this.scheduler.initForLive().then(vhallyunLiveData=>{this.logReporter.updateReportConfig({s:vhallyunLiveData.log_info.session_id}),this.scheduler.initGslbLive(vhallyunLiveData).then(data=>{this.logReporter.updateReportConfig({picture_quality:data.currentQuality,s:vhallyunLiveData.log_info.session_id}),this.logReporter.start(),resolve(data)}).catch(error=>{reject(error)})}).catch(error=>{reject(error)})})}},{key:"initVhallyunVod",value:async function initVhallyunVod(){return new Promise((resolve,reject)=>{this.scheduler.initForVod().then(vhallyunVodData=>{this.logReporter.updateReportConfig({s:vhallyunVodData.log_info.session_id}),this.scheduler.initGslbVod(vhallyunVodData).then(data=>{this.logReporter.updateReportConfig({picture_quality:data.currentQuality,s:vhallyunVodData.log_info.session_id}),this.logReporter.start(),resolve(data)}).catch(error=>{reject(error)})}).catch(error=>{reject(error)})})}},{key:"getVideoSrc",value:function getVideoSrc(quality,subtitle){return this.logReporter.updateReportConfig({picture_quality:quality}),this.scheduler.getVideoSrc(quality,subtitle)}},{key:"resume",value:function resume(){this.logReporter?.resume()}},{key:"destroy",value:function destroy(){this.logReporter?.destroy()}}])}();module.exports=VhallPlayerCore;
|
|
1
|
+
"use strict";function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}var hasRequiredCrc32,crc32$1={};let WxHttp=function(){return _createClass(function WxHttp(store){_classCallCheck(this,WxHttp),this.store=store},[{key:"request",value:function request(url,data={},method="POST"){return new Promise((resolve,reject)=>{const config={url:url,method:method,data:data,header:{"Content-Type":"application/x-www-form-urlencoded"},success:res=>this._handleSuccess(res,resolve,reject),fail:err=>this._handleFail(err,reject)};wx.request(config)})}},{key:"_handleSuccess",value:function _handleSuccess(res,resolve,reject){if(200!==res.statusCode)return reject({code:res.statusCode,msg:"网络请求失败"});const response=res.data||{};200===+response.code?resolve(response.data):reject(response)}},{key:"_handleFail",value:function _handleFail(err,reject){reject({code:-1,msg:"网络连接失败",errMsg:err.errMsg})}}])}();const VHALL_API_LIST_PLAYER_CONFIG="/v3/interacts/union/player-config",VHALLYUN_API_LIST_INIT="/sdk/v2/init/start",VHALLYUN_API_LIST_INIT_LIVE="/sdk/v2/room/get-watch-info",VHALLYUN_API_LIST_INIT_VOD="/sdk/v2/demand/get-record-watch-info",VHALLYUN_API_LIST_DISPATCH_LIVE="/api/dispatch_play",VHALLYUN_API_LIST_DISPATCH_VOD="/api/dispatch_replay";function safeUrlJoin(baseUrl,path){return`${baseUrl.replace(/\/$/,"")}/${path.replace(/^\//,"")}`}const envConfig={production:{BASE_URL:"https://open-api.vhall.com",VHALLYUN_API_BASE:"https://api.vhallyun.com",LOG_REPORT_BASE_URL:"https://dc.e.vhall.com/login",PUBLIC_KEY:"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0eUJFtW3vryA2NXx4M4f\n1w7dg3PHwOCA6Kx7JVfD/9eBGfqLhqsp+pg4AXG4PhuQx8EsV+sncQIiQO5J2//T\n3pO8LftDtCQztLnxnhq+BjhbFeswgfez2CwV2YKLTX2zyZ69T1Vu/M4H4gWSLeiV\n1FcH6xycA2+jG+EvOxSSItCKYT9EkB9BZSKf5RU7gM+qPtzdPtJP5vlsMCa0WnpY\nI6Qrmu/w9CZkL0397gUek9nBpPHkyPYg7ZijF3Gj8EqCMCVVTYpX96k4dd/Rz1em\ns4OSPF5jDsYZi58p+LmTcc3g7W9bD3QWWxzn47ie/Dh9LbnWfCqpGjUaHd3d42vR\ncQIDAQAB\n-----END PUBLIC KEY-----"},test:{BASE_URL:"https://test01-open-api.vhou.tv",VHALLYUN_API_BASE:"https://test01-api.vhallyun.com",LOG_REPORT_BASE_URL:"https://t-dc.e.vhall.com/login",PUBLIC_KEY:"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxWGCgHz2NLdVNa91CsNX\nFfCsxfgkTx738t3yMpuPYLL/5wwuWRrX7hBfNsfC+R5BW5b13ISzD001NNt+BWGK\np3V5fdWO18j9M/AhaTV2Ao/IpdP5huvVoNFVWPUQvX70FHu0sPVTev8ycAZHUpKx\n+mm83wxOpWBN5vAMJYx75pRCQfidb73XbOm6JXLJlxN91TUTrTiblxBhRwH0AQyr\ns9dUr+IJUZ1ea2uU3fkB4uYh7V/cHuNDMsJowfLtEU2+9IqEuJY4OwqX0qdfPF72\nsGMjCgghgL0z/7kv7Qe1+tOkJTBQTzODXBheGTVbF7hH2+5XuZsK2TfgBIew0I4k\n1wIDAQAB\n-----END PUBLIC KEY-----"}};let WxApi=function(){return _createClass(function WxApi(store){_classCallCheck(this,WxApi),this.currentEnvConfig=store?.env&&envConfig[store.env]?envConfig[store.env]:envConfig.production,this.http=new WxHttp(store)},[{key:"requestPlayerConfig",value:function requestPlayerConfig(webinarId){const url=safeUrlJoin(this.currentEnvConfig.BASE_URL,VHALL_API_LIST_PLAYER_CONFIG),data={webinar_id:webinarId,tags:["basic-config","definition","screen-config","water-mark"]};return this.http.request(url,data)}},{key:"initVhallyun",value:function initVhallyun(){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT);return this.http.request(url)}},{key:"requestVhallyunLive",value:function requestVhallyunLive(data){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT_LIVE);return this.http.request(url,{...data,client:"pc_browser",package_check:"peter"})}},{key:"requestGslbLive",value:function requestGslbLive(domain,data){const url=safeUrlJoin(domain,VHALLYUN_API_LIST_DISPATCH_LIVE);return this.http.request(url,{...data,bu:1})}},{key:"requestVhallyunVod",value:function requestVhallyunVod(data){const url=safeUrlJoin(this.currentEnvConfig.VHALLYUN_API_BASE,VHALLYUN_API_LIST_INIT_VOD);return this.http.request(url,{...data,client:"pc_browser",package_check:"peter"})}},{key:"requestGslbVod",value:function requestGslbVod(domain,data){const url=safeUrlJoin(domain,VHALLYUN_API_LIST_DISPATCH_VOD);return this.http.request(url,{...data,bu:1})}}])}();const LOG_LEVEL_trace=0,LOG_LEVEL_debug=1,LOG_LEVEL_info=2,LOG_LEVEL_log=2,LOG_LEVEL_warn=3,LOG_LEVEL_error=4;let _logLevel=LOG_LEVEL_info;function formatTime(){const date=new Date,pad=(n,len=2)=>String(n).padStart(len,"0");return`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}:${pad(date.getMilliseconds(),3)}`}function createLogger(module=""){const prefix=module?`[${module}]`:"",appPrefix="VhallMiniSDK",enabled=level=>level>=_logLevel;return{trace:function trace(...args){enabled(LOG_LEVEL_trace)&&console.trace(`${appPrefix} [${formatTime()}] <TRACE> ${prefix} `,...args)},debug:function debug(...args){enabled(LOG_LEVEL_debug)&&console.debug(`${appPrefix} [${formatTime()}] <DEBUG> ${prefix} `,...args)},info:function info(...args){enabled(LOG_LEVEL_info)&&console.info(`${appPrefix} [${formatTime()}] <INFO> ${prefix}`,...args)},log:function log(...args){enabled(LOG_LEVEL_log)&&console.log(`${appPrefix} [${formatTime()}] <LOG> ${prefix}`,...args)},warn:function warn(...args){enabled(LOG_LEVEL_warn)&&console.warn(`${appPrefix} [${formatTime()}] <WARN> ${prefix}`,...args)},error:function error(...args){enabled(LOG_LEVEL_error)&&console.error(`${appPrefix} [${formatTime()}] <ERROR> ${prefix}`,...args)}}}const crc32=function requireCrc32(){return hasRequiredCrc32||(hasRequiredCrc32=1,factory=function(CRC32){CRC32.version="1.2.2";var T0=function signed_crc_table(){for(var c=0,table=new Array(256),n=0;256!=n;++n)c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=1&(c=n)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1)?-306674912^c>>>1:c>>>1,table[n]=c;return"undefined"!=typeof Int32Array?new Int32Array(table):table}(),TT=function slice_by_16_tables(T){var c=0,v=0,n=0,table="undefined"!=typeof Int32Array?new Int32Array(4096):new Array(4096);for(n=0;256!=n;++n)table[n]=T[n];for(n=0;256!=n;++n)for(v=T[n],c=256+n;c<4096;c+=256)v=table[c]=v>>>8^T[255&v];var out=[];for(n=1;16!=n;++n)out[n-1]="undefined"!=typeof Int32Array?table.subarray(256*n,256*n+256):table.slice(256*n,256*n+256);return out}(T0),T1=TT[0],T2=TT[1],T3=TT[2],T4=TT[3],T5=TT[4],T6=TT[5],T7=TT[6],T8=TT[7],T9=TT[8],Ta=TT[9],Tb=TT[10],Tc=TT[11],Td=TT[12],Te=TT[13],Tf=TT[14];CRC32.table=T0,CRC32.bstr=function crc32_bstr(bstr,seed){for(var C=-1^seed,i=0,L=bstr.length;i<L;)C=C>>>8^T0[255&(C^bstr.charCodeAt(i++))];return~C},CRC32.buf=function crc32_buf(B,seed){for(var C=-1^seed,L=B.length-15,i=0;i<L;)C=Tf[B[i++]^255&C]^Te[B[i++]^C>>8&255]^Td[B[i++]^C>>16&255]^Tc[B[i++]^C>>>24]^Tb[B[i++]]^Ta[B[i++]]^T9[B[i++]]^T8[B[i++]]^T7[B[i++]]^T6[B[i++]]^T5[B[i++]]^T4[B[i++]]^T3[B[i++]]^T2[B[i++]]^T1[B[i++]]^T0[B[i++]];for(L+=15;i<L;)C=C>>>8^T0[255&(C^B[i++])];return~C},CRC32.str=function crc32_str(str,seed){for(var C=-1^seed,i=0,L=str.length,c=0,d=0;i<L;)(c=str.charCodeAt(i++))<128?C=C>>>8^T0[255&(C^c)]:c<2048?C=(C=C>>>8^T0[255&(C^(192|c>>6&31))])>>>8^T0[255&(C^(128|63&c))]:c>=55296&&c<57344?(c=64+(1023&c),d=1023&str.charCodeAt(i++),C=(C=(C=(C=C>>>8^T0[255&(C^(240|c>>8&7))])>>>8^T0[255&(C^(128|c>>2&63))])>>>8^T0[255&(C^(128|d>>6&15|(3&c)<<4))])>>>8^T0[255&(C^(128|63&d))]):C=(C=(C=C>>>8^T0[255&(C^(224|c>>12&15))])>>>8^T0[255&(C^(128|c>>6&63))])>>>8^T0[255&(C^(128|63&c))];return~C}},"undefined"==typeof DO_NOT_EXPORT_CRC?factory(crc32$1):factory({})),crc32$1;var factory}(),logger$2=createLogger("playerCore_scheduler"),QUALITY_SORTED_LIST=["same","origin","720p","720sp","480p","480sp","360p","360sp","a"];let Scheduler=function(){function Scheduler(option){_classCallCheck(this,Scheduler),this.option=option,this.audioMode=!1,this.hideSameQuality=!1,this.api=new WxApi(option)}return _createClass(Scheduler,[{key:"getVhallPlayerConfig",value:async function getVhallPlayerConfig(webinarId){return this.api.requestPlayerConfig(webinarId)}},{key:"initForLive",value:function initForLive(){return new Promise((resolve,reject)=>{this.api.requestVhallyunLive({app_id:this.option.paasAppId,room_id:this.option.paasRoomId,third_party_user_id:this.option.uid,access_token:this.option.paasAccessToken}).then(data=>{logger$2.debug("vhallyun直播接口成功: ",data);var vhallyunLiveData=(data=>{const{dispatch_server:dispatch_server,live_delay:live_delay,live_subtitle_mps:live_subtitle_mps,log_info:log_info}=data;return{log_info:log_info,uid:log_info.uid,dispatch_server:dispatch_server,subtitles:(live_subtitle_mps||"").split(",").map(s=>s.trim()).filter(s=>s.length>0),live_delay:live_delay}})(data);this.vhallyunLiveData=vhallyunLiveData,resolve(vhallyunLiveData)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initGslbLive",value:function initGslbLive(){const _parseGslbLive=data=>{const{dispatch_urls_v2:dispatch_urls_v2,token:token}=data,{stream_id:stream_id,quality:quality,multi_lang_subtitle:multi_lang_subtitle,rtmp_urls:rtmp_urls}=dispatch_urls_v2;let qualitys,httpflv_urls=dispatch_urls_v2.httpflv_urls;if(this.audioMode)qualitys=["same"];else if(qualitys=quality.sort((a,b)=>{const indexA=QUALITY_SORTED_LIST.indexOf(a),indexB=QUALITY_SORTED_LIST.indexOf(b);return-1===indexA&&-1===indexB?0:-1===indexA?1:-1===indexB?-1:indexA-indexB}),this.hideSameQuality){qualitys.some(item=>"same"!==item&&"a"!==item)&&(qualitys=qualitys.filter(item=>"same"!==item))}const subtitles=this.vhallyunLiveData.subtitles;subtitles.length>0&&(httpflv_urls=httpflv_urls.filter(item=>"tx"===item.cdn_name));const lines=[];httpflv_urls.forEach(item=>{lines.push(item.cdn_name)}),logger$2.debug("优先清晰度: ",this.option.defaultDefinition),logger$2.debug("全部清晰度: ",qualitys),logger$2.debug("全部字幕: ",subtitles),logger$2.debug("全部线路: ",lines);const defaultDefinition=this.option.defaultDefinition;let currentSubtitle=subtitles.length>0?subtitles[0]:"",currentQuality=Scheduler._decideCurrentQuality(defaultDefinition,qualitys);if(!currentQuality)return log.error("无法获取有效的直播播放地址!"),null;logger$2.debug("选择清晰度: ",currentQuality),logger$2.debug("选择字幕: ",currentSubtitle),logger$2.debug("选择线路: ",0);const newToken=Scheduler._createPlayToken(token),http_flv_domain=httpflv_urls[0].url,http_flv_app=httpflv_urls[0].app;return{httpflv_urls:httpflv_urls,stream_id:stream_id,newToken:newToken,lines:lines,currentLines:0,videoSrc:`${http_flv_domain}/${http_flv_app}/${stream_id}${""==currentSubtitle?"":`_${currentSubtitle}`}${"same"==currentQuality?"":`_${currentQuality}`}.flv?token=${newToken}`,qualitys:qualitys,currentQuality:currentQuality,subtitles:subtitles,currentSubtitle:currentSubtitle}};return new Promise((resolve,reject)=>{this.api.requestGslbLive(this.vhallyunLiveData.dispatch_server,{app_id:this.option.paasAppId,webinar_id:this.option.paasRoomId,uid:this.option.uid,rand:Scheduler._getRandom()}).then(data=>{logger$2.debug("GSLB直播接口成功: ",data);const livePlayInfo=_parseGslbLive(data);this.livePlayInfo=livePlayInfo,resolve(livePlayInfo)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initForVod",value:function initForVod(){return new Promise((resolve,reject)=>{this.api.requestVhallyunVod({app_id:this.option.paasAppId,record_id:this.option.paasVodId,third_party_user_id:this.option.uid,access_token:this.option.paasAccessToken}).then(data=>{logger$2.debug("vhallyun点播接口成功: ",data);var vhallyunVodData=(data=>{const{cue_point:cue_point,default_server:default_server,definition:definition,dispatch_server:dispatch_server,log_info:log_info,safe_server:safe_server,subtitle_info:subtitle_info,watermark:watermark}=data,vodEncrypted=safe_server.hasOwnProperty("cipher_key"),videoUri=default_server.uri,rand=default_server.rand,uid=log_info.uid;return definition.sort((a,b)=>{const indexA=QUALITY_SORTED_LIST.indexOf(a),indexB=QUALITY_SORTED_LIST.indexOf(b);return-1===indexA&&-1===indexB?0:-1===indexA?1:-1===indexB?-1:indexA-indexB}),{log_info:log_info,uid:uid,rand:rand,vodEncrypted:vodEncrypted,cue_point:cue_point,videoUri:videoUri,definition:definition,dispatch_server:dispatch_server,subtitle_info:subtitle_info,watermark:watermark}})(data);this.vhallyunVodData=vhallyunVodData,resolve(vhallyunVodData)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"initGslbVod",value:function initGslbVod(){const _parseGslbVod=data=>{const{hls_domainnames:hls_domainnames,token:token}=data;let qualitys;qualitys=this.audioMode?["same"]:this.vhallyunVodData.definition;const qualitySample=qualitys.indexOf("same")>=0?"same":qualitys[0],lines=[];hls_domainnames[qualitySample].forEach(item=>{lines.push(item.cdn_name)}),logger$2.debug("优先清晰度: ",this.option.defaultDefinition),logger$2.debug("全部清晰度: ",qualitys),logger$2.debug("全部线路: ",lines);const defaultDefinition=this.option.defaultDefinition;let currentQuality=Scheduler._decideCurrentQuality(defaultDefinition,qualitys);if(!currentQuality)return log.error("无法获取有效的点播播放地址!"),null;logger$2.debug("选择清晰度: ",currentQuality),logger$2.debug("选择线路: ",0);const newToken=Scheduler._createPlayToken(token),hls_url_tmp=hls_domainnames[currentQuality][0].hls_domainname;return{hls_domainnames:hls_domainnames,newToken:newToken,lines:lines,currentLines:0,videoSrc:`${hls_url_tmp}?token=${newToken}`,qualitys:qualitys,currentQuality:currentQuality}};return new Promise((resolve,reject)=>{this.api.requestGslbVod(this.vhallyunVodData.dispatch_server,{app_id:this.option.paasAppId,webinar_id:this.option.paasVodId,uid:this.vhallyunVodData.uid,rand:this.vhallyunVodData.rand,uri:this.vhallyunVodData.videoUri,quality:`["${this.vhallyunVodData.definition.join('","')}"]`}).then(data=>{logger$2.debug("GSLB点播接口成功: ",data);const vodPlayInfo=_parseGslbVod(data);this.vodPlayInfo=vodPlayInfo,resolve(vodPlayInfo)}).catch(err=>{logger$2.error("初始化失败",err),reject(err)})})}},{key:"getVideoSrc",value:function getVideoSrc(quality,subtitle){if("vod"==this.option.type){const newToken=this.vodPlayInfo.newToken;return`${this.vodPlayInfo.hls_domainnames[quality][this.vodPlayInfo.currentLines].hls_domainname}?token=${newToken}`}{const newToken=this.livePlayInfo.newToken,http_flv_quality="same"==quality?"":`_${quality}`,http_flv_subtitle=""==subtitle?"":`_${subtitle}`;return`${this.livePlayInfo.httpflv_urls[this.livePlayInfo.currentLines].url}/${this.livePlayInfo.httpflv_urls[this.livePlayInfo.currentLines].app}/${this.livePlayInfo.stream_id}${http_flv_subtitle}${http_flv_quality}.flv?token=${newToken}`}}}],[{key:"_getRandom",value:function _getRandom(){return 1e8+(899999999*Math.random()|0)}},{key:"_createPlayToken",value:function _createPlayToken(originToken){const pre=originToken.split("_")[0],last=originToken.split("_")[1],reverseToken=pre.split("").reverse().join("");return`${(crc32.str(reverseToken)>>>0).toString(16).toUpperCase()}_${last}`}}])}();!function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}(Scheduler,"_decideCurrentQuality",function(defaultDefinition,qualitys){let currentQuality=null;if(0==qualitys.length)log.error("调度无法获取点播播放地址!");else if(1==qualitys.length)currentQuality=qualitys[0];else if(qualitys.indexOf(defaultDefinition)>=0)currentQuality=defaultDefinition;else{let alternatives=qualitys.filter(item=>"same"!==item&&"a"!==item);currentQuality=alternatives.length>0?alternatives[0]:qualitys[0]}return currentQuality});const _hasBuffer="function"==typeof Buffer,_TE=("function"==typeof TextDecoder&&new TextDecoder,"function"==typeof TextEncoder?new TextEncoder:void 0),b64chs=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),b64tab=(()=>{let tab={};return b64chs.forEach((c,i)=>tab[c]=i),tab})(),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_mkUriSafe=("function"==typeof Uint8Array.from&&Uint8Array.from.bind(Uint8Array),src=>src.replace(/=/g,"").replace(/[+\/]/g,m0=>"+"==m0?"-":"_")),_tidyB64=s=>s.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=bin=>{let u32,c0,c1,c2,asc="";const pad=bin.length%3;for(let i=0;i<bin.length;){if((c0=bin.charCodeAt(i++))>255||(c1=bin.charCodeAt(i++))>255||(c2=bin.charCodeAt(i++))>255)throw new TypeError("invalid character found");u32=c0<<16|c1<<8|c2,asc+=b64chs[u32>>18&63]+b64chs[u32>>12&63]+b64chs[u32>>6&63]+b64chs[63&u32]}return pad?asc.slice(0,pad-3)+"===".substring(pad):asc},_btoa="function"==typeof btoa?bin=>btoa(bin):_hasBuffer?bin=>Buffer.from(bin,"binary").toString("base64"):btoaPolyfill,_fromUint8Array=_hasBuffer?u8a=>Buffer.from(u8a).toString("base64"):u8a=>{let strs=[];for(let i=0,l=u8a.length;i<l;i+=4096)strs.push(_fromCC.apply(null,u8a.subarray(i,i+4096)));return _btoa(strs.join(""))},cb_utob=c=>{if(c.length<2)return(cc=c.charCodeAt(0))<128?c:cc<2048?_fromCC(192|cc>>>6)+_fromCC(128|63&cc):_fromCC(224|cc>>>12&15)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc);var cc=65536+1024*(c.charCodeAt(0)-55296)+(c.charCodeAt(1)-56320);return _fromCC(240|cc>>>18&7)+_fromCC(128|cc>>>12&63)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=u=>u.replace(re_utob,cb_utob),_encode=_hasBuffer?s=>Buffer.from(s,"utf8").toString("base64"):_TE?s=>_fromUint8Array(_TE.encode(s)):s=>_btoa(utob(s)),encode=(src,urlsafe=!1)=>urlsafe?_mkUriSafe(_encode(src)):_encode(src),atobPolyfill=asc=>{if(asc=asc.replace(/\s+/g,""),!b64re.test(asc))throw new TypeError("malformed base64.");asc+="==".slice(2-(3&asc.length));let u24,r1,r2,bin="";for(let i=0;i<asc.length;)u24=b64tab[asc.charAt(i++)]<<18|b64tab[asc.charAt(i++)]<<12|(r1=b64tab[asc.charAt(i++)])<<6|(r2=b64tab[asc.charAt(i++)]),bin+=64===r1?_fromCC(u24>>16&255):64===r2?_fromCC(u24>>16&255,u24>>8&255):_fromCC(u24>>16&255,u24>>8&255,255&u24);return bin},gBase64_encode=encode;function formatTimestamp(timestamp,format="YYYY-MM-DD HH:mm:ss"){const ms=10===timestamp.toString().length?1e3*timestamp:timestamp,date=new Date(ms),year=date.getFullYear(),month=String(date.getMonth()+1).padStart(2,"0"),day=String(date.getDate()).padStart(2,"0"),hours=String(date.getHours()).padStart(2,"0"),minutes=String(date.getMinutes()).padStart(2,"0"),seconds=String(date.getSeconds()).padStart(2,"0");return format?format.replaceAll("YYYY",year).replaceAll("MM",month).replaceAll("DD",day).replaceAll("HH",hours).replaceAll("mm",minutes).replaceAll("ss",seconds):`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`}const logger$1=createLogger("playerCore_logReport"),app=getApp(),DF="wxminiprogram",LIVE_CODE_Start=102001,LIVE_CODE_Info=102002,VOD_CODE_Start=92001,VOD_CODE_Info=92005;let LogReport=function(){return _createClass(function LogReport(option){_classCallCheck(this,LogReport);const currentEnvConfig=option?.env&&envConfig[option.env]?envConfig[option.env]:envConfig.production;this.logReportBaseUrl=currentEnvConfig.LOG_REPORT_BASE_URL,this.option=option,this._infoPackInterval=void 0,this.infoPackIntervalMs=3e4,this.body={},this.uuid=void 0},[{key:"justUpdateData",value:function justUpdateData(option){this.option=option,this.initReportConfig()}},{key:"init",value:function init(){logger$1.debug("init() exec!"),!1!==this.option.enable&&this.initReportConfig()}},{key:"initReportConfig",value:function initReportConfig(){const uuid=this.uuid?this.uuid:function guid(){return"xxxxxxxx-xxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)})}();this.uuid=uuid,this.body={ver:this.option.componetVersion,bu:1,flow_type:2,vtype:"",topic:"",webUrl:"",pf:9,df:DF,ua:DF,browser_name:DF,osv:DF,ndi:DF,uid:this.option.uid||"",_uuid:uuid,s:uuid,app_id:"",p:"",aid:"",biz_id:"",guid:"",vid:"",vfid:"",videoWidth:0,videoHeight:0,protocol:"live"===this.option.type?"flv":"hls",picture_quality:"",sd:"",fd:"",tt:this.infoPackIntervalMs,bc:0,bt:0,tf:0,errcode:0,pushTime:Date.now(),reportTime:Date.now()},Object.assign(this.body,this.option.otherOption)}},{key:"updateReportConfig",value:function updateReportConfig(obj){Object.assign(this.body,obj)}},{key:"start",value:function start(){logger$1.debug("start() exec"),this.startPack(),this.resume()}},{key:"resume",value:function resume(){logger$1.debug("resume() call"),this._clearTimer(),this._infoPackInterval=setInterval(this.infoPack.bind(this),this.infoPackIntervalMs),app.globalData?.playerReportTimer||(app.globalData.playerReportTimer=[]),app.globalData.playerReportTimer.push(this._infoPackInterval)}},{key:"startPack",value:function startPack(){if(Date.now()-app.globalData.playerReportStartTs<1e3)return void(app.globalData.playerReportStartTs=Date.now());app.globalData.playerReportStartTs=Date.now();const code="live"===this.option.type?LIVE_CODE_Start:VOD_CODE_Start;this._report(code),logger$1.debug(`startPack() call:, ${formatTimestamp(Date.now())}, ${code}: `,this.body)}},{key:"infoPack",value:function infoPack(){const code="live"===this.option.type?LIVE_CODE_Info:VOD_CODE_Info;this._report(code),logger$1.debug(`infoPack() call: timerId=${this._infoPackInterval}, ${formatTimestamp(Date.now())}, ${code}: `,this.body)}},{key:"_stringToBase64",value:function _stringToBase64(str){let arrayBuffer=function stringToUtf8ArrayBuffer(input){let utf8=[];for(let i=0;i<input.length;i++){let code=input.charCodeAt(i);code<128?utf8.push(code):code<2048?utf8.push(192|code>>6,128|63&code):code<55296||code>=57344?utf8.push(224|code>>12,128|code>>6&63,128|63&code):(i++,code=65536+((1023&code)<<10|1023&input.charCodeAt(i)),utf8.push(240|code>>18,128|code>>12&63,128|code>>6&63,128|63&code))}return new Uint8Array(utf8)}(str);return wx.arrayBufferToBase64(arrayBuffer)}},{key:"_report",value:function _report(code){this.body.reportTime=Date.now();const data={k:code,id:Date.now(),token:gBase64_encode(JSON.stringify(this.body))};wx.request({url:this.logReportBaseUrl,method:"GET",data:data,success(res){}})}},{key:"_clearTimer",value:function _clearTimer(){if(this._infoPackInterval&&(clearInterval(this._infoPackInterval),this._infoPackInterval=void 0),app.globalData?.playerReportTimer){for(const timer of app.globalData.playerReportTimer)clearInterval(timer);app.globalData.playerReportTimer=[]}}},{key:"destroy",value:function destroy(){logger$1.debug("destroy() call"),this._clearTimer()}}])}();const logger=createLogger("playerCore");let VhallPlayerCore=function(){return _createClass(function VhallPlayerCore(){_classCallCheck(this,VhallPlayerCore)},[{key:"init",value:function init(option){this.option=option,this.scheduler=new Scheduler(option),this.logReporter&&this.logReporter._infoPackInterval>0?(logger.debug("LogReport justUpdateData"),this.logReporter.justUpdateData(option)):(this.logReporter=new LogReport(option),this.logReporter.init())}},{key:"initVhallPlayer",value:async function initVhallPlayer(){try{const vhallInitData=this.option.watchInitData,webinarId=vhallInitData.webinar.id,uid=vhallInitData.join_info.third_party_user_id,nickname=vhallInitData.join_info.nickname,vhallPlayerConfig=await this.scheduler.getVhallPlayerConfig(webinarId),webinar_type=vhallInitData.webinar.type,isWarmVideo=!!(2==webinar_type&&vhallInitData.warmup?.warmup_paas_record_id?.length>0);let type="";1==webinar_type?type="live":(isWarmVideo||4==webinar_type||5==webinar_type)&&(type="vod");const paasAppId=vhallInitData.interact.paas_app_id,paasRoomId=vhallInitData.interact.room_id,warmVideoIds=isWarmVideo?vhallInitData.warmup.warmup_paas_record_id:[],warmupPlayerType=isWarmVideo?Number(vhallInitData.warmup?.warmup_player_type):1,advancePlayTime=isWarmVideo?Number(vhallInitData.warmup?.advance_play_time):0,webinarStartTime=vhallInitData.webinar?.start_time||"",paasVodId=isWarmVideo?warmVideoIds[0]:vhallInitData.paas_record_id,paasAccessToken=vhallInitData.interact.paas_access_token,audioMode=Boolean(1==parseInt(vhallInitData.webinar.mode));this.scheduler.audioMode=audioMode;const verticalMode=Boolean(0==vhallInitData.webinar.webinar_show_type),liveDelayMode=1==vhallInitData.webinar.no_delay_webinar?"RTC":"live",autoplay=1==vhallPlayerConfig["basic-config"].data.autoplay,showProgress=1==vhallPlayerConfig["basic-config"].data.progress_bar,defaultDefinition=vhallPlayerConfig.definition.data.default_definition,permission_value_obj=this.option.permissionValue,hideSameQuality=Boolean("1"==permission_value_obj?.live_hidden_same);this.scheduler.hideSameQuality=hideSameQuality;let posterUrl=vhallInitData.webinar.img_url;verticalMode&&vhallInitData.webinar.vertical_img_url&&(posterUrl=vhallInitData.webinar.vertical_img_url),isWarmVideo&&(verticalMode&&vhallInitData.warmup.warmup_vertical_img_url?posterUrl=vhallInitData.warmup.warmup_vertical_img_url:vhallInitData.warmup.warmup_img_url&&(posterUrl=vhallInitData.warmup.warmup_img_url));const posterOption=posterUrl.length>0?{enable:!0,url:posterUrl}:{},watermarkConfig=vhallPlayerConfig["water-mark"].data;let watermarkOption={};if(1==watermarkConfig.watermark_open&&watermarkConfig.img_url.length>0){const align=["tl","tr","bl","br"][watermarkConfig.img_position-1],size=[["12%","12%"],["10%","10%"],["8%","8%"]][watermarkConfig.img_size-1];watermarkOption={enable:!0,url:watermarkConfig.img_url,align:align,position:["20px","20px"],size:size,alpha:watermarkConfig.img_alpha}}const marqueeConfig=vhallPlayerConfig["screen-config"].data;let marqueeOption={};if(1==marqueeConfig.scrolling_open){const displayType=marqueeConfig.scroll_type-1,alpha=marqueeConfig.alpha,size=marqueeConfig.size,color=marqueeConfig.color,speed=marqueeConfig.speed,interval=marqueeConfig.interval,position=marqueeConfig.position;marqueeOption={enable:!0,displayType:displayType,text:1==marqueeConfig.text_type?marqueeConfig.text:`${uid}-${nickname}`,alpha:alpha,size:size,color:color,interval:interval,speed:speed,position:position}}return Object.assign(this.scheduler.option,{uid:uid,type:type,paasAppId:paasAppId,paasRoomId:paasRoomId,paasVodId:paasVodId,paasAccessToken:paasAccessToken,defaultDefinition:defaultDefinition}),this.logReporter.updateReportConfig(vhallInitData.report_data),this.logReporter.option.type=type,this.logReporter.updateReportConfig({app_id:paasAppId,aid:"live"==type?paasRoomId:paasVodId,p:"live"==type?paasRoomId:paasVodId,uid:uid}),{type:type,paasAppId:paasAppId,paasRoomId:paasRoomId,paasVodId:paasVodId,paasAccessToken:paasAccessToken,audioMode:audioMode,liveDelayMode:liveDelayMode,verticalMode:verticalMode,autoplay:autoplay,showProgress:showProgress,defaultDefinition:defaultDefinition,isWarmVideo:isWarmVideo,warmVideoIds:warmVideoIds,warmVideoIndex:0,warmupPlayerType:warmupPlayerType,advancePlayTime:advancePlayTime,webinarStartTime:webinarStartTime,posterOption:posterOption,watermarkOption:watermarkOption,marqueeOption:marqueeOption}}catch(err){throw logger.error("初始化失败",err),err}}},{key:"initVhallyunLive",value:function initVhallyunLive(){return new Promise((resolve,reject)=>{this.scheduler.initForLive().then(vhallyunLiveData=>{this.logReporter.updateReportConfig({s:vhallyunLiveData.log_info.session_id}),this.scheduler.initGslbLive(vhallyunLiveData).then(data=>{this.logReporter.updateReportConfig({picture_quality:data.currentQuality,s:vhallyunLiveData.log_info.session_id}),this.logReporter.start(),resolve(data)}).catch(error=>{reject(error)})}).catch(error=>{reject(error)})})}},{key:"initVhallyunVod",value:async function initVhallyunVod(){return new Promise((resolve,reject)=>{this.scheduler.initForVod().then(vhallyunVodData=>{this.logReporter.updateReportConfig({s:vhallyunVodData.log_info.session_id}),this.scheduler.initGslbVod(vhallyunVodData).then(data=>{this.logReporter.updateReportConfig({picture_quality:data.currentQuality,s:vhallyunVodData.log_info.session_id}),this.logReporter.start(),resolve(data)}).catch(error=>{reject(error)})}).catch(error=>{reject(error)})})}},{key:"getVideoSrc",value:function getVideoSrc(quality,subtitle){return this.logReporter.updateReportConfig({picture_quality:quality}),this.scheduler.getVideoSrc(quality,subtitle)}},{key:"resume",value:function resume(){this.logReporter?.resume()}},{key:"destroy",value:function destroy(){this.logReporter?.destroy()}}])}();module.exports=VhallPlayerCore;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function _callSuper(t,o,e){return o=_getPrototypeOf(o),function _possibleConstructorReturn(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}(t,_isNativeReflectConstruct()?Reflect.construct(o,[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _createClass(e,r,t){return r&&function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}class BaseServer{constructor(){this.handlers=Object.create(null)}on=(type,handler)=>{const bindings=[];if("object"==typeof type&&null!==type)Object.entries(type).forEach(([eventName,eventHandler])=>{this._validateParams(eventName,eventHandler),this._addHandler(eventName,eventHandler),bindings.push({type:eventName,handler:eventHandler})});else{if("string"!=typeof type||"function"!=typeof handler)throw new Error("参数格式错误,支持:$on(事件名, 处理函数) 或 $on({事件名: 处理函数, ...})");this._validateParams(type,handler),this._addHandler(type,handler),bindings.push({type:type,handler:handler})}return()=>{bindings.forEach(({type:eventName,handler:eventHandler})=>{if(!this.handlers[eventName])return;const index=this.handlers[eventName].findIndex(handler=>handler===eventHandler);-1!==index&&(this.handlers[eventName].splice(index,1),0===this.handlers[eventName].length&&delete this.handlers[eventName])})}};emit=(type,...params)=>{this.handlers[type]&&[...this.handlers[type]].forEach(handler=>{handler(...params)})};off=(type,handler)=>{if(!this.handlers[type])throw new Error(`不存在事件: ${type}`);if(handler){const index=this.handlers[type].findIndex(ele=>ele===handler);this.handlers[type].splice(index,1),0===this.handlers[type].length&&delete this.handlers[type]}else delete this.handlers[type]};_validateParams(type,handler){if("string"!=typeof type)throw new Error("事件名必须为字符串");if("function"!=typeof handler)throw new Error("事件处理函数必须为函数")}_addHandler(type,handler){this.handlers[type]||(this.handlers[type]=[]),this.handlers[type].includes(handler)||this.handlers[type].push(handler)}}let LotteryServer=function(){function LotteryServer(sdkInstance){var _this;return function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,LotteryServer),(_this=_callSuper(this,LotteryServer)).sdkInstance=sdkInstance,_this.sdkInstance.EVENT=Object.assign({LOTTERY_START:"lottery_push",LOTTERY_END:"lottery_result_notice",LOTTERY_WIN:"lottery_win",LOTTERY_MISS:"lottery_miss"},_this.sdkInstance.EVENT),_this.wxApi=sdkInstance.wxApi,_this.lotteryList=[],_this.lastMsgTime="",_this.listenerEvent(),_this}return function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}(LotteryServer,BaseServer),_createClass(LotteryServer,[{key:"getLotteryList",value:async function getLotteryList(params){return this.wxApi.sendGet("/v3/vss/lottery/check-list",{show_all:1,...params}).then(res=>(200==res.code&&(this.lotteryList=res.data||[],this.sdkInstance.store.set("lotteryList",res.data)),res))}},{key:"getLotteryDetail",value:async function getLotteryDetail(params){return this.wxApi.sendGet("/v3/lottery/webinar/get-lottery-info",{...params}).then(res=>(200==res.code&&this.sdkInstance.store.set("currentLottery",res.data),res))}},{key:"listenerEvent",value:function listenerEvent(){const{LOTTERY_START:LOTTERY_START,LOTTERY_END:LOTTERY_END}=this.sdkInstance.EVENT;this.sdkInstance.on(this.sdkInstance.EVENT.ROOM_MSG,msg=>{[LOTTERY_START,LOTTERY_END].includes(msg.data.type)&&msg.date_time>this.lastMsgTime&&(this._handleLotteryMsg(msg.data),this.lastMsgTime=msg.date_time)})}},{key:"_handleLotteryMsg",value:async function _handleLotteryMsg(data){const{LOTTERY_START:LOTTERY_START,LOTTERY_END:LOTTERY_END}=this.sdkInstance.EVENT,userInfo=this.sdkInstance.store.get("user");switch(data.type){case LOTTERY_START:this.sdkInstance.emit(LOTTERY_START,data),this.updateLotteryList({id:data.lottery_id,lottery_status:0,can_look_award_pool:data.can_look_award_pool,win:0});break;case LOTTERY_END:const{lottery_winners_award:lottery_winners_award,receive_award_way:receive_award_way}=data,result=lottery_winners_award.find(el=>userInfo.user_id==el.uid);result&&(result.receive_award_way=receive_award_way),this.sdkInstance.emit(LOTTERY_END,result,data),this.updateLotteryList({id:data.lottery_id,lottery_status:1,receive_award_way:receive_award_way,win:result?1:0,title:data.title,publish_winner:data.publish_winner})}}},{key:"updateLotteryList",value:function updateLotteryList(newLottery){const currentList=this.sdkInstance.store.get("lotteryList")||[],index=currentList.findIndex(item=>item.lottery_id===newLottery.lottery_id);index>=0?currentList[index]={...currentList[index],...newLottery}:currentList.unshift(newLottery),this.sdkInstance.store.set("lotteryList",[...currentList]),this.lotteryList=currentList}},{key:"joinLottery",value:async function joinLottery(params){return this.wxApi.sendPost("/v3/lottery/webinar/join-lottery",{...params})}},{key:"getLotteryWinners",value:async function getLotteryWinners(params){return this.wxApi.sendGet("/v3/lottery/webinar/get-lottery-winners",{...params})}},{key:"getReceiveAwardSetting",value:async function getReceiveAwardSetting(params){return this.wxApi.sendPost("/v3/vss/lottery/get-receive-award-setting",params,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"submitLotteryAward",value:async function submitLotteryAward(params){return this.wxApi.sendPost("/v3/vss/lottery/award",params,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getLotteryUserInfo",value:async function getLotteryUserInfo(params){const{interact:interact}=this.sdkInstance.store.get("");return this.wxApi.sendPost("/v3/vss/lottery/user-info",Object.assign({room_id:interact.room_id},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getAwardList",value:async function getAwardList(params){return this.wxApi.sendPost("/v3/vss/lottery/award/list",Object.assign({pos:0,limit:20},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getWinnerList",value:async function getWinnerList(params){const{interact:interact}=this.sdkInstance.store.get("");return this.wxApi.sendPost("/v3/vss/lottery/users-get",Object.assign({room_id:interact.room_id},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}}])}();!function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}(LotteryServer,"name","LotteryServer"),module.exports=LotteryServer;
|
|
1
|
+
"use strict";function _callSuper(t,o,e){return o=_getPrototypeOf(o),function _possibleConstructorReturn(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}(t,_isNativeReflectConstruct()?Reflect.construct(o,[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _createClass(e,r,t){return r&&function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}class BaseServer{constructor(){this.handlers=Object.create(null)}on=(type,handler)=>{const bindings=[];if("object"==typeof type&&null!==type)Object.entries(type).forEach(([eventName,eventHandler])=>{this._validateParams(eventName,eventHandler),this._addHandler(eventName,eventHandler),bindings.push({type:eventName,handler:eventHandler})});else{if("string"!=typeof type||"function"!=typeof handler)throw new Error("参数格式错误,支持:$on(事件名, 处理函数) 或 $on({事件名: 处理函数, ...})");this._validateParams(type,handler),this._addHandler(type,handler),bindings.push({type:type,handler:handler})}return()=>{bindings.forEach(({type:eventName,handler:eventHandler})=>{if(!this.handlers[eventName])return;const index=this.handlers[eventName].findIndex(handler=>handler===eventHandler);-1!==index&&(this.handlers[eventName].splice(index,1),0===this.handlers[eventName].length&&delete this.handlers[eventName])})}};emit=(type,...params)=>{this.handlers[type]&&[...this.handlers[type]].forEach(handler=>{handler(...params)})};off=(type,handler)=>{if(!this.handlers[type])throw new Error(`不存在事件: ${type}`);if(handler){const index=this.handlers[type].findIndex(ele=>ele===handler);this.handlers[type].splice(index,1),0===this.handlers[type].length&&delete this.handlers[type]}else delete this.handlers[type]};_validateParams(type,handler){if("string"!=typeof type)throw new Error("事件名必须为字符串");if("function"!=typeof handler)throw new Error("事件处理函数必须为函数")}_addHandler(type,handler){this.handlers[type]||(this.handlers[type]=[]),this.handlers[type].includes(handler)||this.handlers[type].push(handler)}}let LotteryServer=function(){function LotteryServer(sdkInstance){var _this;return function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,LotteryServer),(_this=_callSuper(this,LotteryServer)).sdkInstance=sdkInstance,_this.sdkInstance.EVENT=Object.assign({LOTTERY_START:"lottery_push",LOTTERY_END:"lottery_result_notice",LOTTERY_WIN:"lottery_win",LOTTERY_MISS:"lottery_miss"},_this.sdkInstance.EVENT),_this.wxApi=sdkInstance.wxApi,_this.lotteryList=[],_this.lastMsgTime="",_this.listenerEvent(),_this}return function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}(LotteryServer,BaseServer),_createClass(LotteryServer,[{key:"getLotteryList",value:async function getLotteryList(params){return this.wxApi.sendGet("/v3/vss/lottery/check-list",{show_all:1,...params}).then(res=>(200==res.code&&(this.lotteryList=res.data||[],this.sdkInstance.store.set("lotteryList",res.data)),res))}},{key:"getLotteryDetail",value:async function getLotteryDetail(params){return this.wxApi.sendGet("/v3/lottery/webinar/get-lottery-info",{...params}).then(res=>(200==res.code&&this.sdkInstance.store.set("currentLottery",res.data),res))}},{key:"listenerEvent",value:function listenerEvent(){const{LOTTERY_START:LOTTERY_START,LOTTERY_END:LOTTERY_END}=this.sdkInstance.EVENT;this.sdkInstance.on(this.sdkInstance.EVENT.ROOM_MSG,msg=>{[LOTTERY_START,LOTTERY_END].includes(msg.data.type)&&msg.date_time>this.lastMsgTime&&(this._handleLotteryMsg(msg.data),this.lastMsgTime=msg.date_time)})}},{key:"_handleLotteryMsg",value:async function _handleLotteryMsg(data){const{LOTTERY_START:LOTTERY_START,LOTTERY_END:LOTTERY_END}=this.sdkInstance.EVENT,userInfo=this.sdkInstance.store.get("user");switch(data.type){case LOTTERY_START:this.sdkInstance.emit(LOTTERY_START,data),this.updateLotteryList({id:data.lottery_id,lottery_status:0,can_look_award_pool:data.can_look_award_pool,win:0});break;case LOTTERY_END:const{lottery_winners_award:lottery_winners_award,receive_award_way:receive_award_way}=data,result=lottery_winners_award.find(el=>userInfo.user_id==el.uid);result&&(result.receive_award_way=receive_award_way),this.sdkInstance.emit(LOTTERY_END,result,data),this.updateLotteryList({id:data.lottery_id,lottery_status:1,receive_award_way:receive_award_way,win:result?1:0,title:data.title,publish_winner:data.publish_winner})}}},{key:"updateLotteryList",value:function updateLotteryList(newLottery){const currentList=this.sdkInstance.store.get("lotteryList")||[],index=currentList.findIndex(item=>item.lottery_id===newLottery.lottery_id);index>=0?currentList[index]={...currentList[index],...newLottery}:currentList.unshift(newLottery),this.sdkInstance.store.set("lotteryList",[...currentList]),this.lotteryList=currentList}},{key:"joinLottery",value:async function joinLottery(params){return this.wxApi.sendPost("/v3/lottery/webinar/join-lottery",{...params})}},{key:"participateLottery",value:async function participateLottery(params){return this.wxApi.sendPost("/v3/vss/lottery/participation",{...params},{headers:{"Content-Type":"application/x-www-form-urlencoded"}})}},{key:"getLotteryWinners",value:async function getLotteryWinners(params){return this.wxApi.sendGet("/v3/lottery/webinar/get-lottery-winners",{...params})}},{key:"getReceiveAwardSetting",value:async function getReceiveAwardSetting(params){return this.wxApi.sendPost("/v3/vss/lottery/get-receive-award-setting",params,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"submitLotteryAward",value:async function submitLotteryAward(params){return this.wxApi.sendPost("/v3/vss/lottery/award",params,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getLotteryUserInfo",value:async function getLotteryUserInfo(params){const{interact:interact}=this.sdkInstance.store.get("");return this.wxApi.sendPost("/v3/vss/lottery/user-info",Object.assign({room_id:interact.room_id},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getAwardList",value:async function getAwardList(params){return this.wxApi.sendPost("/v3/vss/lottery/award/list",Object.assign({pos:0,limit:20},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}},{key:"getWinnerList",value:async function getWinnerList(params){const{interact:interact}=this.sdkInstance.store.get("");return this.wxApi.sendPost("/v3/vss/lottery/users-get",Object.assign({room_id:interact.room_id},params),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(res=>res)}}])}();!function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}(LotteryServer,"name","LotteryServer"),module.exports=LotteryServer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function _callSuper(t,o,e){return o=_getPrototypeOf(o),function _possibleConstructorReturn(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}(t,_isNativeReflectConstruct()?Reflect.construct(o,[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _createClass(e,r,t){return r&&function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}class BaseServer{constructor(){this.handlers=Object.create(null)}on=(type,handler)=>{const bindings=[];if("object"==typeof type&&null!==type)Object.entries(type).forEach(([eventName,eventHandler])=>{this._validateParams(eventName,eventHandler),this._addHandler(eventName,eventHandler),bindings.push({type:eventName,handler:eventHandler})});else{if("string"!=typeof type||"function"!=typeof handler)throw new Error("参数格式错误,支持:$on(事件名, 处理函数) 或 $on({事件名: 处理函数, ...})");this._validateParams(type,handler),this._addHandler(type,handler),bindings.push({type:type,handler:handler})}return()=>{bindings.forEach(({type:eventName,handler:eventHandler})=>{if(!this.handlers[eventName])return;const index=this.handlers[eventName].findIndex(handler=>handler===eventHandler);-1!==index&&(this.handlers[eventName].splice(index,1),0===this.handlers[eventName].length&&delete this.handlers[eventName])})}};emit=(type,...params)=>{this.handlers[type]&&[...this.handlers[type]].forEach(handler=>{handler(...params)})};off=(type,handler)=>{if(!this.handlers[type])throw new Error(`不存在事件: ${type}`);if(handler){const index=this.handlers[type].findIndex(ele=>ele===handler);this.handlers[type].splice(index,1),0===this.handlers[type].length&&delete this.handlers[type]}else delete this.handlers[type]};_validateParams(type,handler){if("string"!=typeof type)throw new Error("事件名必须为字符串");if("function"!=typeof handler)throw new Error("事件处理函数必须为函数")}_addHandler(type,handler){this.handlers[type]||(this.handlers[type]=[]),this.handlers[type].includes(handler)||this.handlers[type].push(handler)}}let ProductServer=function(){function ProductServer(sdkInstance){var _this;return function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,ProductServer),_defineProperty(_this=_callSuper(this,ProductServer),"onForeground",({gap:gap})=>{_this.getProductList({}).catch(e=>console.error("ProductServer.onForeground refresh failed:",e))}),_this.sdkInstance=sdkInstance,_this.wxApi=sdkInstance.wxApi,_this.productList=[],_this.lastMsgTime="",_this.listenerEvent(),_this.sdkInstance.on(_this.sdkInstance.EVENT.FOREGROUND_REFRESH,(...args)=>_this.onForeground(...args)),_this}return function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}(ProductServer,BaseServer),_createClass(ProductServer,[{key:"getProductList",value:async function getProductList(params){return this.wxApi.sendGet("/v3/goods/webinar/get-online-goods",{...params}).then(res=>(200==res.code&&(res.data=res.data.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.productList=res.data,this.sdkInstance.store.set("productList",res.data)),res))}},{key:"listenerEvent",value:function listenerEvent(){this.sdkInstance.on(this.sdkInstance.EVENT.CUSTOM_MSG,msg=>{["goods_update_info","push_goods_change"].includes(msg.data.type)&&(this.sdkInstance.get("logReportServer")?.report("116999",{stage:msg.data.type,logData:msg}),msg.date_time>this.lastMsgTime&&(this._getProductListByCdn(msg.data),this.sdkInstance.BRSAgent?.customLog("product:update"),this.lastMsgTime=msg.date_time))})}},{key:"_getProductListByCdn",value:async function _getProductListByCdn(params){try{const res=await this.wxApi.sendGet(params.cdn_url,{},{timeout:5e3});return this.sdkInstance.get("logReportServer")?.report("116999",{stage:"getProductListByCdn",logData:res}),this.productList=res.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.sdkInstance.store.set("productList",this.productList),res}catch(error){if(console.error("请求 cdn_url 失败:",error),!params.access_url)throw error;try{const res=await this.wxApi.sendGet(params.access_url);return this.sdkInstance.get("logReportServer")?.report("116999",{stage:"getProductListByCdn2",logData:res}),this.productList=res.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.sdkInstance.store.set("productList",this.productList),res}catch(accessError){throw console.error("请求 access_url 也失败:",accessError),accessError}}}},{key:"_getCurClientBuyTypeInfo",value:function _getCurClientBuyTypeInfo(info){if(0==info.enable_multi_config)return info;{let platform,extLink,appEmbed,miniProgram;info.sku.forEach(el=>{const item=Object(el,el.sku_conf);1==item.buy_type?platform=item:2==item.buy_type?extLink=item:3==item.buy_type?appEmbed=item:4==item.buy_type&&(miniProgram=item)});const data=platform||miniProgram||extLink||appEmbed;return Object.assign(info,data,{mini_program_config:miniProgram})}}}])}();_defineProperty(ProductServer,"name","ProductServer"),module.exports=ProductServer;
|
|
1
|
+
"use strict";function _callSuper(t,o,e){return o=_getPrototypeOf(o),function _possibleConstructorReturn(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}(t,_isNativeReflectConstruct()?Reflect.construct(o,[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _createClass(e,r,t){return r&&function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function(){return!!t})()}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _toPropertyKey(t){var i=function _toPrimitive(t,r){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}class BaseServer{constructor(){this.handlers=Object.create(null)}on=(type,handler)=>{const bindings=[];if("object"==typeof type&&null!==type)Object.entries(type).forEach(([eventName,eventHandler])=>{this._validateParams(eventName,eventHandler),this._addHandler(eventName,eventHandler),bindings.push({type:eventName,handler:eventHandler})});else{if("string"!=typeof type||"function"!=typeof handler)throw new Error("参数格式错误,支持:$on(事件名, 处理函数) 或 $on({事件名: 处理函数, ...})");this._validateParams(type,handler),this._addHandler(type,handler),bindings.push({type:type,handler:handler})}return()=>{bindings.forEach(({type:eventName,handler:eventHandler})=>{if(!this.handlers[eventName])return;const index=this.handlers[eventName].findIndex(handler=>handler===eventHandler);-1!==index&&(this.handlers[eventName].splice(index,1),0===this.handlers[eventName].length&&delete this.handlers[eventName])})}};emit=(type,...params)=>{this.handlers[type]&&[...this.handlers[type]].forEach(handler=>{handler(...params)})};off=(type,handler)=>{if(!this.handlers[type])throw new Error(`不存在事件: ${type}`);if(handler){const index=this.handlers[type].findIndex(ele=>ele===handler);this.handlers[type].splice(index,1),0===this.handlers[type].length&&delete this.handlers[type]}else delete this.handlers[type]};_validateParams(type,handler){if("string"!=typeof type)throw new Error("事件名必须为字符串");if("function"!=typeof handler)throw new Error("事件处理函数必须为函数")}_addHandler(type,handler){this.handlers[type]||(this.handlers[type]=[]),this.handlers[type].includes(handler)||this.handlers[type].push(handler)}}let ProductServer=function(){function ProductServer(sdkInstance){var _this;return function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}(this,ProductServer),_defineProperty(_this=_callSuper(this,ProductServer),"onForeground",({gap:gap})=>{_this.getProductList({}).catch(e=>console.error("ProductServer.onForeground refresh failed:",e))}),_this.sdkInstance=sdkInstance,_this.wxApi=sdkInstance.wxApi,_this.productList=[],_this.lastMsgTime="",_this.listenerEvent(),_this.sdkInstance.on(_this.sdkInstance.EVENT.FOREGROUND_REFRESH,(...args)=>_this.onForeground(...args)),_this}return function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}(ProductServer,BaseServer),_createClass(ProductServer,[{key:"getProductList",value:async function getProductList(params){return this.wxApi.sendGet("/v3/goods/webinar/get-online-goods",{...params}).then(res=>(200==res.code&&(res.data=res.data.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.productList=res.data,this.sdkInstance.store.set("productList",res.data)),res))}},{key:"reportGoodsView",value:async function reportGoodsView(params){const watchInitData=this.sdkInstance.store.get("watchInitData");if(!watchInitData)return;const reportData={business_uid:watchInitData.webinar?.userinfo?.user_id,webinar_id:watchInitData.webinar?.id,user_id:watchInitData.join_info?.user_id,third_user_id:watchInitData.join_info?.third_party_user_id,visitor_id:watchInitData.visitor_id,user_name:watchInitData.join_info?.nickname,act_timestamp:Date.now(),...params};return this.wxApi.sendPost("/v3/goods/good/view/add",reportData)}},{key:"listenerEvent",value:function listenerEvent(){this.sdkInstance.on(this.sdkInstance.EVENT.CUSTOM_MSG,msg=>{["goods_update_info","push_goods_change"].includes(msg.data.type)&&(this.sdkInstance.get("logReportServer")?.report("116999",{stage:msg.data.type,logData:msg}),msg.date_time>this.lastMsgTime&&(this._getProductListByCdn(msg.data),this.sdkInstance.BRSAgent?.customLog("product:update"),this.lastMsgTime=msg.date_time))})}},{key:"_getProductListByCdn",value:async function _getProductListByCdn(params){try{const res=await this.wxApi.sendGet(params.cdn_url,{},{timeout:5e3});return this.sdkInstance.get("logReportServer")?.report("116999",{stage:"getProductListByCdn",logData:res}),this.productList=res.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.sdkInstance.store.set("productList",this.productList),res}catch(error){if(console.error("请求 cdn_url 失败:",error),!params.access_url)throw error;try{const res=await this.wxApi.sendGet(params.access_url);return this.sdkInstance.get("logReportServer")?.report("116999",{stage:"getProductListByCdn2",logData:res}),this.productList=res.filter(el=>1==el.status).map(item=>this._getCurClientBuyTypeInfo(item)),this.sdkInstance.store.set("productList",this.productList),res}catch(accessError){throw console.error("请求 access_url 也失败:",accessError),accessError}}}},{key:"_getCurClientBuyTypeInfo",value:function _getCurClientBuyTypeInfo(info){if(0==info.enable_multi_config)return info;{let platform,extLink,appEmbed,miniProgram;info.sku.forEach(el=>{const item=Object(el,el.sku_conf);1==item.buy_type?platform=item:2==item.buy_type?extLink=item:3==item.buy_type?appEmbed=item:4==item.buy_type&&(miniProgram=item)});const data=platform||miniProgram||extLink||appEmbed;return Object.assign(info,data,{mini_program_config:miniProgram})}}}])}();_defineProperty(ProductServer,"name","ProductServer"),module.exports=ProductServer;
|
package/lib/shared/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function guid(){return"xxxxxxxx-xxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function generateShortId(e=8){const t="abcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let n=0;n<e;n++){r+=t[Math.floor(36*Math.random())]}return r}function debounce(e,t=300){let r=null;return function(){const n=
|
|
1
|
+
"use strict";function guid(){return"xxxxxxxx-xxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function generateShortId(e=8){const t="abcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let n=0;n<e;n++){r+=t[Math.floor(36*Math.random())]}return r}function debounce(e,t=300){let r=null;return function(){const n=arguments,o=!r;clearTimeout(r),r=setTimeout((()=>{r=null}),t),o&&e.apply(this,n)}}function throttle(e,t){let r=null,n=0;return function(...o){const s=Date.now(),a=s-n;a>=t?(e.apply(this,o),n=s):r||(r=setTimeout((()=>{e.apply(this,o),n=Date.now(),r=null}),t-a))}}function isString(e){return"string"==typeof e}function isObj(e){return"[object Object]"===Object.prototype.toString.call(e)}function deepCopy(e){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return e.map((e=>deepCopy(e)));if(e instanceof Set)return new Set(Array.from(e).map((e=>deepCopy(e))));if(e instanceof Map)return new Map(Array.from(e).map((([e,t])=>[e,deepCopy(t)])));if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);const t={};for(const r in e)e.hasOwnProperty(r)&&(t[r]=deepCopy(e[r]));return t}function timeToTimestamp(e){if(!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(e)||!e)return console.error('时间格式错误,请使用"YYYY-MM-DD HH:MM:SS"格式'),null;try{const t=e.replace(/-/g,"/"),r=new Date(t);return"Invalid Date"===r.toString()?(console.error("无效的日期"),null):r.getTime()}catch(e){return console.error("时间转换失败:",e),null}}function safeUrlJoin(e,t){return!e||t.startsWith("http")?t:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.appendParamsToPath=appendParamsToPath,exports.debounce=debounce,exports.deepCopy=deepCopy,exports.deepDecodeObjectValues=void 0,exports.firstLetterToLower=firstLetterToLower,exports.formatDateTime=void 0,exports.formatSeconds2Time=formatSeconds2Time,exports.genRandom=genRandom,exports.generateShortId=generateShortId,exports.guid=guid,exports.isEmpty=isEmpty,exports.isObj=isObj,exports.isString=isString,exports.parseQueryString=parseQueryString,exports.safeJsonParse=void 0,exports.safeUrlJoin=safeUrlJoin,exports.sleep=sleep,exports.throttle=throttle,exports.timeToTimestamp=timeToTimestamp,exports.truncateString=void 0;const formatDateTime=function(e,t="YYYY-MM-DD HH:MM:SS"){const r=String(e.getFullYear()),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),i=String(e.getSeconds()).padStart(2,"0");let p=t;return p=p.replace("YYYY",r).replace("MM",n).replace("DD",o).replace("HH",s).replace("MM",a).replace("SS",i),p};function parseQueryString(e){return e.split("&").reduce(((e,t)=>{const[r,n]=t.split("=");return r&&(e[decodeURIComponent(r)]=n?decodeURIComponent(n):""),e}),{})}function appendParamsToPath(e,t,r=!0){let[n,o]=e.split("?");const s={};o&&o.split("&").forEach((e=>{const[t,r]=e.split("=");t&&(s[t]=decodeURIComponent(r||""))})),Object.entries(t).forEach((([e,t])=>{s.hasOwnProperty(e)&&!r||(s[e]=t)}));const a=Object.entries(s).map((([e,t])=>`${e}=${encodeURIComponent(t)}`)).join("&");return a?`${n}?${a}`:n}function firstLetterToLower(e){return"string"!=typeof e||0===e.length?e:e.charAt(0).toLowerCase()+e.slice(1)}exports.formatDateTime=formatDateTime;const safeJsonParse=function(e){const t=Object.prototype.toString.call(e);if(["[object Array]","[object Object]","[object Null]"].includes(t))return e;try{return JSON.parse(e)}catch(e){return null}};exports.safeJsonParse=safeJsonParse;const truncateString=function(e,t=30){return e&&"string"==typeof e?e.length>t?e.substring(0,30):e:""};exports.truncateString=truncateString;const deepDecodeObjectValues=function(e){if("object"!=typeof e||null===e){if("string"==typeof e)try{return decodeURIComponent(e)}catch(t){return e}return e}if(Array.isArray(e))return e.map(deepDecodeObjectValues);const t={};for(const r in e)e.hasOwnProperty(r)&&(t[r]=deepDecodeObjectValues(e[r]));return t};function isEmpty(e){return null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length)}function formatSeconds2Time(e){if(!isNaN(e)&&e>=0){const t=Math.floor(e/3600),r=Math.floor(e%3600/60),n=e%60;if(t>0){const padTwo=e=>String(e).padStart(2,"0");return`${padTwo(t)}:${padTwo(r)}:${padTwo(n)}`}{const padTwo=e=>String(e).padStart(2,"0");return`${padTwo(r)}:${padTwo(n)}`}}return"--:--"}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}function genRandom(e,t){return Math.floor(Math.random()*(t-e+1))+e}exports.deepDecodeObjectValues=deepDecodeObjectValues;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vhall-mini-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"author": "vhall",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"miniprogram": "lib",
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
"files": [
|
|
19
19
|
"dist",
|
|
20
20
|
"lib",
|
|
21
|
-
"postinstall.js"
|
|
21
|
+
"postinstall.js",
|
|
22
|
+
"CHANGELOG.md"
|
|
22
23
|
],
|
|
23
24
|
"lint-staged": {
|
|
24
25
|
"*.{ts,js}": [
|