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