• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 "js_ani_ability.h"
17 #include "ani_base_context.h"
18 #include "extension_context.h"
19 #include "log_print.h"
20 namespace OHOS {
21 namespace PreferencesJsKit {
22 namespace JSAbility {
23 static CONTEXT_MODE gContextNode = CONTEXT_MODE::INIT;
24 std::mutex g_contextModeMutex;
25 
GetContextMode(ani_env * env,ani_object context)26 CONTEXT_MODE GetContextMode(ani_env* env, ani_object context)
27 {
28     std::lock_guard<std::mutex> lock(g_contextModeMutex);
29     if (gContextNode == CONTEXT_MODE::INIT) {
30         ani_boolean isStageMode;
31         ani_status status = OHOS::AbilityRuntime::IsStageContext(env, context, isStageMode);
32         LOG_INFO("GetContextMode is %{public}d", static_cast<bool>(isStageMode));
33         if (status == ANI_OK) {
34             gContextNode = isStageMode ? CONTEXT_MODE::STAGE : CONTEXT_MODE::FA;
35         }
36     }
37     LOG_INFO("gContextNode is: %{public}d", gContextNode);
38     return gContextNode;
39 }
40 
GetContextInfo(ani_env * env,ani_object context,const std::string & dataGroupId,ContextInfo & contextInfo)41 std::shared_ptr<JSError> GetContextInfo(ani_env* env, ani_object context,
42     const std::string &dataGroupId, ContextInfo &contextInfo)
43 {
44     if (GetContextMode(env, context) == CONTEXT_MODE::STAGE) {
45         auto stageContext = OHOS::AbilityRuntime::GetStageModeContext(env, context);
46         if (stageContext != nullptr) {
47             int errcode = stageContext->GetSystemPreferencesDir(dataGroupId, false, contextInfo.preferencesDir);
48             LOG_INFO("after GetContextMode, in stage. errcode is %{public}d.", errcode);
49             if (errcode != 0) {
50                 return std::make_shared<InnerError>(E_DATA_GROUP_ID_INVALID);
51             }
52             contextInfo.bundleName = stageContext->GetBundleName();
53             return nullptr;
54         } else {
55             LOG_INFO("The context is invalid.");
56             return std::make_shared<ParamTypeError>("The context is invalid.");
57         }
58     }
59 
60     if (!dataGroupId.empty()) {
61         return std::make_shared<InnerError>(E_NOT_STAGE_MODE);
62     }
63 
64     return nullptr;
65 }
66 } // namespace JSAbility
67 } // namespace PreferencesJsKit
68 } // namespace OHOS
69