CCDownloader-android.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "network/CCDownloader-android.h"
  22. #include "network/CCDownloader.h"
  23. #include "platform/android/jni/JniHelper.h"
  24. #include "platform/android/jni/JniImp.h"
  25. #include <mutex>
  26. #ifndef JCLS_DOWNLOADER
  27. #define JCLS_DOWNLOADER "org/cocos2dx/lib/Cocos2dxDownloader"
  28. #endif
  29. #define JARG_STR "Ljava/lang/String;"
  30. #define JARG_DOWNLOADER "L" JCLS_DOWNLOADER ";"
  31. #ifndef ORG_DOWNLOADER_CLASS_NAME
  32. #define ORG_DOWNLOADER_CLASS_NAME org_cocos2dx_lib_Cocos2dxDownloader
  33. #endif
  34. #define JNI_DOWNLOADER(FUNC) JNI_METHOD1(ORG_DOWNLOADER_CLASS_NAME,FUNC)
  35. std::unordered_map<int, cocos2d::network::DownloaderAndroid*> sDownloaderMap;
  36. std::mutex sDownloaderMutex;
  37. static void _insertDownloaderAndroid(int id, cocos2d::network::DownloaderAndroid* downloaderPtr)
  38. {
  39. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  40. sDownloaderMap.insert(std::make_pair(id, downloaderPtr));
  41. }
  42. static void _eraseDownloaderAndroid(int id)
  43. {
  44. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  45. sDownloaderMap.erase(id);
  46. }
  47. /**
  48. * If not found, return nullptr, otherwise return the Downloader
  49. */
  50. static cocos2d::network::DownloaderAndroid* _findDownloaderAndroid(int id)
  51. {
  52. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  53. auto iter = sDownloaderMap.find(id);
  54. if (sDownloaderMap.end() == iter) {
  55. return nullptr;
  56. } else {
  57. return iter->second;
  58. }
  59. }
  60. namespace cocos2d { namespace network {
  61. static int sTaskCounter = 0;
  62. static int sDownloaderCounter = 0;
  63. struct DownloadTaskAndroid : public IDownloadTask
  64. {
  65. DownloadTaskAndroid()
  66. :id(++sTaskCounter)
  67. {
  68. DLLOG("Construct DownloadTaskAndroid: %p", this);
  69. }
  70. virtual ~DownloadTaskAndroid()
  71. {
  72. DLLOG("Destruct DownloadTaskAndroid: %p", this);
  73. }
  74. int id;
  75. std::shared_ptr<const DownloadTask> task; // reference to DownloadTask, when task finish, release
  76. };
  77. DownloaderAndroid::DownloaderAndroid(const DownloaderHints& hints)
  78. : _id(++sDownloaderCounter)
  79. , _impl(nullptr)
  80. {
  81. DLLOG("Construct DownloaderAndroid: %p", this);
  82. JniMethodInfo methodInfo;
  83. if (JniHelper::getStaticMethodInfo(methodInfo,
  84. JCLS_DOWNLOADER,
  85. "createDownloader",
  86. "(II" JARG_STR "I)" JARG_DOWNLOADER))
  87. {
  88. jobject jStr = methodInfo.env->NewStringUTF(hints.tempFileNameSuffix.c_str());
  89. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  90. methodInfo.classID,
  91. methodInfo.methodID,
  92. _id,
  93. hints.timeoutInSeconds,
  94. jStr,
  95. hints.countOfMaxProcessingTasks
  96. );
  97. _impl = methodInfo.env->NewGlobalRef(jObj);
  98. DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl);
  99. //It's not thread-safe here, use thread-safe method instead
  100. //sDownloaderMap.insert(make_pair(_id, this));
  101. _insertDownloaderAndroid(_id, this);
  102. methodInfo.env->DeleteLocalRef(jStr);
  103. methodInfo.env->DeleteLocalRef(jObj);
  104. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  105. }
  106. }
  107. DownloaderAndroid::~DownloaderAndroid()
  108. {
  109. if(_impl != nullptr)
  110. {
  111. JniMethodInfo methodInfo;
  112. if (JniHelper::getStaticMethodInfo(methodInfo,
  113. JCLS_DOWNLOADER,
  114. "cancelAllRequests",
  115. "(" JARG_DOWNLOADER ")V"))
  116. {
  117. methodInfo.env->CallStaticVoidMethod(
  118. methodInfo.classID,
  119. methodInfo.methodID,
  120. _impl
  121. );
  122. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  123. }
  124. //It's not thread-safe here, use thread-safe method instead
  125. //sDownloaderMap.erase(_id);
  126. _eraseDownloaderAndroid(_id);
  127. JniHelper::getEnv()->DeleteGlobalRef(_impl);
  128. }
  129. DLLOG("Destruct DownloaderAndroid: %p", this);
  130. }
  131. IDownloadTask *DownloaderAndroid::createCoTask(std::shared_ptr<const DownloadTask>& task)
  132. {
  133. DownloadTaskAndroid *coTask = new DownloadTaskAndroid;
  134. coTask->task = task;
  135. JniMethodInfo methodInfo;
  136. if (JniHelper::getStaticMethodInfo(methodInfo,
  137. JCLS_DOWNLOADER,
  138. "createTask",
  139. "(" JARG_DOWNLOADER "I" JARG_STR JARG_STR "[" JARG_STR")V"))
  140. {
  141. jclass jclassString = methodInfo.env->FindClass("java/lang/String");
  142. jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str());
  143. jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str());
  144. jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size()*2, jclassString, NULL);
  145. const std::map<std::string, std::string> &headMap = task->header;
  146. int index = 0;
  147. for (auto it = headMap.cbegin(); it != headMap.cend(); ++it) {
  148. methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it->first.c_str()));
  149. methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it->second.c_str()));
  150. }
  151. methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, _impl, coTask->id, jstrURL, jstrPath, jarrayHeader);
  152. for (int i = 0; i < index; ++i) {
  153. methodInfo.env->DeleteLocalRef(methodInfo.env->GetObjectArrayElement(jarrayHeader, i));
  154. }
  155. methodInfo.env->DeleteLocalRef(jclassString);
  156. methodInfo.env->DeleteLocalRef(jstrURL);
  157. methodInfo.env->DeleteLocalRef(jstrPath);
  158. methodInfo.env->DeleteLocalRef(jarrayHeader);
  159. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  160. }
  161. DLLOG("DownloaderAndroid::createCoTask id: %d", coTask->id);
  162. _taskMap.insert(std::make_pair(coTask->id, coTask));
  163. return coTask;
  164. }
  165. void DownloaderAndroid::abort(const std::unique_ptr<IDownloadTask>& task) {
  166. auto iter = _taskMap.begin();
  167. for (; iter != _taskMap.end(); iter++) {
  168. if (task.get() == iter->second) {
  169. break;
  170. }
  171. }
  172. if(_impl != nullptr && iter != _taskMap.end())
  173. {
  174. JniMethodInfo methodInfo;
  175. if (JniHelper::getStaticMethodInfo(methodInfo,
  176. JCLS_DOWNLOADER,
  177. "abort",
  178. "(" JARG_DOWNLOADER "I" ")V"))
  179. {
  180. methodInfo.env->CallStaticVoidMethod(
  181. methodInfo.classID,
  182. methodInfo.methodID,
  183. _impl,
  184. iter->first
  185. );
  186. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  187. DownloadTaskAndroid *coTask = iter->second;
  188. _taskMap.erase(iter);
  189. std::vector<unsigned char> emptyBuffer;
  190. onTaskFinish(*coTask->task,
  191. DownloadTask::ERROR_ABORT,
  192. DownloadTask::ERROR_ABORT,
  193. "downloadFile:fail abort",
  194. emptyBuffer
  195. );
  196. coTask->task.reset();
  197. }
  198. }
  199. DLLOG("DownloaderAndroid:abort");
  200. }
  201. void DownloaderAndroid::_onProcess(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal)
  202. {
  203. DLLOG("DownloaderAndroid::onProgress(taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", taskId, dl, dlNow, dlTotal);
  204. auto iter = _taskMap.find(taskId);
  205. if (_taskMap.end() == iter)
  206. {
  207. DLLOG("DownloaderAndroid::onProgress can't find task with id: %d", taskId);
  208. return;
  209. }
  210. DownloadTaskAndroid *coTask = iter->second;
  211. std::function<int64_t(void*, int64_t)> transferDataToBuffer;
  212. onTaskProgress(*coTask->task, dl, dlNow, dlTotal, transferDataToBuffer);
  213. }
  214. void DownloaderAndroid::_onFinish(int taskId, int errCode, const char *errStr, std::vector<unsigned char>& data)
  215. {
  216. DLLOG("DownloaderAndroid::_onFinish(taskId: %d, errCode: %d, errStr: %s)", taskId, errCode, (errStr)?errStr:"null");
  217. auto iter = _taskMap.find(taskId);
  218. if (_taskMap.end() == iter)
  219. {
  220. DLLOG("DownloaderAndroid::_onFinish can't find task with id: %d", taskId);
  221. return;
  222. }
  223. DownloadTaskAndroid *coTask = iter->second;
  224. std::string str = (errStr ? errStr : "");
  225. _taskMap.erase(iter);
  226. onTaskFinish(*coTask->task,
  227. errStr ? DownloadTask::ERROR_IMPL_INTERNAL : DownloadTask::ERROR_NO_ERROR,
  228. errCode,
  229. str,
  230. data
  231. );
  232. coTask->task.reset();
  233. }
  234. }
  235. } // namespace cocos2d::network
  236. extern "C" {
  237. JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnProgress)(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal)
  238. {
  239. if(getApplicationExited()) {
  240. return;
  241. }
  242. DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal);
  243. //It's not thread-safe here, use thread-safe method instead
  244. cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
  245. if (nullptr == downloader)
  246. {
  247. DLLOG("_nativeOnProgress can't find downloader by key: %p for task: %d", clazz, id);
  248. return;
  249. }
  250. downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal);
  251. }
  252. JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data)
  253. {
  254. if(getApplicationExited())
  255. {
  256. return;
  257. }
  258. DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId);
  259. //It's not thread-safe here, use thread-safe method instead
  260. cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
  261. if (nullptr == downloader)
  262. {
  263. DLLOG("_nativeOnFinish can't find downloader id: %d for task: %d", id, taskId);
  264. return;
  265. }
  266. std::vector<unsigned char> buf;
  267. if (errStr)
  268. {
  269. // failure
  270. const char *nativeErrStr = env->GetStringUTFChars(errStr, JNI_FALSE);
  271. downloader->_onFinish((int)taskId, (int)errCode, nativeErrStr, buf);
  272. env->ReleaseStringUTFChars(errStr, nativeErrStr);
  273. return;
  274. }
  275. // success
  276. if (data)
  277. {
  278. int len = env->GetArrayLength(data);
  279. if (len)
  280. {
  281. buf.resize(len);
  282. env->GetByteArrayRegion(data, 0, len, reinterpret_cast<jbyte*>(buf.data()));
  283. }
  284. }
  285. downloader->_onFinish((int)taskId, (int)errCode, nullptr, buf);
  286. }
  287. } // extern "C" {