UpdateManager.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. cc.Class({
  2. extends: cc.BaseClass,
  3. properties: {
  4. m_Manifest : cc.Asset
  5. },
  6. ctor: function () {
  7. this.m_nNeedUpdate = 0;
  8. },
  9. // use this for initialization
  10. onLoad: function () {
  11. this.InitView();
  12. this.m_Download.active = false;
  13. this.m_Progress.node.active = false;
  14. this.m_ItemProgress.node.active = false;
  15. window.MyLogger = (function () {
  16. var loghost = `${window.PHP_HOME}/log.php?`;
  17. var log = function (err) {
  18. if (WebCenter) {
  19. var pGlobalUserData = g_GlobalUserInfo.GetGlobalUserData();
  20. var _url = [];
  21. _url.push(`GetMark=1`);
  22. if(err.name) _url.push(`name=${encodeURIComponent(err.name)}`);
  23. if(err.message) _url.push(`message=${encodeURIComponent(err.message)}`);
  24. if(err.location) _url.push(`location=${encodeURIComponent(err.location)}`);
  25. if (err.line) _url.push(`line=${encodeURIComponent(err.line)}`);
  26. if (err.func) _url.push(`func=${encodeURIComponent(err.func)}`);
  27. if (err.file) _url.push(`file=${encodeURIComponent(err.file)}`);
  28. if (g_CurScene) {
  29. if (g_CurScene == g_Launch) _url.push(`where=${encodeURIComponent('運行場景')}`);
  30. else if (g_CurScene == g_Lobby) _url.push(`where=${encodeURIComponent('大廳場景')}`);
  31. else if (g_CurScene == g_Table) _url.push(`where=${encodeURIComponent('遊戲場景')}`);
  32. }
  33. var platform = '';
  34. if (cc.sys.OS_ANDROID == cc.sys.os) platform = 'ANDROID';
  35. else if (cc.sys.OS_IOS == cc.sys.os) platform = 'IOS';
  36. else if (cc.sys.isBrowser) platform = 'WEB';
  37. if (pGlobalUserData && pGlobalUserData.dwUserID) {
  38. _url.push(`userID=${pGlobalUserData.dwUserID}`);
  39. _url.push(`gameID=${pGlobalUserData.dwGameID}`);
  40. var p = cc.sys.localStorage.getItem(window.Key_LoginPlatform);
  41. if (p == window.PLATFORM_WX) platform += '微信登入';
  42. if (p == window.PLATFORM_PHONE) platform += '手機登入';
  43. if (p == window.PLATFORM_TEST) platform += '測試登入';
  44. } else {
  45. _url.push(`userID=0`);
  46. }
  47. if (platform.length > 0) {
  48. _url.push(`platform=${encodeURIComponent(platform)}`);
  49. }
  50. var url = `${loghost}${_url.join('&')}`;
  51. WebCenter.GetData(url, 0, function (data) {}.bind(this));
  52. }
  53. }
  54. return {
  55. log: log
  56. };
  57. })();
  58. window.trapError = function (msg, URI, ln) {
  59. var e = new Error(msg);
  60. e.location = URI;
  61. e.line = ln;
  62. window.MyLogger.log(e);
  63. return false;
  64. };
  65. window.trapExceptional = function (msg, file) {
  66. var e = new Error(msg);
  67. e.file = file;
  68. window.MyLogger.log(e);
  69. return false;
  70. };
  71. // window.onerror = trapError;
  72. },
  73. start: function () {
  74. g_UpdateManager = this;
  75. },
  76. onEnable: function() {
  77. cc.director.on('UpdateItemProgress',this.OnItemProgress, this);
  78. },
  79. OnItemProgress: function(a, b) {
  80. this.m_ItemProgress.SetProgress(a / b);
  81. this.m_ItemProgress.node.active = this.m_Progress.node.active;
  82. },
  83. onDisable: function() {
  84. cc.director.off('UpdateItemProgress',this.OnItemProgress, this);
  85. },
  86. InitView: function () {
  87. if (!this.m_Download) this.m_Download = this.$('Download');
  88. if (!this.m_Progress) this.m_Progress = this.$('Slider@CustomSlider');
  89. if (!this.m_ItemProgress) this.m_ItemProgress = this.$('ItemSlider@CustomSlider');
  90. if(!this.m_LbTitle) this.m_LbTitle = this.$('Title@Label', this.m_Progress.node);
  91. if(!this.m_LbByte) this.m_LbByte = this.$('Layout/Byte@Label', this.m_Progress.node);
  92. if(!this.m_LbFile) this.m_LbFile = this.$('Layout/File@Label', this.m_Progress.node);
  93. this.m_LbTitle.string = '';
  94. this.m_LbByte.string = '';
  95. this.m_LbFile.string = '';
  96. },
  97. StartPreload: function (bLoadLobby, wKindID, Callback) {
  98. var ver = cc.sys.localStorage.getItem(window.Key_HUVersionA);
  99. cc.director.emit('LocalVersion', ver);
  100. this.m_LbTitle.string = '加載中,請稍候…';
  101. this.m_LbByte.string = '';
  102. this.m_LbFile.string = '';
  103. this.m_PreloadArray = cc.gPreLoader.StartPreload(bLoadLobby, wKindID);
  104. this.m_Progress.node.active = false;
  105. this.m_ItemProgress.node.active = false;
  106. this.m_nAllCnt = this.m_PreloadArray.length;
  107. this.m_nIndex = 0;
  108. this.m_nErrorCnt = 0;
  109. this.m_nNeedUpdate = 1;
  110. this.m_PreloadCall = Callback;
  111. if(this.m_nAllCnt > 0) {
  112. var ver = cc.sys.localStorage.getItem(`${window.Key_ABVersion}_UpdateManager_7`);
  113. if(LOG_NET_DATA) console.log(` !@~ start Preload[${this.m_nAllCnt}][${this.m_PreloadArray.join(' ')}][${ver}]!`);
  114. this.m_bFinish = false;
  115. ShowO2I(this.m_Progress.node);
  116. ShowO2I(this.m_ItemProgress.node);
  117. this.OnUpdateProgress(0);
  118. cc.director.emit('UpdateItemProgress', 0, 1);
  119. return true;
  120. } else {
  121. this.m_bFinish = true;
  122. return false;
  123. }
  124. },
  125. update: function () {
  126. if (this.m_nNeedUpdate > 0) {
  127. this.m_nNeedUpdate--;
  128. } else {
  129. return;
  130. }
  131. if(this.m_bFinish) {
  132. if(this.m_PreloadCall) this.m_PreloadCall();
  133. if(this.m_Progress.node.active) {
  134. HideI2O(this.m_Progress.node);
  135. HideI2O(this.m_ItemProgress.node);
  136. }
  137. } else {
  138. cc.gPreLoader.NextPreload(this.m_PreloadArray[this.m_nIndex], function () {
  139. this.m_nIndex++;
  140. this.OnUpdateProgress(this.m_nIndex / this.m_nAllCnt * 100);
  141. this.m_nNeedUpdate = 1;
  142. }.bind(this), function (err) {
  143. if (err) {
  144. this.ShowAlert(`部分資源因網絡問題未加載成功,可能存在資源顯示不全的問題,如想避免問題請重新加載。`, Alert_Yes, function (Res) {}.bind(this));
  145. }
  146. this.m_nErrorCnt++;
  147. // this.m_nIndex++;
  148. // this.OnUpdateProgress(this.m_nIndex / this.m_nAllCnt * 100);
  149. window.trapExceptional(`Load ${this.m_PreloadArray[this.m_nIndex]} ${err}`, `UpdateManager`);
  150. this.m_nNeedUpdate = 1;
  151. }.bind(this));
  152. }
  153. },
  154. OnShowView: function () {
  155. this.InitView();
  156. this.m_Download.active = false;
  157. this.m_Progress.node.active = false;
  158. this.m_ItemProgress.node.active = false;
  159. ShowO2I(this.node);
  160. },
  161. OnHideView: function () {
  162. HideI2O(this.node);
  163. },
  164. ShowDownload: function (bShow, Ver) {
  165. this.m_Download.active = bShow;
  166. this.m_Progress.node.active = false;
  167. this.m_ItemProgress.node.active = false;
  168. this.m_Ver = Ver;
  169. this.m_LbTitle.string = '下載中,請稍候…'
  170. },
  171. OnClicked_Download: function () {
  172. this.m_Download.active = false;
  173. ShowO2I(this.m_Progress.node);
  174. HideI2O(this.m_ItemProgress.node);
  175. this.OnUpdateProgress(0);
  176. ThirdPartyUpdateGame(window.UPDATE_URL, `${window.APK_NAME}-${this.m_Ver}.apk`, this.m_Ver);
  177. },
  178. OnClicked_Exit: function () {
  179. ThirdPartyExitGame();
  180. },
  181. OnUpdateProgress: function (progress) {
  182. this.m_Progress.SetProgress(progress / 100);
  183. if(progress >= 100) this.m_bFinish = true;
  184. return progress;
  185. },
  186. /////////////////////////////////////////////////////////////////////////////////////
  187. CheckUpdate: function (Callback) {
  188. if (this._updating) { return cc.log("檢測中…"); }
  189. this.m_HotupateCall = Callback;
  190. if (window.LOG_NET_DATA) console.log(` !@~ CheckUpdate url ${this.m_Manifest}`);
  191. this._storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'take-remote-asset');
  192. if (window.LOG_NET_DATA) console.log(` !@~ CheckUpdate Storage path for remote asset : ${this._storagePath}`);
  193. this._am = new jsb.AssetsManager(this.m_Manifest, this._storagePath, this.Compare.bind(this));
  194. this._am.setVerifyCallback(function (filePath, asset) { return true; });
  195. //初始化脚本版本信息
  196. if (cc.sys.os === cc.sys.OS_ANDROID) {
  197. //一些安卓设备不支持同时下载文件过多
  198. this._am.setMaxConcurrentTask(2);
  199. } else {
  200. this._am.setMaxConcurrentTask(2);
  201. }
  202. if (this._am.getState() === jsb.AssetsManager.State.UNINITED) {
  203. var url = this.m_Manifest.nativeUrl;
  204. if (window.LOG_NET_DATA) console.log(` !@~ CheckUpdate url1 ${url}`);
  205. if (cc.assetManager.transformPipeline) {
  206. url = cc.assetManager.transformPipeline.transformURL(url);
  207. }
  208. if (window.LOG_NET_DATA) console.log(` !@~ CheckUpdate url2 ${url}`);
  209. this._am.loadLocalManifest(url);
  210. }
  211. if (!this._am.getLocalManifest() || !this._am.getLocalManifest().isLoaded()) {
  212. this.ShowAlert('加載manifest檔案失敗', Alert_Yes, function (Res) {}.bind(this));
  213. return;
  214. }
  215. this._am.setEventCallback(this.checkCallback.bind(this));
  216. this._am.checkUpdate();
  217. this._updating = true;
  218. this.OnUpdateProgress(0);
  219. },
  220. Compare: function (versionA, versionB) {
  221. cc.sys.localStorage.setItem(window.Key_HUVersionA, versionA);
  222. cc.sys.localStorage.setItem(window.Key_HUVersionB, versionB);
  223. this.m_NewVer = versionB;
  224. if (window.LOG_NET_DATA) console.log(` !@~ JS Custom Version Compare: versionA[${versionA}] <=> versionB[${versionB}]`);
  225. var vA = versionA.split('.');
  226. var vB = versionB.split('.');
  227. for(var i in vA) vA[i] = parseInt(vA[i]);
  228. for(var i in vB) vB[i] = parseInt(vB[i]);
  229. if (vA[0] != vB[0]) {
  230. this.ShowDownload(true, versionA);
  231. return 0;
  232. }
  233. for (var i = 1; i < vA.length; ++i) {
  234. var a = vA[i];
  235. var b = (vB[i] || 0);
  236. if (a === b) {
  237. continue;
  238. } else {
  239. return a - b;
  240. }
  241. }
  242. if (vB.length > vA.length) {
  243. return -1;
  244. } else {
  245. return 0;
  246. }
  247. },
  248. checkCallback: function (event) {
  249. switch (event.getEventCode()) {
  250. case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
  251. if (window.LOG_NET_DATA) console.log(` !@~ checkCallback[${event.getEventCode()}]ERROR_NO_LOCAL_MANIFEST No local manifest file found, hot update skipped.`);
  252. break;
  253. case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
  254. case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
  255. if (window.LOG_NET_DATA) console.log(` !@~ checkCallback[${event.getEventCode()}]ERROR_DOWNLOAD_MANIFEST Fail to download manifest file, hot update skipped.`);
  256. break;
  257. case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
  258. if (window.LOG_NET_DATA) console.log(` !@~ checkCallback[${event.getEventCode()}]ALREADY_UP_TO_DATE Already up to date with the latest remote version.`);
  259. this.unschedule(this.OnTimer_DelayStartPreload);
  260. this.scheduleOnce(this.OnTimer_DelayStartPreload, 0.1);
  261. break;
  262. case jsb.EventAssetsManager.NEW_VERSION_FOUND:
  263. if (window.LOG_NET_DATA) console.log(` !@~ checkCallback[${event.getEventCode()}]NEW_VERSION_FOUND New version found, please try to update.`);
  264. this._am.setEventCallback(null);
  265. this._checkListener = null;
  266. this._updating = false;
  267. this.hotUpdate();
  268. return;
  269. default:
  270. return;
  271. }
  272. this._am.setEventCallback(null);
  273. this._checkListener = null;
  274. this._updating = false;
  275. },
  276. OnTimer_DelayStartPreload: function() {
  277. this.unschedule(this.OnTimer_DelayStartPreload);
  278. this.StartPreload(true, false, this.m_HotupateCall);
  279. },
  280. updateCallback: function (event) {
  281. var needRestart = false;
  282. var failed = false;
  283. switch (event.getEventCode()) {
  284. case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
  285. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]ERROR_NO_LOCAL_MANIFEST No local manifest file found, hot update skipped.`);
  286. failed = true;
  287. break;
  288. case jsb.EventAssetsManager.UPDATE_PROGRESSION:
  289. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]UPDATE_PROGRESSION ${event.getAssetId()}`);
  290. case jsb.EventAssetsManager.ASSET_UPDATED:
  291. var progress = event.getPercent() * 100;
  292. progress = event.getPercentByFile() * 100;
  293. if (progress > 0) progress = parseInt(progress);
  294. else progress = 0;
  295. this.m_LbTitle.string = "自動加載進度" + progress + "%...";
  296. // this.m_LbByte.string = event.getDownloadedBytes() + ' / ' + event.getTotalBytes();
  297. // this.m_LbFile.string = event.getDownloadedFiles() + ' / ' + event.getTotalFiles();
  298. this.m_ItemProgress.SetProgress(event.getPercentByFile());
  299. this.OnUpdateProgress(progress);
  300. var msg = event.getMessage();
  301. if (msg) if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]UPDATE_PROGRESSION Updated file: ${msg}`);
  302. break;
  303. case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
  304. case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
  305. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]ERROR_DOWNLOAD_MANIFEST Fail to download manifest file, hot update skipped.`);
  306. failed = true;
  307. break;
  308. case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
  309. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]ALREADY_UP_TO_DATE Already up to date with the latest remote version.`);
  310. failed = true;
  311. break;
  312. case jsb.EventAssetsManager.UPDATE_FINISHED:
  313. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]UPDATE_FINISHED Update finished. ${event.getMessage()}`);
  314. needRestart = true;
  315. break;
  316. case jsb.EventAssetsManager.UPDATE_FAILED:
  317. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]UPDATE_FAILED Update failed. ${event.getMessage()}`);
  318. this._updating = false;
  319. this._canRetry = true;
  320. break;
  321. case jsb.EventAssetsManager.ERROR_UPDATING:
  322. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]ERROR_UPDATING Asset update error: ${event.getAssetId()},${event.getMessage()}`);
  323. break;
  324. case jsb.EventAssetsManager.ERROR_DECOMPRESS:
  325. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]ERROR_DECOMPRESS ${event.getMessage()}`);
  326. break;
  327. default:
  328. if (window.LOG_NET_DATA) console.log(` !@~ updateCallback[${event.getEventCode()}]default ${event.getEventCode()}`);
  329. break;
  330. }
  331. if (failed) {
  332. this._am.setEventCallback(null);
  333. this._updating = false;
  334. this._updateListener = null;
  335. }
  336. if (needRestart) {
  337. this._am.setEventCallback(null);
  338. this._updateListener = null;
  339. var searchPaths = jsb.fileUtils.getSearchPaths();
  340. var newPaths = this._am.getLocalManifest().getSearchPaths();
  341. if (window.LOG_NET_DATA) console.log(` !@~ newPaths ${JSON.stringify(newPaths)}`);
  342. Array.prototype.unshift.apply(searchPaths, newPaths);
  343. cc.sys.localStorage.setItem('HotUpdateSearchPaths', JSON.stringify(searchPaths));
  344. if (window.LOG_NET_DATA) console.log(` !@~ HotUpdateSearchPaths ${JSON.stringify(searchPaths)}`);
  345. jsb.fileUtils.setSearchPaths(searchPaths);
  346. this.m_LbTitle.string = "自動加載檔案100%...";
  347. this.OnUpdateProgress(100);
  348. this.schedule(this.OnReStart, 1);
  349. }
  350. },
  351. OnReStart: function () {
  352. console.log(' ###### restart');
  353. cc.game.restart();
  354. },
  355. hotUpdate: function () {
  356. if (this._am && !this._updating) {
  357. if(LOG_NET_DATA) console.log(` !@~ start hotUpdate !`);
  358. this.m_LbTitle.string = '加載中,請稍候…'
  359. this._am.setEventCallback(this.updateCallback.bind(this));
  360. if (this._am.getState() === jsb.AssetsManager.State.UNINITED) {
  361. var url = this.m_Manifest.nativeUrl;
  362. if (cc.assetManager.transformPipeline) {
  363. url = cc.assetManager.transformPipeline.transformURL(url);
  364. }
  365. this._am.loadLocalManifest(url);
  366. }
  367. this._failCount = 0;
  368. this._am.update();
  369. this._updating = true;
  370. var ver = cc.sys.localStorage.getItem(window.Key_HUVersionA);
  371. cc.director.emit('LocalVersion', ver);
  372. ShowO2I(this.m_Progress.node);
  373. ShowO2I(this.m_ItemProgress.node);
  374. }
  375. },
  376. onDestroy: function () {
  377. if(this._am) {
  378. this._am.setEventCallback(null);
  379. this._am = null;
  380. }
  381. },
  382. });