1
0

AssetsManagerEx.h 11 KB

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