AssetsManagerEx.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /****************************************************************************
  2. Copyright (c) 2013 cocos2d-x.org
  3. Copyright (c) 2014-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #ifndef __AssetsManagerEx__
  23. #define __AssetsManagerEx__
  24. #include <string>
  25. #include <unordered_map>
  26. #include <vector>
  27. #include "platform/CCFileUtils.h"
  28. #include "network/CCDownloader.h"
  29. #include "CCEventAssetsManagerEx.h"
  30. #include "Manifest.h"
  31. #include "extensions/ExtensionMacros.h"
  32. #include "extensions/ExtensionExport.h"
  33. #include "json/document-wrapper.h"
  34. NS_CC_EXT_BEGIN
  35. /**
  36. * @brief This class is used to auto update resources, such as pictures or scripts.
  37. */
  38. class CC_EX_DLL AssetsManagerEx : public Ref
  39. {
  40. public:
  41. //! Update states
  42. enum class State
  43. {
  44. UNINITED,
  45. UNCHECKED,
  46. PREDOWNLOAD_VERSION,
  47. DOWNLOADING_VERSION,
  48. VERSION_LOADED,
  49. PREDOWNLOAD_MANIFEST,
  50. DOWNLOADING_MANIFEST,
  51. MANIFEST_LOADED,
  52. NEED_UPDATE,
  53. READY_TO_UPDATE,
  54. UPDATING,
  55. UNZIPPING,
  56. UP_TO_DATE,
  57. FAIL_TO_UPDATE
  58. };
  59. const static std::string VERSION_ID;
  60. const static std::string MANIFEST_ID;
  61. typedef std::function<int(const std::string& versionA, const std::string& versionB)> VersionCompareHandle;
  62. typedef std::function<bool(const std::string& path, Manifest::Asset asset)> VerifyCallback;
  63. typedef std::function<void(EventAssetsManagerEx *event)> EventCallback;
  64. /** @brief Create function for creating a new AssetsManagerEx
  65. @param manifestUrl The url for the local manifest file
  66. @param storagePath The storage path for downloaded assets
  67. @warning The cached manifest in your storage path have higher priority and will be searched first,
  68. only if it doesn't exist, AssetsManagerEx will use the given manifestUrl.
  69. */
  70. static AssetsManagerEx* create(const std::string &manifestUrl, const std::string &storagePath);
  71. /** @brief Check out if there is a new version of manifest.
  72. * You may use this method before updating, then let user determine whether
  73. * he wants to update resources.
  74. */
  75. void checkUpdate();
  76. /** @brief Prepare the update process, this will cleanup download process flags, fill up download units with temporary manifest or remote manifest
  77. */
  78. void prepareUpdate();
  79. /** @brief Update with the current local manifest.
  80. */
  81. void update();
  82. /** @brief Reupdate all failed assets under the current AssetsManagerEx context
  83. */
  84. void downloadFailedAssets();
  85. /** @brief Gets the current update state.
  86. */
  87. State getState() const;
  88. /** @brief Gets storage path.
  89. */
  90. const std::string& getStoragePath() const;
  91. /** @brief Function for retrieving the local manifest object
  92. */
  93. const Manifest* getLocalManifest() const;
  94. /** @brief Load a custom local manifest object, the local manifest must be loaded already.
  95. * You can only manually load local manifest when the update state is UNCHECKED, it will fail once the update process is began.
  96. * This API will do the following things:
  97. * 1. Reset storage path
  98. * 2. Set local storage
  99. * 3. Search for cached manifest and compare with the local manifest
  100. * 4. Init temporary manifest and remote manifest
  101. * If successfully load the given local manifest and inited other manifests, it will return true, otherwise it will return false
  102. * @param localManifest The local manifest object to be set
  103. * @param storagePath The local storage path
  104. */
  105. bool loadLocalManifest(Manifest* localManifest, const std::string& storagePath);
  106. /** @brief Load a local manifest from url.
  107. * You can only manually load local manifest when the update state is UNCHECKED, it will fail once the update process is began.
  108. * This API will do the following things:
  109. * 1. Reset storage path
  110. * 2. Set local storage
  111. * 3. Search for cached manifest and compare with the local manifest
  112. * 4. Init temporary manifest and remote manifest
  113. * If successfully load the given local manifest and inited other manifests, it will return true, otherwise it will return false
  114. * @param manifestUrl The local manifest url
  115. */
  116. bool loadLocalManifest(const std::string& manifestUrl);
  117. /** @brief Function for retrieving the remote manifest object
  118. */
  119. const Manifest* getRemoteManifest() const;
  120. /** @brief Load a custom remote manifest object, the manifest must be loaded already.
  121. * You can only manually load remote manifest when the update state is UNCHECKED and local manifest is already inited, it will fail once the update process is began.
  122. * @param remoteManifest The remote manifest object to be set
  123. */
  124. bool loadRemoteManifest(Manifest* remoteManifest);
  125. /** @brief Gets whether the current download is resuming previous unfinished job, this will only be available after READY_TO_UPDATE state, under unknown states it will return false by default.
  126. */
  127. bool isResuming() const {return _downloadResumed;};
  128. /** @brief Gets the total byte size to be downloaded of the update, this will only be available after READY_TO_UPDATE state, under unknown states it will return 0 by default.
  129. */
  130. double getTotalBytes() const {return _totalSize;};
  131. /** @brief Gets the current downloaded byte size of the update, this will only be available after READY_TO_UPDATE state, under unknown states it will return 0 by default.
  132. */
  133. double getDownloadedBytes() const {return _totalDownloaded;};
  134. /** @brief Gets the total files count to be downloaded of the update, this will only be available after READY_TO_UPDATE state, under unknown states it will return 0 by default.
  135. */
  136. int getTotalFiles() const {return _totalToDownload;};
  137. /** @brief Gets the current downloaded files count of the update, this will only be available after READY_TO_UPDATE state, under unknown states it will return 0 by default.
  138. */
  139. int getDownloadedFiles() const {return _totalToDownload - _totalWaitToDownload;};
  140. /** @brief Function for retrieving the max concurrent task count
  141. */
  142. const int getMaxConcurrentTask() const {return _maxConcurrentTask;};
  143. /** @brief Function for setting the max concurrent task count
  144. */
  145. void setMaxConcurrentTask(const int max) {_maxConcurrentTask = max;};
  146. /** @brief Set the handle function for comparing manifests versions
  147. * @param handle The compare function
  148. */
  149. void setVersionCompareHandle(const VersionCompareHandle& handle) {_versionCompareHandle = handle;};
  150. /** @brief Set the verification function for checking whether downloaded asset is correct, e.g. using md5 verification
  151. * @param callback The verify callback function
  152. */
  153. void setVerifyCallback(const VerifyCallback& callback) {_verifyCallback = callback;};
  154. /** @brief Set the event callback for receiving update process events
  155. * @param callback The event callback function
  156. */
  157. void setEventCallback(const EventCallback& callback) {_eventCallback = callback;};
  158. CC_CONSTRUCTOR_ACCESS:
  159. AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath);
  160. AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath, const VersionCompareHandle& handle);
  161. virtual ~AssetsManagerEx();
  162. protected:
  163. void init(const std::string& manifestUrl, const std::string& storagePath);
  164. std::string basename(const std::string& path) const;
  165. std::string get(const std::string& key) const;
  166. void initManifests();
  167. void prepareLocalManifest();
  168. void setStoragePath(const std::string& storagePath);
  169. void adjustPath(std::string &path);
  170. void dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, const std::string &message = "", const std::string &assetId = "", int curle_code = 0, int curlm_code = 0);
  171. void downloadVersion();
  172. void parseVersion();
  173. void downloadManifest();
  174. void parseManifest();
  175. void startUpdate();
  176. void updateSucceed();
  177. bool decompress(const std::string &filename);
  178. void decompressDownloadedZip(const std::string &customId, const std::string &storagePath);
  179. /** @brief Update a list of assets under the current AssetsManagerEx context
  180. */
  181. void updateAssets(const DownloadUnits& assets);
  182. /** @brief Retrieve all failed assets during the last update
  183. */
  184. const DownloadUnits& getFailedAssets() const;
  185. /** @brief Function for destroying the downloaded version file and manifest file
  186. */
  187. void destroyDownloadedVersion();
  188. /** @brief Download items in queue with max concurrency setting
  189. */
  190. void queueDowload();
  191. void fileError(const std::string& identifier, const std::string& errorStr, int errorCode = 0, int errorCodeInternal = 0);
  192. void fileSuccess(const std::string &customId, const std::string &storagePath);
  193. /** @brief Call back function for error handling,
  194. the error will then be reported to user's listener registed in addUpdateEventListener
  195. @param error The error object contains ErrorCode, message, asset url, asset key
  196. @warning AssetsManagerEx internal use only
  197. * @js NA
  198. * @lua NA
  199. */
  200. virtual void onError(const network::DownloadTask& task,
  201. int errorCode,
  202. int errorCodeInternal,
  203. const std::string& errorStr);
  204. /** @brief Call back function for recording downloading percent of the current asset,
  205. the progression will then be reported to user's listener registed in addUpdateProgressEventListener
  206. @param total Total size to download for this asset
  207. @param downloaded Total size already downloaded for this asset
  208. @param url The url of this asset
  209. @param customId The key of this asset
  210. @warning AssetsManagerEx internal use only
  211. * @js NA
  212. * @lua NA
  213. */
  214. virtual void onProgress(double total, double downloaded, const std::string &url, const std::string &customId);
  215. /** @brief Call back function for success of the current asset
  216. the success event will then be send to user's listener registed in addUpdateEventListener
  217. @param srcUrl The url of this asset
  218. @param customId The key of this asset
  219. @warning AssetsManagerEx internal use only
  220. * @js NA
  221. * @lua NA
  222. */
  223. virtual void onSuccess(const std::string &srcUrl, const std::string &storagePath, const std::string &customId);
  224. private:
  225. void batchDownload();
  226. // Called when one DownloadUnits finished
  227. void onDownloadUnitsFinished();
  228. //! The event of the current AssetsManagerEx in event dispatcher
  229. std::string _eventName;
  230. //! Reference to the global event dispatcher
  231. // EventDispatcher *_eventDispatcher;
  232. //! Reference to the global file utils
  233. FileUtils *_fileUtils;
  234. //! State of update
  235. State _updateState;
  236. //! Downloader
  237. std::shared_ptr<network::Downloader> _downloader;
  238. //! The reference to the local assets
  239. const std::unordered_map<std::string, Manifest::Asset> *_assets;
  240. //! The path to store successfully downloaded version.
  241. std::string _storagePath;
  242. //! The path to store downloading version.
  243. std::string _tempStoragePath;
  244. //! The local path of cached temporary version file
  245. std::string _tempVersionPath;
  246. //! The local path of cached manifest file
  247. std::string _cacheManifestPath;
  248. //! The local path of cached temporary manifest file
  249. std::string _tempManifestPath;
  250. //! The path of local manifest file
  251. std::string _manifestUrl;
  252. //! Local manifest
  253. Manifest *_localManifest;
  254. //! Local temporary manifest for download resuming
  255. Manifest *_tempManifest;
  256. //! Remote manifest
  257. Manifest *_remoteManifest;
  258. //! Whether user have requested to update
  259. enum class UpdateEntry : char
  260. {
  261. NONE,
  262. CHECK_UPDATE,
  263. DO_UPDATE
  264. };
  265. UpdateEntry _updateEntry;
  266. //! All assets unit to download
  267. DownloadUnits _downloadUnits;
  268. //! All failed units
  269. DownloadUnits _failedUnits;
  270. //! Download queue
  271. std::vector<std::string> _queue;
  272. bool _downloadResumed;
  273. //! Max concurrent task count for downloading
  274. int _maxConcurrentTask;
  275. //! Current concurrent task count
  276. int _currConcurrentTask;
  277. //! Download percent
  278. float _percent;
  279. //! Download percent by file
  280. float _percentByFile;
  281. //! Indicate whether the total size should be enabled
  282. int _totalEnabled;
  283. //! Indicate the number of file whose total size have been collected
  284. int _sizeCollected;
  285. //! Total file size need to be downloaded (sum of all files)
  286. double _totalSize;
  287. //! Total downloaded file size (sum of all downloaded files)
  288. double _totalDownloaded;
  289. //! Downloaded size for each file
  290. std::unordered_map<std::string, double> _downloadedSize;
  291. //! Total number of assets to download
  292. int _totalToDownload;
  293. //! Total number of assets still waiting to be downloaded
  294. int _totalWaitToDownload;
  295. //! Next target percent for saving the manifest file
  296. float _nextSavePoint;
  297. //! Handle function to compare versions between different manifests
  298. VersionCompareHandle _versionCompareHandle;
  299. //! Callback function to verify the downloaded assets
  300. VerifyCallback _verifyCallback;
  301. //! Callback function to dispatch events
  302. EventCallback _eventCallback;
  303. //! Marker for whether the assets manager is inited
  304. bool _inited;
  305. };
  306. NS_CC_EXT_END
  307. #endif /* defined(__AssetsManagerEx__) */