1 /*
2  * Copyright (c) 2023 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 #include "ipc/cloud_sync_service.h"
16 
17 #include <cstdint>
18 #include <memory>
19 
20 #include "battery_status.h"
21 #include "cloud_file_kit.h"
22 #include "cloud_status.h"
23 #include "cycle_task/cycle_task_runner.h"
24 #include "data_sync_const.h"
25 #include "data_syncer_rdb_store.h"
26 #include "dfs_error.h"
27 #include "dfsu_access_token_helper.h"
28 #include "directory_ex.h"
29 #include "ffrt_inner.h"
30 #include "ipc/download_asset_callback_manager.h"
31 #include "meta_file.h"
32 #include "net_conn_callback_observer.h"
33 #include "parameters.h"
34 #include "periodic_check_task.h"
35 #include "plugin_loader.h"
36 #include "network_status.h"
37 #include "sandbox_helper.h"
38 #include "screen_status.h"
39 #include "session_manager.h"
40 #include "system_ability_definition.h"
41 #include "system_load.h"
42 #include "task_state_manager.h"
43 #include "utils_log.h"
44 
45 namespace OHOS::FileManagement::CloudSync {
46 using namespace std;
47 using namespace OHOS;
48 using namespace CloudFile;
49 constexpr int32_t MIN_USER_ID = 100;
50 constexpr int LOAD_SA_TIMEOUT_MS = 4000;
51 constexpr int FFRT_WORKER_EFFECT_LEN = 2;
52 constexpr int MAX_THREAD_NUM = 2;
53 
54 REGISTER_SYSTEM_ABILITY_BY_ID(CloudSyncService, FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, false);
55 
SetFfrtWorkerNum()56 void SetFfrtWorkerNum()
57 {
58     LOGI("begin set ffrt worker num");
59     ffrt_worker_num_param qosConfig;
60     if (memset_s(&qosConfig, sizeof(qosConfig), -1, sizeof(qosConfig)) == EOK) {
61         qosConfig.effectLen = FFRT_WORKER_EFFECT_LEN;
62         qosConfig.qosConfigArray[0].qos = ffrt_qos_deadline_request;
63         qosConfig.qosConfigArray[0].hardLimit = MAX_THREAD_NUM;
64         qosConfig.qosConfigArray[1].qos = ffrt_qos_user_initiated;
65         qosConfig.qosConfigArray[1].hardLimit = MAX_THREAD_NUM;
66         if (ffrt_set_qos_worker_num(&qosConfig) == E_OK) {
67             LOGI("set ffrt qos param success !");
68         }
69     }
70 }
71 
CloudSyncService(int32_t saID, bool runOnCreate)72 CloudSyncService::CloudSyncService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate)
73 {
74     SetFfrtWorkerNum();
75 }
76 
PublishSA()77 void CloudSyncService::PublishSA()
78 {
79     LOGI("Begin to init");
80     if (!SystemAbility::Publish(this)) {
81         throw runtime_error("Failed to publish the daemon");
82     }
83     LOGI("Init finished successfully");
84 }
85 
PreInit()86 void CloudSyncService::PreInit()
87 {
88     /* load cloud file ext plugin */
89     CloudFile::PluginLoader::GetInstance().LoadCloudKitPlugin(true);
90     auto instance = CloudFile::CloudFileKit::GetInstance();
91     if (instance == nullptr) {
92         LOGE("get cloud file helper instance failed");
93         dataSyncManager_ = make_shared<DataSyncManager>();
94     } else {
95         dataSyncManager_ = instance->GetDataSyncManager();
96     }
97 
98     batteryStatusListener_ = make_shared<BatteryStatusListener>(dataSyncManager_);
99     screenStatusListener_ = make_shared<ScreenStatusListener>(dataSyncManager_);
100     userStatusListener_ = make_shared<UserStatusListener>(dataSyncManager_);
101 }
102 
Init()103 void CloudSyncService::Init()
104 {
105     NetworkStatus::InitNetwork(dataSyncManager_);
106     /* Get Init Charging status */
107     BatteryStatus::GetInitChargingStatus();
108     ScreenStatus::InitScreenStatus();
109 }
110 
111 constexpr int TEST_MAIN_USR_ID = 100;
GetBundleNameUserInfo(BundleNameUserInfo &bundleNameUserInfo)112 int32_t CloudSyncService::GetBundleNameUserInfo(BundleNameUserInfo &bundleNameUserInfo)
113 {
114     string bundleName;
115     if (DfsuAccessTokenHelper::GetCallerBundleName(bundleName)) {
116         return E_INVAL_ARG;
117     }
118     bundleNameUserInfo.bundleName = bundleName;
119 
120     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
121     if (callerUserId == 0) {
122         callerUserId = TEST_MAIN_USR_ID; // for root user change id to main user for test
123     }
124     bundleNameUserInfo.userId = callerUserId;
125 
126     auto callerPid = DfsuAccessTokenHelper::GetPid();
127     bundleNameUserInfo.pid = callerPid;
128 
129     return E_OK;
130 }
131 
GetBundleNameUserInfo(const std::vector<std::string> &uriVec, BundleNameUserInfo &bundleNameUserInfo)132 void CloudSyncService::GetBundleNameUserInfo(const std::vector<std::string> &uriVec,
133                                              BundleNameUserInfo &bundleNameUserInfo)
134 {
135     Uri uri(uriVec[0]);
136     string bundleName = uri.GetAuthority();
137     bundleNameUserInfo.bundleName = bundleName;
138 
139     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
140     if (callerUserId == 0) {
141         callerUserId = TEST_MAIN_USR_ID; // for root user change id to main user for test
142     }
143     bundleNameUserInfo.userId = callerUserId;
144 
145     auto callerPid = DfsuAccessTokenHelper::GetPid();
146     bundleNameUserInfo.pid = callerPid;
147 }
148 
GetHmdfsPath(const std::string &uri, int32_t userId)149 std::string CloudSyncService::GetHmdfsPath(const std::string &uri, int32_t userId)
150 {
151     const std::string HMDFS_DIR = "/mnt/hmdfs/";
152     const std::string DATA_DIR = "/account/device_view/local/data/";
153     const std::string FILE_DIR = "data/storage/el2/distributedfiles/";
154     const std::string URI_PREFIX = "://";
155     if (uri.empty() || uri.find("..") != std::string::npos) {
156         return "";
157     }
158 
159     std::string bundleName;
160     size_t uriPrefixPos = uri.find(URI_PREFIX);
161     if (uriPrefixPos == std::string::npos) {
162         return "";
163     }
164     uriPrefixPos += URI_PREFIX.length();
165     size_t bundleNameEndPos = uri.find('/', uriPrefixPos);
166     if (bundleNameEndPos == std::string::npos) {
167         return "";
168     }
169     bundleName = uri.substr(uriPrefixPos, bundleNameEndPos - uriPrefixPos);
170 
171     std::string relativePath;
172     size_t fileDirPos = uri.find(FILE_DIR);
173     if (fileDirPos == std::string::npos) {
174         return "";
175     }
176     fileDirPos += FILE_DIR.length();
177     relativePath = uri.substr(fileDirPos);
178 
179     std::string outputPath = HMDFS_DIR + std::to_string(userId) + DATA_DIR + bundleName + "/" + relativePath;
180     std::string dir = outputPath.substr(0, outputPath.find_last_of('/'));
181 
182     ForceCreateDirectory(dir);
183     return outputPath;
184 }
185 
OnStart(const SystemAbilityOnDemandReason& startReason)186 void CloudSyncService::OnStart(const SystemAbilityOnDemandReason& startReason)
187 {
188     PreInit();
189     try {
190         PublishSA();
191         AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
192         AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID);
193         AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID);
194     } catch (const exception &e) {
195         LOGE("%{public}s", e.what());
196     }
197     LOGI("Start service successfully");
198     Init();
199     LOGI("init service successfully");
200     system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_START);
201     TaskStateManager::GetInstance().StartTask();
202     // 跟随进程生命周期
203     ffrt::submit([startReason, this]() {
204         this->HandleStartReason(startReason);
205     });
206 }
207 
OnActive(const SystemAbilityOnDemandReason& startReason)208 void CloudSyncService::OnActive(const SystemAbilityOnDemandReason& startReason)
209 {
210     LOGI("active service successfully");
211     system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_START);
212     TaskStateManager::GetInstance().StartTask();
213     ffrt::submit([startReason, this]() {
214         this->HandleStartReason(startReason);
215     });
216 }
217 
OnStop()218 void CloudSyncService::OnStop()
219 {
220     LOGI("Stop finished successfully");
221 }
222 
HandleStartReason(const SystemAbilityOnDemandReason& startReason)223 void CloudSyncService::HandleStartReason(const SystemAbilityOnDemandReason& startReason)
224 {
225     string reason = startReason.GetName();
226     int32_t userId = 0;
227 
228     LOGI("Begin to start service reason: %{public}s", reason.c_str());
229 
230     if (reason == "usual.event.USER_UNLOCKED") {
231         return;
232     }
233 
234     if (dataSyncManager_->GetUserId(userId) != E_OK) {
235         return;
236     }
237 
238     if (reason == "usual.event.wifi.CONN_STATE") {
239         dataSyncManager_->TriggerRecoverySync(SyncTriggerType::NETWORK_AVAIL_TRIGGER);
240         dataSyncManager_->DownloadThumb();
241         dataSyncManager_->CacheVideo();
242     } else if (reason == "usual.event.BATTERY_OKAY") {
243         dataSyncManager_->TriggerRecoverySync(SyncTriggerType::BATTERY_OK_TRIGGER);
244     } else if (reason == "usual.event.SCREEN_OFF" || reason == "usual.event.POWER_CONNECTED") {
245         dataSyncManager_->DownloadThumb();
246         dataSyncManager_->CacheVideo();
247     }
248 
249     if (reason != "load") {
250         shared_ptr<CycleTaskRunner> taskRunner = make_shared<CycleTaskRunner>(dataSyncManager_);
251         taskRunner->StartTask();
252     }
253 }
254 
OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)255 void CloudSyncService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
256 {
257     LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
258     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
259         userStatusListener_->Start();
260         batteryStatusListener_->Start();
261         screenStatusListener_->Start();
262     } else if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
263         auto sessionManager = make_shared<SessionManager>();
264         sessionManager->Init();
265         userStatusListener_->AddObserver(sessionManager);
266         fileTransferManager_ = make_shared<FileTransferManager>(sessionManager);
267         fileTransferManager_->Init();
268     } else if (systemAbilityId == RES_SCHED_SYS_ABILITY_ID) {
269         SystemLoadStatus::InitSystemload(dataSyncManager_);
270     } else {
271         LOGE("unexpected");
272     }
273 }
274 
OnLoadSACompleteForRemote(const std::string &deviceId, int32_t systemAbilityId, const sptr<IRemoteObject> &remoteObject)275 void CloudSyncService::LoadRemoteSACallback::OnLoadSACompleteForRemote(const std::string &deviceId,
276                                                                        int32_t systemAbilityId,
277                                                                        const sptr<IRemoteObject> &remoteObject)
278 {
279     LOGI("Load CloudSync SA success,systemAbilityId:%{public}d, remoteObj result:%{public}s", systemAbilityId,
280          (remoteObject == nullptr ? "false" : "true"));
281     unique_lock<mutex> lock(loadRemoteSAMutex_);
282     if (remoteObject == nullptr) {
283         isLoadSuccess_.store(false);
284     } else {
285         isLoadSuccess_.store(true);
286         remoteObjectMap_[deviceId] = remoteObject;
287     }
288     proxyConVar_.notify_one();
289 }
290 
SetDeathRecipient(const sptr<IRemoteObject> &remoteObject)291 void CloudSyncService::SetDeathRecipient(const sptr<IRemoteObject> &remoteObject)
292 {
293     LOGD("set death recipient");
294     auto deathCallback = [this](const wptr<IRemoteObject> &obj) {
295         unique_lock<mutex> lock(loadRemoteSAMutex_);
296         for (auto it = remoteObjectMap_.begin(); it != remoteObjectMap_.end();) {
297             if (it->second.GetRefPtr() == obj.GetRefPtr()) {
298                 it = remoteObjectMap_.erase(it);
299                 LOGD("remote sa died");
300             } else {
301                 ++it;
302             }
303         }
304     };
305     deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback));
306     remoteObject->AddDeathRecipient(deathRecipient_);
307 }
308 
LoadRemoteSA(const std::string &deviceId)309 int32_t CloudSyncService::LoadRemoteSA(const std::string &deviceId)
310 {
311     unique_lock<mutex> lock(loadRemoteSAMutex_);
312     auto iter = remoteObjectMap_.find(deviceId);
313     if (iter != remoteObjectMap_.end()) {
314         return E_OK;
315     }
316     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
317     if (samgr == nullptr) {
318         LOGE("Samgr is nullptr");
319         return E_SA_LOAD_FAILED;
320     }
321     sptr<LoadRemoteSACallback> cloudSyncLoadCallback = new LoadRemoteSACallback();
322     if (cloudSyncLoadCallback == nullptr) {
323         LOGE("cloudSyncLoadCallback is nullptr");
324         return E_SA_LOAD_FAILED;
325     }
326     int32_t ret = samgr->LoadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, deviceId, cloudSyncLoadCallback);
327     if (ret != E_OK) {
328         LOGE("Failed to Load systemAbility, systemAbilityId:%{pulbic}d, ret code:%{pulbic}d",
329              FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, ret);
330         return E_SA_LOAD_FAILED;
331     }
332 
333     auto waitStatus = cloudSyncLoadCallback->proxyConVar_.wait_for(
334         lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS),
335         [cloudSyncLoadCallback]() { return cloudSyncLoadCallback->isLoadSuccess_.load(); });
336     if (!waitStatus) {
337         LOGE("Load CloudSynd SA timeout");
338         return E_SA_LOAD_FAILED;
339     }
340     SetDeathRecipient(remoteObjectMap_[deviceId]);
341     return E_OK;
342 }
343 
GetTargetBundleName(string &targetBundleName, string &callerBundleName)344 static int32_t GetTargetBundleName(string &targetBundleName, string &callerBundleName)
345 {
346     if (DfsuAccessTokenHelper::GetCallerBundleName(callerBundleName)) {
347         return E_INVAL_ARG;
348     }
349     if (targetBundleName == "") {
350         targetBundleName = callerBundleName;
351     }
352     if (targetBundleName != callerBundleName &&
353         !DfsuAccessTokenHelper::CheckCallerPermission(PERM_CLOUD_SYNC_MANAGER)) {
354         LOGE("permission denied: cloudfile_sync_manager");
355         return E_PERMISSION_DENIED;
356     }
357     return E_OK;
358 }
359 
UnRegisterCallbackInner(const string &bundleName)360 int32_t CloudSyncService::UnRegisterCallbackInner(const string &bundleName)
361 {
362     string targetBundleName = bundleName;
363     string callerBundleName = "";
364     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
365     if (ret != E_OK) {
366         LOGE("get bundle name failed: %{public}d", ret);
367         return ret;
368     }
369     dataSyncManager_->UnRegisterCloudSyncCallback(targetBundleName, callerBundleName);
370     return E_OK;
371 }
372 
RegisterCallbackInner(const sptr<IRemoteObject> &remoteObject, const string &bundleName)373 int32_t CloudSyncService::RegisterCallbackInner(const sptr<IRemoteObject> &remoteObject, const string &bundleName)
374 {
375     if (remoteObject == nullptr) {
376         LOGE("remoteObject is nullptr");
377         return E_INVAL_ARG;
378     }
379 
380     string targetBundleName = bundleName;
381     string callerBundleName = "";
382     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
383     if (ret != E_OK) {
384         LOGE("get bundle name failed: %{public}d", ret);
385         return ret;
386     }
387 
388     auto callback = iface_cast<ICloudSyncCallback>(remoteObject);
389     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
390     dataSyncManager_->RegisterCloudSyncCallback(targetBundleName, callerBundleName, callerUserId, callback);
391     return E_OK;
392 }
393 
StartSyncInner(bool forceFlag, const string &bundleName)394 int32_t CloudSyncService::StartSyncInner(bool forceFlag, const string &bundleName)
395 {
396     string targetBundleName = bundleName;
397     string callerBundleName = "";
398     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
399     if (ret != E_OK) {
400         LOGE("get bundle name failed: %{public}d", ret);
401         return ret;
402     }
403     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
404     return dataSyncManager_->TriggerStartSync(targetBundleName, callerUserId, forceFlag,
405         SyncTriggerType::APP_TRIGGER);
406 }
407 
TriggerSyncInner(const std::string &bundleName, const int32_t &userId)408 int32_t CloudSyncService::TriggerSyncInner(const std::string &bundleName, const int32_t &userId)
409 {
410     if (bundleName.empty() || userId < MIN_USER_ID) {
411         LOGE("Trigger sync parameter is invalid");
412         return E_INVAL_ARG;
413     }
414     return dataSyncManager_->TriggerStartSync(bundleName, userId, false,
415         SyncTriggerType::APP_TRIGGER);
416 }
417 
StopSyncInner(const string &bundleName, bool forceFlag)418 int32_t CloudSyncService::StopSyncInner(const string &bundleName, bool forceFlag)
419 {
420     string targetBundleName = bundleName;
421     string callerBundleName = "";
422     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
423     if (ret != E_OK) {
424         LOGE("get bundle name failed: %{public}d", ret);
425         return ret;
426     }
427     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
428     return dataSyncManager_->TriggerStopSync(targetBundleName, callerUserId, forceFlag, SyncTriggerType::APP_TRIGGER);
429 }
430 
ResetCursor(const string &bundleName)431 int32_t CloudSyncService::ResetCursor(const string &bundleName)
432 {
433     string targetBundleName = bundleName;
434     string callerBundleName = "";
435     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
436     if (ret != E_OK) {
437         LOGE("get bundle name failed: %{public}d", ret);
438         return ret;
439     }
440     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
441     return dataSyncManager_->ResetCursor(targetBundleName, callerUserId);
442 }
443 
GetSyncTimeInner(int64_t &syncTime, const string &bundleName)444 int32_t CloudSyncService::GetSyncTimeInner(int64_t &syncTime, const string &bundleName)
445 {
446     string targetBundleName = bundleName;
447     string callerBundleName = "";
448     int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName);
449     if (ret != E_OK) {
450         LOGE("get bundle name failed: %{public}d", ret);
451         return ret;
452     }
453     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
454     return DataSyncerRdbStore::GetInstance().GetLastSyncTime(callerUserId, targetBundleName, syncTime);
455 }
456 
CleanCacheInner(const std::string &uri)457 int32_t CloudSyncService::CleanCacheInner(const std::string &uri)
458 {
459     string bundleName;
460     if (DfsuAccessTokenHelper::GetCallerBundleName(bundleName)) {
461         return E_INVAL_ARG;
462     }
463     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
464     return dataSyncManager_->CleanCache(bundleName, callerUserId, uri);
465 }
466 
ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status)467 int32_t CloudSyncService::ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status)
468 {
469     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
470 
471     /* update app switch status */
472     auto ret = CloudStatus::ChangeAppSwitch(bundleName, callerUserId, status);
473     if (ret != E_OK) {
474         return ret;
475     }
476     if (status) {
477         return dataSyncManager_->TriggerStartSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER);
478     } else {
479         system::SetParameter(CLOUDSYNC_STATUS_KEY, CLOUDSYNC_STATUS_SWITCHOFF);
480         return dataSyncManager_->TriggerStopSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER);
481     }
482 }
483 
NotifyDataChange(const std::string &accoutId, const std::string &bundleName)484 int32_t CloudSyncService::NotifyDataChange(const std::string &accoutId, const std::string &bundleName)
485 {
486     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
487     return dataSyncManager_->TriggerStartSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER);
488 }
489 
NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData)490 int32_t CloudSyncService::NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData)
491 {
492     auto instance = CloudFile::CloudFileKit::GetInstance();
493     if (instance == nullptr) {
494         LOGE("get cloud file helper instance failed");
495         return E_NULLPTR;
496     }
497 
498     string appBundleName;
499     string prepareTraceId;
500     auto ret = instance->ResolveNotificationEvent(userId, extraData, appBundleName, prepareTraceId);
501     if (ret != E_OK) {
502         LOGE("ResolveNotificationEvent failed, ret:%{public}d", ret);
503         return E_CLOUD_SDK;
504     }
505 
506     return dataSyncManager_->TriggerStartSync(appBundleName, userId, false,
507         SyncTriggerType::CLOUD_TRIGGER, prepareTraceId);
508 }
509 
DisableCloud(const std::string &accoutId)510 int32_t CloudSyncService::DisableCloud(const std::string &accoutId)
511 {
512     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
513     system::SetParameter(CLOUDSYNC_STATUS_KEY, CLOUDSYNC_STATUS_LOGOUT);
514     return dataSyncManager_->DisableCloud(callerUserId);
515 }
516 
EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData)517 int32_t CloudSyncService::EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData)
518 {
519     return E_OK;
520 }
521 
Clean(const std::string &accountId, const CleanOptions &cleanOptions)522 int32_t CloudSyncService::Clean(const std::string &accountId, const CleanOptions &cleanOptions)
523 {
524     for (auto &iter : cleanOptions.appActionsData) {
525         LOGD("Clean key is: %s, value is: %d", iter.first.c_str(), iter.second);
526     }
527 
528     MetaFileMgr::GetInstance().ClearAll();
529     MetaFileMgr::GetInstance().CloudDiskClearAll();
530     auto callerUserId = DfsuAccessTokenHelper::GetUserId();
531     LOGI("Clean callerUserId is: %{public}d", callerUserId);
532     for (auto iter = cleanOptions.appActionsData.begin(); iter != cleanOptions.appActionsData.end(); ++iter) {
533         dataSyncManager_->CleanCloudFile(callerUserId, iter->first, iter->second);
534     }
535 
536     return E_OK;
537 }
StartFileCache(const std::vector<std::string> &uriVec, int64_t &downloadId)538 int32_t CloudSyncService::StartFileCache(const std::vector<std::string> &uriVec,
539                                          int64_t &downloadId)
540 {
541     BundleNameUserInfo bundleNameUserInfo;
542     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
543     if (ret != E_OK) {
544         LOGE("GetBundleNameUserInfo failed.");
545         return ret;
546     }
547     LOGI("start StartFileCache");
548     return dataSyncManager_->StartDownloadFile(bundleNameUserInfo, uriVec, downloadId);
549 }
550 
StartDownloadFile(const std::string &path)551 int32_t CloudSyncService::StartDownloadFile(const std::string &path)
552 {
553     BundleNameUserInfo bundleNameUserInfo;
554     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
555     if (ret != E_OK) {
556         return ret;
557     }
558     std::vector<std::string> pathVec;
559     pathVec.push_back(path);
560     int64_t downloadId = 0;
561     LOGI("start StartDownloadFile");
562     return dataSyncManager_->StartDownloadFile(bundleNameUserInfo, pathVec, downloadId);
563 }
564 
StopDownloadFile(const std::string &path, bool needClean)565 int32_t CloudSyncService::StopDownloadFile(const std::string &path, bool needClean)
566 {
567     BundleNameUserInfo bundleNameUserInfo;
568     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
569     if (ret != E_OK) {
570         return ret;
571     }
572     LOGI("start StopDownloadFile");
573     return dataSyncManager_->StopDownloadFile(bundleNameUserInfo, path, needClean);
574 }
575 
StopFileCache(const int64_t &downloadId, bool needClean)576 int32_t CloudSyncService::StopFileCache(const int64_t &downloadId,  bool needClean)
577 {
578     BundleNameUserInfo bundleNameUserInfo;
579     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
580     if (ret != E_OK) {
581         return ret;
582     }
583     LOGI("start StopFileCache");
584     return dataSyncManager_->StopFileCache(bundleNameUserInfo, downloadId, needClean);
585 }
586 
RegisterDownloadFileCallback(const sptr<IRemoteObject> &downloadCallback)587 int32_t CloudSyncService::RegisterDownloadFileCallback(const sptr<IRemoteObject> &downloadCallback)
588 {
589     BundleNameUserInfo bundleNameUserInfo;
590     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
591     if (ret != E_OK) {
592         return ret;
593     }
594     auto downloadCb = iface_cast<ICloudDownloadCallback>(downloadCallback);
595     LOGI("start RegisterDownloadFileCallback");
596     return dataSyncManager_->RegisterDownloadFileCallback(bundleNameUserInfo, downloadCb);
597 }
598 
UnregisterDownloadFileCallback()599 int32_t CloudSyncService::UnregisterDownloadFileCallback()
600 {
601     BundleNameUserInfo bundleNameUserInfo;
602     int ret = GetBundleNameUserInfo(bundleNameUserInfo);
603     if (ret != E_OK) {
604         return ret;
605     }
606     LOGI("start UnregisterDownloadFileCallback");
607     return dataSyncManager_->UnregisterDownloadFileCallback(bundleNameUserInfo);
608 }
609 
UploadAsset(const int32_t userId, const std::string &request, std::string &result)610 int32_t CloudSyncService::UploadAsset(const int32_t userId, const std::string &request, std::string &result)
611 {
612     auto instance = CloudFile::CloudFileKit::GetInstance();
613     if (instance == nullptr) {
614         LOGE("get cloud file helper instance failed");
615         return E_NULLPTR;
616     }
617 
618     string bundleName("distributeddata");
619     TaskStateManager::GetInstance().StartTask(bundleName, TaskType::UPLOAD_ASSET_TASK);
620     auto ret = instance->OnUploadAsset(userId, request, result);
621     TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::UPLOAD_ASSET_TASK);
622     return ret;
623 }
624 
DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj)625 int32_t CloudSyncService::DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj)
626 {
627     auto instance = CloudFile::CloudFileKit::GetInstance();
628     if (instance == nullptr) {
629         LOGE("get cloud file helper instance failed");
630         return E_NULLPTR;
631     }
632 
633     auto assetsDownloader = instance->GetCloudAssetsDownloader(userId, bundleName);
634     if (assetsDownloader == nullptr) {
635         LOGE("get asset downloader failed");
636         return E_NULLPTR;
637     }
638 
639     Asset asset;
640     asset.assetName = assetInfoObj.assetName;
641 
642     asset.uri = GetHmdfsPath(assetInfoObj.uri, userId);
643     if (asset.uri.empty()) {
644         LOGE("fail to get download path from %{public}s", GetAnonyString(assetInfoObj.uri).c_str());
645         return E_INVAL_ARG;
646     }
647 
648     // Not to pass the assetinfo.fieldkey
649     DownloadAssetInfo assetsToDownload{assetInfoObj.recordType, assetInfoObj.recordId, {}, asset, {}};
650     TaskStateManager::GetInstance().StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK);
651     auto ret = assetsDownloader->DownloadAssets(assetsToDownload);
652     TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK);
653     return ret;
654 }
655 
DownloadFiles(const int32_t userId, const std::string &bundleName, const std::vector<AssetInfoObj> &assetInfoObj, std::vector<bool> &assetResultMap)656 int32_t CloudSyncService::DownloadFiles(const int32_t userId, const std::string &bundleName,
657     const std::vector<AssetInfoObj> &assetInfoObj, std::vector<bool> &assetResultMap)
658 {
659     auto instance = CloudFile::CloudFileKit::GetInstance();
660     if (instance == nullptr) {
661         LOGE("get cloud file helper instance failed");
662         return E_NULLPTR;
663     }
664 
665     auto assetsDownloader = instance->GetCloudAssetsDownloader(userId, bundleName);
666     if (assetsDownloader == nullptr) {
667         LOGE("get asset downloader failed");
668         return E_NULLPTR;
669     }
670 
671     std::vector<DownloadAssetInfo> assetsToDownload;
672     for (const auto &obj: assetInfoObj) {
673         Asset asset;
674         asset.assetName = obj.assetName;
675         asset.uri = GetHmdfsPath(obj.uri, userId);
676         if (asset.uri.empty()) {
677             LOGE("fail to get download path from %{private}s", GetAnonyString(obj.uri).c_str());
678             return E_INVAL_ARG;
679         }
680         DownloadAssetInfo assetToDownload{obj.recordType, obj.recordId, {}, asset, {}};
681         assetsToDownload.emplace_back(assetToDownload);
682     }
683 
684     TaskStateManager::GetInstance().StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK);
685     auto ret = assetsDownloader->DownloadAssets(assetsToDownload, assetResultMap);
686     TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK);
687     return ret;
688 }
689 
DownloadAsset(const uint64_t taskId, const int32_t userId, const std::string &bundleName, const std::string &networkId, AssetInfoObj &assetInfoObj)690 int32_t CloudSyncService::DownloadAsset(const uint64_t taskId,
691                                         const int32_t userId,
692                                         const std::string &bundleName,
693                                         const std::string &networkId,
694                                         AssetInfoObj &assetInfoObj)
695 {
696     if (networkId == "edge2cloud") {
697         LOGE("now not support");
698         return E_INVAL_ARG;
699     }
700     // Load sa for remote device
701     if (LoadRemoteSA(networkId) != E_OK) { // maybe need to convert deviceId
702         return E_SA_LOAD_FAILED;
703     }
704 
705     string uri = assetInfoObj.uri;
706     fileTransferManager_->DownloadFileFromRemoteDevice(networkId, userId, taskId, uri);
707     return E_OK;
708 }
709 
RegisterDownloadAssetCallback(const sptr<IRemoteObject> &remoteObject)710 int32_t CloudSyncService::RegisterDownloadAssetCallback(const sptr<IRemoteObject> &remoteObject)
711 {
712     if (remoteObject == nullptr) {
713         LOGE("remoteObject is nullptr");
714         return E_INVAL_ARG;
715     }
716     auto callback = iface_cast<IDownloadAssetCallback>(remoteObject);
717     DownloadAssetCallbackManager::GetInstance().AddCallback(callback);
718     return E_OK;
719 }
720 
DeleteAsset(const int32_t userId, const std::string &uri)721 int32_t CloudSyncService::DeleteAsset(const int32_t userId, const std::string &uri)
722 {
723     std::string physicalPath = "";
724     int ret = AppFileService::SandboxHelper::GetPhysicalPath(uri, std::to_string(userId), physicalPath);
725     if (ret != 0) {
726         LOGE("Get physical path failed with %{public}d", ret);
727         return E_GET_PHYSICAL_PATH_FAILED;
728     }
729 
730     LOGD("delete assert, path %{public}s", GetAnonyString(physicalPath).c_str());
731 
732     ret = unlink(physicalPath.c_str());
733     if (ret != 0) {
734         LOGE("fail to delete asset, errno %{public}d", errno);
735         return E_DELETE_FAILED;
736     }
737     return E_OK;
738 }
739 } // namespace OHOS::FileManagement::CloudSync
740