Skip to content

Commit

Permalink
Fix eslint errors in AssetManager.js, cache-manager.js (#17324)
Browse files Browse the repository at this point in the history
* Fix eslint errors in AssetManager.js, cache-manager.js

* Revert

* More `return` fixes.

* Tweak.
dumganhar authored Jul 8, 2024
1 parent 8a27e52 commit 590c3c6
Showing 10 changed files with 133 additions and 96 deletions.
76 changes: 44 additions & 32 deletions platforms/minigame/common/engine/AssetManager.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
/****************************************************************************
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of cache-manager software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in cache-manager License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

/* eslint-disable no-global-assign */
/* eslint-disable no-undef */
/* eslint-disable import/no-dynamic-require */
const cacheManager = require('./cache-manager');

const { fs, downloadFile, readText, readArrayBuffer, readJson, loadSubpackage, getUserDataPath, exists } = window.fsUtils;
@@ -51,34 +79,6 @@ function handleZip (url, options, onComplete) {
}
}

function loadInnerAudioContext (url) {
return new Promise((resolve, reject) => {
const nativeAudio = __globalAdapter.createInnerAudioContext();

const timer = setTimeout(() => {
clearEvent();
resolve(nativeAudio);
}, 8000);
function clearEvent () {
nativeAudio.offCanplay(success);
nativeAudio.offError(fail);
}
function success () {
clearEvent();
clearTimeout(timer);
resolve(nativeAudio);
}
function fail () {
clearEvent();
clearTimeout(timer);
reject(`failed to load innerAudioContext: ${err}`);
}
nativeAudio.onCanplay(success);
nativeAudio.onError(fail);
nativeAudio.src = url;
});
}

