1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "context_deal.h"
17
18 #include <regex>
19
20 #include "ability_constants.h"
21 #include "ability_manager_client.h"
22 #include "ability_manager_interface.h"
23 #include "app_context.h"
24 #include "directory_ex.h"
25 #include "file_ex.h"
26 #include "hilog_wrapper.h"
27 #include "iservice_registry.h"
28 #include "os_account_manager_wrapper.h"
29 #include "sys_mgr_client.h"
30 #include "system_ability_definition.h"
31
32 #define MODE 0771
33 namespace OHOS {
34 namespace AppExecFwk {
35 using namespace OHOS::AbilityRuntime::Constants;
36
37 const std::string ContextDeal::CONTEXT_DEAL_FILE_SEPARATOR("/");
38 const std::string ContextDeal::CONTEXT_DEAL_CODE_CACHE("code_cache");
39 const std::string ContextDeal::CONTEXT_DEAL_Files("files");
40 const std::string ContextDeal::CONTEXT_DEAL_NO_BACKUP_Files("no_backup");
41 const std::string ContextDeal::CONTEXT_DEAL_DIRNAME("preferences");
42 const int64_t ContextDeal::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001);
43 const std::string ContextDeal::CONTEXT_DISTRIBUTED_BASE_BEFORE("/mnt/hmdfs/");
44 const std::string ContextDeal::CONTEXT_DISTRIBUTED_BASE_MIDDLE("/device_view/local/data/");
45 const std::string ContextDeal::CONTEXT_DISTRIBUTED("distributedfiles");
46 const std::string ContextDeal::CONTEXT_DATA_STORAGE("/data/storage/");
47 const std::string ContextDeal::CONTEXT_ELS[] = {"el1", "el2"};
48 const std::string ContextDeal::CONTEXT_DEAL_DATA_APP("/data/app/");
49 const std::string ContextDeal::CONTEXT_DEAL_BASE("base");
50 const std::string ContextDeal::CONTEXT_DEAL_DATABASE("database");
51 const std::string ContextDeal::CONTEXT_DEAL_PREFERENCES("preferences");
52 const std::string ContextDeal::CONTEXT_DEAL_DISTRIBUTEDFILES("distributedfiles");
53 const std::string ContextDeal::CONTEXT_DEAL_CACHE("cache");
54 const std::string ContextDeal::CONTEXT_DEAL_DATA("data");
55
ContextDeal(bool isCreateBySystemApp)56 ContextDeal::ContextDeal(bool isCreateBySystemApp) : isCreateBySystemApp_(isCreateBySystemApp)
57 {}
58
59 /**
60 * Called when getting the ProcessInfo
61 *
62 * @return ProcessInfo
63 */
GetProcessInfo() const64 std::shared_ptr<ProcessInfo> ContextDeal::GetProcessInfo() const
65 {
66 return processInfo_;
67 }
68
69 /**
70 * Called when setting the ProcessInfo
71 *
72 * @param info ProcessInfo instance
73 */
SetProcessInfo(const std::shared_ptr<ProcessInfo> & info)74 void ContextDeal::SetProcessInfo(const std::shared_ptr<ProcessInfo> &info)
75 {
76 HILOG_DEBUG("ContextDeal::SetProcessInfo");
77 if (info == nullptr) {
78 HILOG_ERROR("ContextDeal::SetProcessInfo failed, info is empty");
79 return;
80 }
81 processInfo_ = info;
82 }
83
84 /**
85 * @brief Obtains information about the current application. The returned application information includes basic
86 * information such as the application name and application permissions.
87 *
88 * @return Returns the ApplicationInfo for the current application.
89 */
GetApplicationInfo() const90 std::shared_ptr<ApplicationInfo> ContextDeal::GetApplicationInfo() const
91 {
92 return applicationInfo_;
93 }
94
95 /**
96 * @brief Set ApplicationInfo
97 *
98 * @param info ApplicationInfo instance.
99 */
SetApplicationInfo(const std::shared_ptr<ApplicationInfo> & info)100 void ContextDeal::SetApplicationInfo(const std::shared_ptr<ApplicationInfo> &info)
101 {
102 HILOG_DEBUG("ContextDeal::SetApplicationInfo");
103 if (info == nullptr) {
104 HILOG_ERROR("ContextDeal::SetApplicationInfo failed, info is empty");
105 return;
106 }
107 applicationInfo_ = info;
108 }
109
110 /**
111 * @brief Obtains the Context object of the application.
112 *
113 * @return Returns the Context object of the application.
114 */
GetApplicationContext() const115 std::shared_ptr<Context> ContextDeal::GetApplicationContext() const
116 {
117 return appContext_;
118 }
119
120 /**
121 * @brief Set ApplicationContext
122 *
123 * @param context ApplicationContext instance.
124 */
SetApplicationContext(const std::shared_ptr<Context> & context)125 void ContextDeal::SetApplicationContext(const std::shared_ptr<Context> &context)
126 {
127 HILOG_DEBUG("ContextDeal::SetApplicationContext");
128 if (context == nullptr) {
129 HILOG_ERROR("ContextDeal::SetApplicationContext failed, context is empty");
130 return;
131 }
132 appContext_ = context;
133 }
134
135 /**
136 * @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
137 * source code, and configuration files of a module.
138 *
139 * @return Returns the path of the package file.
140 */
GetBundleCodePath()141 std::string ContextDeal::GetBundleCodePath()
142 {
143 if (applicationInfo_ == nullptr) {
144 return "";
145 }
146
147 std::string dir;
148 if (isCreateBySystemApp_) {
149 dir = std::regex_replace(applicationInfo_->codePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
150 } else {
151 dir = LOCAL_CODE_PATH;
152 }
153
154 return dir;
155 }
156
157 /**
158 * @brief SetBundleCodePath
159 *
160 * @param Returns string path
161 */
SetBundleCodePath(std::string & path)162 void ContextDeal::SetBundleCodePath(std::string &path)
163 {
164 path_ = path;
165 }
166
167 /**
168 * @brief Obtains information about the current ability.
169 * The returned information includes the class name, bundle name, and other information about the current ability.
170 *
171 * @return Returns the AbilityInfo object for the current ability.
172 */
GetAbilityInfo()173 const std::shared_ptr<AbilityInfo> ContextDeal::GetAbilityInfo()
174 {
175 return abilityInfo_;
176 }
177
178 /**
179 * @brief Set AbilityInfo
180 *
181 * @param info AbilityInfo instance.
182 */
SetAbilityInfo(const std::shared_ptr<AbilityInfo> & info)183 void ContextDeal::SetAbilityInfo(const std::shared_ptr<AbilityInfo> &info)
184 {
185 HILOG_DEBUG("ContextDeal::SetAbilityInfo");
186 if (info == nullptr) {
187 HILOG_ERROR("ContextDeal::SetAbilityInfo failed, info is empty");
188 return;
189 }
190 abilityInfo_ = info;
191 }
192
193 /**
194 * @brief Obtains the Context object of the ability.
195 *
196 * @return Returns the Context object of the ability.
197 */
GetContext()198 std::shared_ptr<Context> ContextDeal::GetContext()
199 {
200 return abilityContext_;
201 }
202
203 /**
204 * @brief Set Ability context
205 *
206 * @param context Ability object
207 */
SetContext(const std::shared_ptr<Context> & context)208 void ContextDeal::SetContext(const std::shared_ptr<Context> &context)
209 {
210 HILOG_DEBUG("ContextDeal::SetContext");
211 if (context == nullptr) {
212 HILOG_ERROR("ContextDeal::SetContext failed, context is empty");
213 return;
214 }
215 abilityContext_ = context;
216 }
217
218 /**
219 * @brief Obtains an IBundleMgr instance.
220 * You can use this instance to obtain information about the application bundle.
221 *
222 * @return Returns an IBundleMgr instance.
223 */
GetBundleManager() const224 sptr<IBundleMgr> ContextDeal::GetBundleManager() const
225 {
226 HILOG_DEBUG("ContextDeal::GetBundleManager");
227 auto bundleObj =
228 OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
229 if (bundleObj == nullptr) {
230 HILOG_ERROR("failed to get bundle manager service");
231 return nullptr;
232 }
233 sptr<IBundleMgr> bms = iface_cast<IBundleMgr>(bundleObj);
234 return bms;
235 }
236
237 /**
238 * @brief Obtains a resource manager.
239 *
240 * @return Returns a ResourceManager object.
241 */
GetResourceManager() const242 std::shared_ptr<Global::Resource::ResourceManager> ContextDeal::GetResourceManager() const
243 {
244 return resourceManager_;
245 }
246
247 /**
248 * @brief Set Profile instance.
249 *
250 * @param Profile instance.
251 */
SetProfile(const std::shared_ptr<Profile> & profile)252 void ContextDeal::SetProfile(const std::shared_ptr<Profile> &profile)
253 {
254 HILOG_DEBUG("ContextDeal::SetProfile");
255 if (profile == nullptr) {
256 HILOG_ERROR("ContextDeal::SetProfile failed, profile is nullptr");
257 return;
258 }
259 profile_ = profile;
260 }
261
262 /**
263 * @brief Obtains an Profile instance.
264 *
265 * @return Returns an Profile instance.
266 */
GetProfile() const267 std::shared_ptr<Profile> ContextDeal::GetProfile() const
268 {
269 return profile_;
270 }
271
272 /**
273 * @brief Deletes the specified private file associated with the application.
274 *
275 * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators.
276 *
277 * @return Returns true if the file is deleted successfully; returns false otherwise.
278 */
DeleteFile(const std::string & fileName)279 bool ContextDeal::DeleteFile(const std::string &fileName)
280 {
281 HILOG_DEBUG("ContextDeal::DeleteFile begin");
282 std::string path = GetDataDir() + CONTEXT_DEAL_FILE_SEPARATOR + fileName;
283 bool ret = OHOS::RemoveFile(path);
284 HILOG_DEBUG("ContextDeal::DeleteFile end");
285 return ret;
286 }
287
288 /**
289 * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template.
290 * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE
291 * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE
292 * template. The current ability itself can be destroyed by calling the terminateAbility() method.
293 *
294 * @param want Indicates the Want containing information about the ability to destroy.
295 *
296 * @return Returns true if the ability is destroyed successfully; returns false otherwise.
297 */
StopAbility(const AAFwk::Want & want)298 bool ContextDeal::StopAbility(const AAFwk::Want &want)
299 {
300 return false;
301 }
302
303 /**
304 * @brief Obtains the application-specific cache directory on the device's internal storage. The system
305 * automatically deletes files from the cache directory if disk space is required elsewhere on the device.
306 * Older files are always deleted first.
307 *
308 * @return Returns the application-specific cache directory.
309 */
GetCacheDir()310 std::string ContextDeal::GetCacheDir()
311 {
312 std::string dir = GetBaseDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_CACHE;
313 CreateDirIfNotExist(dir);
314 HILOG_DEBUG("ContextDeal::GetCacheDir:%{public}s", dir.c_str());
315 return dir;
316 }
317
IsUpdatingConfigurations()318 bool ContextDeal::IsUpdatingConfigurations()
319 {
320 return false;
321 }
322
PrintDrawnCompleted()323 bool ContextDeal::PrintDrawnCompleted()
324 {
325 return false;
326 }
327
328 /**
329 * @brief Obtains the application-specific code-cache directory on the device's internal storage.
330 * The system will delete any files stored in this location both when your specific application is upgraded,
331 * and when the entire platform is upgraded.
332 *
333 * @return Returns the application-specific code-cache directory.
334 */
GetCodeCacheDir()335 std::string ContextDeal::GetCodeCacheDir()
336 {
337 std::string dir = GetDataDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_CODE_CACHE;
338 CreateDirIfNotExist(dir);
339 HILOG_DEBUG("ContextDeal::GetCodeCacheDir:%{public}s", dir.c_str());
340 return dir;
341 }
342
343 /**
344 * @brief Obtains the local database path.
345 * If the local database path does not exist, the system creates one and returns the created path.
346 *
347 * @return Returns the local database file.
348 */
GetDatabaseDir()349 std::string ContextDeal::GetDatabaseDir()
350 {
351 std::string dir;
352 if (IsCreateBySystemApp()) {
353 dir = CONTEXT_DEAL_DATA_APP + currArea_ + CONTEXT_DEAL_FILE_SEPARATOR + std::to_string(GetCurrentAccountId())
354 + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_DATABASE + CONTEXT_DEAL_FILE_SEPARATOR + GetBundleName();
355 } else {
356 dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_DATABASE;
357 }
358 CreateDirIfNotExist(dir);
359 HILOG_DEBUG("ContextDeal::GetDatabaseDir:%{public}s", dir.c_str());
360 return dir;
361 }
362
363 /**
364 * @brief Obtains the absolute path where all private data files of this application are stored.
365 *
366 * @return Returns the absolute path storing all private data files of this application.
367 */
GetDataDir()368 std::string ContextDeal::GetDataDir()
369 {
370 std::string dir = GetBaseDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_DATA;
371 CreateDirIfNotExist(dir);
372 HILOG_DEBUG("ContextDeal::GetDataDir dir = %{public}s", dir.c_str());
373 return dir;
374 }
375
376 /**
377 * @brief Obtains the directory for storing custom data files of the application.
378 * You can use the returned File object to create and access files in this directory. The files
379 * can be accessible only by the current application.
380 *
381 * @param name Indicates the name of the directory to retrieve. This directory is created as part
382 * of your application data.
383 * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE.
384 *
385 * @return Returns a File object for the requested directory.
386 */
GetDir(const std::string & name,int mode)387 std::string ContextDeal::GetDir(const std::string &name, int mode)
388 {
389 HILOG_DEBUG("ContextDeal::GetDir begin");
390 if (applicationInfo_ == nullptr) {
391 HILOG_ERROR("ContextDeal::GetDir failed, applicationInfo_ == nullptr");
392 return "";
393 }
394 std::string dir = applicationInfo_->dataDir + CONTEXT_DEAL_FILE_SEPARATOR + name;
395 if (!OHOS::FileExists(dir)) {
396 HILOG_INFO("ContextDeal::GetDir File is not exits");
397 OHOS::ForceCreateDirectory(dir);
398 OHOS::ChangeModeDirectory(dir, mode);
399 }
400 HILOG_DEBUG("ContextDeal::GetDir end");
401 return dir;
402 }
403
404 /**
405 * @brief Obtains the absolute path to the application-specific cache directory
406 * on the primary external or shared storage device.
407 *
408 * @return Returns the absolute path to the application-specific cache directory on the external or
409 * shared storage device; returns null if the external or shared storage device is temporarily unavailable.
410 */
GetExternalCacheDir()411 std::string ContextDeal::GetExternalCacheDir()
412 {
413 return "";
414 }
415
416 /**
417 * @brief Obtains the absolute path to the directory for storing files for the application on the
418 * primary external or shared storage device.
419 *
420 * @param type Indicates the type of the file directory to return
421 *
422 * @return Returns the absolute path to the application file directory on the external or shared storage
423 * device; returns null if the external or shared storage device is temporarily unavailable.
424 */
GetExternalFilesDir(std::string & type)425 std::string ContextDeal::GetExternalFilesDir(std::string &type)
426 {
427 return "";
428 }
429
430 /**
431 * @brief Obtains the directory for storing files for the application on the device's internal storage.
432 *
433 * @return Returns the application file directory.
434 */
GetFilesDir()435 std::string ContextDeal::GetFilesDir()
436 {
437 std::string dir = GetBaseDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_Files;
438 CreateDirIfNotExist(dir);
439 HILOG_DEBUG("ContextDeal::GetFilesDir dir = %{public}s", dir.c_str());
440 return dir;
441 }
442
443 /**
444 * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage.
445 * The returned path maybe changed if the application is moved to an adopted storage device.
446 *
447 * @return The path of the directory holding application files that will not be automatically backed up to remote
448 * storage.
449 */
GetNoBackupFilesDir()450 std::string ContextDeal::GetNoBackupFilesDir()
451 {
452 HILOG_DEBUG("ContextDeal::GetNoBackupFilesDir begin");
453 std::string dir = GetDataDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_NO_BACKUP_Files;
454 if (!OHOS::FileExists(dir)) {
455 HILOG_INFO("ContextDeal::GetDir GetNoBackupFilesDir is not exits");
456 OHOS::ForceCreateDirectory(dir);
457 OHOS::ChangeModeDirectory(dir, MODE);
458 }
459 HILOG_DEBUG("ContextDeal::GetCodeCacheDir:%{public}s", dir.c_str());
460 return dir;
461 }
462
463 /**
464 * @brief Checks whether the current process has the given permission.
465 * You need to call requestPermissionsFromUser(std::vector<std::string>,std::vector<int>, int) to request a permission
466 * only if the current process does not have the specific permission.
467 *
468 * @param permission Indicates the permission to check. This parameter cannot be null.
469 *
470 * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
471 * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
472 */
VerifySelfPermission(const std::string & permission)473 int ContextDeal::VerifySelfPermission(const std::string &permission)
474 {
475 return 0;
476 }
477
478 /**
479 * @brief Obtains the bundle name of the current ability.
480 *
481 * @return Returns the bundle name of the current ability.
482 */
GetBundleName() const483 std::string ContextDeal::GetBundleName() const
484 {
485 return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : "";
486 }
487
488 /**
489 * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability.
490 *
491 * @return Returns the path of the HAP containing this ability.
492 */
GetBundleResourcePath()493 std::string ContextDeal::GetBundleResourcePath()
494 {
495 if (abilityInfo_ == nullptr) {
496 return "";
497 }
498
499 std::string dir;
500 if (isCreateBySystemApp_) {
501 dir = std::regex_replace(abilityInfo_->resourcePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
502 } else {
503 std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + abilityInfo_->bundleName);
504 dir = std::regex_replace(abilityInfo_->resourcePath, pattern, LOCAL_CODE_PATH);
505 }
506 return dir;
507 }
508
509 /**
510 * @brief Starts a new ability.
511 * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method
512 * to start a specific ability. The system locates the target ability from installed abilities based on the value
513 * of the want parameter and then starts it. You can specify the ability to start using the want parameter.
514 *
515 * @param want Indicates the Want containing information about the target ability to start.
516 *
517 * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE
518 * template is started. You can define the request code to identify the results returned by abilities. The value
519 * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE
520 * template.
521 *
522 * @return errCode ERR_OK on success, others on failure.
523 */
StartAbility(const AAFwk::Want & want,int requestCode)524 ErrCode ContextDeal::StartAbility(const AAFwk::Want &want, int requestCode)
525 {
526 HILOG_DEBUG("ContextDeal::StartAbility is called");
527 return ERR_INVALID_VALUE;
528 }
529
530 /**
531 * @brief Remove permissions for all users who have access to specific permissions
532 *
533 * @param permission Indicates the permission to unauth. This parameter cannot be null.
534 * @param uri Indicates the URI to unauth. This parameter cannot be null.
535 * @param uid Indicates the UID of the unauth to check.
536 *
537 */
UnauthUriPermission(const std::string & permission,const Uri & uri,int uid)538 void ContextDeal::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid)
539 {}
540
541 /**
542 * @brief Obtains an ability manager.
543 * The ability manager provides information about running processes and memory usage of an application.
544 *
545 * @return Returns an IAbilityManager instance.
546 */
GetAbilityManager()547 sptr<AAFwk::IAbilityManager> ContextDeal::GetAbilityManager()
548 {
549 HILOG_DEBUG("ContextDeal::GetAbilityManager begin");
550 auto remoteObject = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
551 if (remoteObject == nullptr) {
552 HILOG_ERROR("failed to get ability manager service");
553 return nullptr;
554 }
555 sptr<AAFwk::IAbilityManager> ams = iface_cast<AAFwk::IAbilityManager>(remoteObject);
556 HILOG_DEBUG("ContextDeal::GetAbilityManager end");
557 return ams;
558 }
559
560 /**
561 * @brief Obtains the type of this application.
562 *
563 * @return Returns system if this application is a system application;
564 * returns normal if it is released in OHOS AppGallery;
565 * returns other if it is released by a third-party vendor;
566 * returns an empty string if the query fails.
567 */
GetAppType()568 std::string ContextDeal::GetAppType()
569 {
570 HILOG_DEBUG("ContextDeal::GetAppType begin");
571 sptr<IBundleMgr> ptr = GetBundleManager();
572 if (ptr == nullptr) {
573 HILOG_ERROR("GetAppType failed to get bundle manager service");
574 return "";
575 }
576 std::string retString = ptr->GetAppType(applicationInfo_->bundleName);
577 HILOG_DEBUG("ContextDeal::GetAppType end");
578 return retString;
579 }
580
581 /**
582 * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult
583 * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed.
584 *
585 * @param requestCode Indicates the request code passed for starting the ability.
586 *
587 * @return errCode ERR_OK on success, others on failure.
588 */
TerminateAbility(int requestCode)589 ErrCode ContextDeal::TerminateAbility(int requestCode)
590 {
591 return ERR_INVALID_VALUE;
592 }
593
594 /**
595 * @brief Query whether the application of the specified PID and UID has been granted a certain permission
596 *
597 * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
598 * @param pid Process id
599 * @param uid
600 * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
601 * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
602 */
VerifyPermission(const std::string & permission,int pid,int uid)603 int ContextDeal::VerifyPermission(const std::string &permission, int pid, int uid)
604 {
605 return 0;
606 }
607
IsCreateBySystemApp() const608 bool ContextDeal::IsCreateBySystemApp() const
609 {
610 return (static_cast<uint64_t>(flags_) & static_cast<uint64_t>(CONTEXT_CREATE_BY_SYSTEM_APP)) == 1;
611 }
612
GetCurrentAccountId() const613 int ContextDeal::GetCurrentAccountId() const
614 {
615 int userId = 0;
616 DelayedSingleton<OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromProcess(userId);
617 return userId;
618 }
619
CreateDirIfNotExist(const std::string & dirPath) const620 void ContextDeal::CreateDirIfNotExist(const std::string &dirPath) const
621 {
622 HILOG_DEBUG("CreateDirIfNotExist: create directory if not exists.");
623 if (!OHOS::FileExists(dirPath)) {
624 HILOG_DEBUG("ContextDeal::CreateDirIfNotExist File is not exits");
625 bool createDir = OHOS::ForceCreateDirectory(dirPath);
626 if (!createDir) {
627 HILOG_INFO("CreateDirIfNotExist: create dir %{public}s failed.", dirPath.c_str());
628 return;
629 }
630 }
631 }
632
633 /**
634 * @brief Obtains the distributed file path.
635 * If the distributed file path does not exist, the system creates one and returns the created path. This method is
636 * applicable only to the context of an ability rather than that of an application.
637 *
638 * @return Returns the distributed file.
639 */
GetDistributedDir()640 std::string ContextDeal::GetDistributedDir()
641 {
642 HILOG_DEBUG("ContextDeal::GetDistributedDir");
643 std::string dir;
644 if (IsCreateBySystemApp()) {
645 dir = CONTEXT_DISTRIBUTED_BASE_BEFORE + std::to_string(GetCurrentAccountId()) +
646 CONTEXT_DISTRIBUTED_BASE_MIDDLE + GetBundleName();
647 } else {
648 dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_DISTRIBUTEDFILES;
649 }
650 CreateDirIfNotExist(dir);
651 HILOG_DEBUG("ContextDeal::GetDistributedDir:%{public}s", dir.c_str());
652 return dir;
653 }
654 /**
655 * @brief Sets the pattern of this Context based on the specified pattern ID.
656 *
657 * @param patternId Indicates the resource ID of the pattern to set.
658 */
SetPattern(int patternId)659 void ContextDeal::SetPattern(int patternId)
660 {
661 HILOG_DEBUG("ContextDeal::SetPattern begin");
662 if (resourceManager_ != nullptr) {
663 if (!pattern_.empty()) {
664 pattern_.clear();
665 }
666 OHOS::Global::Resource::RState errval = resourceManager_->GetPatternById(patternId, pattern_);
667 if (errval != OHOS::Global::Resource::RState::SUCCESS) {
668 HILOG_ERROR("ContextDeal::SetPattern GetPatternById(patternId:%d) retval is %u", patternId, errval);
669 }
670 } else {
671 HILOG_ERROR("ContextDeal::SetPattern resourceManager_ is nullptr");
672 }
673 HILOG_DEBUG("ContextDeal::SetPattern end");
674 }
675
676 /**
677 * @brief Obtains the Context object of this ability.
678 *
679 * @return Returns the Context object of this ability.
680 */
GetAbilityPackageContext()681 std::shared_ptr<Context> ContextDeal::GetAbilityPackageContext()
682 {
683 return nullptr;
684 }
685
686 /**
687 * @brief Obtains the HapModuleInfo object of the application.
688 *
689 * @return Returns the HapModuleInfo object of the application.
690 */
GetHapModuleInfo()691 std::shared_ptr<HapModuleInfo> ContextDeal::GetHapModuleInfo()
692 {
693 // fix set HapModuleInfoLocal data failed, request only once
694 if (hapModuleInfoLocal_ == nullptr) {
695 HapModuleInfoRequestInit();
696 if (hapModuleInfoLocal_ == nullptr) {
697 HILOG_ERROR("hapModuleInfoLocal_ is nullptr");
698 return nullptr;
699 }
700 }
701 HILOG_DEBUG("ContextDeal::GetHapModuleInfo end");
702 return hapModuleInfoLocal_;
703 }
704
705 /**
706 * @brief Obtains the name of the current process.
707 *
708 * @return Returns the current process name.
709 */
GetProcessName()710 std::string ContextDeal::GetProcessName()
711 {
712 return (processInfo_ != nullptr) ? processInfo_->GetProcessName() : "";
713 }
714
715 /**
716 * @brief Obtains the bundle name of the ability that called the current ability.
717 * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will
718 * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int,
719 * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned.
720 *
721 * @return Returns the bundle name of the calling ability; returns null if no calling ability is available.
722 */
GetCallingBundle()723 std::string ContextDeal::GetCallingBundle()
724 {
725 return "";
726 }
727
728 /**
729 * @brief Requests certain permissions from the system.
730 * This method is called for permission request. This is an asynchronous method. When it is executed,
731 * the task will be called back.
732 *
733 * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
734 * @param permissionsState Indicates the list of permissions' state to be requested. This parameter cannot be null.
735 * @param task The callback or promise fo js interface.
736 */
RequestPermissionsFromUser(std::vector<std::string> & permissions,std::vector<int> & permissionsState,PermissionRequestTask && task)737 void ContextDeal::RequestPermissionsFromUser(std::vector<std::string> &permissions, std::vector<int> &permissionsState,
738 PermissionRequestTask &&task) {}
739
740 /**
741 * @brief Starts a new ability with special ability start setting.
742 *
743 * @param want Indicates the Want containing information about the target ability to start.
744 * @param requestCode Indicates the request code returned after the ability is started. You can define the request code
745 * to identify the results returned by abilities. The value ranges from 0 to 65535.
746 * @param abilityStartSetting Indicates the special start setting used in starting ability.
747 *
748 * @return errCode ERR_OK on success, others on failure.
749 */
StartAbility(const Want & want,int requestCode,const AbilityStartSetting & abilityStartSetting)750 ErrCode ContextDeal::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting)
751 {
752 return ERR_INVALID_VALUE;
753 }
754
755 /**
756 * @brief Destroys the current ability.
757 *
758 * @return errCode ERR_OK on success, others on failure.
759 */
TerminateAbility()760 ErrCode ContextDeal::TerminateAbility()
761 {
762 return ERR_INVALID_VALUE;
763 }
764
765 /**
766 * @brief Connects the current ability to an ability
767 *
768 * @param want Indicates the want containing information about the ability to connect
769 *
770 * @param conn Indicates the callback object when the target ability is connected.
771 *
772 * @return True means success and false means failure
773 */
ConnectAbility(const Want & want,const sptr<AAFwk::IAbilityConnection> & conn)774 bool ContextDeal::ConnectAbility(const Want &want, const sptr<AAFwk::IAbilityConnection> &conn)
775 {
776 return false;
777 }
778
779 /**
780 * @brief Disconnects the current ability from an ability
781 *
782 * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
783 * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
784 *
785 * @return errCode ERR_OK on success, others on failure.
786 */
DisconnectAbility(const sptr<AAFwk::IAbilityConnection> & conn)787 ErrCode ContextDeal::DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn)
788 {
789 return ERR_INVALID_VALUE;
790 }
791
GetToken()792 sptr<IRemoteObject> ContextDeal::GetToken()
793 {
794 return nullptr;
795 }
796
797 /**
798 * @brief init the ResourceManager for ContextDeal.
799 *
800 * @param the ResourceManager has been inited.
801 *
802 */
initResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)803 void ContextDeal::initResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
804 {
805 HILOG_DEBUG("ContextDeal::initResourceManager. Start.");
806 resourceManager_ = resourceManager;
807 HILOG_DEBUG("ContextDeal::initResourceManager. End.");
808 }
809
810 /**
811 * @brief Obtains information about the caller of this ability.
812 *
813 * @return Returns the caller information.
814 */
GetCaller()815 Uri ContextDeal::GetCaller()
816 {
817 Uri uri(uriString_);
818 return uri;
819 }
820
821 /**
822 * @brief SerUriString
823 */
SerUriString(const std::string & uri)824 void ContextDeal::SerUriString(const std::string &uri)
825 {
826 uriString_ = uri;
827 }
828
829 /**
830 * @brief Get the string of this Context based on the specified resource ID.
831 *
832 * @param resId Indicates the resource ID of the string to get.
833 *
834 * @return Returns the string of this Context.
835 */
GetString(int resId)836 std::string ContextDeal::GetString(int resId)
837 {
838 HILOG_DEBUG("ContextDeal::GetString begin");
839 if (resourceManager_ == nullptr) {
840 HILOG_ERROR("ContextDeal::GetString resourceManager_ is nullptr");
841 return "";
842 }
843
844 std::string ret;
845 OHOS::Global::Resource::RState errval = resourceManager_->GetStringById(resId, ret);
846 if (errval == OHOS::Global::Resource::RState::SUCCESS) {
847 return ret;
848 } else {
849 HILOG_ERROR("ContextDeal::GetString GetStringById(resId:%d) retval is %u", resId, errval);
850 return "";
851 }
852 HILOG_DEBUG("ContextDeal::GetString end");
853 }
854
855 /**
856 * @brief Get the string array of this Context based on the specified resource ID.
857 *
858 * @param resId Indicates the resource ID of the string array to get.
859 *
860 * @return Returns the string array of this Context.
861 */
GetStringArray(int resId)862 std::vector<std::string> ContextDeal::GetStringArray(int resId)
863 {
864 HILOG_DEBUG("ContextDeal::GetStringArray begin");
865 if (resourceManager_ == nullptr) {
866 HILOG_ERROR("ContextDeal::GetStringArray resourceManager_ is nullptr");
867 return std::vector<std::string>();
868 }
869
870 std::vector<std::string> retv;
871 OHOS::Global::Resource::RState errval = resourceManager_->GetStringArrayById(resId, retv);
872 if (errval == OHOS::Global::Resource::RState::SUCCESS) {
873 return retv;
874 } else {
875 HILOG_ERROR("ContextDeal::GetStringArray GetStringArrayById(resId:%d) retval is %u", resId, errval);
876 return std::vector<std::string>();
877 }
878 HILOG_DEBUG("ContextDeal::GetStringArray end");
879 }
880
881 /**
882 * @brief Get the integer array of this Context based on the specified resource ID.
883 *
884 * @param resId Indicates the resource ID of the integer array to get.
885 *
886 * @return Returns the integer array of this Context.
887 */
GetIntArray(int resId)888 std::vector<int> ContextDeal::GetIntArray(int resId)
889 {
890 HILOG_DEBUG("ContextDeal::GetIntArray begin");
891 if (resourceManager_ == nullptr) {
892 HILOG_ERROR("ContextDeal::GetIntArray resourceManager_ is nullptr");
893 return std::vector<int>();
894 }
895
896 std::vector<int> retv;
897 OHOS::Global::Resource::RState errval = resourceManager_->GetIntArrayById(resId, retv);
898 if (errval == OHOS::Global::Resource::RState::SUCCESS) {
899 return retv;
900 } else {
901 HILOG_ERROR("ContextDeal::GetIntArray GetIntArrayById(resId:%d) retval is %u", resId, errval);
902 return std::vector<int>();
903 }
904 HILOG_DEBUG("ContextDeal::GetIntArray end");
905 }
906
907 /**
908 * @brief Obtains the theme of this Context.
909 *
910 * @return theme Returns the theme of this Context.
911 */
GetTheme()912 std::map<std::string, std::string> ContextDeal::GetTheme()
913 {
914 HILOG_DEBUG("ContextDeal::GetTheme begin");
915 if (theme_.empty()) {
916 SetTheme(GetThemeId());
917 }
918 HILOG_DEBUG("ContextDeal::GetTheme end");
919 return theme_;
920 }
921
922 /**
923 * @brief Sets the theme of this Context based on the specified theme ID.
924 *
925 * @param themeId Indicates the resource ID of the theme to set.
926 */
SetTheme(int themeId)927 void ContextDeal::SetTheme(int themeId)
928 {
929 HILOG_DEBUG("ContextDeal::SetTheme begin");
930 if (resourceManager_ == nullptr) {
931 HILOG_ERROR("ContextDeal::SetTheme resourceManager_ is nullptr");
932 return;
933 }
934
935 auto hapModInfo = GetHapModuleInfo();
936 if (hapModInfo == nullptr) {
937 HILOG_ERROR("ContextDeal::SetTheme hapModInfo is nullptr");
938 return;
939 }
940
941 if (!theme_.empty()) {
942 theme_.clear();
943 }
944 OHOS::Global::Resource::RState errval = resourceManager_->GetThemeById(themeId, theme_);
945 if (errval != OHOS::Global::Resource::RState::SUCCESS) {
946 HILOG_ERROR("ContextDeal::SetTheme GetThemeById(themeId:%d) retval is %u", themeId, errval);
947 return;
948 }
949
950 HILOG_DEBUG("ContextDeal::SetTheme end");
951 return;
952 }
953
954 /**
955 * @brief Obtains the pattern of this Context.
956 *
957 * @return getPattern in interface Context
958 */
GetPattern()959 std::map<std::string, std::string> ContextDeal::GetPattern()
960 {
961 HILOG_DEBUG("ContextDeal::GetPattern begin");
962 if (!pattern_.empty()) {
963 HILOG_DEBUG("ContextDeal::GetPattern end");
964 return pattern_;
965 } else {
966 HILOG_ERROR("ContextDeal::GetPattern pattern_ is empty");
967 return std::map<std::string, std::string>();
968 }
969 }
970
971 /**
972 * @brief Get the color of this Context based on the specified resource ID.
973 *
974 * @param resId Indicates the resource ID of the color to get.
975 *
976 * @return Returns the color value of this Context.
977 */
GetColor(int resId)978 int ContextDeal::GetColor(int resId)
979 {
980 HILOG_DEBUG("ContextDeal::GetColor begin");
981 if (resourceManager_ == nullptr) {
982 HILOG_ERROR("ContextDeal::GetColor resourceManager_ is nullptr");
983 return INVALID_RESOURCE_VALUE;
984 }
985
986 uint32_t ret = INVALID_RESOURCE_VALUE;
987 OHOS::Global::Resource::RState errval = resourceManager_->GetColorById(resId, ret);
988 if (errval == OHOS::Global::Resource::RState::SUCCESS) {
989 return ret;
990 } else {
991 HILOG_ERROR("ContextDeal::GetColor GetColorById(resId:%d) retval is %u", resId, errval);
992 return INVALID_RESOURCE_VALUE;
993 }
994 HILOG_DEBUG("ContextDeal::GetColor end");
995 }
996
997 /**
998 * @brief Obtains the theme id of this Context.
999 *
1000 * @return int Returns the theme id of this Context.
1001 */
GetThemeId()1002 int ContextDeal::GetThemeId()
1003 {
1004 auto hapModInfo = GetHapModuleInfo();
1005 if (hapModInfo != nullptr) {
1006 return -1;
1007 } else {
1008 HILOG_ERROR("ContextDeal::GetThemeId hapModInfo is nullptr");
1009 return -1;
1010 }
1011 }
1012
1013 /**
1014 * @brief
1015 * Destroys this Service ability if the number of times it has been started equals the number represented by the
1016 * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service
1017 * ability, except that this method helps you avoid destroying it if a client has requested a Service
1018 * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it.
1019 *
1020 * @param startId Indicates the number of startup times of this Service ability passed to
1021 * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is
1022 * incremented by 1 every time this ability is started. For example,
1023 * if this ability has been started for six times, the value of {@code startId} is {@code 6}.
1024 *
1025 * @return Returns {@code true} if the {@code startId} matches the number of startup times
1026 * and this Service ability will be destroyed; returns {@code false} otherwise.
1027 */
TerminateAbilityResult(int startId)1028 bool ContextDeal::TerminateAbilityResult(int startId)
1029 {
1030 return false;
1031 }
1032
1033 /**
1034 * @brief Obtains the current display orientation of this ability.
1035 *
1036 * @return Returns the current display orientation.
1037 */
GetDisplayOrientation()1038 int ContextDeal::GetDisplayOrientation()
1039 {
1040 HILOG_DEBUG("ContextDeal::GetDisplayOrientation begin");
1041 if (abilityInfo_ != nullptr) {
1042 HILOG_DEBUG("ContextDeal::GetDisplayOrientation end");
1043 return static_cast<int>(abilityInfo_->orientation);
1044 } else {
1045 HILOG_ERROR("ContextDeal::GetDisplayOrientation abilityInfo_ is nullptr");
1046 return static_cast<int>(DisplayOrientation::UNSPECIFIED);
1047 }
1048 }
1049
1050 /**
1051 * @brief Obtains the path storing the preference file of the application.
1052 * If the preference file path does not exist, the system creates one and returns the created path.
1053 *
1054 * @return Returns the preference file path .
1055 */
GetPreferencesDir()1056 std::string ContextDeal::GetPreferencesDir()
1057 {
1058 HILOG_DEBUG("ContextDeal::GetPreferencesDir begin");
1059 std::string dir = GetBaseDir() + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_PREFERENCES;
1060 CreateDirIfNotExist(dir);
1061 HILOG_DEBUG("ContextDeal::GetPreferencesDir:%{public}s", dir.c_str());
1062 return dir;
1063 }
1064
1065 /**
1066 * @brief Set color mode
1067 *
1068 * @param the value of color mode.
1069 */
SetColorMode(int mode)1070 void ContextDeal::SetColorMode(int mode)
1071 {
1072 HILOG_DEBUG("ContextDeal::SetColorMode begin");
1073 auto hapModInfo = GetHapModuleInfo();
1074 if (hapModInfo == nullptr) {
1075 HILOG_ERROR("ContextDeal::SetColorMode hapModInfo is nullptr");
1076 return;
1077 }
1078
1079 if (mode == static_cast<int>(ModuleColorMode::DARK)) {
1080 hapModInfo->colorMode = ModuleColorMode::DARK;
1081 } else if (mode == static_cast<int>(ModuleColorMode::LIGHT)) {
1082 hapModInfo->colorMode = ModuleColorMode::LIGHT;
1083 } else { // default use AUTO
1084 hapModInfo->colorMode = ModuleColorMode::AUTO;
1085 }
1086 HILOG_DEBUG("ContextDeal::SetColorMode end");
1087 }
1088
1089 /**
1090 * @brief Obtains color mode.
1091 *
1092 * @return Returns the color mode value.
1093 */
GetColorMode()1094 int ContextDeal::GetColorMode()
1095 {
1096 HILOG_DEBUG("ContextDeal::GetColorMode begin");
1097 auto hapModInfo = GetHapModuleInfo();
1098 if (hapModInfo == nullptr) {
1099 HILOG_ERROR("ContextDeal::GetColorMode hapModInfo is nullptr");
1100 return -1;
1101 }
1102 HILOG_DEBUG("ContextDeal::GetColorMode end");
1103 return static_cast<int>(hapModInfo->colorMode);
1104 }
1105
1106 /**
1107 * @brief Set the LifeCycleStateInfo to the deal.
1108 *
1109 * @param info the info to set.
1110 */
SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo & info)1111 void ContextDeal::SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info)
1112 {
1113 lifeCycleStateInfo_ = info;
1114 }
1115
1116 /**
1117 * @brief Obtains the unique ID of the mission containing this ability.
1118 *
1119 * @return Returns the unique mission ID.
1120 */
GetMissionId()1121 int ContextDeal::GetMissionId()
1122 {
1123 return lifeCycleStateInfo_.missionId;
1124 }
1125
1126 /**
1127 * @brief Obtains the lifecycle state info.
1128 *
1129 * @return Returns the lifecycle state info.
1130 */
GetLifeCycleStateInfo() const1131 AAFwk::LifeCycleStateInfo ContextDeal::GetLifeCycleStateInfo() const
1132 {
1133 return lifeCycleStateInfo_;
1134 }
1135
1136 /**
1137 * @brief Starts multiple abilities.
1138 *
1139 * @param wants Indicates the Want containing information array about the target ability to start.
1140 */
StartAbilities(const std::vector<AAFwk::Want> & wants)1141 void ContextDeal::StartAbilities(const std::vector<AAFwk::Want> &wants)
1142 {}
1143
1144 /**
1145 * @brief Set EventRunner for main thread.
1146 *
1147 * @param runner The EventRunner.
1148 */
SetRunner(const std::shared_ptr<EventRunner> & runner)1149 void ContextDeal::SetRunner(const std::shared_ptr<EventRunner> &runner)
1150 {
1151 mainEventRunner_ = runner;
1152 }
1153
1154 /**
1155 * @brief init HapModuleInfo data
1156 *
1157 * @return Returns true on success, others on failure.
1158 */
HapModuleInfoRequestInit()1159 bool ContextDeal::HapModuleInfoRequestInit()
1160 {
1161 HILOG_DEBUG("ContextDeal::HapModuleInfoRequestInit begin");
1162
1163 sptr<IBundleMgr> ptr = GetBundleManager();
1164 if (ptr == nullptr) {
1165 HILOG_ERROR("GetHapModuleInfo failed to get bundle manager service");
1166 return false;
1167 }
1168
1169 if (abilityInfo_ == nullptr) {
1170 HILOG_ERROR("GetHapModuleInfo failed for abilityInfo_ is nullptr");
1171 return false;
1172 }
1173
1174 hapModuleInfoLocal_ = std::make_shared<HapModuleInfo>();
1175 if (!ptr->GetHapModuleInfo(*abilityInfo_.get(), *hapModuleInfoLocal_)) {
1176 HILOG_ERROR("IBundleMgr::GetHapModuleInfo failed, will retval false value");
1177 return false;
1178 }
1179 HILOG_DEBUG("ContextDeal::HapModuleInfoRequestInit end");
1180 return true;
1181 }
1182
GetBaseDir() const1183 std::string ContextDeal::GetBaseDir() const
1184 {
1185 std::string baseDir;
1186 if (IsCreateBySystemApp()) {
1187 baseDir = CONTEXT_DEAL_DATA_APP + currArea_ + CONTEXT_DEAL_FILE_SEPARATOR +
1188 std::to_string(GetCurrentAccountId()) + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_BASE +
1189 CONTEXT_DEAL_FILE_SEPARATOR + GetBundleName();
1190 } else {
1191 baseDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_DEAL_FILE_SEPARATOR + CONTEXT_DEAL_BASE;
1192 }
1193
1194 HILOG_DEBUG("ContextDeal::GetBaseDir:%{public}s", baseDir.c_str());
1195 return baseDir;
1196 }
1197 } // namespace AppExecFwk
1198 } // namespace OHOS
1199