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