• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 : public IUploadTask, public std::enable_shared_from_this<UploadTask> {
46 public:
47     UPLOAD_API UploadTask(std::shared_ptr<UploadConfig> &uploadConfig);
48     UPLOAD_API ~UploadTask();
49     UPLOAD_API bool Remove();
50     UPLOAD_API void ExecuteTask();
51     static void Run(std::shared_ptr<Upload::UploadTask> task);
52     void OnRun();
53 
54     UPLOAD_API void SetCallback(Type type, void *callback);
55     UPLOAD_API void SetContext(std::shared_ptr<OHOS::AbilityRuntime::Context> context);
56     UPLOAD_API void SetUploadProxy(std::shared_ptr<UploadTaskNapiV5> proxy);
57 
58 protected:
59     uint32_t InitFileArray();
60     void ClearFileArray();
61 
62 private:
63     void OnFail();
64     void OnComplete();
65     void ReportTaskFault(uint32_t ret) const;
66     uint32_t StartUploadFile();
67 
68     std::shared_ptr<UploadConfig> uploadConfig_;
69     std::unique_ptr<std::thread> thread_;
70     std::shared_ptr<CUrlAdp> curlAdp_;
71     std::shared_ptr<UploadTaskNapiV5> uploadProxy_;
72     std::shared_ptr<OHOS::AbilityRuntime::Context> context_;
73     int64_t uploadedSize_;
74     int64_t totalSize_;
75     std::vector<std::string> headerArray_;
76     std::string header_;
77     std::vector<FileData> fileDatas_;
78     UploadTaskState state_;
79     std::mutex mutex_;
80     bool isRemoved_{ false };
81     std::mutex removeMutex_;
82     std::thread::native_handle_type thread_handle_;
83     static constexpr int USLEEP_INTERVAL_BEFORE_RUN = 50 * 1000;
84 };
85 } // namespace OHOS::Request::Upload
86 #endif