123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- var UpdatePanel = require('UpdatePanel');
- var Global = require("Global");
- const JSB_MD5 = require("jsb_md5");
- // var customManifestStr = JSON.stringify();
- cc.Class({
- extends: cc.Component,
- editor: {
- executionOrder: -1
- },
- properties: {
- panel: UpdatePanel,
- manifestUrl: {
- default: null,
- type: cc.Asset
- },
- updateUI: cc.Node,
- _updating: false,
- _canRetry: false,
- _storagePath: ''
- },
- checkCb: function (event) {
- // Global.print('checkCb Code: ' + event.getEventCode());
- switch (event.getEventCode())
- {
- case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
- Global.print("No local manifest file found, hot update skipped.");
- break;
- case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
- case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
- Global.print("Fail to download manifest file, hot update skipped.");
- break;
- case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
- Global.print("Already up to date with the latest remote version.");
- // this.node.getComponent("Login").showVersionInfo();
- this.node.getComponent("Login").ready2Login();
- cc.userOperate.sendRecord("no Update");
- break;
- case jsb.EventAssetsManager.NEW_VERSION_FOUND:
- Global.print('New version found, please try to update. (' + this._am.getTotalBytes() + ')');
- // this.panel.checkBtn.active = false;
- this.panel.fileProgress.progress = 0;
- this.panel.byteProgress.progress = 0;
- // Global.print(this._am.getTotalBytes());
- //启动更新
- this._updating = false;
- this._updateStartTime = Date.now();
- cc.userOperate.sendRecord("start Hotupdate");
- this.node.getComponent("Login").hideRightPanel();
- this.node.getComponent("Login").hideWaitting();
- this.show();
- this.hotUpdate();
- return;
- default:
- return;
- }
- // Global.print("1this._am.setEventCallback(null);");
- this._am.setEventCallback(null);
- this._checkListener = null;
- this._updating = false;
- },
- updateCb: function (event) {
- // Global.print('updateCb Code: ' + event.getEventCode());
- var needRestart = false;
- var failed = false;
- switch (event.getEventCode())
- {
- case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
- this.panel.info.string = 'No local manifest file found, hot update skipped.';
- failed = true;
- break;
- case jsb.EventAssetsManager.UPDATE_PROGRESSION:
- if (!isNaN(event.getPercent()))
- {
- this.panel.byteProgress.progress = event.getPercent();
- // this.panel.fileProgress.progress = event.getPercentByFile();
-
- // this.panel.fileLabel.string = event.getDownloadedFiles() + ' / ' + event.getTotalFiles();
- // this.panel.byteLabel.string = event.getDownloadedBytes() + ' / ' + event.getTotalBytes();
-
- var msg = event.getMessage();
- if (msg) {
- // this.panel.info.string = 'Updated file: ' + msg;
- Global.print("getEventCode Updated file: "+msg);
- }
- }
- break;
- case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
- case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
- Global.print('Fail to download manifest file, hot update skipped.');
- failed = true;
- break;
- case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
- Global.print('Already up to date with the latest remote version.');
- failed = true;
- // this.node.getComponent("Login").showVersionInfo();
- this.node.getComponent("Login").ready2Login();
- break;
- case jsb.EventAssetsManager.UPDATE_FINISHED:
- Global.print('Update finished. ' + event.getMessage());
- needRestart = true;
- let updateTime = (Date.now() - this._updateStartTime) / 1000;
- cc.userOperate.sendRecord("hall-Average hot update duration", updateTime);
- this._updateStartTime = undefined;
- break;
- case jsb.EventAssetsManager.UPDATE_FAILED:
- Global.print('Update failed. ' + event.getMessage());
- // this.panel.retryBtn.active = true;
- this._updating = false;
- this._canRetry = true;
- this.retry();
- break;
- case jsb.EventAssetsManager.ERROR_UPDATING:
- Global.print('Asset update error: ' + event.getAssetId() + ', ' + event.getMessage());
- break;
- case jsb.EventAssetsManager.ERROR_DECOMPRESS:
- Global.print(event.getMessage());
- break;
- default:
- break;
- }
- if (failed) {
- // Global.print("this._am.setEventCallback(null)")
- this._am.setEventCallback(null);
- this._updateListener = null;
- this._updating = false;
- }
- if (needRestart) {
- this._am.setEventCallback(null);
- this._updateListener = null;
- // Prepend the manifest's search path
- var searchPaths = jsb.fileUtils.getSearchPaths();
- var newPaths = this._am.getLocalManifest().getSearchPaths();
- // Global.print(JSON.stringify(newPaths));
- Array.prototype.unshift.apply(searchPaths, newPaths);
- // This value will be retrieved and appended to the default search path during game startup,
- // please refer to samples/js-tests/main.js for detailed usage.
- // !!! Re-add the search paths in main.js is very important, otherwise, new scripts won't take effect.
- cc.sys.localStorage.setItem('HotUpdateSearchPaths', JSON.stringify(searchPaths));
- jsb.fileUtils.setSearchPaths(searchPaths);
- cc.userOperate.sendRecord("hotUpdate Success");
- //防止在重新加载过程中刷新IP(会出现闪崩)
- cc.ddos_refresh = false;
- cc.audioEngine.stopAll();
- //延迟0.5秒重启
- setTimeout(()=>{
- cc.game.restart();
- }, 500)
- // cc.game.restart();
- }
- },
- retry: function () {
- if (!this._updating && this._canRetry) {
- // this.panel.retryBtn.active = false;
- this._canRetry = false;
-
- // this.panel.info.string = 'Retry failed Assets...';
- this._am.downloadFailedAssets();
- }
- },
- removeAssets: function() {
- Global.print("清理热更新资源");
- jsb.fileUtils.removeDirectory(this._storagePath);
- },
- setManifestInfo(manifestInfo) {
- if(manifestInfo) {
- this.manifestUrl = manifestInfo;
- }
- },
-
- checkUpdate: function () {
- if (this._updating) {
- return;
- }
-
- if (this._am.getState() === jsb.AssetsManager.State.UNINITED) {
- // Resolve md5 url
- var url = this.manifestUrl.nativeUrl;
- if (cc.loader.md5Pipe) {
- url = cc.loader.md5Pipe.transformURL(url);
- }
- this._am.loadLocalManifest(url);
- }
- Global.print(this._am);
- if (!this._am.getLocalManifest() || !this._am.getLocalManifest().isLoaded()) {
- Global.print("Failed to load local manifest ...123");
- return;
- }
- this._am.setEventCallback(this.checkCb.bind(this));
- this._am.checkUpdate();
- this._updating = true;
- },
- hotUpdate: function () {
- if (this._am && !this._updating) {
- this._am.setEventCallback(this.updateCb.bind(this));
- if (this._am.getState() === jsb.AssetsManager.State.UNINITED) {
- // Resolve md5 url
- var url = this.manifestUrl.nativeUrl;
- if (cc.loader.md5Pipe) {
- url = cc.loader.md5Pipe.transformURL(url);
- }
- this._am.loadLocalManifest(url);
- }
- this._failCount = 0;
- this._am.update();
- // this.panel.updateBtn.active = false;
- this._updating = true;
- }
- },
-
- show: function () {
- if (this.updateUI.active === false) {
- this.updateUI.active = true;
- }
- },
- // use this for initialization
- onLoad: function () {
- Global.print("执行HotUpdate onLoad");
- // Hot update is only available in Native build
- if (!cc.sys.isNative) {
- return;
- }
- this._storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'blackjack-remote-asset');
- Global.print('Storage path for remote asset : ' + this._storagePath);
- //版本比较函数
- // 返回<0表示需要更新
- this.versionCompareHandle = function (localVersion, tarVersion) {
- Global.print("JS Custom Version Compare: localVersion is " + localVersion + ', tarVersion is ' + tarVersion);
-
- var a = parseInt(localVersion);
- var b = parseInt(tarVersion);
- return a - b;
- };
- var self = this;
- // Init with empty manifest url for testing custom manifest
- this._am = new jsb.AssetsManager('', this._storagePath, this.versionCompareHandle);
- // Global.print("+++++++++++++++++");
- // Global.print(JSON.stringify(this._am));
- var panel = this.panel;
- // Setup the verification callback, but we don't have md5 check function yet, so only print some message
- // Return true if the verification passed, otherwise return false
- this._am.setVerifyCallback(function (path, asset) {
- //TODO 下载后的文件再做一次md5校验,此处未实现
- //下载过程中仍然有小概率可能由于网络原因或其他网络库的问题导致下载的文件内容有问题
- // var md5 = calculateMD5(path);
- // if (md5 === asset.md5)
- // return true;
- // else
- // return false;
- cc.log("setVerifyCallback " + JSON.stringify(asset));
- // When asset is compressed, we don't need to check its md5, because zip file have been deleted.
- var compressed = asset.compressed;
- // Retrieve the correct md5 value.
- var expectedMD5 = asset.md5;
- // asset.path is relative path and path is absolute.
- var relativePath = asset.path;
- // The size of asset file, but this value could be absent.
- var size = asset.size;
- if (compressed) {
- // panel.info.string = "Verification passed : " + relativePath;
- return true;
- }
- else {
- // panel.info.string = "Verification passed : " + relativePath + ' (' + expectedMD5 + ')';
- // return true;
- /*var filePath = self._storagePath + "_temp/"+ asset.path;
- if(!jsb.fileUtils.isFileExist(filePath)){
- cc.log("file doesn't exist " + asset.path);
- return false;
- }*/
-
- var resMD5 = JSB_MD5(jsb.fileUtils.getDataFromFile(path));
- return asset.md5 == resMD5;
- }
- });
- // this.panel.info.string = 'Hot update is ready, please check or directly update.';
- if (cc.sys.os === cc.sys.OS_ANDROID && cc.sys.isNative) {
- // Some Android device may slow down the download process when concurrent tasks is too much.
- // The value may not be accurate, please do more test and find what's most suitable for your game.
- this._am.setMaxConcurrentTask(2);
- // this.panel.info.string = "Max concurrent tasks count have been limited to 2";
- }
-
- this.panel.fileProgress.progress = 0;
- this.panel.byteProgress.progress = 0;
- },
- onDestroy: function () {
- }
- });
|