function loadAudioPlayer (url, options, onComplete) {
cc.AudioPlayer.load(url).then((player) => {
const audioMeta = {
@@ -255,31 +255,43 @@ function downloadBundle (nameOrUrl, options, onComplete) {
const originParsePVRTex = parser.parsePVRTex;
const parsePVRTex = function (file, options, onComplete) {
readArrayBuffer(file, (err, data) => {
if (err) return onComplete(err);
if (err) {
onComplete(err);
return;
}
originParsePVRTex(data, options, onComplete);
});
};

const originParsePKMTex = parser.parsePKMTex;
const parsePKMTex = function (file, options, onComplete) {
readArrayBuffer(file, (err, data) => {
if (err) return onComplete(err);
if (err) {
onComplete(err);
return;
}
originParsePKMTex(data, options, onComplete);
});
};

const originParseASTCTex = parser.parseASTCTex;
const parseASTCTex = function (file, options, onComplete) {
readArrayBuffer(file, (err, data) => {
if (err) return onComplete(err);
if (err) {
onComplete(err);
return;
}
originParseASTCTex(data, options, onComplete);
});
};

const originParsePlist = parser.parsePlist;
const parsePlist = function (url, options, onComplete) {
readText(url, (err, file) => {
if (err) return onComplete(err);
if (err) {
onComplete(err);
return;
}
originParsePlist(file, options, onComplete);
});
};
100 changes: 48 additions & 52 deletions platforms/minigame/common/engine/cache-manager.js
Original file line number Diff line number Diff line change
@@ -22,15 +22,19 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
const { getUserDataPath, readJsonSync, makeDirSync, writeFileSync, copyFile, downloadFile, deleteFile, rmdirSync, unzip, isOutOfStorage } = window.fsUtils;

var checkNextPeriod = false;
var writeCacheFileList = null;
var cleaning = false;
var suffix = 0;
const {
getUserDataPath, readJsonSync, makeDirSync,
writeFileSync, copyFile, downloadFile, deleteFile,
rmdirSync, unzip, isOutOfStorage,
} = window.fsUtils;

let checkNextPeriod = false;
let writeCacheFileList = null;
let cleaning = false;
let suffix = 0;
const REGEX = /^https?:\/\/.*/;

var cacheManager = {
const cacheManager = {

cacheDir: 'gamecaches',

@@ -69,31 +73,30 @@ var cacheManager = {
},

init () {
this.cacheDir = getUserDataPath() + '/' + this.cacheDir;
var cacheFilePath = this.cacheDir + '/' + this.cachedFileName;
var result = readJsonSync(cacheFilePath);
this.cacheDir = `${getUserDataPath()}/${this.cacheDir}`;
const cacheFilePath = `${this.cacheDir}/${this.cachedFileName}`;
const result = readJsonSync(cacheFilePath);
if (result instanceof Error || !result.version) {
if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
this.cachedFiles = new cc.AssetManager.Cache();
makeDirSync(this.cacheDir, true);
writeFileSync(cacheFilePath, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
}
else {
} else {
this.cachedFiles = new cc.AssetManager.Cache(result.files);
}
this.tempFiles = new cc.AssetManager.Cache();
},

updateLastTime (url) {
if (this.cachedFiles.has(url)) {
var cache = this.cachedFiles.get(url);
const cache = this.cachedFiles.get(url);
cache.lastTime = Date.now();
}
},

_write () {
writeCacheFileList = null;
writeFileSync(this.cacheDir + '/' + this.cachedFileName, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
writeFileSync(`${this.cacheDir}/${this.cachedFileName}`, JSON.stringify({ files: this.cachedFiles._map, version: this.version }), 'utf8');
},

writeCacheFile () {
@@ -104,25 +107,25 @@ var cacheManager = {

_cache () {
checkNextPeriod = false;
var self = this;
const self = this;
let id = '';
for (var key in this.cacheQueue) {
// eslint-disable-next-line no-unreachable-loop
for (const key in this.cacheQueue) {
id = key;
break;
}
if (!id) return;
var { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
var time = Date.now().toString();
const { srcUrl, isCopy, cacheBundleRoot } = this.cacheQueue[id];
const time = Date.now().toString();

var localPath = '';
let localPath = '';

if (cacheBundleRoot) {
localPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}${cc.path.extname(id)}`;
}
else {
} else {
localPath = `${this.cacheDir}/${time}${suffix++}${cc.path.extname(id)}`;
}

function callback (err) {
if (err) {
if (isOutOfStorage(err.message)) {
@@ -142,8 +145,7 @@ var cacheManager = {
}
if (!isCopy) {
downloadFile(srcUrl, localPath, null, callback);
}
else {
} else {
copyFile(srcUrl, localPath, callback);
}
},
@@ -166,66 +168,60 @@ var cacheManager = {
this.outOfStorage = false;
clearTimeout(writeCacheFileList);
this._write();
cc.assetManager.bundles.forEach(bundle => {
cc.assetManager.bundles.forEach((bundle) => {
if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name);
});
},

clearLRU () {
if (cleaning) return;
cleaning = true;
var caches = [];
var self = this;
this.cachedFiles.forEach(function (val, key) {
if (self._isZipFile(key) && cc.assetManager.bundles.find(bundle => bundle.base.indexOf(val.url) !== -1)) return;
const caches = [];
const self = this;
this.cachedFiles.forEach((val, key) => {
if (self._isZipFile(key) && cc.assetManager.bundles.find((bundle) => bundle.base.indexOf(val.url) !== -1)) return;
caches.push({ originUrl: key, url: val.url, lastTime: val.lastTime });
});
caches.sort(function (a, b) {
return a.lastTime - b.lastTime;
});
caches.sort((a, b) => a.lastTime - b.lastTime);
caches.length = Math.floor(caches.length / 3);
if (caches.length === 0) {
cleaning = false;
return;
}
for (var i = 0, l = caches.length; i < l; i++) {
var cacheKey = cc.assetManager.utils.getUuidFromURL(caches[i].originUrl) + "@native";
for (let i = 0, l = caches.length; i < l; i++) {
const cacheKey = `${cc.assetManager.utils.getUuidFromURL(caches[i].originUrl)}@native`;
cc.assetManager._files.remove(cacheKey);
this.cachedFiles.remove(caches[i].originUrl);
}

clearTimeout(writeCacheFileList);
this._write();
function deferredDelete () {
var item = caches.pop();
const item = caches.pop();
if (self._isZipFile(item.originUrl)) {
rmdirSync(item.url, true);
self._deleteFileCB();
}
else {
} else {
deleteFile(item.url, self._deleteFileCB.bind(self));
}
if (caches.length > 0) {
setTimeout(deferredDelete, self.deleteInterval);
}
else {
if (caches.length > 0) {
setTimeout(deferredDelete, self.deleteInterval);
} else {
cleaning = false;
}
}
setTimeout(deferredDelete, self.deleteInterval);

},

removeCache (url) {
if (this.cachedFiles.has(url)) {
var path = this.cachedFiles.remove(url).url;
const path = this.cachedFiles.remove(url).url;
clearTimeout(writeCacheFileList);
this._write();
if (this._isZipFile(url)) {
rmdirSync(path, true);
this._deleteFileCB();
}
else {
} else {
deleteFile(path, this._deleteFileCB.bind(this));
}
}
@@ -236,15 +232,15 @@ var cacheManager = {
},

makeBundleFolder (bundleName) {
makeDirSync(this.cacheDir + '/' + bundleName, true);
makeDirSync(`${this.cacheDir}/${bundleName}`, true);
},

unzipAndCacheBundle (id, zipFilePath, cacheBundleRoot, onComplete) {
let time = Date.now().toString();
let targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}`;
let self = this;
const time = Date.now().toString();
const targetPath = `${this.cacheDir}/${cacheBundleRoot}/${time}${suffix++}`;
const self = this;
makeDirSync(targetPath, true);
unzip(zipFilePath, targetPath, function (err) {
unzip(zipFilePath, targetPath, (err) => {
if (err) {
rmdirSync(targetPath, true);
if (isOutOfStorage(err.message)) {
@@ -265,4 +261,4 @@ var cacheManager = {
},
};

cc.assetManager.cacheManager = module.exports = cacheManager;
cc.assetManager.cacheManager = module.exports = cacheManager;
4 changes: 3 additions & 1 deletion platforms/minigame/platforms/alipay/wrapper/fs-utils.js
Original file line number Diff line number Diff line change
@@ -22,6 +22,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */
const fs = my.getFileSystemManager ? my.getFileSystemManager() : null;
const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right

@@ -211,6 +212,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync({ dirPath, recursive });
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
@@ -232,7 +234,7 @@ const fsUtils = {
loadSubpackage (name, onProgress, onComplete) {
const task = my.loadSubpackage({
name,
success: (res) => {
success: () => {
onComplete && onComplete();
},
fail: (res) => {
5 changes: 4 additions & 1 deletion platforms/minigame/platforms/baidu/wrapper/fs-utils.js
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */

const fs = swan.getFileSystemManager ? swan.getFileSystemManager() : null;
const outOfStorageRegExp = /file size over/;

@@ -87,7 +89,7 @@ const fsUtils = {
swan.saveFile({
tempFilePath: srcPath,
filePath: destPath,
success (res) {
success () {
onComplete && onComplete(null);
},
fail (res) {
@@ -209,6 +211,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync(dirPath, recursive);
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
8 changes: 6 additions & 2 deletions platforms/minigame/platforms/bytedance/wrapper/fs-utils.js
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */

const fs = tt.getFileSystemManager ? tt.getFileSystemManager() : null;
const outOfStorageRegExp = /size.*limit.*exceeded/;

@@ -87,7 +89,7 @@ const fsUtils = {
tt.saveFile({
tempFilePath: srcPath,
filePath: destPath,
success (res) {
success () {
onComplete && onComplete(null);
},
fail (res) {
@@ -209,6 +211,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync(dirPath, recursive);
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
@@ -230,9 +233,10 @@ const fsUtils = {
loadSubpackage (name, onProgress, onComplete) {
if (!tt.loadSubpackage) {
console.warn('tt.loadSubpackage not supported, fallback to loading bundle');
// eslint-disable-next-line import/no-dynamic-require
require(`subpackages/${name}/game.js`);
onComplete && onComplete();
return;
return null;
}
const task = tt.loadSubpackage({
name,
Original file line number Diff line number Diff line change
@@ -22,11 +22,12 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */

const fs = my.getFileSystemManager ? my.getFileSystemManager() : null;
const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right

const fsUtils = {

fs,

isOutOfStorage (errMsg) {
@@ -205,6 +206,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync({ dirPath, recursive });
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
@@ -234,7 +236,8 @@ const fsUtils = {
},

loadSubpackage (name, onProgress, onComplete) {
const task = my.loadSubPackage({
// const task =
my.loadSubPackage({
name,
success () {
onComplete && onComplete();
4 changes: 4 additions & 0 deletions platforms/minigame/platforms/taobao/wrapper/fs-utils.js
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */

const fs = my.getFileSystemManager ? my.getFileSystemManager() : null;
const outOfStorageRegExp = /the maximum size of the file storage/; // not exactly right

@@ -205,6 +207,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync({ dirPath, recursive });
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
@@ -233,6 +236,7 @@ const fsUtils = {
});
},

// eslint-disable-next-line no-unused-vars
loadSubpackage (name, onProgress, onComplete) {
throw new Error('Not Implemented');
},
6 changes: 4 additions & 2 deletions platforms/minigame/platforms/wechat/wrapper/fs-utils.js
Original file line number Diff line number Diff line change
@@ -22,11 +22,12 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* eslint-disable no-undef */

const fs = wx.getFileSystemManager ? wx.getFileSystemManager() : null;
const outOfStorageRegExp = /the maximum size of the file storage/;

const fsUtils = {

fs,

isOutOfStorage (errMsg) {
@@ -87,7 +88,7 @@ const fsUtils = {
wx.saveFile({
tempFilePath: srcPath,
filePath: destPath,
success (res) {
success () {
onComplete && onComplete(null);
},
fail (res) {
@@ -209,6 +210,7 @@ const fsUtils = {
rmdirSync (dirPath, recursive) {
try {
fs.rmdirSync(dirPath, recursive);
return null;
} catch (e) {
console.warn(`rm directory failed: path: ${dirPath} message: ${e.message}`);
return new Error(e.message);
1 change: 1 addition & 0 deletions platforms/native/engine/jsb-cache-manager.js
Original file line number Diff line number Diff line change
@@ -43,6 +43,7 @@ const cacheManager = {
return this.cachedFiles.has(url) ? `${this.cacheDir}/${this.cachedFiles.get(url).url}` : '';
},

// eslint-disable-next-line no-unused-vars
getTemp (url) {
return '';
},
18 changes: 14 additions & 4 deletions platforms/native/engine/jsb-loader.js
Original file line number Diff line number Diff line change
@@ -24,6 +24,8 @@
THE SOFTWARE.
****************************************************************************/

/* eslint-disable no-undef */

const jsbWindow = require('../jsbWindow');
const cacheManager = require('./jsb-cache-manager');
const { downloadFile, readText, readArrayBuffer, readJson, getUserDataPath, initJsbDownloader } = require('./jsb-fs-utils');
@@ -52,7 +54,10 @@ function downloadScript (url, options, onComplete) {
options = null;
}

if (loadedScripts[url]) return onComplete && onComplete();
if (loadedScripts[url]) {
onComplete && onComplete();
return;
}

download(url, (src, options, onComplete) => {
if (window.oh && window.scriptEngineType === 'napi') {
@@ -200,7 +205,8 @@ function downloadBundle (nameOrUrl, options, onComplete) {
options.__cacheBundleRoot__ = bundleName;
downloadJson(config, options, (err, response) => {
if (err) {
return onComplete(err, null);
onComplete(err, null);
return;
}
const out = response;
out && (out.base = `${url}/`);
@@ -209,7 +215,8 @@ function downloadBundle (nameOrUrl, options, onComplete) {
const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : `js`}`;
downloadScript(js, options, (err) => {
if (err) {
return onComplete(err, null);
onComplete(err, null);
return;
}
onComplete(null, out);
});
@@ -241,7 +248,10 @@ function loadFont (url, options, onComplete) {
const originParsePlist = parser.parsePlist;
const parsePlist = function (url, options, onComplete) {
readText(url, (err, file) => {
if (err) return onComplete(err);
if (err) {
onComplete(err);
return;
}
originParsePlist(file, options, onComplete);
});
};

0 comments on commit 590c3c6

Please sign in to comment.