1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef UPLOAD_TASK_ 17 #define UPLOAD_TASK_ 18 19 #include <pthread.h> 20 21 #include <cstdio> 22 #include <thread> 23 #include <vector> 24 25 #include "ability_context.h" 26 #include "context.h" 27 #include "curl/curl.h" 28 #include "curl/easy.h" 29 #include "data_ability_helper.h" 30 #include "i_upload_task.h" 31 #include "upload/curl_adp.h" 32 #include "upload/obtain_file.h" 33 #include "upload/upload_common.h" 34 #include "upload/upload_hilog_wrapper.h" 35 #include "upload_config.h" 36 37 namespace OHOS::Request::Upload { 38 enum UploadTaskState { 39 STATE_INIT, 40 STATE_RUNNING, 41 STATE_SUCCESS, 42 STATE_FAILURE, 43 }; 44 class UploadTaskNapiV5; 45 class UploadTask 46 : public IUploadTask 47 , public std::enable_shared_from_this<UploadTask> { 48 public: 49 UPLOAD_API UploadTask(std::shared_ptr<UploadConfig> &uploadConfig); 50 UPLOAD_API ~UploadTask(); 51 UPLOAD_API bool Remove(); 52 UPLOAD_API void ExecuteTask(); 53 static void Run(std::shared_ptr<Upload::UploadTask> task); 54 void OnRun(); 55 56 UPLOAD_API void SetCallback(Type type, void *callback); 57 UPLOAD_API void SetContext(std::shared_ptr<OHOS::AbilityRuntime::Context> context); 58 UPLOAD_API void SetUploadProxy(std::shared_ptr<UploadTaskNapiV5> proxy); 59 60 protected: 61 uint32_t InitFileArray(); 62 void ClearFileArray(); 63 64 private: 65 void OnFail(); 66 void OnComplete(); 67 void ReportTaskFault(uint32_t ret) const; 68 uint32_t StartUploadFile(); 69 70 std::shared_ptr<UploadConfig> uploadConfig_; 71 std::unique_ptr<std::thread> thread_; 72 std::shared_ptr<CUrlAdp> curlAdp_; 73 std::shared_ptr<UploadTaskNapiV5> uploadProxy_; 74 std::shared_ptr<OHOS::AbilityRuntime::Context> context_; 75 int64_t uploadedSize_; 76 int64_t totalSize_; 77 std::vector<std::string> headerArray_; 78 std::string header_; 79 std::vector<FileData> fileDatas_; 80 UploadTaskState state_; 81 std::mutex mutex_; 82 bool isRemoved_{ false }; 83 std::mutex removeMutex_; 84 std::thread::native_handle_type thread_handle_; 85 static constexpr int USLEEP_INTERVAL_BEFORE_RUN = 50 * 1000; 86 }; 87 } // namespace OHOS::Request::Upload 88 #endif