1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "napi_preferences_helper.h"
16 
17 #include <string>
18 
19 #include "js_ability.h"
20 #include "js_sendable_utils.h"
21 #include "js_common_utils.h"
22 #include "napi_async_call.h"
23 #include "napi_preferences.h"
24 #include "preferences.h"
25 #include "preferences_errno.h"
26 
27 using namespace OHOS::NativePreferences;
28 using namespace OHOS::PreferencesJsKit;
29 
30 namespace OHOS::Sendable::JSPreferences {
31 constexpr const char *DATA_GROUP_ID = "dataGroupId";
32 constexpr const char *NAME = "name";
33 
34 struct HelperAysncContext : public BaseContext {
35     std::string path;
36     std::string name;
37     std::string bundleName;
38     std::string dataGroupId;
39     std::shared_ptr<NativePreferences::Preferences> proxy;
40 
HelperAysncContextOHOS::Sendable::JSPreferences::HelperAysncContext41     HelperAysncContext()
42     {
43     }
~HelperAysncContextOHOS::Sendable::JSPreferences::HelperAysncContext44     virtual ~HelperAysncContext(){};
45 };
46 
ParseParameters(const napi_env env,napi_value * argv,std::shared_ptr<HelperAysncContext> context)47 int ParseParameters(const napi_env env, napi_value *argv, std::shared_ptr<HelperAysncContext> context)
48 {
49     if (Utils::ConvertFromSendable(env, argv[1], context->name) != napi_ok) {
50         napi_value temp = nullptr;
51         napi_get_named_property(env, argv[1], NAME, &temp);
52         PRE_CHECK_RETURN_ERR_SET(temp && Utils::ConvertFromSendable(env, temp, context->name) == napi_ok,
53             std::make_shared<ParamTypeError>("The name must be string."));
54 
55         bool hasGroupId = false;
56         napi_has_named_property(env, argv[1], DATA_GROUP_ID, &hasGroupId);
57         if (hasGroupId) {
58             temp = nullptr;
59             napi_get_named_property(env, argv[1], DATA_GROUP_ID, &temp);
60             napi_valuetype type = napi_undefined;
61             napi_status status = napi_typeof(env, temp, &type);
62             if (status == napi_ok && (type != napi_null && type != napi_undefined)) {
63                 PRE_CHECK_RETURN_ERR_SET(Utils::ConvertFromSendable(env, temp, context->dataGroupId) == napi_ok,
64                     std::make_shared<ParamTypeError>("The dataGroupId must be string."));
65             }
66         }
67     }
68     JSAbility::ContextInfo contextInfo;
69     std::shared_ptr<JSError> err = JSAbility::GetContextInfo(env, argv[0], context->dataGroupId, contextInfo);
70     PRE_CHECK_RETURN_ERR_SET(err == nullptr, err);
71 
72     context->bundleName = contextInfo.bundleName;
73     context->path = contextInfo.preferencesDir.append("/").append(context->name);
74     return OK;
75 }
76 
GetPreferences(napi_env env,napi_callback_info info)77 napi_value GetPreferences(napi_env env, napi_callback_info info)
78 {
79     auto context = std::make_shared<HelperAysncContext>();
80     auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) {
81         PRE_CHECK_RETURN_VOID_SET(argc == 2, std::make_shared<ParamNumError>("2 or 3"));
82         PRE_CHECK_RETURN_VOID(ParseParameters(env, argv, context) == OK);
83     };
84     auto exec = [context]() -> int {
85         int errCode = E_OK;
86         Options options(context->path, context->bundleName, context->dataGroupId);
87         context->proxy = PreferencesHelper::GetPreferences(options, errCode);
88         return errCode;
89     };
90     auto output = [context](napi_env env, napi_value &result) {
91         auto status = PreferencesProxy::NewInstance(env, context->proxy, &result);
92         PRE_CHECK_RETURN_VOID_SET(status == napi_ok, std::make_shared<InnerError>("Failed to get instance when "
93                                                                                   "getting preferences."));
94     };
95     context->SetAction(env, info, input, exec, output);
96 
97     PRE_CHECK_RETURN_NULL(context->error == nullptr || context->error->GetCode() == OK);
98     return AsyncCall::Call(env, context, "GetPreferences");
99 }
100 
DeletePreferences(napi_env env,napi_callback_info info)101 napi_value DeletePreferences(napi_env env, napi_callback_info info)
102 {
103     auto context = std::make_shared<HelperAysncContext>();
104     auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) {
105         PRE_CHECK_RETURN_VOID_SET(argc == 2, std::make_shared<ParamNumError>("2 or 3"));
106         PRE_CHECK_RETURN_VOID(ParseParameters(env, argv, context) == OK);
107     };
108     auto exec = [context]() -> int { return PreferencesHelper::DeletePreferences(context->path); };
109     auto output = [context](napi_env env, napi_value &result) {
110         napi_status status = napi_get_undefined(env, &result);
111         PRE_CHECK_RETURN_VOID_SET(status == napi_ok, std::make_shared<InnerError>("Failed to get undefined when "
112                                                                                   "deleting preferences."));
113     };
114     context->SetAction(env, info, input, exec, output);
115 
116     PRE_CHECK_RETURN_NULL(context->error == nullptr || context->error->GetCode() == OK);
117     return AsyncCall::Call(env, context, "DeletePreferences");
118 }
119 
RemovePreferencesFromCache(napi_env env,napi_callback_info info)120 napi_value RemovePreferencesFromCache(napi_env env, napi_callback_info info)
121 {
122     auto context = std::make_shared<HelperAysncContext>();
123     auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) {
124         PRE_CHECK_RETURN_VOID_SET(argc == 2, std::make_shared<ParamNumError>("2 or 3"));
125         PRE_CHECK_RETURN_VOID(ParseParameters(env, argv, context) == OK);
126     };
127     auto exec = [context]() -> int { return PreferencesHelper::RemovePreferencesFromCache(context->path); };
128     auto output = [context](napi_env env, napi_value &result) {
129         napi_status status = napi_get_undefined(env, &result);
130         PRE_CHECK_RETURN_VOID_SET(status == napi_ok, std::make_shared<InnerError>("Failed to get undefined when "
131                                                                                   "removing preferences."));
132     };
133     context->SetAction(env, info, input, exec, output);
134 
135     PRE_CHECK_RETURN_NULL(context->error == nullptr || context->error->GetCode() == OK);
136     return AsyncCall::Call(env, context, "RemovePreferencesFromCache");
137 }
138 
InitPreferencesHelper(napi_env env,napi_value exports)139 napi_value InitPreferencesHelper(napi_env env, napi_value exports)
140 {
141     napi_property_descriptor properties[] = {
142         DECLARE_NAPI_FUNCTION_WITH_DATA("getPreferences", GetPreferences, ASYNC),
143         DECLARE_NAPI_FUNCTION_WITH_DATA("getPreferencesSync", GetPreferences, SYNC),
144         DECLARE_NAPI_FUNCTION_WITH_DATA("deletePreferences", DeletePreferences, ASYNC),
145         DECLARE_NAPI_FUNCTION_WITH_DATA("deletePreferencesSync", DeletePreferences, SYNC),
146         DECLARE_NAPI_FUNCTION_WITH_DATA("removePreferencesFromCache", RemovePreferencesFromCache, ASYNC),
147         DECLARE_NAPI_FUNCTION_WITH_DATA("removePreferencesFromCacheSync", RemovePreferencesFromCache, SYNC),
148         DECLARE_NAPI_PROPERTY("MAX_KEY_LENGTH", JSUtils::Convert2JSValue(env, Preferences::MAX_KEY_LENGTH)),
149         DECLARE_NAPI_PROPERTY("MAX_VALUE_LENGTH", JSUtils::Convert2JSValue(env, Preferences::MAX_VALUE_LENGTH)),
150     };
151     NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties));
152     return exports;
153 }
154 } // namespace OHOS::Sendable::JSPreferences
155