• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "wallpaper_service.h"
16 
17 #include <cerrno>
18 #include <cstdio>
19 #include <cstdlib>
20 #include <cstring>
21 #include <fcntl.h>
22 #include <iostream>
23 #include <sys/prctl.h>
24 #include <sys/sendfile.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <thread>
28 #include <unistd.h>
29 #include <window_manager.h>
30 
31 #include "ability_manager_client.h"
32 #include "bundle_mgr_interface.h"
33 #include "bundle_mgr_proxy.h"
34 #include "color_picker.h"
35 #include "command.h"
36 #include "directory_ex.h"
37 #include "dump_helper.h"
38 #include "effect_errors.h"
39 #include "export/color.h"
40 #include "file_deal.h"
41 #include "file_ex.h"
42 #include "hilog_wrapper.h"
43 #include "hitrace_meter.h"
44 #include "image_packer.h"
45 #include "image_source.h"
46 #include "image_type.h"
47 #include "image_utils.h"
48 #include "iservice_registry.h"
49 #include "memory_guard.h"
50 #include "nlohmann/json.hpp"
51 #include "parameter.h"
52 #include "pixel_map.h"
53 #include "scene_board_judgement.h"
54 #include "surface.h"
55 #include "system_ability_definition.h"
56 #include "tokenid_kit.h"
57 #include "uri.h"
58 #include "uri_permission_manager_client.h"
59 #include "wallpaper_common.h"
60 #include "wallpaper_common_event_manager.h"
61 #include "wallpaper_extension_ability_connection.h"
62 #include "wallpaper_extension_ability_death_recipient.h"
63 #include "wallpaper_service_cb_proxy.h"
64 #include "want.h"
65 #include "window.h"
66 
67 namespace OHOS {
68 namespace WallpaperMgrService {
69 REGISTER_SYSTEM_ABILITY_BY_ID(WallpaperService, WALLPAPER_MANAGER_SERVICE_ID, true);
70 
71 using namespace OHOS::Media;
72 using namespace OHOS::MiscServices;
73 using namespace OHOS::Security::AccessToken;
74 using namespace OHOS::AccountSA;
75 
76 constexpr const char *WALLPAPER_SYSTEM_ORIG = "wallpaper_system_orig";
77 constexpr const char *WALLPAPER_LOCK_ORIG = "wallpaper_lock_orig";
78 constexpr const char *LIVE_WALLPAPER_SYSTEM_ORIG = "live_wallpaper_system_orig";
79 constexpr const char *LIVE_WALLPAPER_LOCK_ORIG = "live_wallpaper_lock_orig";
80 constexpr const char *CUSTOM_WALLPAPER_LOCK = "custom_wallpaper_lock";
81 constexpr const char *CUSTOM_WALLPAPER_SYSTEM = "custom_wallpaper_system";
82 constexpr const char *OHOS_WALLPAPER_BUNDLE_NAME = "com.ohos.launcher";
83 constexpr const char *SHOW_SYSTEM_SCREEN = "SHOW_SYSTEMSCREEN";
84 constexpr const char *SHOW_LOCK_SCREEN = "SHOW_LOCKSCREEN";
85 constexpr const char *SYSTEM_RES_TYPE = "SystemResType";
86 constexpr const char *LOCKSCREEN_RES_TYPE = "LockScreenResType";
87 constexpr const char *WALLPAPER_CHANGE = "wallpaperChange";
88 constexpr const char *COLOR_CHANGE = "colorChange";
89 constexpr const char *BUNDLE_NAME_KEY = "persist.wallpaper_mgr.bundleName";
90 constexpr const char *SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
91 
92 constexpr const char *WALLPAPER_USERID_PATH = "/data/service/el1/public/wallpaper/";
93 constexpr const char *WALLPAPER_SYSTEM_DIRNAME = "system";
94 constexpr const char *WALLPAPER_TMP_DIRNAME = "fwsettmp";
95 constexpr const char *WALLPAPER_LOCKSCREEN_DIRNAME = "lockscreen";
96 constexpr const char *WALLPAPER_DEFAULT_FILEFULLPATH = "/system/etc/wallpaperdefault.jpeg";
97 constexpr const char *WALLPAPER_DEFAULT_LOCK_FILEFULLPATH = "/system/etc/wallpaperlockdefault.jpeg";
98 constexpr const char *WALLPAPER_PREFABRICATE_FILEFULLPATH = "/sys_prod/media/themes/wallpaperdefault.jpeg";
99 constexpr const char *WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH = "/sys_prod/media/themes/wallpaperlockdefault.jpeg";
100 constexpr const char *WALLPAPER_CROP_PICTURE = "crop_file";
101 
102 constexpr int64_t INIT_INTERVAL = 10000L;
103 constexpr int64_t DELAY_TIME = 1000L;
104 constexpr int64_t QUERY_USER_ID_INTERVAL = 300L;
105 constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100;
106 constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 50;
107 constexpr int32_t FOO_MAX_LEN = 52428800;
108 constexpr int32_t MAX_RETRY_TIMES = 20;
109 constexpr int32_t QUERY_USER_MAX_RETRY_TIMES = 100;
110 constexpr int32_t DEFAULT_WALLPAPER_ID = -1;
111 constexpr int32_t DEFAULT_USER_ID = 0;
112 constexpr int32_t DEFAULT_VALUE = -1;
113 constexpr int32_t MAX_VIDEO_SIZE = 104857600;
114 const int CONFIG_LEN = 30;
115 
116 std::mutex WallpaperService::instanceLock_;
117 
118 sptr<WallpaperService> WallpaperService::instance_;
119 
120 std::shared_ptr<AppExecFwk::EventHandler> WallpaperService::serviceHandler_;
121 
WallpaperService(int32_t systemAbilityId,bool runOnCreate)122 WallpaperService::WallpaperService(int32_t systemAbilityId, bool runOnCreate)
123     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
124 {
125 }
126 
WallpaperService()127 WallpaperService::WallpaperService() : state_(ServiceRunningState::STATE_NOT_START)
128 {
129 }
130 
~WallpaperService()131 WallpaperService::~WallpaperService()
132 {
133 }
134 
Init()135 int32_t WallpaperService::Init()
136 {
137     InitQueryUserId(QUERY_USER_MAX_RETRY_TIMES);
138     bool ret = Publish(this);
139     if (!ret) {
140         HILOG_ERROR("Publish failed.");
141         ReporterFault(FaultType::SERVICE_FAULT, FaultCode::SF_SERVICE_UNAVAILABLE);
142         return -1;
143     }
144     HILOG_INFO("Publish success.");
145     state_ = ServiceRunningState::STATE_RUNNING;
146     StartExtensionAbility(CONNECT_EXTENSION_MAX_RETRY_TIMES);
147     return E_OK;
148 }
149 
OnStart()150 void WallpaperService::OnStart()
151 {
152     HILOG_INFO("Enter OnStart.");
153     MemoryGuard cacheGuard;
154     if (state_ == ServiceRunningState::STATE_RUNNING) {
155         HILOG_ERROR("WallpaperService is already running.");
156         return;
157     }
158     InitData();
159     InitServiceHandler();
160     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
161     auto cmd = std::make_shared<Command>(std::vector<std::string>({ "-all" }), "Show all",
162         [this](const std::vector<std::string> &input, std::string &output) -> bool {
163             output.append(
164                 "WallpaperExtensionAbility\t: ExtensionInfo{" + std::string(OHOS_WALLPAPER_BUNDLE_NAME) + "}\n");
165             return true;
166         });
167     DumpHelper::GetInstance().RegisterCommand(cmd);
168     StatisticReporter::StartTimerThread();
169     if (Init() != E_OK) {
170         auto callback = [=]() { Init(); };
171         serviceHandler_->PostTask(callback, INIT_INTERVAL);
172         HILOG_ERROR("Init failed. Try again 10s later");
173     }
174     return;
175 }
176 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)177 void WallpaperService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
178 {
179     HILOG_INFO("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
180     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
181         int32_t times = 0;
182         RegisterSubscriber(times);
183     }
184 }
185 
RegisterSubscriber(int32_t times)186 void WallpaperService::RegisterSubscriber(int32_t times)
187 {
188     MemoryGuard cacheGuard;
189     times++;
190     subscriber_ = std::make_shared<WallpaperCommonEventSubscriber>(*this);
191     bool subRes = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
192     if (!subRes && times <= MAX_RETRY_TIMES) {
193         HILOG_INFO("RegisterSubscriber failed");
194         auto callback = [this, times]() { RegisterSubscriber(times); };
195         serviceHandler_->PostTask(callback, DELAY_TIME);
196     }
197 }
198 
InitServiceHandler()199 void WallpaperService::InitServiceHandler()
200 {
201     HILOG_INFO("InitServiceHandler started.");
202     if (serviceHandler_ != nullptr) {
203         HILOG_ERROR("InitServiceHandler already init.");
204         return;
205     }
206     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("WallpaperService");
207     serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
208 
209     HILOG_INFO("InitServiceHandler succeeded.");
210 }
211 
OnStop()212 void WallpaperService::OnStop()
213 {
214     HILOG_INFO("OnStop started.");
215     if (state_ != ServiceRunningState::STATE_RUNNING) {
216         return;
217     }
218     serviceHandler_ = nullptr;
219     connection_ = nullptr;
220     recipient_ = nullptr;
221     extensionRemoteObject_ = nullptr;
222     if (subscriber_ != nullptr) {
223         bool unSubscribeResult = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_);
224         subscriber_ = nullptr;
225         HILOG_INFO("UnregisterSubscriber end, unSubscribeResult = %{public}d", unSubscribeResult);
226     }
227     state_ = ServiceRunningState::STATE_NOT_START;
228     HILOG_INFO("OnStop end.");
229 }
230 
InitData()231 void WallpaperService::InitData()
232 {
233     HILOG_INFO("WallpaperService::initData --> start ");
234     wallpaperId_ = DEFAULT_WALLPAPER_ID;
235     int32_t userId = DEFAULT_USER_ID;
236     systemWallpaperMap_.Clear();
237     lockWallpaperMap_.Clear();
238     wallpaperTmpFullPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_TMP_DIRNAME);
239     wallpaperCropPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_CROP_PICTURE);
240     systemWallpaperColor_ = 0;
241     lockWallpaperColor_ = 0;
242     wallpaperEventMap_.clear();
243     appBundleName_ = SCENEBOARD_BUNDLE_NAME;
244     InitBundleNameParameter();
245     InitUserDir(userId);
246     LoadSettingsLocked(userId, true);
247     InitResources(userId, WALLPAPER_SYSTEM);
248     InitResources(userId, WALLPAPER_LOCKSCREEN);
249     LoadWallpaperState();
250     HILOG_INFO("WallpaperService::initData --> end ");
251 }
252 
InitBundleNameParameter()253 void WallpaperService::InitBundleNameParameter()
254 {
255     char value[CONFIG_LEN] = "";
256     if (GetParameter(BUNDLE_NAME_KEY, "", value, CONFIG_LEN) < 0 || strlen(value) == 0) {
257         HILOG_ERROR("No found bundle name from system parameter.");
258         return;
259     }
260     appBundleName_ = value;
261     HILOG_INFO("get appBundleName_ :%{public}s", appBundleName_.c_str());
262 }
263 
AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> & remoteObject)264 void WallpaperService::AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> &remoteObject)
265 {
266     if (remoteObject != nullptr) {
267         std::lock_guard<std::mutex> lock(remoteObjectMutex_);
268         IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
269         if (recipient_ == nullptr) {
270             recipient_ = sptr<IRemoteObject::DeathRecipient>(new WallpaperExtensionAbilityDeathRecipient(*this));
271         }
272         if (proxy != nullptr && !proxy->IsObjectDead()) {
273             HILOG_INFO("get remoteObject succeed");
274             proxy->AddDeathRecipient(recipient_);
275             extensionRemoteObject_ = remoteObject;
276         }
277     }
278 }
279 
RemoveExtensionDeathRecipient()280 void WallpaperService::RemoveExtensionDeathRecipient()
281 {
282     if (extensionRemoteObject_ != nullptr && recipient_ != nullptr) {
283         HILOG_INFO("Remove Extension DeathRecipient");
284         std::lock_guard<std::mutex> lock(remoteObjectMutex_);
285         extensionRemoteObject_->RemoveDeathRecipient(recipient_);
286         recipient_ = nullptr;
287         extensionRemoteObject_ = nullptr;
288     }
289 }
290 
InitQueryUserId(int32_t times)291 void WallpaperService::InitQueryUserId(int32_t times)
292 {
293     times--;
294     bool ret = InitUsersOnBoot();
295     if (!ret && times > 0) {
296         HILOG_INFO("InitQueryUserId failed");
297         auto callback = [this, times]() { InitQueryUserId(times); };
298         serviceHandler_->PostTask(callback, QUERY_USER_ID_INTERVAL);
299     }
300 }
301 
StartExtensionAbility(int32_t times)302 void WallpaperService::StartExtensionAbility(int32_t times)
303 {
304     times--;
305     bool ret = ConnectExtensionAbility();
306     if (!ret && times > 0 && serviceHandler_ != nullptr) {
307         HILOG_ERROR("StartExtensionAbilty failed, remainder of the times: %{public}d", times);
308         auto callback = [this, times]() { StartExtensionAbility(times); };
309         serviceHandler_->PostTask(callback, CONNECT_EXTENSION_INTERVAL);
310     }
311 }
312 
InitUsersOnBoot()313 bool WallpaperService::InitUsersOnBoot()
314 {
315     std::vector<int32_t> userIds;
316     if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(userIds) != ERR_OK || userIds.empty()) {
317         HILOG_INFO("WallpaperService: failed to get current userIds");
318         return false;
319     }
320     HILOG_INFO("WallpaperService::get current userIds success, Current userId: %{public}d", userIds[0]);
321     for (auto userId : userIds) {
322         InitUserDir(userId);
323         LoadSettingsLocked(userId, true);
324         InitResources(userId, WALLPAPER_SYSTEM);
325         InitResources(userId, WALLPAPER_LOCKSCREEN);
326     }
327     return true;
328 }
329 
OnInitUser(int32_t userId)330 void WallpaperService::OnInitUser(int32_t userId)
331 {
332     if (userId < 0) {
333         HILOG_ERROR("userId error, userId = %{public}d", userId);
334         return;
335     }
336     std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
337     if (FileDeal::IsFileExist(userDir)) {
338         std::lock_guard<std::mutex> lock(mtx_);
339         if (!OHOS::ForceRemoveDirectory(userDir)) {
340             HILOG_ERROR("Force remove user directory path failed, errno %{public}d, userId:%{public}d", errno, userId);
341             return;
342         }
343     }
344     if (!InitUserDir(userId)) {
345         return;
346     }
347     LoadSettingsLocked(userId, true);
348     InitResources(userId, WALLPAPER_SYSTEM);
349     InitResources(userId, WALLPAPER_LOCKSCREEN);
350     HILOG_INFO("OnInitUser success, userId = %{public}d", userId);
351 }
352 
InitResources(int32_t userId,WallpaperType wallpaperType)353 void WallpaperService::InitResources(int32_t userId, WallpaperType wallpaperType)
354 {
355     std::string pathName;
356     if (!GetFileNameFromMap(userId, wallpaperType, pathName)) {
357         HILOG_ERROR("Get user file name from map failed, userId = %{public}d", userId);
358         return;
359     }
360     if (!FileDeal::IsFileExist(pathName)) {
361         WallpaperData wallpaperData;
362         if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
363             HILOG_ERROR("Get wallpaper data failed, userId = %{public}d", userId);
364             return;
365         }
366         if (!RestoreUserResources(wallpaperData, wallpaperType)) {
367             HILOG_ERROR("RestoreUserResources error");
368             return;
369         }
370     }
371 }
372 
InitUserDir(int32_t userId)373 bool WallpaperService::InitUserDir(int32_t userId)
374 {
375     std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
376     if (!FileDeal::Mkdir(userDir)) {
377         HILOG_ERROR("Failed to create destination path, userId:%{public}d ", userId);
378         return false;
379     }
380     std::string wallpaperSystemFilePath = userDir + "/" + WALLPAPER_SYSTEM_DIRNAME;
381     if (!FileDeal::Mkdir(wallpaperSystemFilePath)) {
382         HILOG_ERROR("Failed to create destination wallpaper system path, userId:%{public}d, type:%{public}s", userId,
383             WALLPAPER_SYSTEM_DIRNAME);
384         return false;
385     }
386     std::string wallpaperLockScreenFilePath = userDir + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
387     if (!FileDeal::Mkdir(wallpaperLockScreenFilePath)) {
388         HILOG_ERROR("Failed to create destination wallpaper lockscreen path, userId:%{public}d, type:%{public}s",
389             userId, WALLPAPER_LOCKSCREEN_DIRNAME);
390         return false;
391     }
392     return true;
393 }
394 
RestoreUserResources(const WallpaperData & wallpaperData,WallpaperType wallpaperType)395 bool WallpaperService::RestoreUserResources(const WallpaperData &wallpaperData, WallpaperType wallpaperType)
396 {
397     std::string wallpaperDefaultPath = wallpaperType == WallpaperType::WALLPAPER_SYSTEM
398                                            ? WALLPAPER_DEFAULT_FILEFULLPATH
399                                            : WALLPAPER_DEFAULT_LOCK_FILEFULLPATH;
400     if (wallpaperType == WallpaperType::WALLPAPER_SYSTEM) {
401         if (FileDeal::IsFileExist(WALLPAPER_PREFABRICATE_FILEFULLPATH)) {
402             wallpaperDefaultPath = WALLPAPER_PREFABRICATE_FILEFULLPATH;
403         }
404     } else {
405         if (FileDeal::IsFileExist(WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH)) {
406             wallpaperDefaultPath = WALLPAPER_PREFABRICATE_LOCK_FILEFULLPATH;
407         }
408     }
409     if (!FileDeal::IsFileExist(wallpaperDefaultPath) ||
410         !FileDeal::IsFileExist(GetWallpaperDir(wallpaperData.userId, wallpaperType))) {
411         HILOG_INFO("Copy file path is not exist");
412         return false;
413     }
414     std::lock_guard<std::mutex> lock(mtx_);
415     if (!FileDeal::CopyFile(wallpaperDefaultPath, wallpaperData.wallpaperFile)) {
416         HILOG_INFO("CopyFile WALLPAPER_DEFAULT_FILEFULLPATH failed");
417         return false;
418     }
419     HILOG_INFO("Restore user resources end ");
420     return true;
421 }
422 
OnRemovedUser(int32_t userId)423 void WallpaperService::OnRemovedUser(int32_t userId)
424 {
425     if (userId < 0) {
426         HILOG_ERROR("userId error, userId = %{public}d", userId);
427         return;
428     }
429     ClearWallpaperLocked(userId, WALLPAPER_SYSTEM);
430     ClearWallpaperLocked(userId, WALLPAPER_LOCKSCREEN);
431     std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
432     std::lock_guard<std::mutex> lock(mtx_);
433     if (!OHOS::ForceRemoveDirectory(userDir)) {
434         HILOG_ERROR("Force remove user directory path failed, errno %{public}d.", errno);
435     }
436     HILOG_INFO("OnRemovedUser end, userId = %{public}d", userId);
437 }
438 
OnSwitchedUser(int32_t userId)439 void WallpaperService::OnSwitchedUser(int32_t userId)
440 {
441     if (userId < 0) {
442         HILOG_ERROR("userId error, userId = %{public}d", userId);
443         return;
444     }
445     RemoveExtensionDeathRecipient();
446     ConnectExtensionAbility();
447     std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
448     LoadSettingsLocked(userId, true);
449     if (!FileDeal::IsFileExist(userDir)) {
450         HILOG_INFO("User file is not exist, userId = %{public}d", userId);
451         InitUserDir(userId);
452         InitResources(userId, WALLPAPER_SYSTEM);
453         InitResources(userId, WALLPAPER_LOCKSCREEN);
454     }
455     LoadWallpaperState();
456     GrantUriPermissionByUserId(userId);
457     SendWallpaperChangeEvent(userId, WALLPAPER_SYSTEM);
458     SendWallpaperChangeEvent(userId, WALLPAPER_LOCKSCREEN);
459     SaveColor(userId, WALLPAPER_SYSTEM);
460     SaveColor(userId, WALLPAPER_LOCKSCREEN);
461     HILOG_INFO("OnSwitchedUser end, newUserId = %{public}d", userId);
462 }
463 
GrantUriPermissionByUserId(int32_t userId)464 void WallpaperService::GrantUriPermissionByUserId(int32_t userId)
465 {
466     WallpaperData systemData;
467     WallpaperData lockScreenData;
468     if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData) ||
469         !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
470         return;
471     }
472     if (systemData.resourceType == PACKAGE) {
473         GrantUriPermission(systemData.customPackageUri, appBundleName_);
474     }
475     if (lockScreenData.resourceType == PACKAGE) {
476         GrantUriPermission(lockScreenData.customPackageUri, appBundleName_);
477     }
478 }
479 
OnBootPhase()480 void WallpaperService::OnBootPhase()
481 {
482     HILOG_INFO("WallpaperService OnBootPhase");
483 }
484 
GetWallpaperDir(int32_t userId,WallpaperType wallpaperType)485 std::string WallpaperService::GetWallpaperDir(int32_t userId, WallpaperType wallpaperType)
486 {
487     std::string userIdPath = WALLPAPER_USERID_PATH + std::to_string(userId);
488     std::string wallpaperFilePath;
489     if (wallpaperType == WALLPAPER_SYSTEM) {
490         wallpaperFilePath = userIdPath + "/" + WALLPAPER_SYSTEM_DIRNAME;
491     } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
492         wallpaperFilePath = userIdPath + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
493     }
494     return wallpaperFilePath;
495 }
496 
GetFileNameFromMap(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)497 bool WallpaperService::GetFileNameFromMap(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
498 {
499     auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
500                                                       : lockWallpaperMap_.Find(userId);
501     if (!iterator.first) {
502         HILOG_ERROR("system wallpaper already cleared");
503         return false;
504     }
505     HILOG_INFO("GetFileNameFromMap resourceType : %{public}d", static_cast<int32_t>(iterator.second.resourceType));
506     switch (iterator.second.resourceType) {
507         case PICTURE:
508             filePathName = iterator.second.wallpaperFile;
509             break;
510         case VIDEO:
511             filePathName = iterator.second.liveWallpaperFile;
512             break;
513         case DEFAULT:
514             filePathName = iterator.second.wallpaperFile;
515             break;
516         case PACKAGE:
517             filePathName = iterator.second.customPackageUri;
518             break;
519         default:
520             filePathName = "";
521             break;
522     }
523     return filePathName != "";
524 }
525 
GetPictureFileName(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)526 bool WallpaperService::GetPictureFileName(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
527 {
528     auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
529                                                       : lockWallpaperMap_.Find(userId);
530     if (!iterator.first) {
531         HILOG_ERROR("system wallpaper already cleared");
532         return false;
533     }
534     filePathName = iterator.second.wallpaperFile;
535     HILOG_INFO("GetPictureFileName filePathName : %{public}s", filePathName.c_str());
536     return filePathName != "";
537 }
538 
MakeWallpaperIdLocked()539 int32_t WallpaperService::MakeWallpaperIdLocked()
540 {
541     HILOG_INFO("MakeWallpaperIdLocked start");
542     if (wallpaperId_ == INT32_MAX) {
543         wallpaperId_ = DEFAULT_WALLPAPER_ID;
544     }
545     return ++wallpaperId_;
546 }
547 
LoadSettingsLocked(int32_t userId,bool keepDimensionHints)548 void WallpaperService::LoadSettingsLocked(int32_t userId, bool keepDimensionHints)
549 {
550     HILOG_INFO("load Setting locked start.");
551     if (!systemWallpaperMap_.Contains(userId)) {
552         HILOG_INFO("systemWallpaperMap_ does not contains userId");
553         std::string wallpaperSystemFilePath = GetWallpaperDir(userId, WALLPAPER_SYSTEM);
554         WallpaperData wallpaperSystem(userId, wallpaperSystemFilePath + "/" + WALLPAPER_SYSTEM_ORIG);
555         wallpaperSystem.liveWallpaperFile = wallpaperSystemFilePath + "/" + LIVE_WALLPAPER_SYSTEM_ORIG;
556         wallpaperSystem.customPackageUri = wallpaperSystemFilePath + "/" + CUSTOM_WALLPAPER_SYSTEM;
557         wallpaperSystem.allowBackup = true;
558         wallpaperSystem.resourceType = PICTURE;
559         wallpaperSystem.wallpaperId = DEFAULT_WALLPAPER_ID;
560         systemWallpaperMap_.InsertOrAssign(userId, wallpaperSystem);
561     }
562     if (!lockWallpaperMap_.Contains(userId)) {
563         HILOG_INFO("lockWallpaperMap_ does not Contains userId");
564         std::string wallpaperLockScreenFilePath = GetWallpaperDir(userId, WALLPAPER_LOCKSCREEN);
565         WallpaperData wallpaperLock(userId, wallpaperLockScreenFilePath + "/" + WALLPAPER_LOCK_ORIG);
566         wallpaperLock.liveWallpaperFile = wallpaperLockScreenFilePath + "/" + LIVE_WALLPAPER_LOCK_ORIG;
567         wallpaperLock.customPackageUri = wallpaperLockScreenFilePath + "/" + CUSTOM_WALLPAPER_LOCK;
568         wallpaperLock.allowBackup = true;
569         wallpaperLock.resourceType = PICTURE;
570         wallpaperLock.wallpaperId = DEFAULT_WALLPAPER_ID;
571         lockWallpaperMap_.InsertOrAssign(userId, wallpaperLock);
572     }
573     HILOG_INFO("load Setting locked end.");
574 }
575 
GetColors(int32_t wallpaperType,std::vector<uint64_t> & colors)576 ErrorCode WallpaperService::GetColors(int32_t wallpaperType, std::vector<uint64_t> &colors)
577 {
578     if (wallpaperType == WALLPAPER_SYSTEM) {
579         colors.emplace_back(systemWallpaperColor_);
580     } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
581         colors.emplace_back(lockWallpaperColor_);
582     }
583     HILOG_INFO(" Service End!");
584     return E_OK;
585 }
586 
GetColorsV9(int32_t wallpaperType,std::vector<uint64_t> & colors)587 ErrorCode WallpaperService::GetColorsV9(int32_t wallpaperType, std::vector<uint64_t> &colors)
588 {
589     if (!IsSystemApp()) {
590         HILOG_INFO("CallingApp is not SystemApp");
591         return E_NOT_SYSTEM_APP;
592     }
593     return GetColors(wallpaperType, colors);
594 }
595 
GetFile(int32_t wallpaperType,int32_t & wallpaperFd)596 ErrorCode WallpaperService::GetFile(int32_t wallpaperType, int32_t &wallpaperFd)
597 {
598     if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
599         HILOG_ERROR("GetPixelMap no get permission!");
600         return E_NO_PERMISSION;
601     }
602     if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) &&
603         wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
604         return E_PARAMETERS_INVALID;
605     }
606     auto type = static_cast<WallpaperType>(wallpaperType);
607     int32_t userId = QueryActiveUserId();
608     if (GetResType(userId, type) == WallpaperResourceType::PACKAGE) {
609         HILOG_ERROR("Current user's wallpaper is custom package");
610         wallpaperFd = -1; // -1: invalid file description
611         return E_OK;
612     }
613     HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
614     ErrorCode ret = GetImageFd(userId, type, wallpaperFd);
615     HILOG_INFO("GetImageFd fd:%{public}d, ret:%{public}d", wallpaperFd, ret);
616     return ret;
617 }
618 
CompareColor(const uint64_t & localColor,const ColorManager::Color & color)619 bool WallpaperService::CompareColor(const uint64_t &localColor, const ColorManager::Color &color)
620 {
621     return localColor == color.PackValue();
622 }
623 
SaveColor(int32_t userId,WallpaperType wallpaperType)624 bool WallpaperService::SaveColor(int32_t userId, WallpaperType wallpaperType)
625 {
626     uint32_t errorCode = 0;
627     OHOS::Media::SourceOptions opts;
628     opts.formatHint = "image/jpeg";
629     std::string pathName;
630     if (!GetPictureFileName(userId, wallpaperType, pathName)) {
631         return false;
632     }
633     std::unique_ptr<OHOS::Media::ImageSource> imageSource =
634         OHOS::Media::ImageSource::CreateImageSource(pathName, opts, errorCode);
635     if (errorCode != 0) {
636         HILOG_ERROR("CreateImageSource failed");
637         return false;
638     }
639     OHOS::Media::DecodeOptions decodeOpts;
640     std::unique_ptr<PixelMap> wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
641     if (errorCode != 0) {
642         HILOG_ERROR("CreatePixelMap failed");
643         return false;
644     }
645 
646     pictureHeight_ = wallpaperPixelMap->GetHeight();
647     pictureWidth_ = wallpaperPixelMap->GetWidth();
648 
649     auto colorPicker = Rosen::ColorPicker::CreateColorPicker(std::move(wallpaperPixelMap), errorCode);
650     if (errorCode != 0) {
651         HILOG_ERROR("CreateColorPicker failed");
652         return false;
653     }
654     auto color = ColorManager::Color();
655     uint32_t ret = colorPicker->GetMainColor(color);
656     if (ret != Rosen::SUCCESS) {
657         HILOG_ERROR("GetMainColor failed ret is : %{public}d", ret);
658         return false;
659     }
660     OnColorsChange(wallpaperType, color);
661     return true;
662 }
663 
SetWallpaper(int32_t fd,int32_t wallpaperType,int32_t length)664 ErrorCode WallpaperService::SetWallpaper(int32_t fd, int32_t wallpaperType, int32_t length)
665 {
666     StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
667     ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, PICTURE);
668     FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
669     return wallpaperErrorCode;
670 }
671 
SetWallpaperV9(int32_t fd,int32_t wallpaperType,int32_t length)672 ErrorCode WallpaperService::SetWallpaperV9(int32_t fd, int32_t wallpaperType, int32_t length)
673 {
674     if (!IsSystemApp()) {
675         HILOG_INFO("CallingApp is not SystemApp");
676         return E_NOT_SYSTEM_APP;
677     }
678     return SetWallpaper(fd, wallpaperType, length);
679 }
680 
SetWallpaperBackupData(int32_t userId,WallpaperResourceType resourceType,const std::string & uriOrPixelMap,WallpaperType wallpaperType)681 ErrorCode WallpaperService::SetWallpaperBackupData(int32_t userId, WallpaperResourceType resourceType,
682     const std::string &uriOrPixelMap, WallpaperType wallpaperType)
683 {
684     HILOG_INFO("set wallpaper and backup data Start.");
685     if (!OHOS::FileExists(uriOrPixelMap)) {
686         return E_DEAL_FAILED;
687     }
688     WallpaperData wallpaperData;
689     bool ret = GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData);
690     if (!ret) {
691         HILOG_ERROR("GetWallpaperSafeLocked failed !");
692         return E_DEAL_FAILED;
693     }
694     wallpaperData.resourceType = resourceType;
695     wallpaperData.wallpaperId = MakeWallpaperIdLocked();
696     std::string wallpaperFile = resourceType == VIDEO ? wallpaperData.liveWallpaperFile : wallpaperData.wallpaperFile;
697     if (!FileDeal::CopyFile(uriOrPixelMap, wallpaperFile)) {
698         HILOG_ERROR("CopyFile failed !");
699         return E_DEAL_FAILED;
700     }
701     if (!FileDeal::DeleteFile(uriOrPixelMap)) {
702         return E_DEAL_FAILED;
703     }
704     if (!SaveWallpaperState(userId, wallpaperType)) {
705         HILOG_ERROR("Save wallpaper state failed!");
706     }
707     if (wallpaperType == WALLPAPER_SYSTEM) {
708         systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
709         ReporterUsageTimeStatistic();
710     } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
711         lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
712         ReporterUsageTimeStatistic();
713     }
714     if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
715         HILOG_ERROR("Send wallpaper state failed!");
716         return E_DEAL_FAILED;
717     }
718     return E_OK;
719 }
720 
GetResType(int32_t userId,WallpaperType wallpaperType)721 WallpaperResourceType WallpaperService::GetResType(int32_t userId, WallpaperType wallpaperType)
722 {
723     if (wallpaperType == WALLPAPER_LOCKSCREEN) {
724         auto iterator = lockWallpaperMap_.Find(userId);
725         if (iterator.first) {
726             return iterator.second.resourceType;
727         }
728     } else if (wallpaperType == WALLPAPER_SYSTEM) {
729         auto iterator = systemWallpaperMap_.Find(userId);
730         if (iterator.first) {
731             return iterator.second.resourceType;
732         }
733     }
734     return WallpaperResourceType::DEFAULT;
735 }
736 
SendEvent(const std::string & eventType)737 ErrorCode WallpaperService::SendEvent(const std::string &eventType)
738 {
739     HILOG_DEBUG("Send event start.");
740     if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
741         HILOG_ERROR("Send event not set permission!");
742         return E_NO_PERMISSION;
743     }
744 
745     int32_t userId = QueryActiveUserId();
746     WallpaperType wallpaperType;
747     WallpaperData data;
748     if (eventType == SHOW_SYSTEM_SCREEN) {
749         wallpaperType = WALLPAPER_SYSTEM;
750     } else if (eventType == SHOW_LOCK_SCREEN) {
751         wallpaperType = WALLPAPER_LOCKSCREEN;
752     } else {
753         HILOG_ERROR("Event type error!");
754         return E_PARAMETERS_INVALID;
755     }
756 
757     if (!GetWallpaperSafeLocked(userId, wallpaperType, data)) {
758         HILOG_ERROR("Get wallpaper safe locked failed!");
759         return E_PARAMETERS_INVALID;
760     }
761     ReporterUsageTimeStatistic();
762     std::string uri;
763     GetFileNameFromMap(userId, WALLPAPER_SYSTEM, uri);
764     WallpaperChanged(wallpaperType, data.resourceType, uri);
765     return E_OK;
766 }
767 
SendWallpaperChangeEvent(int32_t userId,WallpaperType wallpaperType)768 bool WallpaperService::SendWallpaperChangeEvent(int32_t userId, WallpaperType wallpaperType)
769 {
770     WallpaperData wallpaperData;
771     if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
772         HILOG_ERROR("GetWallpaperSafeLocked failed !");
773         return false;
774     }
775     shared_ptr<WallpaperCommonEventManager> wallpaperCommonEventManager = make_shared<WallpaperCommonEventManager>();
776     if (wallpaperType == WALLPAPER_SYSTEM) {
777         HILOG_INFO("Send wallpaper system setting message");
778         wallpaperCommonEventManager->SendWallpaperSystemSettingMessage(wallpaperData.resourceType);
779     } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
780         HILOG_INFO("Send wallpaper lock setting message");
781         wallpaperCommonEventManager->SendWallpaperLockSettingMessage(wallpaperData.resourceType);
782     }
783     HILOG_INFO("SetWallpaperBackupData callbackProxy_->OnCall start");
784     if (callbackProxy_ != nullptr && (wallpaperData.resourceType == PICTURE || wallpaperData.resourceType == DEFAULT)) {
785         callbackProxy_->OnCall(wallpaperType);
786     }
787     std::string uri;
788     WallpaperChanged(wallpaperType, wallpaperData.resourceType, uri);
789     return true;
790 }
791 
SetVideo(int32_t fd,int32_t wallpaperType,int32_t length)792 ErrorCode WallpaperService::SetVideo(int32_t fd, int32_t wallpaperType, int32_t length)
793 {
794     if (!IsSystemApp()) {
795         HILOG_ERROR("current app is not SystemApp");
796         return E_NOT_SYSTEM_APP;
797     }
798     StartAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
799     ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, VIDEO);
800     FinishAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
801     return wallpaperErrorCode;
802 }
803 
SetCustomWallpaper(const std::string & uri,int32_t type)804 ErrorCode WallpaperService::SetCustomWallpaper(const std::string &uri, int32_t type)
805 {
806     if (!IsSystemApp()) {
807         HILOG_ERROR("current app is not SystemApp");
808         return E_NOT_SYSTEM_APP;
809     }
810     if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
811         HILOG_INFO("SetWallpaper no set permission!");
812         return E_NO_PERMISSION;
813     }
814     if (type != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) && type != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
815         return E_PARAMETERS_INVALID;
816     }
817     StartAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
818     int32_t userId = QueryActiveUserId();
819     WallpaperType wallpaperType = static_cast<WallpaperType>(type);
820     WallpaperData wallpaperData;
821     if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
822         HILOG_ERROR("GetWallpaper data failed!");
823         return E_DEAL_FAILED;
824     }
825     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
826         HILOG_ERROR("SceneBoard is not Enabled");
827         return E_NO_PERMISSION;
828     }
829     wallpaperData.resourceType = PACKAGE;
830     wallpaperData.wallpaperId = MakeWallpaperIdLocked();
831     if (wallpaperType == WALLPAPER_SYSTEM) {
832         systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
833     } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
834         lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
835     }
836     if (!SaveWallpaperState(userId, wallpaperType)) {
837         HILOG_ERROR("Save wallpaper state failed!");
838     }
839     if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
840         HILOG_ERROR("Send wallpaper state failed!");
841         return E_DEAL_FAILED;
842     }
843     FinishAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
844     return E_OK;
845 }
846 
ReporterUsageTimeStatistic()847 void WallpaperService::ReporterUsageTimeStatistic()
848 {
849     int32_t uid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
850     std::string bundleName;
851     bool bRet = GetBundleNameByUid(uid, bundleName);
852     if (!bRet) {
853         bundleName = OHOS_WALLPAPER_BUNDLE_NAME;
854     }
855     UsageTimeStat timeStat;
856     timeStat.packagesName = bundleName;
857     timeStat.startTime = time(nullptr);
858     StatisticReporter::ReportUsageTimeStatistic(uid, timeStat);
859 }
860 
GetPixelMap(int32_t wallpaperType,IWallpaperService::FdInfo & fdInfo)861 ErrorCode WallpaperService::GetPixelMap(int32_t wallpaperType, IWallpaperService::FdInfo &fdInfo)
862 {
863     HILOG_INFO("WallpaperService::getPixelMap start ");
864     if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
865         HILOG_INFO("GetPixelMap no get permission!");
866         return E_NO_PERMISSION;
867     }
868     if (!IsSystemApp()) {
869         HILOG_INFO("CallingApp is not SystemApp");
870         return E_NOT_SYSTEM_APP;
871     }
872     if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) &&
873         wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
874         return E_PARAMETERS_INVALID;
875     }
876     auto type = static_cast<WallpaperType>(wallpaperType);
877     int32_t userId = QueryActiveUserId();
878     HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
879     // current user's wallpaper is live video, not image
880     WallpaperResourceType resType = GetResType(userId, type);
881     if (resType != PICTURE && resType != DEFAULT) {
882         HILOG_ERROR("Current user's wallpaper is live video, not image");
883         fdInfo.size = 0; // 0: empty file size
884         fdInfo.fd = -1;  // -1: invalid file description
885         return E_OK;
886     }
887     ErrorCode ret = GetImageSize(userId, type, fdInfo.size);
888     if (ret != E_OK) {
889         HILOG_ERROR("GetImageSize failed");
890         return ret;
891     }
892     ret = GetImageFd(userId, type, fdInfo.fd);
893     if (ret != E_OK) {
894         HILOG_ERROR("GetImageFd failed");
895         return ret;
896     }
897     return E_OK;
898 }
899 
GetPixelMapV9(int32_t wallpaperType,IWallpaperService::FdInfo & fdInfo)900 ErrorCode WallpaperService::GetPixelMapV9(int32_t wallpaperType, IWallpaperService::FdInfo &fdInfo)
901 {
902     return GetPixelMap(wallpaperType, fdInfo);
903 }
904 
GetWallpaperId(int32_t wallpaperType)905 int32_t WallpaperService::GetWallpaperId(int32_t wallpaperType)
906 {
907     HILOG_INFO("WallpaperService::GetWallpaperId --> start ");
908     int32_t iWallpaperId = -1;
909     int32_t userId = QueryActiveUserId();
910     HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
911     if (wallpaperType == WALLPAPER_LOCKSCREEN) {
912         auto iterator = lockWallpaperMap_.Find(userId);
913         if (iterator.first) {
914             iWallpaperId = iterator.second.wallpaperId;
915         }
916     } else if (wallpaperType == WALLPAPER_SYSTEM) {
917         auto iterator = systemWallpaperMap_.Find(userId);
918         if (iterator.first) {
919             iWallpaperId = iterator.second.wallpaperId;
920         }
921     }
922     HILOG_INFO("WallpaperService::GetWallpaperId --> end ID[%{public}d]", iWallpaperId);
923     return iWallpaperId;
924 }
925 
IsChangePermitted()926 bool WallpaperService::IsChangePermitted()
927 {
928     HILOG_INFO("IsChangePermitted wallpaper Start!");
929     bool bFlag = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
930     return bFlag;
931 }
932 
IsOperationAllowed()933 bool WallpaperService::IsOperationAllowed()
934 {
935     HILOG_INFO("IsOperationAllowed wallpaper Start!");
936     bool bFlag = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
937     return bFlag;
938 }
939 
ResetWallpaper(int32_t wallpaperType)940 ErrorCode WallpaperService::ResetWallpaper(int32_t wallpaperType)
941 {
942     HILOG_INFO("reset wallpaper Start!");
943     bool permissionSet = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
944     if (!permissionSet) {
945         HILOG_INFO("reset wallpaper no set permission!");
946         return E_NO_PERMISSION;
947     }
948 
949     if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) &&
950         wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
951         HILOG_INFO("wallpaperType = %{public}d type not support ", wallpaperType);
952         return E_PARAMETERS_INVALID;
953     }
954     WallpaperType type = static_cast<WallpaperType>(wallpaperType);
955     int32_t userId = QueryActiveUserId();
956     HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
957     if (!CheckUserPermissionById(userId)) {
958         return E_USER_IDENTITY_ERROR;
959     }
960     ErrorCode wallpaperErrorCode = SetDefaultDataForWallpaper(userId, type);
961     HILOG_INFO(" Set default data result[%{public}d]", wallpaperErrorCode);
962     return wallpaperErrorCode;
963 }
964 
ResetWallpaperV9(int32_t wallpaperType)965 ErrorCode WallpaperService::ResetWallpaperV9(int32_t wallpaperType)
966 {
967     if (!IsSystemApp()) {
968         HILOG_INFO("CallingApp is not SystemApp");
969         return E_NOT_SYSTEM_APP;
970     }
971     return ResetWallpaper(wallpaperType);
972 }
973 
SetDefaultDataForWallpaper(int32_t userId,WallpaperType wallpaperType)974 ErrorCode WallpaperService::SetDefaultDataForWallpaper(int32_t userId, WallpaperType wallpaperType)
975 {
976     WallpaperData wallpaperData;
977     if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
978         return E_DEAL_FAILED;
979     }
980     if (!RestoreUserResources(wallpaperData, wallpaperType)) {
981         HILOG_ERROR("RestoreUserResources error");
982         return E_DEAL_FAILED;
983     }
984     wallpaperData.wallpaperId = DEFAULT_WALLPAPER_ID;
985     wallpaperData.allowBackup = true;
986     if (wallpaperType == WALLPAPER_LOCKSCREEN) {
987         lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
988     } else if (wallpaperType == WALLPAPER_SYSTEM) {
989         systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
990     }
991     if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
992         HILOG_ERROR("Send wallpaper state failed!");
993         return E_DEAL_FAILED;
994     }
995     SaveColor(userId, wallpaperType);
996     return E_OK;
997 }
998 
On(const std::string & type,sptr<IWallpaperEventListener> listener)999 ErrorCode WallpaperService::On(const std::string &type, sptr<IWallpaperEventListener> listener)
1000 {
1001     HILOG_DEBUG("WallpaperService::On in");
1002     if (listener == nullptr) {
1003         HILOG_ERROR("WallpaperService::On listener is null");
1004         return E_DEAL_FAILED;
1005     }
1006     if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1007         HILOG_ERROR("current app is not SystemApp");
1008         return E_NOT_SYSTEM_APP;
1009     }
1010     std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1011     wallpaperEventMap_[type].insert_or_assign(IPCSkeleton::GetCallingTokenID(), listener);
1012     HILOG_DEBUG("WallpaperService::On out");
1013     return E_OK;
1014 }
1015 
Off(const std::string & type,sptr<IWallpaperEventListener> listener)1016 ErrorCode WallpaperService::Off(const std::string &type, sptr<IWallpaperEventListener> listener)
1017 {
1018     HILOG_DEBUG("WallpaperService::Off in");
1019     (void)listener;
1020     if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1021         HILOG_ERROR("current app is not SystemApp");
1022         return E_NOT_SYSTEM_APP;
1023     }
1024     std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1025     auto iter = wallpaperEventMap_.find(type);
1026     if (iter != wallpaperEventMap_.end()) {
1027         auto it = iter->second.find(IPCSkeleton::GetCallingTokenID());
1028         if (it != iter->second.end()) {
1029             it->second = nullptr;
1030             iter->second.erase(it);
1031         }
1032     }
1033     HILOG_DEBUG("WallpaperService::Off out");
1034     return E_OK;
1035 }
1036 
RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)1037 bool WallpaperService::RegisterWallpaperCallback(const sptr<IWallpaperCallback> callback)
1038 {
1039     HILOG_INFO("  WallpaperService::RegisterWallpaperCallback");
1040     callbackProxy_ = callback;
1041     return true;
1042 }
1043 
GetWallpaperSafeLocked(int32_t userId,WallpaperType wallpaperType,WallpaperData & wallpaperData)1044 bool WallpaperService::GetWallpaperSafeLocked(int32_t userId, WallpaperType wallpaperType, WallpaperData &wallpaperData)
1045 {
1046     HILOG_INFO("function start.");
1047     auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1048                                                       : lockWallpaperMap_.Find(userId);
1049     if (!iterator.first) {
1050         HILOG_INFO(" No Lock wallpaper?  Not tracking for lock-only ");
1051         LoadSettingsLocked(userId, true);
1052         iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1053                                                      : lockWallpaperMap_.Find(userId);
1054         if (!iterator.first) {
1055             HILOG_ERROR("Fail to get wallpaper data");
1056             return false;
1057         }
1058     }
1059     wallpaperData = iterator.second;
1060     return true;
1061 }
1062 
ClearWallpaperLocked(int32_t userId,WallpaperType wallpaperType)1063 void WallpaperService::ClearWallpaperLocked(int32_t userId, WallpaperType wallpaperType)
1064 {
1065     HILOG_INFO("Clear wallpaper Start!");
1066     auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1067                                                       : lockWallpaperMap_.Find(userId);
1068     if (!iterator.first) {
1069         HILOG_INFO("Lock wallpaper already cleared");
1070         return;
1071     }
1072     if (!iterator.second.wallpaperFile.empty() || !iterator.second.liveWallpaperFile.empty()) {
1073         if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1074             lockWallpaperMap_.Erase(userId);
1075         } else if (wallpaperType == WALLPAPER_SYSTEM) {
1076             systemWallpaperMap_.Erase(userId);
1077         }
1078     }
1079     HILOG_INFO("Clear wallpaper End!");
1080 }
1081 
CheckCallingPermission(const std::string & permissionName)1082 bool WallpaperService::CheckCallingPermission(const std::string &permissionName)
1083 {
1084     bool bflag = false;
1085     int32_t result;
1086     AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1087     auto tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
1088     if (tokenType == TOKEN_NATIVE || tokenType == TOKEN_SHELL || tokenType == TOKEN_HAP) {
1089         result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
1090     } else {
1091         HILOG_INFO("Check permission tokenId illegal");
1092         return false;
1093     }
1094     if (result == TypePermissionState::PERMISSION_GRANTED) {
1095         bflag = true;
1096     } else {
1097         bflag = false;
1098     }
1099     HILOG_INFO("Check permission result %{public}d", result);
1100     return bflag;
1101 }
1102 
GetBundleNameByUid(std::int32_t uid,std::string & bname)1103 bool WallpaperService::GetBundleNameByUid(std::int32_t uid, std::string &bname)
1104 {
1105     sptr<ISystemAbilityManager> systemMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1106     if (systemMgr == nullptr) {
1107         HILOG_ERROR("Fail to get system ability mgr");
1108         return false;
1109     }
1110 
1111     sptr<IRemoteObject> remoteObject = systemMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1112     if (remoteObject == nullptr) {
1113         HILOG_ERROR("Fail to get bundle manager proxy");
1114         return false;
1115     }
1116 
1117     sptr<OHOS::AppExecFwk::IBundleMgr> bundleMgrProxy = iface_cast<OHOS::AppExecFwk::IBundleMgr>(remoteObject);
1118     if (bundleMgrProxy == nullptr) {
1119         HILOG_ERROR("Bundle mgr proxy is nullptr");
1120         return false;
1121     }
1122 
1123     ErrCode errCode = bundleMgrProxy->GetNameForUid(uid, bname);
1124     if (errCode != ERR_OK) {
1125         HILOG_ERROR("Get bundle name failed errcode:%{public}d", errCode);
1126         return false;
1127     }
1128     HILOG_INFO("Get bundle name is %{public}s", bname.c_str());
1129     return true;
1130 }
1131 
ReporterFault(FaultType faultType,FaultCode faultCode)1132 void WallpaperService::ReporterFault(FaultType faultType, FaultCode faultCode)
1133 {
1134     FaultMsg msg;
1135     msg.faultType = faultType;
1136     msg.errorCode = faultCode;
1137     ReportStatus nRet;
1138     if (faultType == FaultType::SERVICE_FAULT) {
1139         msg.moduleName = "WallpaperService";
1140         nRet = FaultReporter::ReportServiceFault(msg);
1141     } else {
1142         nRet = FaultReporter::ReportRuntimeFault(msg);
1143     }
1144 
1145     if (nRet == ReportStatus::SUCCESS) {
1146         HILOG_INFO("ReporterFault success");
1147     } else {
1148         HILOG_ERROR("ReporterFault failed");
1149     }
1150 }
1151 
Dump(int32_t fd,const std::vector<std::u16string> & args)1152 int32_t WallpaperService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1153 {
1154     int32_t uid = static_cast<int32_t>(IPCSkeleton::GetCallingUid());
1155     const int32_t maxUid = 10000;
1156     if (uid > maxUid) {
1157         AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1158         auto tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
1159         if (tokenType != TOKEN_NATIVE && tokenType != TOKEN_SHELL) {
1160             return 1;
1161         }
1162     }
1163 
1164     std::vector<std::string> argsStr;
1165     for (auto item : args) {
1166         argsStr.emplace_back(Str16ToStr8(item));
1167     }
1168 
1169     if (DumpHelper::GetInstance().Dispatch(fd, argsStr)) {
1170         HILOG_ERROR("DumpHelper Dispatch failed");
1171         return 0;
1172     }
1173     return 1;
1174 }
1175 
ConnectExtensionAbility()1176 bool WallpaperService::ConnectExtensionAbility()
1177 {
1178     HILOG_DEBUG("ConnectAdapter");
1179     MemoryGuard cacheGuard;
1180     AAFwk::Want want;
1181     want.SetElementName(OHOS_WALLPAPER_BUNDLE_NAME, "WallpaperExtAbility");
1182     ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1183     if (errCode != ERR_OK) {
1184         HILOG_ERROR("connect ability server failed errCode=%{public}d", errCode);
1185         return false;
1186     }
1187     if (connection_ == nullptr) {
1188         connection_ = new WallpaperExtensionAbilityConnection(*this);
1189     }
1190     auto ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectExtensionAbility(want, connection_, DEFAULT_VALUE);
1191     HILOG_INFO("ConnectExtensionAbility errCode=%{public}d", ret);
1192     return ret;
1193 }
1194 
IsSystemApp()1195 bool WallpaperService::IsSystemApp()
1196 {
1197     HILOG_INFO("IsSystemApp start");
1198     uint64_t tokenId = IPCSkeleton::GetCallingFullTokenID();
1199     return TokenIdKit::IsSystemAppByFullTokenID(tokenId);
1200 }
1201 
GetImageFd(int32_t userId,WallpaperType wallpaperType,int32_t & fd)1202 ErrorCode WallpaperService::GetImageFd(int32_t userId, WallpaperType wallpaperType, int32_t &fd)
1203 {
1204     HILOG_INFO("WallpaperService::GetImageFd start ");
1205     std::string filePathName;
1206     if (!GetFileNameFromMap(userId, wallpaperType, filePathName)) {
1207         return E_DEAL_FAILED;
1208     }
1209     if (GetResType(userId, wallpaperType) == WallpaperResourceType::PACKAGE) {
1210         HILOG_INFO("The current wallpaper is a custom wallpaper");
1211         return E_OK;
1212     }
1213     {
1214         std::lock_guard<std::mutex> lock(mtx_);
1215         fd = open(filePathName.c_str(), O_RDONLY, S_IREAD);
1216     }
1217     if (fd < 0) {
1218         HILOG_ERROR("Open file failed, errno %{public}d", errno);
1219         ReporterFault(FaultType::LOAD_WALLPAPER_FAULT, FaultCode::RF_FD_INPUT_FAILED);
1220         return E_DEAL_FAILED;
1221     }
1222     HILOG_INFO("fd = %{public}d", fd);
1223     return E_OK;
1224 }
1225 
GetImageSize(int32_t userId,WallpaperType wallpaperType,int32_t & size)1226 ErrorCode WallpaperService::GetImageSize(int32_t userId, WallpaperType wallpaperType, int32_t &size)
1227 {
1228     HILOG_INFO("WallpaperService::GetImageSize start ");
1229     std::string filePathName;
1230     HILOG_INFO("userId = %{public}d", userId);
1231     if (!GetPictureFileName(userId, wallpaperType, filePathName)) {
1232         return E_DEAL_FAILED;
1233     }
1234 
1235     if (!OHOS::FileExists(filePathName)) {
1236         HILOG_ERROR("file is not exist!");
1237         return E_NOT_FOUND;
1238     }
1239     std::lock_guard<std::mutex> lock(mtx_);
1240     FILE *fd = fopen(filePathName.c_str(), "rb");
1241     if (fd == nullptr) {
1242         HILOG_ERROR("fopen file failed, errno %{public}d", errno);
1243         return E_FILE_ERROR;
1244     }
1245     int32_t fend = fseek(fd, 0, SEEK_END);
1246     size = ftell(fd);
1247     int32_t fset = fseek(fd, 0, SEEK_SET);
1248     if (size <= 0 || fend != 0 || fset != 0) {
1249         HILOG_ERROR("ftell file failed or fseek file failed, errno %{public}d", errno);
1250         fclose(fd);
1251         return E_FILE_ERROR;
1252     }
1253     fclose(fd);
1254     return E_OK;
1255 }
1256 
BlockRetry(int64_t interval,uint32_t maxRetryTimes,std::function<bool ()> function)1257 bool WallpaperService::BlockRetry(int64_t interval, uint32_t maxRetryTimes, std::function<bool()> function)
1258 {
1259     uint32_t times = 0;
1260     bool ret = false;
1261     do {
1262         times++;
1263         ret = function();
1264         if (ret) {
1265             break;
1266         }
1267         std::this_thread::sleep_for(std::chrono::milliseconds(interval));
1268         HILOG_INFO("function() is: %d", ret);
1269     } while (times < maxRetryTimes);
1270     HILOG_INFO("retry times: %d", times);
1271     return ret;
1272 }
1273 
QueryActiveUserId()1274 int32_t WallpaperService::QueryActiveUserId()
1275 {
1276     std::vector<int32_t> ids;
1277     ErrCode errCode = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
1278     if (errCode != ERR_OK || ids.empty()) {
1279         HILOG_ERROR("Query active userid failed, errCode: %{public}d, ", errCode);
1280         return DEFAULT_USER_ID;
1281     }
1282     return ids[0];
1283 }
1284 
CheckUserPermissionById(int32_t userId)1285 bool WallpaperService::CheckUserPermissionById(int32_t userId)
1286 {
1287     OsAccountInfo osAccountInfo;
1288     ErrCode errCode = OsAccountManager::QueryOsAccountById(userId, osAccountInfo);
1289     if (errCode != ERR_OK) {
1290         HILOG_ERROR("Query os account info failed, errCode: %{public}d, ", errCode);
1291         return false;
1292     }
1293     HILOG_INFO("osAccountInfo GetType: %{public}d", static_cast<int32_t>(osAccountInfo.GetType()));
1294     if (osAccountInfo.GetType() == OsAccountType::GUEST) {
1295         HILOG_ERROR("The guest does not have permissions");
1296         return false;
1297     }
1298     return true;
1299 }
1300 
SetWallpaper(int32_t fd,int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1301 ErrorCode WallpaperService::SetWallpaper(int32_t fd, int32_t wallpaperType, int32_t length,
1302     WallpaperResourceType resourceType)
1303 {
1304     ErrorCode errCode = CheckValid(wallpaperType, length, resourceType);
1305     if (errCode != E_OK) {
1306         return errCode;
1307     }
1308     std::string uri = wallpaperTmpFullPath_;
1309     char *paperBuf = new (std::nothrow) char[length]();
1310     if (paperBuf == nullptr) {
1311         return E_NO_MEMORY;
1312     }
1313     std::lock_guard<std::mutex> lock(mtx_);
1314     if (read(fd, paperBuf, length) <= 0) {
1315         HILOG_ERROR("read fd failed");
1316         delete[] paperBuf;
1317         return E_DEAL_FAILED;
1318     }
1319     mode_t mode = S_IRUSR | S_IWUSR;
1320     int32_t fdw = open(uri.c_str(), O_WRONLY | O_CREAT, mode);
1321     if (fdw < 0) {
1322         HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1323         delete[] paperBuf;
1324         return E_DEAL_FAILED;
1325     }
1326     if (write(fdw, paperBuf, length) <= 0) {
1327         HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1328         ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1329         delete[] paperBuf;
1330         close(fdw);
1331         return E_DEAL_FAILED;
1332     }
1333     delete[] paperBuf;
1334     close(fdw);
1335     WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1336     int32_t userId = QueryActiveUserId();
1337     HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1338     if (!CheckUserPermissionById(userId)) {
1339         return E_USER_IDENTITY_ERROR;
1340     }
1341     ErrorCode wallpaperErrorCode = SetWallpaperBackupData(userId, resourceType, uri, type);
1342     if (resourceType == PICTURE) {
1343         SaveColor(userId, type);
1344     }
1345     return wallpaperErrorCode;
1346 }
1347 
OnColorsChange(WallpaperType wallpaperType,const ColorManager::Color & color)1348 void WallpaperService::OnColorsChange(WallpaperType wallpaperType, const ColorManager::Color &color)
1349 {
1350     std::vector<uint64_t> colors;
1351     if (wallpaperType == WALLPAPER_SYSTEM && !CompareColor(systemWallpaperColor_, color)) {
1352         systemWallpaperColor_ = color.PackValue();
1353         colors.emplace_back(systemWallpaperColor_);
1354         NotifyColorChange(colors, WALLPAPER_SYSTEM);
1355     } else if (wallpaperType == WALLPAPER_LOCKSCREEN && !CompareColor(lockWallpaperColor_, color)) {
1356         lockWallpaperColor_ = color.PackValue();
1357         colors.emplace_back(lockWallpaperColor_);
1358         NotifyColorChange(colors, WALLPAPER_LOCKSCREEN);
1359     }
1360 }
1361 
CheckValid(int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1362 ErrorCode WallpaperService::CheckValid(int32_t wallpaperType, int32_t length, WallpaperResourceType resourceType)
1363 {
1364     if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
1365         HILOG_INFO("SetWallpaper no set permission!");
1366         return E_NO_PERMISSION;
1367     }
1368     if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) &&
1369         wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
1370         return E_PARAMETERS_INVALID;
1371     }
1372 
1373     int maxLength = resourceType == VIDEO ? MAX_VIDEO_SIZE : FOO_MAX_LEN;
1374     if (length <= 0 || length > maxLength) {
1375         return E_PARAMETERS_INVALID;
1376     }
1377     return E_OK;
1378 }
1379 
WallpaperChanged(WallpaperType wallpaperType,WallpaperResourceType resType,const std::string & uri)1380 bool WallpaperService::WallpaperChanged(WallpaperType wallpaperType, WallpaperResourceType resType,
1381     const std::string &uri)
1382 {
1383     std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1384     auto it = wallpaperEventMap_.find(WALLPAPER_CHANGE);
1385     if (it != wallpaperEventMap_.end()) {
1386         for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1387             if (iter->second == nullptr) {
1388                 continue;
1389             }
1390             iter->second->OnWallpaperChange(wallpaperType, resType, uri);
1391         }
1392         return true;
1393     }
1394     return false;
1395 }
1396 
NotifyColorChange(const std::vector<uint64_t> & colors,const WallpaperType & wallpaperType)1397 void WallpaperService::NotifyColorChange(const std::vector<uint64_t> &colors, const WallpaperType &wallpaperType)
1398 {
1399     std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1400     auto it = wallpaperEventMap_.find(COLOR_CHANGE);
1401     if (it != wallpaperEventMap_.end()) {
1402         for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1403             if (iter->second == nullptr) {
1404                 continue;
1405             }
1406             iter->second->OnColorsChange(colors, wallpaperType);
1407         }
1408     }
1409 }
1410 
SaveWallpaperState(int32_t userId,WallpaperType wallpaperType)1411 bool WallpaperService::SaveWallpaperState(int32_t userId, WallpaperType wallpaperType)
1412 {
1413     WallpaperData systemData;
1414     WallpaperData lockScreenData;
1415     if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData) ||
1416         !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1417         return false;
1418     }
1419     nlohmann::json root;
1420     root[SYSTEM_RES_TYPE] = static_cast<int32_t>(systemData.resourceType);
1421     root[LOCKSCREEN_RES_TYPE] = static_cast<int32_t>(lockScreenData.resourceType);
1422     std::string json = root.dump();
1423     if (json.empty()) {
1424         HILOG_ERROR("write user config file failed. because json content is empty.");
1425         return false;
1426     }
1427 
1428     std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1429     mode_t mode = S_IRUSR | S_IWUSR;
1430     int fd = open(userPath.c_str(), O_CREAT | O_WRONLY | O_SYNC, mode);
1431     if (fd <= 0) {
1432         HILOG_ERROR("open user config file failed.");
1433         return false;
1434     }
1435     ssize_t size = write(fd, json.c_str(), json.size());
1436     if (size <= 0) {
1437         HILOG_ERROR("write user config file failed.");
1438         close(fd);
1439         return false;
1440     }
1441     close(fd);
1442     return true;
1443 }
1444 
LoadWallpaperState()1445 void WallpaperService::LoadWallpaperState()
1446 {
1447     int32_t userId = QueryActiveUserId();
1448     std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1449     int fd = open(userPath.c_str(), O_RDONLY, S_IREAD);
1450     if (fd <= 0) {
1451         HILOG_ERROR("open user config file failed.");
1452         return;
1453     }
1454     const size_t len = 255;
1455     char buf[len] = { 0 };
1456     ssize_t size = read(fd, buf, len);
1457     if (size <= 0) {
1458         HILOG_ERROR("read user config file failed.");
1459         close(fd);
1460         return;
1461     }
1462     close(fd);
1463 
1464     if (buf[0] == '\0') {
1465         return;
1466     }
1467     WallpaperData systemData;
1468     WallpaperData lockScreenData;
1469     if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData) ||
1470         !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1471         return;
1472     }
1473     auto root = nlohmann::json::parse(buf);
1474     if (root.contains(SYSTEM_RES_TYPE)) {
1475         systemData.resourceType = static_cast<WallpaperResourceType>(root[SYSTEM_RES_TYPE].get<int>());
1476     }
1477     if (root.contains(LOCKSCREEN_RES_TYPE)) {
1478         lockScreenData.resourceType = static_cast<WallpaperResourceType>(root[LOCKSCREEN_RES_TYPE].get<int>());
1479     }
1480 }
1481 
GrantUriPermission(const std::string & path,const std::string & bundleName)1482 int32_t WallpaperService::GrantUriPermission(const std::string &path, const std::string &bundleName)
1483 {
1484     Uri uri(path);
1485     return AAFwk::UriPermissionManagerClient::GetInstance().GrantUriPermission(uri,
1486         AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION, bundleName, 0);
1487 }
1488 } // namespace WallpaperMgrService
1489 } // namespace OHOS