From 6f7a1e047bcc8c2497e0aeb2b91ea44522dc87c3 Mon Sep 17 00:00:00 2001 From: duanweiling Date: Fri, 22 Apr 2022 18:29:33 +0800 Subject: [PATCH] =?UTF-8?q?DataShare=20=E4=BB=A3=E7=A0=81=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E8=87=B3=E6=95=B0=E6=8D=AE=E7=AE=A1=E7=90=86=E5=AD=90?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: duanweiling --- bundle.json | 2 - frameworks/kits/ability/native/BUILD.gn | 32 - .../native/include/datashare_connection.h | 95 - .../native/include/datashare_ext_ability.h | 230 -- .../datashare_ext_ability_module_loader.h | 36 - .../ability/native/include/datashare_helper.h | 289 -- .../ability/native/include/datashare_proxy.h | 68 - .../ability/native/include/datashare_stub.h | 54 - .../native/include/datashare_stub_impl.h | 80 - .../native/include/datashare_uv_queue.h | 54 - .../kits/ability/native/include/idatashare.h | 223 -- .../native/include/js_datashare_ext_ability.h | 263 -- .../js_datashare_ext_ability_context.h | 32 - .../native/src/datashare_connection.cpp | 126 - .../native/src/datashare_ext_ability.cpp | 165 - .../datashare_ext_ability_module_loader.cpp | 32 - .../ability/native/src/datashare_helper.cpp | 1110 ------ .../ability/native/src/datashare_proxy.cpp | 596 --- .../ability/native/src/datashare_stub.cpp | 429 --- .../native/src/datashare_stub_impl.cpp | 285 -- .../ability/native/src/datashare_uv_queue.cpp | 101 - .../native/src/js_datashare_ext_ability.cpp | 738 ---- .../src/js_datashare_ext_ability_context.cpp | 61 - interfaces/kits/napi/BUILD.gn | 3 - interfaces/kits/napi/aafwk/dataShare/BUILD.gn | 67 - .../napi/aafwk/dataShare/data_share_common.h | 360 -- .../aafwk/dataShare/napi_datashare_helper.cpp | 3325 ----------------- .../aafwk/dataShare/napi_datashare_helper.h | 426 --- .../dataShare/native_datashare_module.cpp | 54 - .../kits/napi/aafwk/dataShare/test/BUILD.gn | 23 - .../aafwk/dataShare/test/unittest/BUILD.gn | 34 - .../test/unittest/DataShareJsunit.test.js | 1081 ------ .../aafwk/dataShare/test/unittest/config.json | 60 - .../napi/aafwk/datashare_ext_ability/BUILD.gn | 50 - .../datashare_ext_ability.js | 66 - .../datashare_ext_ability_module.cpp | 57 - .../datashare_ext_ability_context/BUILD.gn | 51 - .../datashare_ext_ability_context.js | 24 - .../datashare_ext_ability_context_module.cpp | 57 - 39 files changed, 10839 deletions(-) delete mode 100644 frameworks/kits/ability/native/include/datashare_connection.h delete mode 100644 frameworks/kits/ability/native/include/datashare_ext_ability.h delete mode 100644 frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h delete mode 100644 frameworks/kits/ability/native/include/datashare_helper.h delete mode 100644 frameworks/kits/ability/native/include/datashare_proxy.h delete mode 100644 frameworks/kits/ability/native/include/datashare_stub.h delete mode 100644 frameworks/kits/ability/native/include/datashare_stub_impl.h delete mode 100644 frameworks/kits/ability/native/include/datashare_uv_queue.h delete mode 100644 frameworks/kits/ability/native/include/idatashare.h delete mode 100644 frameworks/kits/ability/native/include/js_datashare_ext_ability.h delete mode 100644 frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h delete mode 100644 frameworks/kits/ability/native/src/datashare_connection.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_ext_ability.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_helper.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_proxy.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_stub.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_stub_impl.cpp delete mode 100644 frameworks/kits/ability/native/src/datashare_uv_queue.cpp delete mode 100644 frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp delete mode 100644 frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp delete mode 100644 interfaces/kits/napi/aafwk/dataShare/BUILD.gn delete mode 100644 interfaces/kits/napi/aafwk/dataShare/data_share_common.h delete mode 100644 interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp delete mode 100644 interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h delete mode 100644 interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp delete mode 100644 interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn delete mode 100644 interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn delete mode 100644 interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js delete mode 100644 interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js delete mode 100644 interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp diff --git a/bundle.json b/bundle.json index 984d9f09234..c843358bc5f 100644 --- a/bundle.json +++ b/bundle.json @@ -57,7 +57,6 @@ "sub_component": [ "//foundation/aafwk/standard/services:services_target", "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", - "//foundation/aafwk/standard/frameworks/kits/ability/native:datashare_ext_ability_module", "//foundation/aafwk/standard/frameworks/kits/ability/native:static_subscriber_ipc", "//foundation/aafwk/standard/frameworks/kits/ability/native:service_extension_module", "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", @@ -161,7 +160,6 @@ "test": [ "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/moduletest:moduletest", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/unittest:unittest", "//foundation/aafwk/standard/frameworks/kits/test:moduletest", diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index c9db76b38d8..ecd53920951 100644 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -142,13 +142,6 @@ ohos_shared_library("abilitykit_native") { "src/data_ability_operation_builder.cpp", "src/data_ability_result.cpp", "src/data_uri_utils.cpp", - "src/datashare_connection.cpp", - "src/datashare_ext_ability.cpp", - "src/datashare_helper.cpp", - "src/datashare_proxy.cpp", - "src/datashare_stub.cpp", - "src/datashare_stub_impl.cpp", - "src/datashare_uv_queue.cpp", "src/extension.cpp", "src/extension_impl.cpp", "src/extension_module_loader.cpp", @@ -158,8 +151,6 @@ ohos_shared_library("abilitykit_native") { #"src/dummy_values_bucket.cpp", "${services_path}/abilitymgr/src/ability_start_setting.cpp", "${services_path}/abilitymgr/src/launch_param.cpp", - "src/js_datashare_ext_ability.cpp", - "src/js_datashare_ext_ability_context.cpp", "src/js_service_extension.cpp", "src/js_service_extension_context.cpp", "src/js_static_subscriber_extension.cpp", @@ -180,7 +171,6 @@ ohos_shared_library("abilitykit_native") { "${aafwk_path}/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp", "${aafwk_path}/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp", "${kits_path}/appkit/native/ability_runtime/context/context_impl.cpp", - "${kits_path}/appkit/native/ability_runtime/datashare_ext_ability_context.cpp", "${kits_path}/appkit/native/ability_runtime/extension_context.cpp", "${kits_path}/appkit/native/ability_runtime/service_extension_context.cpp", "${kits_path}/appkit/native/ability_runtime/static_subscriber_extension_context.cpp", @@ -361,25 +351,3 @@ ohos_shared_library("service_extension_module") { subsystem_name = "aafwk" part_name = "ability_runtime" } - -ohos_shared_library("datashare_ext_ability_module") { - include_dirs = [ "include" ] - - sources = [ "src/datashare_ext_ability_module_loader.cpp" ] - - configs = [ ":ability_config" ] - public_configs = [ ":ability_public_config" ] - - deps = [ ":abilitykit_native" ] - - external_deps = [ - "ability_base:want", - "ability_runtime:runtime", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "utils_base:utils", - ] - - subsystem_name = "aafwk" - part_name = "ability_runtime" -} diff --git a/frameworks/kits/ability/native/include/datashare_connection.h b/frameworks/kits/ability/native/include/datashare_connection.h deleted file mode 100644 index f318feb8ddb..00000000000 --- a/frameworks/kits/ability/native/include/datashare_connection.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H -#define FOUNDATION_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H - -#include - -#include "ability_connect_callback_stub.h" -#include "event_handler.h" -#include "idatashare.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -class DataShareConnection : public AAFwk::AbilityConnectionStub { -public: - DataShareConnection() = default; - virtual ~DataShareConnection() = default; - - /** - * @brief get singleton of Class DataShareConnection - * - * @return The singleton of DataShareConnection - */ - static sptr GetInstance(); - - /** - * @brief This method is called back to receive the connection result after an ability calls the - * ConnectAbility method to connect it to an extension ability. - * - * @param element: Indicates information about the connected extension ability. - * @param remote: Indicates the remote proxy object of the extension ability. - * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any - * other value indicates a connection failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - - /** - * @brief This method is called back to receive the disconnection result after the connected extension ability - * crashes or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and - * each ability previously connected to it will call onAbilityDisconnectDone. - * - * @param element: Indicates information about the disconnected extension ability. - * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, - * and any other value indicates a disconnection failure. - */ - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - - /** - * @brief connect remote ability of DataShareExtAbility. - */ - void ConnectDataShareExtAbility(const AAFwk::Want &want, const sptr &token); - - /** - * @brief disconnect remote ability of DataShareExtAbility. - */ - void DisconnectDataShareExtAbility(); - - /** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ - bool IsExtAbilityConnected(); - - /** - * @brief get the proxy of datashare extension ability. - * - * @return the proxy of datashare extension ability. - */ - sptr GetDataShareProxy(); - -private: - static sptr instance_; - static std::mutex mutex_; - std::atomic isConnected_ = {false}; - sptr dataShareProxy_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H diff --git a/frameworks/kits/ability/native/include/datashare_ext_ability.h b/frameworks/kits/ability/native/include/datashare_ext_ability.h deleted file mode 100644 index b2cfece8151..00000000000 --- a/frameworks/kits/ability/native/include/datashare_ext_ability.h +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H -#define FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H - -#include "extension_base.h" - -namespace OHOS { -namespace NativeRdb { -class AbsSharedResultSet; -class DataAbilityPredicates; -class ValuesBucket; -} -namespace AAFwk { -class IDataAbilityObserver; -} -namespace AppExecFwk { -class DataAbilityOperation; -class DataAbilityResult; -} -namespace AbilityRuntime { -class DataShareExtAbilityContext; -class Runtime; -/** - * @brief Basic datashare extension ability components. - */ -class DataShareExtAbility : public ExtensionBase { -public: - DataShareExtAbility() = default; - virtual ~DataShareExtAbility() = default; - - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - virtual void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The DataShareExtAbility instance. - */ - static DataShareExtAbility* Create(const std::unique_ptr& runtime); - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter); - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - virtual int OpenFile(const Uri &uri, const std::string &mode); - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - virtual int OpenRawFile(const Uri &uri, const std::string &mode); - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value); - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ - virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ - virtual std::shared_ptr Query( - const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - virtual std::string GetType(const Uri &uri); - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - virtual int BatchInsert(const Uri &uri, const std::vector &values); - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - virtual bool NotifyChange(const Uri &uri); - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - virtual Uri NormalizeUri(const Uri &uri); - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - virtual Uri DenormalizeUri(const Uri &uri); - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - virtual std::vector> ExecuteBatch( - const std::vector> &operations); -}; -} // namespace AbilityRuntime -} // namespace OHOS -#endif // FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h b/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h deleted file mode 100644 index cc929460a51..00000000000 --- a/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H -#define FOUNDATION_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H - -#include "extension_module_loader.h" - -namespace OHOS::AbilityRuntime { -class DataShareExtAbilityModuleLoader : public ExtensionModuleLoader, - public Singleton { - DECLARE_SINGLETON(DataShareExtAbilityModuleLoader); - -public: - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The Extension instance. - */ - virtual Extension *Create(const std::unique_ptr& runtime) const override; -}; -} -#endif // FOUNDATION_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/datashare_helper.h b/frameworks/kits/ability/native/include/datashare_helper.h deleted file mode 100644 index 29f15ba6204..00000000000 --- a/frameworks/kits/ability/native/include/datashare_helper.h +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_APPEXECFWK_OHOS_DATASHARE_HELPER_H -#define FOUNDATION_APPEXECFWK_OHOS_DATASHARE_HELPER_H - -#include -#include -#include - -#include "context.h" -#include "datashare_connection.h" -#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" -#include "idatashare.h" -#include "uri.h" -#include "want.h" - -using Uri = OHOS::Uri; - -namespace OHOS { -namespace NativeRdb { -class AbsSharedResultSet; -class DataAbilityPredicates; -class ValuesBucket; -} // namespace NativeRdb -namespace AppExecFwk { -using string = std::string; -class DataAbilityResult; -class DataAbilityOperation; -class PacMap; -class IDataAbilityObserver; -class DataShareHelper final : public std::enable_shared_from_this { -public: - ~DataShareHelper() = default; - - /** - * @brief Creates a DataShareHelper instance without specifying the Uri based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * - * @return Returns the created DataShareHelper instance where Uri is not specified. - */ - static std::shared_ptr Creator(const std::shared_ptr &context, - const AAFwk::Want &want); - - /** - * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * @param uri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance with a specified Uri. - */ - static std::shared_ptr Creator(const std::shared_ptr &context, - const AAFwk::Want &want, const std::shared_ptr &uri); - - /** - * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * @param uri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance with a specified Uri. - */ - static std::shared_ptr Creator(const std::shared_ptr &context, - const AAFwk::Want &want, const std::shared_ptr &uri); - - /** - * @brief Releases the client resource of the Data share. - * You should call this method to releases client resource after the data operations are complete. - * - * @return Returns true if the resource is successfully released; returns false otherwise. - */ - bool Release(); - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - std::vector GetFileTypes(Uri &uri, const std::string &mimeTypeFilter); - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - int OpenFile(Uri &uri, const std::string &mode); - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - int OpenRawFile(Uri &uri, const std::string &mode); - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - int Insert(Uri &uri, const NativeRdb::ValuesBucket &value); - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ - int Update(Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - int Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ - std::shared_ptr Query( - Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates); - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be - * implemented by a Data share. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - std::string GetType(Uri &uri); - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - int BatchInsert(Uri &uri, const std::vector &values); - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - void RegisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - void UnregisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - */ - void NotifyChange(const Uri &uri); - - /** - * @brief Converts the given uri that refer to the Data share into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data share even if the - * context has changed. If you implement URI normalization for a Data share, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data share must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data share does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise. - */ - Uri NormalizeUri(Uri &uri); - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed - * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found - * in the current environment. - */ - Uri DenormalizeUri(Uri &uri); - - /** - * @brief Performs batch operations on the database. - * - * @param uri Indicates the path of data to operate. - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - std::vector> ExecuteBatch( - const Uri &uri, const std::vector> &operations); - -private: - DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want); - DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, - const std::shared_ptr &uri, const sptr &dataShareProxy); - DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, - const std::shared_ptr &uri, const sptr &dataShareProxy); - void AddDataShareDeathRecipient(const sptr &token); - void OnSchedulerDied(const wptr &remote); - bool CheckUriParam(const Uri &uri); - bool CheckOhosUri(const Uri &uri); - - sptr token_ = {}; - std::shared_ptr context_ = nullptr; - AAFwk::Want want_ = {}; - std::shared_ptr uri_ = nullptr; - sptr dataShareProxy_ = nullptr; - bool isSystemCaller_ = false; - static std::mutex oplock_; - sptr callerDeathRecipient_ = nullptr; - std::map, sptr> registerMap_; - std::map, std::string> uriMap_; - sptr dataShareConnection_ = nullptr; -}; - -class DataShareDeathRecipient : public IRemoteObject::DeathRecipient { -public: - using RemoteDiedHandler = std::function &)>; - - explicit DataShareDeathRecipient(RemoteDiedHandler handler); - - virtual ~DataShareDeathRecipient(); - - virtual void OnRemoteDied(const wptr &remote); - -private: - RemoteDiedHandler handler_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_DATASHARE_HELPER_H diff --git a/frameworks/kits/ability/native/include/datashare_proxy.h b/frameworks/kits/ability/native/include/datashare_proxy.h deleted file mode 100644 index 3f14ee17863..00000000000 --- a/frameworks/kits/ability/native/include/datashare_proxy.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_DATASHARE_PROXY_H -#define OHOS_APPEXECFWK_DATASHARE_PROXY_H - -#include -#include "idatashare.h" - -namespace OHOS { -namespace AppExecFwk { -class DataShareProxy : public IRemoteProxy { -public: - explicit DataShareProxy(const sptr& remote) : IRemoteProxy(remote) {} - - virtual ~DataShareProxy() {} - - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - virtual int OpenFile(const Uri &uri, const std::string &mode) override; - - virtual int OpenRawFile(const Uri &uri, const std::string &mode) override; - - virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; - - virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) override; - - virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; - - virtual std::shared_ptr Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; - - virtual std::string GetType(const Uri &uri) override; - - virtual int BatchInsert(const Uri &uri, const std::vector &values) override; - - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool NotifyChange(const Uri &uri) override; - - virtual Uri NormalizeUri(const Uri &uri) override; - - virtual Uri DenormalizeUri(const Uri &uri) override; - - virtual std::vector> ExecuteBatch( - const std::vector> &operations) override; -private: - static inline BrokerDelegator delegator_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_DATASHARE_PROXY_H - diff --git a/frameworks/kits/ability/native/include/datashare_stub.h b/frameworks/kits/ability/native/include/datashare_stub.h deleted file mode 100644 index 55b90d9f775..00000000000 --- a/frameworks/kits/ability/native/include/datashare_stub.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_DATASHARE_STUB_H -#define OHOS_APPEXECFWK_DATASHARE_STUB_H - -#include -#include - -#include "idatashare.h" - -namespace OHOS { -namespace AppExecFwk { -class DataShareStub : public IRemoteStub { -public: - DataShareStub(); - ~DataShareStub(); - int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; -private: - ErrCode CmdGetFileTypes(MessageParcel &data, MessageParcel &reply); - ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply); - ErrCode CmdOpenRawFile(MessageParcel &data, MessageParcel &reply); - ErrCode CmdInsert(MessageParcel &data, MessageParcel &reply); - ErrCode CmdUpdate(MessageParcel &data, MessageParcel &reply); - ErrCode CmdDelete(MessageParcel &data, MessageParcel &reply); - ErrCode CmdQuery(MessageParcel &data, MessageParcel &reply); - ErrCode CmdGetType(MessageParcel &data, MessageParcel &reply); - ErrCode CmdBatchInsert(MessageParcel &data, MessageParcel &reply); - ErrCode CmdRegisterObserver(MessageParcel &data, MessageParcel &reply); - ErrCode CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply); - ErrCode CmdNotifyChange(MessageParcel &data, MessageParcel &reply); - ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply); - ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply); - ErrCode CmdExecuteBatch(MessageParcel &data, MessageParcel &reply); - - using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); - std::map stubFuncMap_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_DATASHARE_STUB_H - diff --git a/frameworks/kits/ability/native/include/datashare_stub_impl.h b/frameworks/kits/ability/native/include/datashare_stub_impl.h deleted file mode 100644 index c2081b42d54..00000000000 --- a/frameworks/kits/ability/native/include/datashare_stub_impl.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H -#define OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H - -#include -#include "datashare_stub.h" -#include "datashare_uv_queue.h" -#include "js_datashare_ext_ability.h" -#include "native_engine/native_value.h" - -namespace OHOS { -namespace AppExecFwk { -using AbilityRuntime::JsDataShareExtAbility; -class DataShareStubImpl : public DataShareStub { -public: - explicit DataShareStubImpl(const std::shared_ptr& extension, napi_env env) - : extension_(extension) - { - uvQueue_ = std::make_shared(env); - } - - virtual ~DataShareStubImpl() {} - - std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - int OpenFile(const Uri &uri, const std::string &mode) override; - - int OpenRawFile(const Uri &uri, const std::string &mode) override; - - int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; - - int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) override; - - int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; - - std::shared_ptr Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; - - std::string GetType(const Uri &uri) override; - - int BatchInsert(const Uri &uri, const std::vector &values) override; - - bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - bool NotifyChange(const Uri &uri) override; - - Uri NormalizeUri(const Uri &uri) override; - - Uri DenormalizeUri(const Uri &uri) override; - - std::vector> ExecuteBatch( - const std::vector> &operations) override; -private: - std::shared_ptr GetOwner(); - -private: - std::shared_ptr extension_; - std::shared_ptr uvQueue_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H - diff --git a/frameworks/kits/ability/native/include/datashare_uv_queue.h b/frameworks/kits/ability/native/include/datashare_uv_queue.h deleted file mode 100644 index 6bf9118be09..00000000000 --- a/frameworks/kits/ability/native/include/datashare_uv_queue.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_UV_QUEUE_H -#define FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_UV_QUEUE_H - -#include - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "uv.h" - -namespace OHOS { -namespace AbilityRuntime { -class DataShareUvQueue { - using NapiVoidFunc = std::function; - -public: - explicit DataShareUvQueue(napi_env env); - virtual ~DataShareUvQueue() = default; - - void SyncCall(NapiVoidFunc func = NapiVoidFunc()); - -private: - struct UvEntry { - napi_env env; - NapiVoidFunc func; - bool done; - bool purge; - std::condition_variable condition; - std::mutex mutex; - }; - - static void Purge(uv_work_t* work); - - napi_env env_ = nullptr; - uv_loop_s* loop_ = nullptr; -}; -} // namespace AbilityRuntime -} // namespace OHOS -#endif // FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_UV_QUEUE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/idatashare.h b/frameworks/kits/ability/native/include/idatashare.h deleted file mode 100644 index ec4275efffe..00000000000 --- a/frameworks/kits/ability/native/include/idatashare.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_I_DATASHARE_H -#define OHOS_APPEXECFWK_I_DATASHARE_H - -#include -#include -#include "uri.h" - -namespace OHOS { -namespace NativeRdb { -class AbsSharedResultSet; -class DataAbilityPredicates; -class ValuesBucket; -} -namespace AAFwk { -class IDataAbilityObserver; -} -namespace AppExecFwk { -class DataAbilityResult; -class DataAbilityOperation; - -class IDataShare : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.AppExecFwk.IDataShare"); - - enum { - CMD_GET_FILE_TYPES = 1, - CMD_OPEN_FILE = 2, - CMD_OPEN_RAW_FILE = 3, - CMD_INSERT = 4, - CMD_UPDATE = 5, - CMD_DELETE = 6, - CMD_QUERY = 7, - CMD_GET_TYPE = 8, - CMD_BATCH_INSERT = 9, - CMD_REGISTER_OBSERVER = 10, - CMD_UNREGISTER_OBSERVER = 11, - CMD_NOTIFY_CHANGE = 12, - CMD_NORMALIZE_URI = 13, - CMD_DENORMALIZE_URI = 14, - CMD_EXECUTE_BATCH = 15, - }; - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - virtual int OpenFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) = 0; - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ - virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) = 0; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) = 0; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ - virtual std::shared_ptr Query( - const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) = 0; - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - virtual std::string GetType(const Uri &uri) = 0; - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - virtual bool NotifyChange(const Uri &uri) = 0; - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - virtual Uri NormalizeUri(const Uri &uri) = 0; - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - virtual Uri DenormalizeUri(const Uri &uri) = 0; - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - virtual std::vector> ExecuteBatch( - const std::vector> &operations) = 0; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_I_DATASHARE_H - diff --git a/frameworks/kits/ability/native/include/js_datashare_ext_ability.h b/frameworks/kits/ability/native/include/js_datashare_ext_ability.h deleted file mode 100644 index 3ab38fb890d..00000000000 --- a/frameworks/kits/ability/native/include/js_datashare_ext_ability.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H -#define FOUNDATION_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "datashare_ext_ability.h" -#include "js_runtime.h" -#include "native_engine/native_reference.h" -#include "native_engine/native_value.h" -#include "values_bucket.h" - -namespace OHOS { -namespace AbilityRuntime { -using RdbValueBucketNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::ValuesBucket& valueBucket); -using RdbResultSetProxyGetNativeObject = OHOS::NativeRdb::AbsSharedResultSet* (*)(const napi_env& env, - const napi_value& arg); -using DataAbilityPredicatesNewInstance = napi_value (*)( - napi_env env, OHOS::NativeRdb::DataAbilityPredicates* predicates); - -/** - * @brief Basic datashare extension ability components. - */ -class JsDataShareExtAbility : public DataShareExtAbility { -public: - JsDataShareExtAbility(JsRuntime& jsRuntime); - virtual ~JsDataShareExtAbility() override; - - /** - * @brief Create JsDataShareExtAbility. - * - * @param runtime The runtime. - * @return The JsDataShareExtAbility instance. - */ - static JsDataShareExtAbility* Create(const std::unique_ptr& runtime); - - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Called when this datashare extension ability is started. You must override this function if you want to - * perform some initialization operations during extension startup. - * - * This function can be called only once in the entire lifecycle of an extension. - * @param Want Indicates the {@link Want} structure containing startup information about the extension. - */ - void OnStart(const AAFwk::Want &want) override; - - /** - * @brief Called when this datashare extension ability is connected for the first time. - * - * You can override this function to implement your own processing logic. - * - * @param want Indicates the {@link Want} structure containing connection information about the datashare - * extension. - * @return Returns a pointer to the sid of the connected datashare extension ability. - */ - sptr OnConnect(const AAFwk::Want &want) override; - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - int OpenFile(const Uri &uri, const std::string &mode) override; - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - int OpenRawFile(const Uri &uri, const std::string &mode) override; - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ - int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) override; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ - std::shared_ptr Query(const Uri &uri, std::vector &columns, - const NativeRdb::DataAbilityPredicates &predicates) override; - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - std::string GetType(const Uri &uri) override; - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - int BatchInsert(const Uri &uri, const std::vector &values) override; - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - bool NotifyChange(const Uri &uri) override; - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - Uri NormalizeUri(const Uri &uri) override; - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - Uri DenormalizeUri(const Uri &uri) override; - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - std::vector> ExecuteBatch( - const std::vector> &operations) override; -private: - NativeValue* CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); - void GetSrcPath(std::string &srcPath); - void LoadLibrary(); - void UnloadLibrary(); - bool CheckCallingPermission(const std::string &permission); - napi_value MakePredicates(napi_env env, const NativeRdb::DataAbilityPredicates &predicates); - - JsRuntime& jsRuntime_; - std::unique_ptr jsObj_; - void* libRdbHandle_ = nullptr; - void* libDataAbilityHandle_ = nullptr; - RdbValueBucketNewInstance rdbValueBucketNewInstance_ = nullptr; - RdbResultSetProxyGetNativeObject rdbResultSetProxyGetNativeObject_ = nullptr; - DataAbilityPredicatesNewInstance dataAbilityPredicatesNewInstance_ = nullptr; -}; -} // namespace AbilityRuntime -} // namespace OHOS -#endif // FOUNDATION_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h b/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h deleted file mode 100644 index 02478ffaf94..00000000000 --- a/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H -#define ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H - -#include - -#include "ability_connect_callback.h" -#include "datashare_ext_ability_context.h" -#include "native_engine/native_engine.h" -#include "native_engine/native_value.h" - -namespace OHOS { -namespace AbilityRuntime { -NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, - std::shared_ptr context); -} // namespace AbilityRuntime -} // namespace OHOS -#endif // ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H diff --git a/frameworks/kits/ability/native/src/datashare_connection.cpp b/frameworks/kits/ability/native/src/datashare_connection.cpp deleted file mode 100644 index 0e013ea6d4d..00000000000 --- a/frameworks/kits/ability/native/src/datashare_connection.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_connection.h" - -#include "ability_manager_client.h" -#include "bytrace.h" -#include "datashare_proxy.h" -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AppExecFwk { -sptr DataShareConnection::instance_ = nullptr; -std::mutex DataShareConnection::mutex_; - -/** - * @brief get singleton of Class DataShareConnection - * - * @return The singleton of DataShareConnection - */ -sptr DataShareConnection::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard lock(mutex_); - if (instance_ == nullptr) { - instance_ = sptr(new (std::nothrow) DataShareConnection()); - } - } - return instance_; -} - -/** - * @brief This method is called back to receive the connection result after an ability calls the - * ConnectAbility method to connect it to an extension ability. - * - * @param element: Indicates information about the connected extension ability. - * @param remote: Indicates the remote proxy object of the extension ability. - * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any - * other value indicates a connection failure. - */ -void DataShareConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s called begin", __func__); - if (remoteObject == nullptr) { - HILOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, remote is nullptr"); - return; - } - dataShareProxy_ = iface_cast(remoteObject); - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, dataShareProxy_ is nullptr"); - return; - } - isConnected_.store(true); - HILOG_INFO("%{public}s called end", __func__); -} - -/** - * @brief This method is called back to receive the disconnection result after the connected extension ability crashes - * or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and each ability - * previously connected to it will call onAbilityDisconnectDone. - * - * @param element: Indicates information about the disconnected extension ability. - * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, and - * any other value indicates a disconnection failure. - */ -void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s called begin", __func__); - dataShareProxy_ = nullptr; - isConnected_.store(false); - HILOG_INFO("%{public}s called end", __func__); -} - -/** - * @brief connect remote ability of DataShareExtAbility. - */ -void DataShareConnection::ConnectDataShareExtAbility(const AAFwk::Want &want, const sptr &token) -{ - HILOG_INFO("%{public}s called begin", __func__); - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token); - HILOG_INFO("%{public}s called end, ret=%{public}d", __func__, ret); -} - -/** - * @brief disconnect remote ability of DataShareExtAbility. - */ -void DataShareConnection::DisconnectDataShareExtAbility() -{ - HILOG_INFO("%{public}s called begin", __func__); - dataShareProxy_ = nullptr; - isConnected_.store(false); - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); - HILOG_INFO("%{public}s called end, ret=%{public}d", __func__, ret); -} - -/** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ -bool DataShareConnection::IsExtAbilityConnected() -{ - return isConnected_.load(); -} - -sptr DataShareConnection::GetDataShareProxy() -{ - return dataShareProxy_; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_ext_ability.cpp b/frameworks/kits/ability/native/src/datashare_ext_ability.cpp deleted file mode 100644 index 917405d9fa4..00000000000 --- a/frameworks/kits/ability/native/src/datashare_ext_ability.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_ext_ability.h" - -#include "ability_loader.h" -#include "connection_manager.h" -#include "hilog_wrapper.h" -#include "js_datashare_ext_ability.h" -#include "runtime.h" -#include "datashare_ext_ability_context.h" - -namespace OHOS { -namespace AbilityRuntime { -using namespace OHOS::AppExecFwk; -DataShareExtAbility* DataShareExtAbility::Create(const std::unique_ptr& runtime) -{ - if (!runtime) { - return new DataShareExtAbility(); - } - HILOG_INFO("DataShareExtAbility::Create runtime"); - switch (runtime->GetLanguage()) { - case Runtime::Language::JS: - return JsDataShareExtAbility::Create(runtime); - - default: - return new DataShareExtAbility(); - } -} - -void DataShareExtAbility::Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) -{ - ExtensionBase::Init(record, application, handler, token); - HILOG_INFO("DataShareExtAbility begin init context"); -} - -std::vector DataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::vector ret; - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int DataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -int DataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -int DataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -int DataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -int DataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -std::shared_ptr DataShareExtAbility::Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::shared_ptr ret; - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -std::string DataShareExtAbility::GetType(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return ""; -} - -int DataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return 0; -} - -bool DataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -bool DataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -bool DataShareExtAbility::NotifyChange(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -Uri DataShareExtAbility::NormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - HILOG_INFO("%{public}s end.", __func__); - return urivalue; -} - -Uri DataShareExtAbility::DenormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - HILOG_INFO("%{public}s end.", __func__); - return urivalue; -} - -std::vector> DataShareExtAbility::ExecuteBatch( - const std::vector> &operations) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::vector> results; - HILOG_INFO("%{public}s end.", __func__); - return results; -} -} // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp b/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp deleted file mode 100644 index 044aec9b225..00000000000 --- a/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_ext_ability_module_loader.h" -#include "datashare_ext_ability.h" - -namespace OHOS::AbilityRuntime { -DataShareExtAbilityModuleLoader::DataShareExtAbilityModuleLoader() = default; -DataShareExtAbilityModuleLoader::~DataShareExtAbilityModuleLoader() = default; - -Extension *DataShareExtAbilityModuleLoader::Create(const std::unique_ptr& runtime) const -{ - return DataShareExtAbility::Create(runtime); -} - -extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() -{ - return &DataShareExtAbilityModuleLoader::GetInstance(); -} -} // namespace OHOS::AbilityRuntime \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_helper.cpp b/frameworks/kits/ability/native/src/datashare_helper.cpp deleted file mode 100644 index 69a4183644b..00000000000 --- a/frameworks/kits/ability/native/src/datashare_helper.cpp +++ /dev/null @@ -1,1110 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_helper.h" - -#include "ability_scheduler_interface.h" -#include "ability_thread.h" -#include "abs_shared_result_set.h" -#include "data_ability_observer_interface.h" -#include "data_ability_operation.h" -#include "data_ability_predicates.h" -#include "data_ability_result.h" -#include "hilog_wrapper.h" -#include "idatashare.h" -#include "values_bucket.h" - -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string SCHEME_DATASHARE = "datashare"; -constexpr int INVALID_VALUE = -1; -} // namespace - -std::mutex DataShareHelper::oplock_; -DataShareHelper::DataShareHelper(const std::shared_ptr &context, - const AAFwk::Want &want) -{ - HILOG_INFO("DataShareHelper::DataShareHelper with context and want start"); - token_ = context->GetToken(); - want_ = want; - uri_ = nullptr; - dataShareProxy_ = nullptr; - dataShareConnection_ = DataShareConnection::GetInstance(); - HILOG_INFO("DataShareHelper::DataShareHelper with context and want end"); -} - -DataShareHelper::DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, - const std::shared_ptr &uri, const sptr &dataShareProxy) -{ - HILOG_INFO("DataShareHelper::DataShareHelper start"); - token_ = context->GetToken(); - context_ = std::shared_ptr(context); - want_ = want; - uri_ = uri; - dataShareProxy_ = dataShareProxy; - dataShareConnection_ = DataShareConnection::GetInstance(); - HILOG_INFO("DataShareHelper::DataShareHelper end"); -} - -DataShareHelper::DataShareHelper(const std::shared_ptr &context, - const AAFwk::Want &want, const std::shared_ptr &uri, const sptr &dataShareProxy) -{ - HILOG_INFO("DataShareHelper::DataShareHelper start"); - token_ = context->GetToken(); - want_ = want; - uri_ = uri; - dataShareProxy_ = dataShareProxy; - dataShareConnection_ = DataShareConnection::GetInstance(); - HILOG_INFO("DataShareHelper::DataShareHelper end"); -} - -void DataShareHelper::AddDataShareDeathRecipient(const sptr &token) -{ - HILOG_INFO("DataShareHelper::AddDataShareDeathRecipient start."); - if (token != nullptr && callerDeathRecipient_ != nullptr) { - HILOG_INFO("token RemoveDeathRecipient."); - token->RemoveDeathRecipient(callerDeathRecipient_); - } - if (callerDeathRecipient_ == nullptr) { - callerDeathRecipient_ = - new DataShareDeathRecipient(std::bind(&DataShareHelper::OnSchedulerDied, this, std::placeholders::_1)); - } - if (token != nullptr) { - HILOG_INFO("token AddDeathRecipient."); - token->AddDeathRecipient(callerDeathRecipient_); - } - HILOG_INFO("DataShareHelper::AddDataShareDeathRecipient end."); -} - -void DataShareHelper::OnSchedulerDied(const wptr &remote) -{ - HILOG_INFO("'%{public}s start':", __func__); - auto object = remote.promote(); - object = nullptr; - dataShareProxy_ = nullptr; - uri_ = nullptr; - HILOG_INFO("DataShareHelper::OnSchedulerDied end."); -} - -/** - * @brief Creates a DataShareHelper instance without specifying the Uri based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * - * @return Returns the created DataShareHelper instance where Uri is not specified. - */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const AAFwk::Want &want) -{ - HILOG_INFO("DataShareHelper::Creator with context start."); - if (context == nullptr) { - HILOG_ERROR("DataShareHelper::Creator (context) failed, context == nullptr"); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator before ConnectDataShareExtAbility."); - sptr dataShareConnection = DataShareConnection::GetInstance(); - if (!dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); - } - HILOG_INFO("DataShareHelper::Creator after ConnectDataShareExtAbility."); - - DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want); - if (ptrDataShareHelper == nullptr) { - HILOG_ERROR("DataShareHelper::Creator (context) failed, create DataShareHelper failed"); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator with context end."); - return std::shared_ptr(ptrDataShareHelper); -} - -/** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * @param uri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const AAFwk::Want &want, const std::shared_ptr &uri) -{ - HILOG_INFO("DataShareHelper::Creator with context, want and uri called start."); - if (context == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, context == nullptr"); - return nullptr; - } - - if (uri == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, uri == nullptr"); - return nullptr; - } - - if (uri->GetScheme() != SCHEME_DATASHARE) { - HILOG_ERROR("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", - uri->GetScheme().c_str()); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator before ConnectDataShareExtAbility."); - sptr dataShareProxy = nullptr; - - sptr dataShareConnection = DataShareConnection::GetInstance(); - if (!dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); - } - dataShareProxy = dataShareConnection->GetDataShareProxy(); - if (dataShareProxy == nullptr) { - HILOG_WARN("DataShareHelper::Creator get invalid dataShareProxy"); - } - HILOG_INFO("DataShareHelper::Creator after ConnectDataShareExtAbility."); - - DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); - if (ptrDataShareHelper == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, create DataShareHelper failed"); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator with context, want and uri called end."); - return std::shared_ptr(ptrDataShareHelper); -} - -/** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param context Indicates the Context object on OHOS. - * @param want Indicates the Want containing information about the target extension ability to connect. - * @param uri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const AAFwk::Want &want, - const std::shared_ptr &uri) -{ - HILOG_INFO("DataShareHelper::Creator with runtime context, want and uri called start."); - if (context == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, context == nullptr"); - return nullptr; - } - - if (uri == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, uri == nullptr"); - return nullptr; - } - - if (uri->GetScheme() != SCHEME_DATASHARE) { - HILOG_ERROR("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", - uri->GetScheme().c_str()); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator before ConnectDataShareExtAbility."); - sptr dataShareProxy = nullptr; - - sptr dataShareConnection = DataShareConnection::GetInstance(); - if (!dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); - } - dataShareProxy = dataShareConnection->GetDataShareProxy(); - if (dataShareProxy == nullptr) { - HILOG_WARN("DataShareHelper::Creator get invalid dataShareProxy"); - } - HILOG_INFO("DataShareHelper::Creator after ConnectDataShareExtAbility."); - - DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); - if (ptrDataShareHelper == nullptr) { - HILOG_ERROR("DataShareHelper::Creator failed, create DataShareHelper failed"); - return nullptr; - } - - HILOG_INFO("DataShareHelper::Creator with runtime context, want and uri called end."); - return std::shared_ptr(ptrDataShareHelper); -} - -/** - * @brief Releases the client resource of the data share. - * You should call this method to releases client resource after the data operations are complete. - * - * @return Returns true if the resource is successfully released; returns false otherwise. - */ -bool DataShareHelper::Release() -{ - HILOG_INFO("DataShareHelper::Release start."); - if (uri_ == nullptr) { - HILOG_ERROR("DataShareHelper::Release failed, uri_ is nullptr"); - return false; - } - - HILOG_INFO("DataShareHelper::Release before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::Release after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - uri_.reset(); - HILOG_INFO("DataShareHelper::Release end."); - return true; -} - -/** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ -std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) -{ - HILOG_INFO("DataShareHelper::GetFileTypes start."); - std::vector matchedMIMEs; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return matchedMIMEs; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::GetFileTypes before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::GetFileTypes after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return matchedMIMEs; - } - - HILOG_INFO("DataShareHelper::GetFileTypes before dataShareProxy_->GetFileTypes."); - matchedMIMEs = dataShareProxy_->GetFileTypes(uri, mimeTypeFilter); - HILOG_INFO("DataShareHelper::GetFileTypes after dataShareProxy_->GetFileTypes."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::GetFileTypes before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::GetFileTypes after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - - HILOG_INFO("DataShareHelper::GetFileTypes end."); - return matchedMIMEs; -} - -/** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ -int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) -{ - HILOG_INFO("DataShareHelper::OpenFile start."); - int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return fd; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::OpenFile before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::OpenFile after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return fd; - } - - HILOG_INFO("DataShareHelper::OpenFile before dataShareProxy_->OpenFile."); - fd = dataShareProxy_->OpenFile(uri, mode); - HILOG_INFO("DataShareHelper::OpenFile after dataShareProxy_->OpenFile."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::OpenFile before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::OpenFile after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::OpenFile end."); - return fd; -} - -/** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ -int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) -{ - HILOG_INFO("DataShareHelper::OpenRawFile start."); - int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return fd; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::OpenRawFile before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::OpenRawFile after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return fd; - } - - HILOG_INFO("DataShareHelper::OpenRawFile before dataShareProxy_->OpenRawFile."); - fd = dataShareProxy_->OpenRawFile(uri, mode); - HILOG_INFO("DataShareHelper::OpenRawFile after dataShareProxy_->OpenRawFile."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::OpenRawFile before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::OpenRawFile after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::OpenRawFile end."); - return fd; -} - -/** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ -int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) -{ - HILOG_INFO("DataShareHelper::Insert start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Insert before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::Insert after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - HILOG_INFO("DataShareHelper::Insert before dataShareProxy_->Insert."); - index = dataShareProxy_->Insert(uri, value); - HILOG_INFO("DataShareHelper::Insert after dataShareProxy_->Insert."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Insert before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::Insert after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::Insert end."); - return index; -} - -/** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ -int DataShareHelper::Update( - Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("DataShareHelper::Update start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Update before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::Update after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - HILOG_INFO("DataShareHelper::Update before dataShareProxy_->Update."); - index = dataShareProxy_->Update(uri, value, predicates); - HILOG_INFO("DataShareHelper::Update after dataShareProxy_->Update."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Update before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::Update after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::Update end."); - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ -int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("DataShareHelper::Delete start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Delete before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::Delete after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - HILOG_INFO("DataShareHelper::Delete before dataShareProxy_->Delete."); - index = dataShareProxy_->Delete(uri, predicates); - HILOG_INFO("DataShareHelper::Delete after dataShareProxy_->Delete."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Delete before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::Delete after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::Delete end."); - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ -std::shared_ptr DataShareHelper::Query( - Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("DataShareHelper::Query start."); - std::shared_ptr resultset = nullptr; - - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return resultset; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Query before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::Query after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return resultset; - } - - HILOG_INFO("DataShareHelper::Query before dataShareProxy_->Query."); - resultset = dataShareProxy_->Query(uri, columns, predicates); - HILOG_INFO("DataShareHelper::Query after dataShareProxy_->Query."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::Query before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::Query after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::Query end."); - return resultset; -} - -/** - * @brief Obtains the MIME type matching the data specified by the URI of the data share. This method should be - * implemented by a data share. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ -std::string DataShareHelper::GetType(Uri &uri) -{ - HILOG_INFO("DataShareHelper::GetType start."); - std::string type; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return type; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::GetType before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::GetType after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return type; - } - - HILOG_INFO("DataShareHelper::GetType before dataShareProxy_->GetType."); - type = dataShareProxy_->GetType(uri); - HILOG_INFO("DataShareHelper::GetType after dataShareProxy_->GetType."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::GetType before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::GetType after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::GetType end."); - return type; -} - -/** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ -int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) -{ - HILOG_INFO("DataShareHelper::BatchInsert start."); - int ret = INVALID_VALUE; - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return ret; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::BatchInsert before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::BatchInsert after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return ret; - } - - HILOG_INFO("DataShareHelper::BatchInsert before dataShareProxy_->BatchInsert."); - ret = dataShareProxy_->BatchInsert(uri, values); - HILOG_INFO("DataShareHelper::BatchInsert after dataShareProxy_->BatchInsert."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::BatchInsert before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::BatchInsert after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::BatchInsert end."); - return ret; -} - -bool DataShareHelper::CheckUriParam(const Uri &uri) -{ - HILOG_INFO("DataShareHelper::CheckUriParam start."); - Uri checkUri(uri.ToString()); - if (!CheckOhosUri(checkUri)) { - HILOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri failed"); - return false; - } - - if (uri_ != nullptr) { - if (!CheckOhosUri(*uri_)) { - HILOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri_ failed"); - return false; - } - - std::vector checkSegments; - checkUri.GetPathSegments(checkSegments); - - std::vector segments; - uri_->GetPathSegments(segments); - - if (checkSegments[0] != segments[0]) { - HILOG_ERROR("DataShareHelper::CheckUriParam failed. the datashare in uri doesn't equal the one in uri_."); - return false; - } - } - HILOG_INFO("DataShareHelper::CheckUriParam end."); - return true; -} - -bool DataShareHelper::CheckOhosUri(const Uri &uri) -{ - HILOG_INFO("DataShareHelper::CheckOhosUri start."); - Uri checkUri(uri.ToString()); - if (checkUri.GetScheme() != SCHEME_DATASHARE) { - HILOG_ERROR("DataShareHelper::CheckOhosUri failed. uri is not a datashare one."); - return false; - } - - std::vector segments; - checkUri.GetPathSegments(segments); - if (segments.empty()) { - HILOG_ERROR("DataShareHelper::CheckOhosUri failed. There is no segments in the uri."); - return false; - } - - if (checkUri.GetPath() == "") { - HILOG_ERROR("DataShareHelper::CheckOhosUri failed. The path in the uri is empty."); - return false; - } - HILOG_INFO("DataShareHelper::CheckOhosUri end."); - return true; -} - -/** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("DataShareHelper::RegisterObserver start."); - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataObserver == nullptr) { - HILOG_ERROR("%{public}s called. dataObserver is nullptr", __func__); - return; - } - - Uri tmpUri(uri.ToString()); - std::lock_guard lock_l(oplock_); - if (uri_ == nullptr) { - auto datashare = registerMap_.find(dataObserver); - if (datashare == registerMap_.end()) { - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - registerMap_.emplace(dataObserver, dataShareProxy_); - uriMap_.emplace(dataObserver, tmpUri.GetPath()); - } else { - auto path = uriMap_.find(dataObserver); - if (path->second != tmpUri.GetPath()) { - HILOG_ERROR("DataShareHelper::RegisterObserver failed input uri's path is not equal the one the " - "observer used"); - return; - } - dataShareProxy_ = datashare->second; - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("DataShareHelper::RegisterObserver failed dataShareProxy_ == nullptr"); - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); - return; - } - dataShareProxy_->RegisterObserver(uri, dataObserver); - HILOG_INFO("DataShareHelper::RegisterObserver end."); -} - -/** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("DataShareHelper::UnregisterObserver start."); - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataObserver == nullptr) { - HILOG_ERROR("%{public}s called. dataObserver is nullptr", __func__); - return; - } - - Uri tmpUri(uri.ToString()); - std::lock_guard lock_l(oplock_); - if (uri_ == nullptr) { - auto datashare = registerMap_.find(dataObserver); - if (datashare == registerMap_.end()) { - return; - } - auto path = uriMap_.find(dataObserver); - if (path->second != tmpUri.GetPath()) { - HILOG_ERROR("DataShareHelper::UnregisterObserver failed input uri's path is not equal the one the " - "observer used"); - return; - } - dataShareProxy_ = datashare->second; - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("DataShareHelper::UnregisterObserver failed dataShareProxy_ == nullptr"); - return; - } - - dataShareProxy_->UnregisterObserver(uri, dataObserver); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::UnregisterObserver before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::UnregisterObserver after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); - HILOG_INFO("DataShareHelper::UnregisterObserver end."); -} - -/** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - */ -void DataShareHelper::NotifyChange(const Uri &uri) -{ - HILOG_INFO("DataShareHelper::NotifyChange start."); - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataShareProxy_ == nullptr) { - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return; - } - - dataShareProxy_->NotifyChange(uri); - - if (uri_ == nullptr) { - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::NotifyChange end."); -} - -/** - * @brief Converts the given uri that refer to the data share into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the data share even if the - * context has changed. If you implement URI normalization for a data share, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any - * method that is called on the data share must require normalization verification and denormalization. The default - * implementation of this method returns null, indicating that this data share does not support URI normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the data share supports URI normalization; returns null otherwise. - */ -Uri DataShareHelper::NormalizeUri(Uri &uri) -{ - HILOG_INFO("DataShareHelper::NormalizeUri start."); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return urivalue; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::NormalizeUri before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::NormalizeUri after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return urivalue; - } - - HILOG_INFO("DataShareHelper::NormalizeUri before dataShareProxy_->NormalizeUri."); - urivalue = dataShareProxy_->NormalizeUri(uri); - HILOG_INFO("DataShareHelper::NormalizeUri after dataShareProxy_->NormalizeUri."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::NormalizeUri before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::NormalizeUri after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::NormalizeUri end."); - return urivalue; -} - -/** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to - * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in - * the current environment. - */ -Uri DataShareHelper::DenormalizeUri(Uri &uri) -{ - HILOG_INFO("DataShareHelper::DenormalizeUri start."); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - HILOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return urivalue; - } - - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::DenormalizeUri before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::DenormalizeUri after ConnectDataShareExtAbility."); - if (isSystemCaller_ && dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return urivalue; - } - - HILOG_INFO("DataShareHelper::DenormalizeUri before dataShareProxy_->DenormalizeUri."); - urivalue = dataShareProxy_->DenormalizeUri(uri); - HILOG_INFO("DataShareHelper::DenormalizeUri after dataShareProxy_->DenormalizeUri."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::DenormalizeUri before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::DenormalizeUri after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::DenormalizeUri end."); - return urivalue; -} - -void DataShareDeathRecipient::OnRemoteDied(const wptr &remote) -{ - HILOG_INFO("recv DataShareDeathRecipient death notice"); - if (handler_) { - handler_(remote); - } - HILOG_INFO("DataShareHelper::OnRemoteDied end."); -} - -DataShareDeathRecipient::DataShareDeathRecipient(RemoteDiedHandler handler) : handler_(handler) -{} - -DataShareDeathRecipient::~DataShareDeathRecipient() -{} - -std::vector> DataShareHelper::ExecuteBatch( - const Uri &uri, const std::vector> &operations) -{ - HILOG_INFO("DataShareHelper::ExecuteBatch start"); - std::vector> results; - if (!CheckUriParam(uri)) { - HILOG_ERROR("DataShareHelper::ExecuteBatch. CheckUriParam uri failed"); - return results; - } - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::ExecuteBatch before ConnectDataShareExtAbility."); - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(want_, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - HILOG_INFO("DataShareHelper::ExecuteBatch after ConnectDataShareExtAbility."); - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("DataShareHelper::ExecuteBatch failed dataShareProxy_ == nullptr"); - return results; - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - HILOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return results; - } - - HILOG_INFO("DataShareHelper::ExecuteBatch before dataShareProxy_->ExecuteBatch."); - results = dataShareProxy_->ExecuteBatch(operations); - HILOG_INFO("DataShareHelper::ExecuteBatch after dataShareProxy_->ExecuteBatch."); - if (uri_ == nullptr) { - HILOG_INFO("DataShareHelper::ExecuteBatch before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - HILOG_INFO("DataShareHelper::ExecuteBatch after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - HILOG_INFO("DataShareHelper::ExecuteBatch end"); - return results; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_proxy.cpp b/frameworks/kits/ability/native/src/datashare_proxy.cpp deleted file mode 100644 index dd967116281..00000000000 --- a/frameworks/kits/ability/native/src/datashare_proxy.cpp +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_proxy.h" - -#include -#include - -#include "abs_shared_result_set.h" -#include "data_ability_observer_interface.h" -#include "data_ability_operation.h" -#include "data_ability_predicates.h" -#include "data_ability_result.h" -#include "hilog_wrapper.h" -#include "ipc_types.h" -#include "ishared_result_set.h" -#include "pac_map.h" -#include "values_bucket.h" - -namespace OHOS { -namespace AppExecFwk { -std::vector DataShareProxy::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::vector types; - - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return types; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return types; - } - - if (!data.WriteString(mimeTypeFilter)) { - HILOG_ERROR("fail to WriteString mimeTypeFilter"); - return types; - } - - int32_t err = Remote()->SendRequest(CMD_GET_FILE_TYPES, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - } - - if (!reply.ReadStringVector(&types)) { - HILOG_ERROR("fail to ReadStringVector types"); - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return types; -} - -int DataShareProxy::OpenFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - int fd = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return fd; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return fd; - } - - if (!data.WriteString(mode)) { - HILOG_ERROR("fail to WriteString mode"); - return fd; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_OPEN_FILE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("OpenFile fail to SendRequest. err: %d", err); - return fd; - } - - fd = reply.ReadFileDescriptor(); - if (fd == -1) { - HILOG_ERROR("fail to ReadFileDescriptor fd"); - return fd; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return fd; -} - -int DataShareProxy::OpenRawFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - int fd = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return fd; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return fd; - } - - if (!data.WriteString(mode)) { - HILOG_ERROR("fail to WriteString mode"); - return fd; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_OPEN_RAW_FILE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("OpenRawFile fail to SendRequest. err: %d", err); - return fd; - } - - if (!reply.ReadInt32(fd)) { - HILOG_ERROR("fail to ReadInt32 fd"); - return fd; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return fd; -} - -int DataShareProxy::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) -{ - HILOG_INFO("%{public}s begin.", __func__); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!data.WriteParcelable(&value)) { - HILOG_ERROR("fail to WriteParcelable value"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_INSERT, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("Insert fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - HILOG_ERROR("fail to ReadInt32 index"); - return index; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return index; -} - -int DataShareProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!data.WriteParcelable(&value)) { - HILOG_ERROR("fail to WriteParcelable value"); - return index; - } - - if (!data.WriteParcelable(&predicates)) { - HILOG_ERROR("fail to WriteParcelable predicates"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_UPDATE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("Update fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - HILOG_ERROR("fail to ReadInt32 index"); - return index; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return index; -} - -int DataShareProxy::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!data.WriteParcelable(&predicates)) { - HILOG_ERROR("fail to WriteParcelable predicates"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_DELETE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("Delete fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - HILOG_ERROR("fail to ReadInt32 index"); - return index; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return index; -} - -std::shared_ptr DataShareProxy::Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return nullptr; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return nullptr; - } - - if (!data.WriteStringVector(columns)) { - HILOG_ERROR("fail to WriteStringVector columns"); - return nullptr; - } - - if (!data.WriteParcelable(&predicates)) { - HILOG_ERROR("fail to WriteParcelable predicates"); - return nullptr; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_QUERY, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("Query fail to SendRequest. err: %d", err); - return nullptr; - } - HILOG_INFO("%{public}s end successfully.", __func__); - return OHOS::NativeRdb::ISharedResultSet::ReadFromParcel(reply); -} - -std::string DataShareProxy::GetType(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::string type; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return type; - } - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return type; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_GET_TYPE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - return type; - } - - type = reply.ReadString(); - if (type.empty()) { - HILOG_ERROR("fail to ReadString type"); - return type; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return type; -} - -int DataShareProxy::BatchInsert(const Uri &uri, const std::vector &values) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return ret; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return ret; - } - - int count = (int)values.size(); - if (!data.WriteInt32(count)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return ret; - } - - for (int i = 0; i < count; i++) { - if (!data.WriteParcelable(&values[i])) { - HILOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i); - return ret; - } - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_BATCH_INSERT, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - return ret; - } - - if (!reply.ReadInt32(ret)) { - HILOG_ERROR("fail to ReadInt32 index"); - return ret; - } - - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -bool DataShareProxy::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - auto remoteObject = dataObserver->AsObject(); - if (remoteObject == nullptr) { - HILOG_ERROR("remoteObject is nullptr"); - return false; - } - - if (!data.WriteRemoteObject(remoteObject)) { - HILOG_ERROR("%{public}s failed to WriteRemoteObject dataObserver ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_REGISTER_OBSERVER, data, reply, option); - if (result == ERR_NONE) { - HILOG_INFO("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); - } else { - HILOG_ERROR("%{public}s SendRequest error, result=%{public}d", __func__, result); - return false; - } - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -bool DataShareProxy::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - auto remoteObject = dataObserver->AsObject(); - if (remoteObject == nullptr) { - HILOG_ERROR("remoteObject is nullptr"); - return false; - } - - if (!data.WriteRemoteObject(remoteObject)) { - HILOG_ERROR("%{public}s failed to WriteRemoteObject dataObserver ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_UNREGISTER_OBSERVER, data, reply, option); - if (result == ERR_NONE) { - HILOG_INFO("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); - } else { - HILOG_ERROR("%{public}s SendRequest error, result=%{public}d", __func__, result); - return false; - } - HILOG_INFO("%{public}s end successfully.", __func__); - return true; -} - -bool DataShareProxy::NotifyChange(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_NOTIFY_CHANGE, data, reply, option); - if (result == ERR_NONE) { - HILOG_INFO("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); - } else { - HILOG_ERROR("%{public}s SendRequest error, result=%{public}d", __func__, result); - return false; - } - HILOG_INFO("%{public}s end successfully.", __func__); - return true; -} - -Uri DataShareProxy::NormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return urivalue; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return urivalue; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_NORMALIZE_URI, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err); - return urivalue; - } - - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - HILOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; - } - HILOG_INFO("%{public}s end successfully.", __func__); - return *info; -} - -Uri DataShareProxy::DenormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return urivalue; - } - - if (!data.WriteParcelable(&uri)) { - HILOG_ERROR("fail to WriteParcelable uri"); - return urivalue; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_DENORMALIZE_URI, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err); - return urivalue; - } - - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - HILOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; - } - HILOG_INFO("%{public}s end successfully.", __func__); - return *info; -} - -std::vector> DataShareProxy::ExecuteBatch( - const std::vector> &operations) -{ - HILOG_INFO("%{public}s begin.", __func__); - MessageParcel data; - std::vector> results; - results.clear(); - - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return results; - } - - int count = (int)operations.size(); - if (!data.WriteInt32(count)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return results; - } - - for (int i = 0; i < count; i++) { - if (!data.WriteParcelable(operations[i].get())) { - HILOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i); - return results; - } - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_EXECUTE_BATCH, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("fail to SendRequest. err: %{public}d", err); - return results; - } - - int total = 0; - if (!reply.ReadInt32(total)) { - HILOG_ERROR("fail to ReadInt32 count %{public}d", total); - return results; - } - - for (int i = 0; i < total; i++) { - AppExecFwk::DataAbilityResult *result = reply.ReadParcelable(); - if (result == nullptr) { - HILOG_ERROR("result is nullptr, index = %{public}d", i); - return results; - } - std::shared_ptr dataAbilityResult(result); - results.push_back(dataAbilityResult); - } - HILOG_INFO("%{public}s end successfully.", __func__); - return results; -} -} // namespace AAFwk -} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/datashare_stub.cpp b/frameworks/kits/ability/native/src/datashare_stub.cpp deleted file mode 100644 index 58907547019..00000000000 --- a/frameworks/kits/ability/native/src/datashare_stub.cpp +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_stub.h" - -#include "data_ability_observer_interface.h" -#include "data_ability_operation.h" -#include "data_ability_predicates.h" -#include "data_ability_result.h" -#include "hilog_wrapper.h" -#include "ipc_types.h" -#include "ishared_result_set.h" -#include "values_bucket.h" - -namespace OHOS { -namespace AppExecFwk { -DataShareStub::DataShareStub() -{ - stubFuncMap_[CMD_GET_FILE_TYPES] = &DataShareStub::CmdGetFileTypes; - stubFuncMap_[CMD_OPEN_FILE] = &DataShareStub::CmdOpenFile; - stubFuncMap_[CMD_OPEN_RAW_FILE] = &DataShareStub::CmdOpenRawFile; - stubFuncMap_[CMD_INSERT] = &DataShareStub::CmdInsert; - stubFuncMap_[CMD_UPDATE] = &DataShareStub::CmdUpdate; - stubFuncMap_[CMD_DELETE] = &DataShareStub::CmdDelete; - stubFuncMap_[CMD_QUERY] = &DataShareStub::CmdQuery; - stubFuncMap_[CMD_GET_TYPE] = &DataShareStub::CmdGetType; - stubFuncMap_[CMD_BATCH_INSERT] = &DataShareStub::CmdBatchInsert; - stubFuncMap_[CMD_REGISTER_OBSERVER] = &DataShareStub::CmdRegisterObserver; - stubFuncMap_[CMD_UNREGISTER_OBSERVER] = &DataShareStub::CmdUnregisterObserver; - stubFuncMap_[CMD_NOTIFY_CHANGE] = &DataShareStub::CmdNotifyChange; - stubFuncMap_[CMD_NORMALIZE_URI] = &DataShareStub::CmdNormalizeUri; - stubFuncMap_[CMD_DENORMALIZE_URI] = &DataShareStub::CmdDenormalizeUri; - stubFuncMap_[CMD_EXECUTE_BATCH] = &DataShareStub::CmdExecuteBatch; -} - -DataShareStub::~DataShareStub() -{ - stubFuncMap_.clear(); -} - -int DataShareStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, - MessageOption& option) -{ - HILOG_INFO("%{public}s Received stub message: %{public}d", __func__, code); - std::u16string descriptor = DataShareStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - HILOG_INFO("local descriptor is not equal to remote"); - return ERR_INVALID_STATE; - } - - const auto &itFunc = stubFuncMap_.find(code); - if (itFunc != stubFuncMap_.end()) { - return (this->*(itFunc->second))(data, reply); - } - - HILOG_INFO("%{public}s remote request unhandled: %{public}d", __func__, code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} - -ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mimeTypeFilter = data.ReadString(); - if (mimeTypeFilter.empty()) { - HILOG_ERROR("DataShareStub mimeTypeFilter is nullptr"); - return ERR_INVALID_VALUE; - } - std::vector types = GetFileTypes(*uri, mimeTypeFilter); - if (!reply.WriteStringVector(types)) { - HILOG_ERROR("fail to WriteStringVector types"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mode = data.ReadString(); - if (mode.empty()) { - HILOG_ERROR("DataShareStub mode is nullptr"); - return ERR_INVALID_VALUE; - } - int fd = OpenFile(*uri, mode); - if (fd < 0) { - HILOG_ERROR("OpenFile fail, fd is %{pubilc}d", fd); - return ERR_INVALID_VALUE; - } - if (!reply.WriteFileDescriptor(fd)) { - HILOG_ERROR("fail to WriteFileDescriptor fd"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mode = data.ReadString(); - if (mode.empty()) { - HILOG_ERROR("DataShareStub mode is nullptr"); - return ERR_INVALID_VALUE; - } - int fd = OpenRawFile(*uri, mode); - if (!reply.WriteInt32(fd)) { - HILOG_ERROR("fail to WriteInt32 fd"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr value(data.ReadParcelable()); - if (value == nullptr) { - HILOG_ERROR("ReadParcelable value is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Insert(*uri, *value); - if (!reply.WriteInt32(index)) { - HILOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - HILOG_INFO("DataShareStub::CmdInsertInner end"); - return NO_ERROR; -} - -ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr value(data.ReadParcelable()); - if (value == nullptr) { - HILOG_ERROR("ReadParcelable value is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - HILOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Update(*uri, *value, *predicates); - if (!reply.WriteInt32(index)) { - HILOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - HILOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Delete(*uri, *predicates); - if (!reply.WriteInt32(index)) { - HILOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::vector columns; - if (!data.ReadStringVector(&columns)) { - HILOG_ERROR("fail to ReadStringVector columns"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - HILOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - auto resultSet = Query(*uri, columns, *predicates); - if (resultSet == nullptr) { - HILOG_ERROR("fail to WriteParcelable resultSet"); - return ERR_INVALID_VALUE; - } - auto result = NativeRdb::ISharedResultSet::WriteToParcel(std::move(resultSet), reply); - if (result == nullptr) { - HILOG_ERROR("!resultSet->Marshalling(reply)"); - return ERR_INVALID_VALUE; - } - HILOG_INFO("DataShareStub::CmdQueryInner end"); - return NO_ERROR; -} - -ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string type = GetType(*uri); - if (!reply.WriteString(type)) { - HILOG_ERROR("fail to WriteString type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - int count = 0; - if (!data.ReadInt32(count)) { - HILOG_ERROR("fail to ReadInt32 index"); - return ERR_INVALID_VALUE; - } - - std::vector values; - for (int i = 0; i < count; i++) { - std::unique_ptr value(data.ReadParcelable()); - if (value == nullptr) { - HILOG_ERROR("DataShareStub value is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - values.emplace_back(*value); - } - - int ret = BatchInsert(*uri, values); - if (!reply.WriteInt32(ret)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - - -ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - auto remoteObject = data.ReadRemoteObject(); - if (remoteObject == nullptr) { - HILOG_ERROR("remoteObject is nullptr"); - return ERR_INVALID_VALUE; - } - auto obServer = iface_cast(remoteObject); - if (obServer == nullptr) { - HILOG_ERROR("the obServer creator is not exists"); - return ERR_INVALID_VALUE; - } - - bool ret = RegisterObserver(*uri, obServer); - if (!reply.WriteInt32(ret)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - auto remoteObject = data.ReadRemoteObject(); - if (remoteObject == nullptr) { - HILOG_ERROR("remoteObject is nullptr"); - return ERR_INVALID_VALUE; - } - auto obServer = iface_cast(remoteObject); - if (obServer == nullptr) { - HILOG_ERROR("the obServer creator is not exists"); - return ERR_INVALID_VALUE; - } - - bool ret = UnregisterObserver(*uri, obServer); - if (!reply.WriteInt32(ret)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - bool ret = NotifyChange(*uri); - if (!reply.WriteInt32(ret)) { - HILOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - Uri ret(""); - ret = NormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - HILOG_ERROR("fail to WriteParcelable type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - HILOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - Uri ret(""); - ret = DenormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - HILOG_ERROR("fail to WriteParcelable type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdExecuteBatch(MessageParcel &data, MessageParcel &reply) -{ - HILOG_INFO("DataShareStub::CmdExecuteBatchInner start"); - int count = 0; - if (!data.ReadInt32(count)) { - HILOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to ReadInt32 count"); - return ERR_INVALID_VALUE; - } - HILOG_INFO("DataShareStub::CmdExecuteBatchInner count:%{public}d", count); - std::vector> operations; - for (int i = 0; i < count; i++) { - AppExecFwk::DataAbilityOperation *operation = data.ReadParcelable(); - if (operation == nullptr) { - HILOG_ERROR("DataShareStub::CmdExecuteBatchInner operation is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - std::shared_ptr dataAbilityOperation(operation); - operations.push_back(dataAbilityOperation); - } - - std::vector> results = ExecuteBatch(operations); - int total = (int)(results.size()); - if (!reply.WriteInt32(total)) { - HILOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - HILOG_INFO("DataShareStub::CmdExecuteBatchInner total:%{public}d", total); - for (int i = 0; i < total; i++) { - if (results[i] == nullptr) { - HILOG_ERROR("DataShareStub::CmdExecuteBatchInner results[i] is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - if (!reply.WriteParcelable(results[i].get())) { - HILOG_ERROR( - "DataShareStub::CmdExecuteBatchInner fail to WriteParcelable operation, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - } - HILOG_INFO("DataShareStub::CmdExecuteBatchInner end"); - return NO_ERROR; -} -} // namespace AAFwk -} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/datashare_stub_impl.cpp b/frameworks/kits/ability/native/src/datashare_stub_impl.cpp deleted file mode 100644 index a45980ff8c3..00000000000 --- a/frameworks/kits/ability/native/src/datashare_stub_impl.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_stub_impl.h" - -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AppExecFwk { -std::shared_ptr DataShareStubImpl::GetOwner() -{ - return extension_; -} - -std::vector DataShareStubImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::vector ret; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->GetFileTypes(uri, mimeTypeFilter); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::OpenFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = -1; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->OpenFile(uri, mode); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::OpenRawFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = -1; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->OpenRawFile(uri, mode); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Insert(uri, value); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Update(uri, value, predicates); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Delete(uri, predicates); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -std::shared_ptr DataShareStubImpl::Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::shared_ptr ret = nullptr; - std::function syncTaskFunc = [=, &columns, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Query(uri, columns, predicates); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -std::string DataShareStubImpl::GetType(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::string ret = ""; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->GetType(uri); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -int DataShareStubImpl::BatchInsert(const Uri &uri, const std::vector &values) -{ - HILOG_INFO("%{public}s begin.", __func__); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->BatchInsert(uri, values); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -bool DataShareStubImpl::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - bool ret = false; - std::function syncTaskFunc = [=, &dataObserver, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->RegisterObserver(uri, dataObserver); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -bool DataShareStubImpl::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - bool ret = false; - std::function syncTaskFunc = [=, &dataObserver, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->UnregisterObserver(uri, dataObserver); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -bool DataShareStubImpl::NotifyChange(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - bool ret = false; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->NotifyChange(uri); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return ret; -} - -Uri DataShareStubImpl::NormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - std::function syncTaskFunc = [=, &urivalue, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - urivalue = extension->NormalizeUri(uri); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return urivalue; -} - -Uri DataShareStubImpl::DenormalizeUri(const Uri &uri) -{ - HILOG_INFO("%{public}s begin.", __func__); - Uri urivalue(""); - std::function syncTaskFunc = [=, &urivalue, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - urivalue = extension->DenormalizeUri(uri); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return urivalue; -} - -std::vector> DataShareStubImpl::ExecuteBatch( - const std::vector> &operations) -{ - HILOG_INFO("%{public}s begin.", __func__); - std::vector> results; - std::function syncTaskFunc = [=, &results, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - HILOG_ERROR("%{public}s end failed.", __func__); - return; - } - results = extension->ExecuteBatch(operations); - }; - uvQueue_->SyncCall(syncTaskFunc); - HILOG_INFO("%{public}s end successfully.", __func__); - return results; -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/datashare_uv_queue.cpp b/frameworks/kits/ability/native/src/datashare_uv_queue.cpp deleted file mode 100644 index f4d2084b6e8..00000000000 --- a/frameworks/kits/ability/native/src/datashare_uv_queue.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_uv_queue.h" - -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AbilityRuntime { -constexpr int WAIT_TIME = 3; -DataShareUvQueue::DataShareUvQueue(napi_env env) - : env_(env) -{ - napi_get_uv_event_loop(env, &loop_); -} - -void DataShareUvQueue::SyncCall(NapiVoidFunc func) -{ - HILOG_INFO("%{public}s begin.", __func__); - uv_work_t* work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - return; - } - work->data = new UvEntry {env_, std::move(func), false, false, {}, {}}; - auto status = uv_queue_work( - loop_, work, [](uv_work_t* work) {}, - [](uv_work_t* work, int uvstatus) { - if (work == nullptr || work->data == nullptr) { - HILOG_ERROR("%{public}s invalid work or work->data.", __func__); - return; - } - auto *entry = static_cast(work->data); - std::unique_lock lock(entry->mutex); - if (entry->func) { - entry->func(); - } - entry->done = true; - if (entry->purge) { - DataShareUvQueue::Purge(work); - } else { - entry->condition.notify_all(); - } - }); - if (status != napi_ok) { - HILOG_ERROR("%{public}s queue work failed", __func__); - DataShareUvQueue::Purge(work); - return; - } - - bool noNeedPurge = false; - auto *uvEntry = static_cast(work->data); - { - std::unique_lock lock(uvEntry->mutex); - if (uvEntry->condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [uvEntry] { return uvEntry->done; })) { - HILOG_INFO("%{public}s Wait uv_queue_work timeout.", __func__); - } - if (!uvEntry->done && !uv_cancel((uv_req_t*)&work)) { - HILOG_ERROR("%{public}s uv_cancel failed.", __func__); - uvEntry->purge = true; - noNeedPurge = true; - } - } - - if (!noNeedPurge) { - DataShareUvQueue::Purge(work); - } - HILOG_INFO("%{public}s end.", __func__); -} - -void DataShareUvQueue::Purge(uv_work_t* work) -{ - HILOG_INFO("%{public}s begin.", __func__); - if (work == nullptr || work->data == nullptr) { - HILOG_ERROR("%{public}s invalid work or work->data.", __func__); - return; - } - - auto *entry = static_cast(work->data); - std::unique_lock lock(entry->mutex); - - delete entry; - entry = nullptr; - - delete work; - work = nullptr; - HILOG_INFO("%{public}s end.", __func__); -} -} // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp deleted file mode 100644 index 532428e9f7e..00000000000 --- a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp +++ /dev/null @@ -1,738 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "js_datashare_ext_ability.h" - -#include "ability_info.h" -#include "accesstoken_kit.h" -#include "bytrace.h" -#include "dataobs_mgr_client.h" -#include "datashare_stub_impl.h" -#include "hilog_wrapper.h" -#include "ipc_skeleton.h" -#include "js_datashare_ext_ability_context.h" -#include "js_runtime.h" -#include "js_runtime_utils.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "napi_common_util.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" - -namespace OHOS { -namespace AbilityRuntime { -namespace { -constexpr size_t ARGC_ONE = 1; -constexpr size_t ARGC_TWO = 2; -constexpr size_t ARGC_THREE = 3; -constexpr int INVALID_VALUE = -1; -#if BINDER_IPC_32BIT -const std::string LIB_RDB_PATH = "/system/lib/module/data/librdb.z.so"; -const std::string LIB_DATA_ABILITY_PATH = "/system/lib/module/data/libdataability.z.so"; -#else -const std::string LIB_RDB_PATH = "/system/lib64/module/data/librdb.z.so"; -const std::string LIB_DATA_ABILITY_PATH = "/system/lib64/module/data/libdataability.z.so"; -#endif -} - -using namespace OHOS::AppExecFwk; -using OHOS::Security::AccessToken::AccessTokenKit; -using DataObsMgrClient = OHOS::AAFwk::DataObsMgrClient; - -JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr& runtime) -{ - return new JsDataShareExtAbility(static_cast(*runtime)); -} - -JsDataShareExtAbility::JsDataShareExtAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} - -JsDataShareExtAbility::~JsDataShareExtAbility() -{ - UnloadLibrary(); -} - -void JsDataShareExtAbility::Init(const std::shared_ptr &record, - const std::shared_ptr &application, std::shared_ptr &handler, - const sptr &token) -{ - DataShareExtAbility::Init(record, application, handler, token); - std::string srcPath = ""; - GetSrcPath(srcPath); - if (srcPath.empty()) { - HILOG_ERROR("Failed to get srcPath"); - return; - } - - std::string moduleName(Extension::abilityInfo_->moduleName); - moduleName.append("::").append(abilityInfo_->name); - HILOG_INFO("%{public}s module:%{public}s, srcPath:%{public}s.", __func__, moduleName.c_str(), srcPath.c_str()); - HandleScope handleScope(jsRuntime_); - auto& engine = jsRuntime_.GetNativeEngine(); - - jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); - if (jsObj_ == nullptr) { - HILOG_ERROR("Failed to get jsObj_"); - return; - } - HILOG_INFO("JsDataShareExtAbility::Init ConvertNativeValueTo."); - NativeObject* obj = ConvertNativeValueTo(jsObj_->Get()); - if (obj == nullptr) { - HILOG_ERROR("Failed to get JsDataShareExtAbility object"); - return; - } - - LoadLibrary(); - - auto context = GetContext(); - if (context == nullptr) { - HILOG_ERROR("Failed to get context"); - return; - } - HILOG_INFO("JsDataShareExtAbility::Init CreateJsDataShareExtAbilityContext."); - NativeValue* contextObj = CreateJsDataShareExtAbilityContext(engine, context); - auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtensionAbilityContext", - &contextObj, ARGC_ONE); - contextObj = contextRef->Get(); - HILOG_INFO("JsDataShareExtAbility::Init Bind."); - context->Bind(jsRuntime_, contextRef.release()); - HILOG_INFO("JsDataShareExtAbility::SetProperty."); - obj->SetProperty("context", contextObj); - - auto nativeObj = ConvertNativeValueTo(contextObj); - if (nativeObj == nullptr) { - HILOG_ERROR("Failed to get datashare extension ability native object"); - return; - } - - HILOG_INFO("Set datashare extension ability context"); - - nativeObj->SetNativePointer(new std::weak_ptr(context), - [](NativeEngine*, void* data, void*) { - HILOG_INFO("Finalizer for weak_ptr datashare extension ability context is called"); - delete static_cast*>(data); - }, nullptr); - - HILOG_INFO("JsDataShareExtAbility::Init end."); -} - -void JsDataShareExtAbility::LoadLibrary() -{ - libRdbHandle_ = dlopen(LIB_RDB_PATH.c_str(), RTLD_LAZY); - if (libRdbHandle_ == nullptr) { - HILOG_ERROR("dlopen failed: %{public}s", dlerror()); - } else { - rdbValueBucketNewInstance_ = reinterpret_cast( - dlsym(libRdbHandle_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_NewInstance")); - if (rdbValueBucketNewInstance_ == nullptr) { - HILOG_ERROR("symbol not found: %{public}s", dlerror()); - } - - rdbResultSetProxyGetNativeObject_ = reinterpret_cast( - dlsym(libRdbHandle_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject")); - if (rdbResultSetProxyGetNativeObject_ == nullptr) { - HILOG_ERROR("symbol not found: %{public}s", dlerror()); - } - } - - libDataAbilityHandle_ = dlopen(LIB_DATA_ABILITY_PATH.c_str(), RTLD_LAZY); - if (libDataAbilityHandle_ == nullptr) { - HILOG_ERROR("dlopen failed: %{public}s", dlerror()); - } else { - dataAbilityPredicatesNewInstance_ = reinterpret_cast( - dlsym(libDataAbilityHandle_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance")); - if (dataAbilityPredicatesNewInstance_ == nullptr) { - HILOG_ERROR("symbol not found: %{public}s", dlerror()); - } - } -} - -void JsDataShareExtAbility::UnloadLibrary() -{ - if (libRdbHandle_ != nullptr) { - dlclose(libRdbHandle_); - } - if (libDataAbilityHandle_ != nullptr) { - dlclose(libDataAbilityHandle_); - } -} - -void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) -{ - HILOG_INFO("%{public}s begin.", __func__); - Extension::OnStart(want); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - NativeValue* argv[] = {nativeWant}; - CallObjectMethod("onCreate", argv, ARGC_ONE); - HILOG_INFO("%{public}s end.", __func__); -} - -sptr JsDataShareExtAbility::OnConnect(const AAFwk::Want &want) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - Extension::OnConnect(want); - sptr remoteObject = new (std::nothrow) DataShareStubImpl( - std::static_pointer_cast(shared_from_this()), - reinterpret_cast(&jsRuntime_.GetNativeEngine())); - if (remoteObject == nullptr) { - HILOG_ERROR("%{public}s No memory allocated for DataShareStubImpl", __func__); - return nullptr; - } - HILOG_INFO("%{public}s end. ", __func__); - return remoteObject->AsObject(); -} - -NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc) -{ - HILOG_INFO("JsDataShareExtAbility::CallObjectMethod(%{public}s), begin", name); - - if (!jsObj_) { - HILOG_WARN("Not found DataShareExtAbility.js"); - return nullptr; - } - - HandleScope handleScope(jsRuntime_); - auto& nativeEngine = jsRuntime_.GetNativeEngine(); - - NativeValue* value = jsObj_->Get(); - NativeObject* obj = ConvertNativeValueTo(value); - if (obj == nullptr) { - HILOG_ERROR("Failed to get DataShareExtAbility object"); - return nullptr; - } - - NativeValue* method = obj->GetProperty(name); - if (method == nullptr) { - HILOG_ERROR("Failed to get '%{public}s' from DataShareExtAbility object", name); - return nullptr; - } - HILOG_INFO("JsDataShareExtAbility::CallFunction(%{public}s), success", name); - return handleScope.Escape(nativeEngine.CallFunction(value, method, argv, argc)); -} - -void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) -{ - if (!Extension::abilityInfo_->isStageBasedModel) { - /* temporary compatibility api8 + config.json */ - srcPath.append(Extension::abilityInfo_->package); - srcPath.append("/assets/js/"); - if (!Extension::abilityInfo_->srcPath.empty()) { - srcPath.append(Extension::abilityInfo_->srcPath); - } - srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); - return; - } - - if (!Extension::abilityInfo_->srcEntrance.empty()) { - srcPath.append(Extension::abilityInfo_->moduleName + "/"); - srcPath.append(Extension::abilityInfo_->srcEntrance); - srcPath.erase(srcPath.rfind('.')); - srcPath.append(".abc"); - } -} - -std::vector JsDataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - napi_value napiMimeTypeFilter = nullptr; - napi_create_string_utf8(env, mimeTypeFilter.c_str(), NAPI_AUTO_LENGTH, &napiMimeTypeFilter); - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMimeTypeFilter = reinterpret_cast(napiMimeTypeFilter); - NativeValue* argv[] = {nativeUri, nativeMimeTypeFilter}; - NativeValue* nativeResult = CallObjectMethod("getFileTypes", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call getFileTypes with return null.", __func__); - return ret; - } - - if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(env, reinterpret_cast(nativeResult), ret)) { - HILOG_ERROR("%{public}s call UnwrapArrayStringFromJS failed", __func__); - return ret; - } - - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::OpenFile(uri, mode); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - napi_value napiMode = nullptr; - napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMode = reinterpret_cast(napiMode); - NativeValue* argv[] = {nativeUri, nativeMode}; - NativeValue* nativeResult = CallObjectMethod("openFile", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call openFile with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) -{ - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::OpenRawFile(uri, mode); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - napi_value napiMode = nullptr; - napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMode = reinterpret_cast(napiMode); - NativeValue* argv[] = {nativeUri, nativeMode}; - NativeValue* nativeResult = CallObjectMethod("openRawFile", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call openRawFile with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - HILOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Insert(uri, value); - if (rdbValueBucketNewInstance_ == nullptr) { - HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); - return ret; - } - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - if (napiValue == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeValue = reinterpret_cast(napiValue); - NativeValue* argv[] = {nativeUri, nativeValue}; - NativeValue* nativeResult = CallObjectMethod("insert", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call insert with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, - const NativeRdb::DataAbilityPredicates &predicates) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - HILOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Update(uri, value, predicates); - if (rdbValueBucketNewInstance_ == nullptr) { - HILOG_ERROR("%{public}s invalid instance of ValuesBucket.", __func__); - return ret; - } - - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - if (napiValue == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeValue = reinterpret_cast(napiValue); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* argv[] = {nativeUri, nativeValue, nativePredicates}; - NativeValue* nativeResult = CallObjectMethod("update", argv, ARGC_THREE); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call update with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - HILOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Delete(uri, predicates); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* argv[] = {nativeUri, nativePredicates}; - NativeValue* nativeResult = CallObjectMethod("delete", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call delete with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -std::shared_ptr JsDataShareExtAbility::Query(const Uri &uri, - std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - std::shared_ptr ret; - if (!CheckCallingPermission(abilityInfo_->readPermission)) { - HILOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Query(uri, columns, predicates); - if (rdbResultSetProxyGetNativeObject_ == nullptr) { - HILOG_ERROR("%{public}s invalid instance of RdbResultSet.", __func__); - return ret; - } - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - - napi_value napiColumns = nullptr; - napi_create_array(env, &napiColumns); - bool isArray = false; - if (napi_is_array(env, napiColumns, &isArray) != napi_ok || !isArray) { - HILOG_ERROR("JsDataShareExtAbility create array failed"); - return ret; - } - int32_t index = 0; - for (const auto &column : columns) { - napi_value result = nullptr; - napi_create_string_utf8(env, column.c_str(), column.length(), &result); - napi_set_element(env, napiColumns, index++, result); - } - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeColumns = reinterpret_cast(napiColumns); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* argv[] = {nativeUri, nativeColumns, nativePredicates}; - NativeValue* nativeResult = CallObjectMethod("query", argv, ARGC_THREE); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call query with return null.", __func__); - return ret; - } - - auto nativeObject = rdbResultSetProxyGetNativeObject_(env, reinterpret_cast(nativeResult)); - if (nativeObject == nullptr) { - return ret; - } - - ret.reset(nativeObject); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -std::string JsDataShareExtAbility::GetType(const Uri &uri) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::GetType(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, - &napiUri); - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("getType", argv, ARGC_ONE); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call getType with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - HILOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::BatchInsert(uri, values); - if (rdbValueBucketNewInstance_ == nullptr) { - HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); - return ret; - } - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - - napi_value napiValues = nullptr; - napi_create_array(env, &napiValues); - bool isArray = false; - if (napi_is_array(env, napiValues, &isArray) != napi_ok || !isArray) { - HILOG_ERROR("JsDataShareExtAbility create array failed"); - return ret; - } - int32_t index = 0; - for (const auto &value : values) { - napi_value result = rdbValueBucketNewInstance_(env, const_cast(value)); - if (result == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - napi_set_element(env, napiValues, index++, result); - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeValues = reinterpret_cast(napiValues); - NativeValue* argv[] = {nativeUri, nativeValues}; - NativeValue* nativeResult = CallObjectMethod("batchInsert", argv, ARGC_TWO); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call batchInsert with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -bool JsDataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - DataShareExtAbility::RegisterObserver(uri, dataObserver); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - HILOG_ERROR("%{public}s obsMgrClient->RegisterObserver error return %{public}d", __func__, ret); - return false; - } - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -bool JsDataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - HILOG_INFO("%{public}s begin.", __func__); - DataShareExtAbility::UnregisterObserver(uri, dataObserver); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - HILOG_ERROR("%{public}s obsMgrClient->UnregisterObserver error return %{public}d", __func__, ret); - return false; - } - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -bool JsDataShareExtAbility::NotifyChange(const Uri &uri) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - DataShareExtAbility::NotifyChange(uri); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->NotifyChange(uri); - if (ret != ERR_OK) { - HILOG_ERROR("%{public}s obsMgrClient->NotifyChange error return %{public}d", __func__, ret); - return false; - } - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::NormalizeUri(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("normalizeUri", argv, ARGC_ONE); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call normalizeUri with return null.", __func__); - return ret; - } - - ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri) -{ - BYTRACE_NAME(BYTRACE_TAG_DISTRIBUTEDDATA, __PRETTY_FUNCTION__); - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::DenormalizeUri(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("denormalizeUri", argv, ARGC_ONE); - if (nativeResult == nullptr) { - HILOG_ERROR("%{public}s call denormalizeUri with return null.", __func__); - return ret; - } - - ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -std::vector> JsDataShareExtAbility::ExecuteBatch( - const std::vector> &operations) -{ - HILOG_INFO("%{public}s begin.", __func__); - auto ret = DataShareExtAbility::ExecuteBatch(operations); - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -bool JsDataShareExtAbility::CheckCallingPermission(const std::string &permission) -{ - HILOG_INFO("%{public}s begin, permission:%{public}s", __func__, permission.c_str()); - if (!permission.empty() && AccessTokenKit::VerifyAccessToken(IPCSkeleton::GetCallingTokenID(), permission) - != AppExecFwk::Constants::PERMISSION_GRANTED) { - HILOG_ERROR("%{public}s permission not granted.", __func__); - return false; - } - HILOG_INFO("%{public}s end.", __func__); - return true; -} - -napi_value JsDataShareExtAbility::MakePredicates(napi_env env, const NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s begin.", __func__); - if (dataAbilityPredicatesNewInstance_ == nullptr) { - HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); - return nullptr; - } - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new (std::nothrow) OHOS::NativeRdb::DataAbilityPredicates(); - if (predicatesPtr == nullptr) { - HILOG_ERROR("%{public}s No memory allocated for predicates", __func__); - return nullptr; - } - *predicatesPtr = predicates; - napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - delete predicatesPtr; - } - HILOG_INFO("%{public}s end.", __func__); - return napiPredicates; -} -} // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp b/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp deleted file mode 100644 index 8315494577b..00000000000 --- a/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "js_datashare_ext_ability_context.h" - -#include - -#include "hilog_wrapper.h" -#include "js_extension_context.h" -#include "js_runtime.h" -#include "js_runtime_utils.h" -#include "napi/native_api.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" -#include "napi_common_start_options.h" -#include "start_options.h" - -namespace OHOS { -namespace AbilityRuntime { -namespace { -class JsDataShareExtAbilityContext final { -public: - explicit JsDataShareExtAbilityContext(const std::shared_ptr& context) - : context_(context) {} - ~JsDataShareExtAbilityContext() = default; - - static void Finalizer(NativeEngine* engine, void* data, void* hint) - { - HILOG_INFO("JsAbilityContext::Finalizer is called"); - std::unique_ptr(static_cast(data)); - } -private: - std::weak_ptr context_; -}; -} // namespace - -NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, - std::shared_ptr context) -{ - HILOG_INFO("CreateJsDataShareExtAbilityContext begin"); - NativeValue* objValue = CreateJsExtensionContext(engine, context); - NativeObject* object = ConvertNativeValueTo(objValue); - - std::unique_ptr jsContext = std::make_unique(context); - object->SetNativePointer(jsContext.release(), JsDataShareExtAbilityContext::Finalizer, nullptr); - return objValue; -} -} // namespace AbilityRuntime -} // namespace OHOS diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index b53f469602a..718e6158895 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -31,10 +31,7 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/callee:callee_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/caller:caller_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/configuration_constant:configurationconstant_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare:datashare", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability:datashareextensionability_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability_context:datashareextensionabilitycontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/extensioncontext:extensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/feature_ability:featureability_napi", diff --git a/interfaces/kits/napi/aafwk/dataShare/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/BUILD.gn deleted file mode 100644 index c89867ea06b..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/BUILD.gn +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/aafwk/standard/aafwk.gni") - -ohos_shared_library("datashare") { - include_dirs = [ - "./", - "//third_party/node/src", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/rdb/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/common/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/dataability/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/rdb/include", - ] - - sources = [ - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/common/src/js_utils.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/js/napi/rdb/src/napi_result_set.cpp", - "napi_datashare_helper.cpp", - "native_datashare_module.cpp", - ] - - deps = [ - "${aafwk_path}/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", - "${innerkits_path}/dataobs_manager:dataobs_manager", - "${kits_path}/appkit:appkit_native", - "//third_party/libuv:uv", - ] - - external_deps = [ - "ability_base:base", - "ability_base:want", - "ability_base:zuri", - "ability_runtime:ability_manager", - "ability_runtime:abilitykit_native", - "ability_runtime:app_manager", - "ability_runtime:napi_base_context", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "eventhandler:libeventhandler", - "eventhandler:libeventhandler", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - "native_appdatamgr:native_appdatafwk", - "native_appdatamgr:native_dataability", - "native_appdatamgr:native_rdb", - "utils_base:utils", - ] - - relative_install_dir = "module/data" - - subsystem_name = "aafwk" - part_name = "ability_runtime" -} diff --git a/interfaces/kits/napi/aafwk/dataShare/data_share_common.h b/interfaces/kits/napi/aafwk/dataShare/data_share_common.h deleted file mode 100644 index b462002faa4..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/data_share_common.h +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_DATASHARE_COMMON_H -#define OHOS_APPEXECFWK_DATASHARE_COMMON_H -#include "ability.h" -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "napi_common.h" -#include "napi_common_util.h" -#include "values_bucket.h" -#include "want.h" - -using Want = OHOS::AAFwk::Want; -using Ability = OHOS::AppExecFwk::Ability; -using AbilityStartSetting = OHOS::AppExecFwk::AbilityStartSetting; - -namespace OHOS { -namespace AppExecFwk { -struct CallAbilityParam { - Want want; - int requestCode = 0; - bool forResultOption = false; - std::shared_ptr setting = nullptr; -}; - -struct OnAbilityCallback { - int requestCode = 0; - int resultCode = 0; - Want resultData; - CallbackInfo cb; -}; - -struct ContinueAbilityOptionsInfo { - bool reversible = false; - std::string deviceId; -}; - -struct AsyncCallbackInfo { - CallbackInfo cbInfo; - napi_async_work asyncWork = nullptr; - napi_deferred deferred = nullptr; - Ability *ability = nullptr; - CallAbilityParam param; - CallbackInfo aceCallback; - bool native_result; - AbilityType abilityType = AbilityType::UNKNOWN; - int errCode = 0; - ContinueAbilityOptionsInfo optionInfo; -}; - -struct CBBase { - CallbackInfo cbInfo; - napi_async_work asyncWork; - napi_deferred deferred; - Ability *ability = nullptr; - AbilityType abilityType = AbilityType::UNKNOWN; - int errCode = 0; -}; - -struct AppInfo_ { - std::string name; - std::string description; - int32_t descriptionId = 0; - bool systemApp = false; - bool enabled = true; // no data - std::string label; - std::string labelId; - std::string icon; - std::string iconId; - std::string process; - int32_t supportedModes = 0; - std::vector moduleSourceDirs; - std::vector permissions; - std::vector moduleInfos; - std::string entryDir; -}; - -struct AppInfoCB { - CBBase cbBase; - AppInfo_ appInfo; -}; - -struct AppTypeCB { - CBBase cbBase; - std::string name; -}; - -struct AbilityInfo_ { - std::string bundleName; - std::string name; - std::string label; - std::string description; - std::string icon; - int32_t labelId; - int32_t descriptionId; - int32_t iconId; - std::string moduleName; - std::string process; - std::string targetAbility; // no data - int32_t backgroundModes; // no data - bool isVisible = true; - bool formEnabled = false; // no data - int32_t type = 0; - int32_t subType = 0; // no data - int32_t orientation = 0; - int32_t launchMode = 0; - std::vector permissions; - std::vector deviceTypes; - std::vector deviceCapabilities; - std::string readPermission; // no data - std::string writePermission; // no data - AppInfo_ appInfo; - int32_t formEntity; // no data - int32_t minFormHeight; // no data - int32_t defaultFormHeight; // no data - int32_t minFormWidth; // no data - int32_t defaultFormWidth; // no data - std::string uri; -}; -struct AbilityInfoCB { - CBBase cbBase; - AbilityInfo_ abilityInfo; -}; - -struct AbilityNameCB { - CBBase cbBase; - std::string name; -}; - -struct ProcessInfoCB { - CBBase cbBase; - pid_t pid = 0; - std::string processName; -}; - -struct ProcessNameCB { - CBBase cbBase; - std::string processName; -}; - -struct CallingBundleCB { - CBBase cbBase; - std::string callingBundleName; -}; - -struct GetOrCreateLocalDirCB { - CBBase cbBase; - std::string rootDir; -}; - -struct DatabaseDirCB { - CBBase cbBase; - std::string dataBaseDir; -}; - -struct PreferencesDirCB { - CBBase cbBase; - std::string preferencesDir; -}; - -struct ElementNameCB { - CBBase cbBase; - std::string deviceId; - std::string bundleName; - std::string abilityName; - std::string uri; - std::string shortName; -}; - -struct HapModuleInfo_ { - std::string name; - std::string description; - int32_t descriptionId = 0; // no data - std::string icon; - std::string label; - int32_t labelId = 0; // no data - int32_t iconId = 0; // no data - std::string backgroundImg; - int32_t supportedModes = 0; - std::vector reqCapabilities; - std::vector deviceTypes; - std::vector abilityInfos; - std::string moduleName; - std::string mainAbilityName; // no data - bool installationFree; // no data -}; - -struct HapModuleInfoCB { - CBBase cbBase; - HapModuleInfo_ hapModuleInfo; -}; - -struct DataShareHelperCB { - CBBase cbBase; - napi_ref uri = nullptr; - napi_value result = nullptr; -}; - -struct DSHelperInsertCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::ValuesBucket valueBucket; - int result = 0; - int execResult; -}; - -class NAPIAbilityConnection; -struct AbilityConnectionCB { - napi_env env; - napi_ref callback[3] = {0}; // onConnect/onDisconnect/onFailed - int resultCode = 0; - ElementName elementName; - sptr connection; -}; -struct ConnectAbilityCB { - CBBase cbBase; - Want want; - sptr abilityConnection; - AbilityConnectionCB abilityConnectionCB; - int64_t id; - bool result; - int errCode = 0; -}; - -struct DSHelperNotifyChangeCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - int execResult; -}; - -class NAPIDataShareObserver; -struct DSHelperOnOffCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - sptr observer; - std::string uri; - int result = 0; - std::vector NotifyList; - std::vector DestoryList; -}; - -struct ShowOnLockScreenCB { - CBBase cbBase; - bool isShow; -}; - -struct DSHelperGetTypeCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperGetFileTypesCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string mimeTypeFilter; - std::vector result; - int execResult; -}; - -struct DSHelperNormalizeUriCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperDenormalizeUriCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperDeleteCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::DataAbilityPredicates predicates; - int result = 0; - int execResult; -}; - -struct DSHelperQueryCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::vector columns; - NativeRdb::DataAbilityPredicates predicates; - std::shared_ptr result; - int execResult; -}; - -struct DSHelperUpdateCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::ValuesBucket valueBucket; - NativeRdb::DataAbilityPredicates predicates; - int result = 0; - int execResult; -}; - -struct DSHelperBatchInsertCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::vector values; - int result = 0; - int execResult; -}; - -struct DSHelperOpenFileCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string mode; - int result = 0; - int execResult; -}; - -struct DSHelperReleaseCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - bool result = false; -}; - -struct DSHelperExecuteBatchCB { - CBBase cbBase; - std::string uri; - std::vector> operations; - DataShareHelper *dataShareHelper = nullptr; - std::vector> result; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif /* OHOS_APPEXECFWK_DATASHARE_COMMON_H */ diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp deleted file mode 100644 index 11b3fa7a08d..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp +++ /dev/null @@ -1,3325 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "napi_datashare_helper.h" - -#include -#include -#include - -#include "datashare_helper.h" -#include "data_ability_observer_interface.h" -#include "uri.h" - -#include "data_ability_result.h" -#include "hilog_wrapper.h" -#include "message_parcel.h" -#include "napi_base_context.h" -#include "napi_data_ability_predicates.h" -#include "napi_rdb_predicates.h" -#include "napi_result_set.h" -#include "securec.h" - -using namespace OHOS::AAFwk; -using namespace OHOS::AppExecFwk; - -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string DATASHARE_CLASS_NAME = "DataShareHelper"; -constexpr int NO_ERROR = 0; -constexpr int INVALID_PARAMETER = -1; - -std::string NapiValueToStringUtf8(napi_env env, napi_value value) -{ - std::string result = ""; - return UnwrapStringFromJS(env, value, result); -} - -bool NapiValueToArrayStringUtf8(napi_env env, napi_value param, std::vector &result) -{ - return UnwrapArrayStringFromJS(env, param, result); -} -} - -std::list> g_dataShareHelperList; -static napi_ref g_constructorRef = nullptr; - -/** - * @brief acquireDataAbilityHelper processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param dataShareHelperCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value AcquireDataShareHelperWrap(napi_env env, napi_callback_info info, DataShareHelperCB *dataShareHelperCB) -{ - HILOG_INFO("%{public}s,called", __func__); - if (dataShareHelperCB == nullptr) { - HILOG_ERROR("%{public}s,dataShareHelperCB == nullptr", __func__); - return nullptr; - } - - size_t requireArgc = ARGS_THREE; - size_t argc = ARGS_THREE; - napi_value args[ARGS_THREE] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - if (argc > requireArgc) { - HILOG_ERROR("%{public}s, Wrong argument count %{public}zu.", __func__, argc); - return nullptr; - } - - napi_value result = nullptr; - napi_value cons = nullptr; - if (napi_get_reference_value(env, g_constructorRef, &cons) != napi_ok) { - return nullptr; - } - NAPI_CALL(env, napi_new_instance(env, cons, ARGS_THREE, args, &result)); - - if (!IsTypeForNapiValue(env, result, napi_object)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); - return nullptr; - } - - if (IsTypeForNapiValue(env, result, napi_null)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue is null", __func__); - return nullptr; - } - - if (IsTypeForNapiValue(env, result, napi_undefined)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue is undefined", __func__); - return nullptr; - } - - delete dataShareHelperCB; - dataShareHelperCB = nullptr; - HILOG_INFO("%{public}s,end", __func__); - return result; -} - -/** - * @brief AcquireDataAbilityHelper. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_AcquireDataShareHelperCommon(napi_env env, napi_callback_info info, AbilityType abilityType) -{ - HILOG_INFO("%{public}s,called", __func__); - DataShareHelperCB *dataShareHelperCB = new (std::nothrow) DataShareHelperCB; - if (dataShareHelperCB == nullptr) { - HILOG_ERROR("%{public}s, dataShareHelperCB == nullptr", __func__); - return WrapVoidToJS(env); - } - - dataShareHelperCB->cbBase.cbInfo.env = env; - dataShareHelperCB->cbBase.errCode = NAPI_ERR_NO_ERROR; - dataShareHelperCB->cbBase.abilityType = abilityType; - napi_value ret = AcquireDataShareHelperWrap(env, info, dataShareHelperCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr", __func__); - if (dataShareHelperCB != nullptr) { - delete dataShareHelperCB; - dataShareHelperCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief DataShareHelper NAPI method : CreateDataShareHelper. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_CreateDataShareHelper(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - return NAPI_AcquireDataShareHelperCommon(env, info, AbilityType::EXTENSION); -} - -/** - * @brief DataShareHelper NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value DataShareHelperInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), - DECLARE_NAPI_FUNCTION("notifyChange", NAPI_NotifyChange), - DECLARE_NAPI_FUNCTION("on", NAPI_Register), - DECLARE_NAPI_FUNCTION("off", NAPI_UnRegister), - DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), - DECLARE_NAPI_FUNCTION("query", NAPI_Query), - DECLARE_NAPI_FUNCTION("update", NAPI_Update), - DECLARE_NAPI_FUNCTION("batchInsert", NAPI_BatchInsert), - DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), - DECLARE_NAPI_FUNCTION("getType", NAPI_GetType), - DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetFileTypes), - DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_NormalizeUri), - DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_DenormalizeUri), - DECLARE_NAPI_FUNCTION("release", NAPI_Release), - }; - - napi_value cons = nullptr; - NAPI_CALL(env, - napi_define_class(env, - DATASHARE_CLASS_NAME.c_str(), - NAPI_AUTO_LENGTH, - DataShareHelperConstructor, - nullptr, - sizeof(properties) / sizeof(*properties), - properties, - &cons)); - g_dataShareHelperList.clear(); - NAPI_CALL(env, napi_create_reference(env, cons, 1, &g_constructorRef)); - NAPI_CALL(env, napi_set_named_property(env, exports, DATASHARE_CLASS_NAME.c_str(), cons)); - - napi_property_descriptor export_properties[] = { - DECLARE_NAPI_FUNCTION("createDataShareHelper", NAPI_CreateDataShareHelper), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(export_properties) / sizeof(export_properties[0]), - export_properties)); - return exports; -} - -napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - size_t argc = ARGS_THREE; - napi_value argv[ARGS_THREE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); - NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); - AAFwk::Want want; - OHOS::AppExecFwk::UnwrapWant(env, argv[PARAM1], want); - std::string strUri = NapiValueToStringUtf8(env, argv[PARAM2]); - std::shared_ptr dataShareHelper = nullptr; - bool isStageMode = false; - napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode); - if (status != napi_ok || !isStageMode) { - auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); - NAPI_ASSERT(env, ability != nullptr, "DataShareHelperConstructor: failed to get native ability"); - HILOG_INFO("FA Model: strUri = %{public}s", strUri.c_str()); - dataShareHelper = DataShareHelper::Creator(ability->GetContext(), want, std::make_shared(strUri)); - } else { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - NAPI_ASSERT(env, context != nullptr, "DataShareHelperConstructor: failed to get native context"); - HILOG_INFO("Stage Model: strUri = %{public}s", strUri.c_str()); - dataShareHelper = DataShareHelper::Creator(context, want, std::make_shared(strUri)); - } - NAPI_ASSERT(env, dataShareHelper != nullptr, "DataShareHelperConstructor: dataShareHelper is nullptr"); - g_dataShareHelperList.emplace_back(dataShareHelper); - napi_wrap(env, thisVar, dataShareHelper.get(), [](napi_env env, void *data, void *hint) { - DataShareHelper *objectInfo = static_cast(data); - auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), - [&objectInfo](const DSHelperOnOffCB *helper) { return helper->dataShareHelper == objectInfo; }); - if (helper != registerInstances_.end()) { - HILOG_INFO("DataShareHelper finalize_cb find helper"); - (*helper)->dataShareHelper->Release(); - delete *helper; - registerInstances_.erase(helper); - } - g_dataShareHelperList.remove_if([objectInfo](const std::shared_ptr &dataShareHelper) { - return objectInfo == dataShareHelper.get(); - }); - }, nullptr, nullptr); - HILOG_INFO("%{public}s,called end", __func__); - return thisVar; -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Insert(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - DSHelperInsertCB *insertCB = new (std::nothrow) DSHelperInsertCB; - if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - insertCB->cbBase.cbInfo.env = env; - insertCB->cbBase.asyncWork = nullptr; - insertCB->cbBase.deferred = nullptr; - insertCB->cbBase.ability = nullptr; - - napi_value ret = InsertWrap(env, info, insertCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (insertCB != nullptr) { - delete insertCB; - insertCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - insertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - insertCB->valueBucket.Clear(); - AnalysisValuesBucket(insertCB->valueBucket, env, args[PARAM1]); - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,set DataShareHelper objectInfo", __func__); - insertCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = InsertAsync(env, args, ARGS_TWO, insertCB); - } else { - ret = InsertPromise(env, insertCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -void AnalysisValuesBucket(NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - napi_value keys = 0; - napi_get_property_names(env, arg, &keys); - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - HILOG_ERROR("ValuesBucket errr"); - return; - } - HILOG_INFO("ValuesBucket num:%{public}d ", arrLen); - for (size_t i = 0; i < arrLen; ++i) { - napi_value key = 0; - status = napi_get_element(env, keys, i, &key); - std::string keyStr = UnwrapStringFromJS(env, key); - napi_value value = 0; - napi_get_property(env, arg, key, &value); - - SetValuesBucketObject(valuesBucket, env, keyStr, value); - } -} - -void SetValuesBucketObject( - NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, value, &valueType); - if (valueType == napi_string) { - std::string valueString = UnwrapStringFromJS(env, value); - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{public}s", - valueType, - keyStr.c_str(), - valueString.c_str()); - valuesBucket.PutString(keyStr, valueString); - } else if (valueType == napi_number) { - double valueNumber = 0; - napi_get_value_double(env, value, &valueNumber); - valuesBucket.PutDouble(keyStr, valueNumber); - HILOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}lf", valueType, keyStr.c_str(), valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, value, &valueBool); - HILOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}d", valueType, keyStr.c_str(), valueBool); - valuesBucket.PutBool(keyStr, valueBool); - } else if (valueType == napi_null) { - valuesBucket.PutNull(keyStr); - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str()); - } else if (valueType == napi_object) { - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str()); - valuesBucket.PutBlob(keyStr, ConvertU8Vector(env, value)); - } else { - HILOG_ERROR("valuesBucket error"); - } -} -napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || insertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &insertCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - InsertExecuteCB, - InsertAsyncCompleteCB, - (void *)insertCB, - &insertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end", __func__); - return result; -} - -napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - insertCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - InsertExecuteCB, - InsertPromiseCompleteCB, - (void *)insertCB, - &insertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end", __func__); - return promise; -} - -void InsertExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Insert, worker pool thread execute."); - DSHelperInsertCB *insertCB = static_cast(data); - if (insertCB->dataShareHelper != nullptr) { - insertCB->execResult = INVALID_PARAMETER; - if (!insertCB->uri.empty()) { - OHOS::Uri uri(insertCB->uri); - insertCB->result = insertCB->dataShareHelper->Insert(uri, insertCB->valueBucket); - insertCB->execResult = NO_ERROR; - } - } else { - HILOG_ERROR("NAPI_Insert, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_Insert, worker pool thread execute end."); -} - -void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Insert, main event thread complete."); - DSHelperInsertCB *insertCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, insertCB->execResult); - napi_create_int32(env, insertCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (insertCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); - delete insertCB; - insertCB = nullptr; - HILOG_INFO("NAPI_Insert, main event thread complete end."); -} - -void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Insert, main event thread complete."); - DSHelperInsertCB *insertCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, insertCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); - delete insertCB; - insertCB = nullptr; - HILOG_INFO("NAPI_Insert, main event thread complete end."); -} - -/** - * @brief Parse the ValuesBucket parameters. - * - * @param param Indicates the want parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, args, &valueType); - if (valueType != napi_object) { - HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); - return nullptr; - } - - std::string strValue = ""; - if (UnwrapStringByPropertyName(env, args, "value", strValue)) { - HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); - value = strValue; - } else { - HILOG_ERROR("%{public}s, value == nullptr.", __func__); - return nullptr; - } - - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - HILOG_INFO("%{public}s,end", __func__); - return result; -} - -/** - * @brief DataShareHelper NAPI method : notifyChange. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperNotifyChangeCB *notifyChangeCB = new (std::nothrow) DSHelperNotifyChangeCB; - if (notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, notifyChangeCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - notifyChangeCB->cbBase.cbInfo.env = env; - notifyChangeCB->cbBase.asyncWork = nullptr; - notifyChangeCB->cbBase.deferred = nullptr; - notifyChangeCB->cbBase.ability = nullptr; - - napi_value ret = NotifyChangeWrap(env, info, notifyChangeCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (notifyChangeCB != nullptr) { - delete notifyChangeCB; - notifyChangeCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief NotifyChange processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - notifyChangeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, notifyChangeCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("Set DataShareHelper objectInfo"); - notifyChangeCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = NotifyChangeAsync(env, args, argcAsync, argcPromise, notifyChangeCB); - } else { - ret = NotifyChangePromise(env, notifyChangeCB); - } - return ret; -} - -napi_value NotifyChangeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, ¬ifyChangeCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NotifyChangeExecuteCB, - NotifyChangeAsyncCompleteCB, - (void *)notifyChangeCB, - ¬ifyChangeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - notifyChangeCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NotifyChangeExecuteCB, - NotifyChangePromiseCompleteCB, - (void *)notifyChangeCB, - ¬ifyChangeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); - return promise; -} - -void NotifyChangeExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, worker pool thread execute."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - if (notifyChangeCB->dataShareHelper != nullptr) { - notifyChangeCB->execResult = INVALID_PARAMETER; - if (!notifyChangeCB->uri.empty()) { - OHOS::Uri uri(notifyChangeCB->uri); - notifyChangeCB->dataShareHelper->NotifyChange(uri); - notifyChangeCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("%{public}s, notifyChangeCB uri is empty.", __func__); - } - } -} - -void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, notifyChangeCB->cbBase.cbInfo.callback, &callback)); - - if (!IsTypeForNapiValue(env, callback, napi_function)) { - delete notifyChangeCB; - notifyChangeCB = nullptr; - HILOG_INFO("NAPI_NotifyChange, callback is invalid."); - return; - } - - result[PARAM0] = GetCallbackErrorValue(env, notifyChangeCB->execResult); - result[PARAM1] = WrapVoidToJS(env); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (notifyChangeCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, notifyChangeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); - delete notifyChangeCB; - notifyChangeCB = nullptr; -} - -void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, 0, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, notifyChangeCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); - delete notifyChangeCB; - notifyChangeCB = nullptr; -} - -/** - * @brief DataShareHelper NAPI method : on. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Register(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - onCB->cbBase.cbInfo.env = env; - onCB->cbBase.asyncWork = nullptr; - onCB->cbBase.deferred = nullptr; - onCB->cbBase.ability = nullptr; - - napi_value ret = RegisterWrap(env, info, onCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief On processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *onCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - onCB->result = NO_ERROR; - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type == "dataChange") { - HILOG_INFO("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type is %{public}s.", __func__, type.c_str()); - onCB->result = INVALID_PARAMETER; - } - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - onCB->result = INVALID_PARAMETER; - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - onCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, onCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - onCB->result = INVALID_PARAMETER; - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("Set DataShareHelper objectInfo"); - onCB->dataShareHelper = objectInfo; - - ret = RegisterAsync(env, args, argcAsync, argcPromise, onCB); - return ret; -} - -napi_value RegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *onCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || onCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - HILOG_INFO("valuetype is napi_function"); - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &onCB->cbBase.cbInfo.callback)); - } else { - HILOG_INFO("not valuetype isn't napi_function"); - onCB->result = INVALID_PARAMETER; - } - - sptr observer(new (std::nothrow) NAPIDataShareObserver()); - observer->SetEnv(env); - observer->SetCallbackRef(onCB->cbBase.cbInfo.callback); - onCB->observer = observer; - - if (onCB->result == NO_ERROR) { - registerInstances_.emplace_back(onCB); - } - - NAPI_CALL(env, - napi_create_async_work( - env, - nullptr, - resourceName, - RegisterExecuteCB, - RegisterCompleteCB, - (void *)onCB, - &onCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, onCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -void RegisterExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Register, worker pool thread execute."); - DSHelperOnOffCB *onCB = static_cast(data); - if (onCB->dataShareHelper != nullptr) { - if (onCB->result != INVALID_PARAMETER && !onCB->uri.empty() && onCB->cbBase.cbInfo.callback != nullptr) { - OHOS::Uri uri(onCB->uri); - onCB->dataShareHelper->RegisterObserver(uri, onCB->observer); - } else { - HILOG_ERROR("%{public}s, dataShareHelper uri is empty or callback is nullptr.", __func__); - } - } -} - -void RegisterCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Register, main event thread complete."); - DSHelperOnOffCB *onCB = static_cast(data); - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, input params onCB is nullptr.", __func__); - return; - } - if (onCB->result == NO_ERROR) { - return; - } - HILOG_INFO("NAPI_Register, input params onCB is invalid params, will be release"); - if (onCB->observer) { - HILOG_INFO("NAPI_Register, call ReleaseJSCallback"); - onCB->observer->ReleaseJSCallback(); - } - delete onCB; - onCB = nullptr; - HILOG_INFO("NAPI_Register, main event thread complete over an release invalid onCB."); -} - -/** - * @brief DataShareHelper NAPI method : Off. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_UnRegister(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOnOffCB *offCB = new (std::nothrow) DSHelperOnOffCB; - if (offCB == nullptr) { - HILOG_ERROR("%{public}s, offCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - offCB->cbBase.cbInfo.env = env; - offCB->cbBase.asyncWork = nullptr; - offCB->cbBase.deferred = nullptr; - offCB->cbBase.ability = nullptr; - - napi_value ret = UnRegisterWrap(env, info, offCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief Off processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *offCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argc = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc <= argCountWithAsync && argc <= ARGS_MAX_COUNT, "UnRegisterWrap: Wrong argument count"); - offCB->result = INVALID_PARAMETER; - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type == "dataChange") { - offCB->result = NO_ERROR; - } - } - offCB->uri = ""; - if (argc > ARGS_TWO) { - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - } else { - offCB->result = INVALID_PARAMETER; - } - NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[PARAM2], 1, &offCB->cbBase.cbInfo.callback)); - } else { - offCB->result = INVALID_PARAMETER; - } - } else { - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - } else if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &offCB->cbBase.cbInfo.callback)); - } else { - offCB->result = INVALID_PARAMETER; - } - } - HILOG_INFO("%{public}s,uri=%{public}s", __func__, offCB->uri.c_str()); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - offCB->dataShareHelper = objectInfo; - ret = UnRegisterAsync(env, args, argc, argcPromise, offCB); - return ret; -} - -napi_value UnRegisterAsync( - napi_env env, napi_value *args, size_t argc, const size_t argcPromise, DSHelperOnOffCB *offCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || offCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - if (offCB->result == NO_ERROR) { - FindRegisterObs(env, offCB); - } - - NAPI_CALL(env, - napi_create_async_work( - env, - nullptr, - resourceName, - UnRegisterExecuteCB, - UnRegisterCompleteCB, - (void *)offCB, - &offCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, offCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -static void FindRegisterObsByCallBack(napi_env env, DSHelperOnOffCB *data) -{ - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); - if (data == nullptr || data->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - return; - } - napi_value callbackA = 0; - napi_get_reference_value(data->cbBase.cbInfo.env, data->cbBase.cbInfo.callback, &callbackA); - std::string strUri = data->uri; - do { - auto helper = std::find_if( - registerInstances_.begin(), - registerInstances_.end(), - [callbackA, strUri](const DSHelperOnOffCB *helper) { - bool result = false; - if (helper == nullptr || helper->cbBase.cbInfo.callback == nullptr) { - HILOG_ERROR("%{public}s is nullptr", ((helper == nullptr) ? "helper" : "cbBase.cbInfo.callback")); - return result; - } - if (helper->uri != strUri) { - HILOG_ERROR("uri inconsistent, h=[%{public}s] u=[%{public}s]", helper->uri.c_str(), strUri.c_str()); - return result; - } - napi_value callbackB = 0; - napi_get_reference_value(helper->cbBase.cbInfo.env, helper->cbBase.cbInfo.callback, &callbackB); - auto ret = napi_strict_equals(helper->cbBase.cbInfo.env, callbackA, callbackB, &result); - HILOG_INFO("NAPI_UnRegister cb equals status=%{public}d result=%{public}d.", ret, result); - return result; - }); - if (helper != registerInstances_.end()) { - data->NotifyList.emplace_back(*helper); - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); - } else { - HILOG_INFO("NAPI_UnRegister not match any callback. %{public}zu", registerInstances_.size()); - break; - } - } while (true); - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB FindRegisterObsByCallBack Called End."); -} - -void FindRegisterObs(napi_env env, DSHelperOnOffCB *data) -{ - HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute."); - if (data == nullptr || data->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - return; - } - if (data->cbBase.cbInfo.callback != nullptr) { - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); - FindRegisterObsByCallBack(env, data); - } else { - if (data->uri.empty()) { - HILOG_ERROR("NAPI_UnRegister, error: uri is empty."); - return; - } - - HILOG_INFO("NAPI_UnRegister, uri=%{public}s.", data->uri.c_str()); - std::string strUri = data->uri; - do { - auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), - [strUri](const DSHelperOnOffCB *helper) { return helper->uri == strUri; }); - if (helper != registerInstances_.end()) { - OHOS::Uri uri((*helper)->uri); - data->NotifyList.emplace_back(*helper); - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); - } else { - HILOG_INFO("NAPI_UnRegister not match any uri."); - break; - } - } while (true); - } - HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute.end %{public}zu", data->NotifyList.size()); -} - -void UnRegisterExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute."); - DSHelperOnOffCB *offCB = static_cast(data); - if (offCB == nullptr || offCB->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - return; - } - HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->NotifyList.size()); - for (auto &iter : offCB->NotifyList) { - if (iter != nullptr && iter->observer != nullptr) { - OHOS::Uri uri(iter->uri); - iter->dataShareHelper->UnregisterObserver(uri, iter->observer); - offCB->DestoryList.emplace_back(iter); - } - } - offCB->NotifyList.clear(); - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute. end"); -} - -void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_UnRegister, main event thread complete."); - // cannot run it in executeCB, because need to use napi_strict_equals compare callbacks. - DSHelperOnOffCB *offCB = static_cast(data); - if (offCB == nullptr || offCB->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - return; - } - HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->DestoryList.size()); - for (auto &iter : offCB->DestoryList) { - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 1 ---"); - if (iter->observer != nullptr) { - if (iter->observer->GetWorkPre() == 1 && iter->observer->GetWorkRun() == 0) { - iter->observer->SetAssociatedObject(iter); - iter->observer->ChangeWorkInt(); - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 3 ---"); - } else { - iter->observer->ReleaseJSCallback(); - delete iter; - iter = nullptr; - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 4 ---"); - } - } - } - - offCB->DestoryList.clear(); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - - HILOG_INFO("NAPI_UnRegister, main event thread complete. end"); -} - -void NAPIDataShareObserver::ReleaseJSCallback() -{ - if (ref_ == nullptr) { - HILOG_ERROR("NAPIDataShareObserver::ReleaseJSCallback, ref_ is null."); - return; - } - napi_delete_reference(env_, ref_); - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::SetAssociatedObject(DSHelperOnOffCB* object) -{ - onCB_ = object; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::ChangeWorkPre() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - workPre_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); -} -void NAPIDataShareObserver::ChangeWorkRun() -{ - workRun_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workRun_); -} -void NAPIDataShareObserver::ChangeWorkInt() -{ - intrust_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); -} - -void NAPIDataShareObserver::ChangeWorkPreDone() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - workPre_ = 0; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); -} - -void NAPIDataShareObserver::ChangeWorkRunDone() -{ - workRun_ = 0; - intrust_ = 0; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called end %{public}d %{public}d", __func__, workRun_, intrust_); -} - -int NAPIDataShareObserver::GetWorkPre() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); - return workPre_; -} - -int NAPIDataShareObserver::GetWorkInt() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); - return intrust_; -} - -int NAPIDataShareObserver::GetWorkRun() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. %{public}d", __func__, workRun_); - return workRun_; -} - -const DSHelperOnOffCB* NAPIDataShareObserver::GetAssociatedObject(void) -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - return onCB_; -} - -void NAPIDataShareObserver::SetEnv(const napi_env &env) -{ - env_ = env; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::SetCallbackRef(const napi_ref &ref) -{ - ref_ = ref; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -static void OnChangeJSThreadWorker(uv_work_t *work, int status) -{ - HILOG_INFO("OnChange, uv_queue_work"); - if (work == nullptr) { - HILOG_ERROR("OnChange, uv_queue_work input work is nullptr"); - return; - } - DSHelperOnOffCB *onCB = (DSHelperOnOffCB *)work->data; - NAPIDataShareObserver* obs = onCB->observer; - onCB->observer = nullptr; - if (obs != nullptr) { - obs->ChangeWorkRun(); - } - napi_value result[ARGS_TWO] = {0}; - result[PARAM0] = GetCallbackErrorValue(onCB->cbBase.cbInfo.env, NO_ERROR); - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(onCB->cbBase.cbInfo.env, &undefined); - napi_value callResult = 0; - napi_get_reference_value(onCB->cbBase.cbInfo.env, onCB->cbBase.cbInfo.callback, &callback); - napi_call_function(onCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - if (obs != nullptr) { - if (obs->GetWorkInt() == 1) { - obs->ReleaseJSCallback(); - const DSHelperOnOffCB* assicuated = obs->GetAssociatedObject(); - if (assicuated != nullptr) { - HILOG_INFO("OnChange, uv_queue_work ReleaseJSCallback Called"); - obs->SetAssociatedObject(nullptr); - delete assicuated; - assicuated = nullptr; - } - } else { - obs->ChangeWorkRunDone(); - obs->ChangeWorkPreDone(); - } - } - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - HILOG_INFO("OnChange, uv_queue_work. end"); -} - -void NAPIDataShareObserver::OnChange() -{ - if (ref_ == nullptr) { - HILOG_ERROR("%{public}s, OnChange ref is nullptr.", __func__); - return; - } - ChangeWorkPre(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env_, &loop); - if (loop == nullptr) { - HILOG_ERROR("%{public}s, loop == nullptr.", __func__); - ChangeWorkPreDone(); - return; - } - uv_work_t *work = new uv_work_t; - if (work == nullptr) { - HILOG_ERROR("%{public}s, work==nullptr.", __func__); - ChangeWorkPreDone(); - return; - } - DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); - if (work != nullptr) { - delete work; - work = nullptr; - } - ChangeWorkPreDone(); - return; - } - onCB->cbBase.cbInfo.env = env_; - onCB->cbBase.cbInfo.callback = ref_; - onCB->observer = this; - work->data = (void *)onCB; - int rev = uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - OnChangeJSThreadWorker); - if (rev != 0) { - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - } - HILOG_INFO("%{public}s, called. end", __func__); -} - -napi_value NAPI_GetType(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperGetTypeCB *gettypeCB = new (std::nothrow) DSHelperGetTypeCB; - if (gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, gettypeCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - gettypeCB->cbBase.cbInfo.env = env; - gettypeCB->cbBase.asyncWork = nullptr; - gettypeCB->cbBase.deferred = nullptr; - gettypeCB->cbBase.ability = nullptr; - - napi_value ret = GetTypeWrap(env, info, gettypeCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (gettypeCB != nullptr) { - delete gettypeCB; - gettypeCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - gettypeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - gettypeCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = GetTypeAsync(env, args, ARGS_ONE, gettypeCB); - } else { - ret = GetTypePromise(env, gettypeCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &gettypeCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetTypeExecuteCB, - GetTypeAsyncCompleteCB, - (void *)gettypeCB, - &gettypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end", __func__); - return result; -} - -napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - gettypeCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetTypeExecuteCB, - GetTypePromiseCompleteCB, - (void *)gettypeCB, - &gettypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void GetTypeExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetType, worker pool thread execute."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - if (gettypeCB->dataShareHelper != nullptr) { - gettypeCB->execResult = INVALID_PARAMETER; - if (!gettypeCB->uri.empty()) { - OHOS::Uri uri(gettypeCB->uri); - gettypeCB->result = gettypeCB->dataShareHelper->GetType(uri); - gettypeCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_GetType, dataShareHelper uri is empty."); - } - } else { - HILOG_ERROR("NAPI_GetType, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_GetType, worker pool thread execute end."); -} - -void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetType, main event thread complete."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, gettypeCB->execResult); - napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (gettypeCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, gettypeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); - delete gettypeCB; - gettypeCB = nullptr; - HILOG_INFO("NAPI_GetType, main event thread complete end."); -} - -void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetType, main event thread complete."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, gettypeCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); - delete gettypeCB; - gettypeCB = nullptr; - HILOG_INFO("NAPI_GetType, main event thread complete end."); -} - -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperGetFileTypesCB *getfiletypesCB = new (std::nothrow) DSHelperGetFileTypesCB; - if (getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, getfiletypesCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - getfiletypesCB->cbBase.cbInfo.env = env; - getfiletypesCB->cbBase.asyncWork = nullptr; - getfiletypesCB->cbBase.deferred = nullptr; - getfiletypesCB->cbBase.ability = nullptr; - - napi_value ret = GetFileTypesWrap(env, info, getfiletypesCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (getfiletypesCB != nullptr) { - delete getfiletypesCB; - getfiletypesCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - getfiletypesCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, getfiletypesCB->uri.c_str()); - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - getfiletypesCB->mimeTypeFilter = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,mimeTypeFilter=%{public}s", __func__, getfiletypesCB->mimeTypeFilter.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - getfiletypesCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = GetFileTypesAsync(env, args, ARGS_TWO, getfiletypesCB); - } else { - ret = GetFileTypesPromise(env, getfiletypesCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value GetFileTypesAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &getfiletypesCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetFileTypesExecuteCB, - GetFileTypesAsyncCompleteCB, - (void *)getfiletypesCB, - &getfiletypesCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - getfiletypesCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetFileTypesExecuteCB, - GetFileTypesPromiseCompleteCB, - (void *)getfiletypesCB, - &getfiletypesCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void GetFileTypesExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - if (getfiletypesCB->dataShareHelper != nullptr) { - getfiletypesCB->execResult = INVALID_PARAMETER; - if (!getfiletypesCB->uri.empty()) { - OHOS::Uri uri(getfiletypesCB->uri); - HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); - HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); - getfiletypesCB->result = getfiletypesCB->dataShareHelper->GetFileTypes( - uri, - getfiletypesCB->mimeTypeFilter); - getfiletypesCB->execResult = NO_ERROR; - } else { - HILOG_INFO("NAPI_GetFileTypes, dataShareHelper uri is empty."); - } - } else { - HILOG_INFO("NAPI_GetFileTypes, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute end."); -} - -void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, getfiletypesCB->execResult); - result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (getfiletypesCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getfiletypesCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); - delete getfiletypesCB; - getfiletypesCB = nullptr; - HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); -} - -napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB) -{ - HILOG_INFO("WrapGetFileTypesCB, called."); - HILOG_INFO("NAPI_GetFileTypes, result.size:%{public}zu", getfiletypesCB.result.size()); - for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { - HILOG_INFO("NAPI_GetFileTypes, result[%{public}zu]:%{public}s", i, getfiletypesCB.result.at(i).c_str()); - } - napi_value proValue = nullptr; - - napi_value jsArrayresult = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayresult)); - for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, getfiletypesCB.result.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayresult, i, proValue)); - } - HILOG_INFO("WrapGetFileTypesCB, end."); - return jsArrayresult; -} - -void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - napi_value result = nullptr; - - result = WrapGetFileTypesCB(env, *getfiletypesCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getfiletypesCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); - delete getfiletypesCB; - getfiletypesCB = nullptr; - HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); -} - -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperNormalizeUriCB *normalizeuriCB = new (std::nothrow) DSHelperNormalizeUriCB; - if (normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, normalizeuriCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - normalizeuriCB->cbBase.cbInfo.env = env; - normalizeuriCB->cbBase.asyncWork = nullptr; - normalizeuriCB->cbBase.deferred = nullptr; - normalizeuriCB->cbBase.ability = nullptr; - - napi_value ret = NormalizeUriWrap(env, info, normalizeuriCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (normalizeuriCB != nullptr) { - delete normalizeuriCB; - normalizeuriCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - normalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, normalizeuriCB->uri.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - normalizeuriCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = NormalizeUriAsync(env, args, ARGS_ONE, normalizeuriCB); - } else { - ret = NormalizeUriPromise(env, normalizeuriCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value NormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &normalizeuriCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NormalizeUriExecuteCB, - NormalizeUriAsyncCompleteCB, - (void *)normalizeuriCB, - &normalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - normalizeuriCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NormalizeUriExecuteCB, - NormalizeUriPromiseCompleteCB, - (void *)normalizeuriCB, - &normalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void NormalizeUriExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - Uri uriValue(normalizeuriCB->uri); - if (normalizeuriCB->dataShareHelper != nullptr) { - normalizeuriCB->execResult = INVALID_PARAMETER; - if (!normalizeuriCB->uri.empty()) { - OHOS::Uri uri(normalizeuriCB->uri); - uriValue = normalizeuriCB->dataShareHelper->NormalizeUri(uri); - normalizeuriCB->result = uriValue.ToString(); - normalizeuriCB->execResult = NO_ERROR; - } - } else { - HILOG_INFO("NAPI_NormalizeUri, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute end."); -} - -void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, normalizeuriCB->execResult); - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (normalizeuriCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, normalizeuriCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); - delete normalizeuriCB; - normalizeuriCB = nullptr; - HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); -} - -void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, normalizeuriCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); - delete normalizeuriCB; - normalizeuriCB = nullptr; - HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); -} - -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperDenormalizeUriCB *denormalizeuriCB = new (std::nothrow) DSHelperDenormalizeUriCB; - if (denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, denormalizeuriCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - denormalizeuriCB->cbBase.cbInfo.env = env; - denormalizeuriCB->cbBase.asyncWork = nullptr; - denormalizeuriCB->cbBase.deferred = nullptr; - denormalizeuriCB->cbBase.ability = nullptr; - - napi_value ret = DenormalizeUriWrap(env, info, denormalizeuriCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (denormalizeuriCB != nullptr) { - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - denormalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, denormalizeuriCB->uri.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - denormalizeuriCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = DenormalizeUriAsync(env, args, ARGS_ONE, denormalizeuriCB); - } else { - ret = DenormalizeUriPromise(env, denormalizeuriCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value DenormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &denormalizeuriCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DenormalizeUriExecuteCB, - DenormalizeUriAsyncCompleteCB, - (void *)denormalizeuriCB, - &denormalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - denormalizeuriCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DenormalizeUriExecuteCB, - DenormalizeUriPromiseCompleteCB, - (void *)denormalizeuriCB, - &denormalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void DenormalizeUriExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - Uri uriValue(denormalizeuriCB->uri); - if (denormalizeuriCB->dataShareHelper != nullptr) { - denormalizeuriCB->execResult = INVALID_PARAMETER; - if (!denormalizeuriCB->uri.empty()) { - OHOS::Uri uri(denormalizeuriCB->uri); - uriValue = denormalizeuriCB->dataShareHelper->DenormalizeUri(uri); - denormalizeuriCB->result = uriValue.ToString(); - denormalizeuriCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute end."); -} - -void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, denormalizeuriCB->execResult); - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (denormalizeuriCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, denormalizeuriCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); -} - -void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, denormalizeuriCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); -} - -void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value) -{ - auto tempPredicates = DataAbilityJsKit::DataAbilityPredicatesProxy::GetNativePredicates(env, value); - if (tempPredicates == nullptr) { - HILOG_ERROR("%{public}s, GetNativePredicates retval Marshalling failed.", __func__); - return; - } - predicates = *tempPredicates; -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Delete(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperDeleteCB *deleteCB = new (std::nothrow) DSHelperDeleteCB; - if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, deleteCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - deleteCB->cbBase.cbInfo.env = env; - deleteCB->cbBase.asyncWork = nullptr; - deleteCB->cbBase.deferred = nullptr; - deleteCB->cbBase.ability = nullptr; - - napi_value ret = DeleteWrap(env, info, deleteCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (deleteCB != nullptr) { - delete deleteCB; - deleteCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); - } - - UnwrapDataAbilityPredicates(deleteCB->predicates, env, args[PARAM1]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - deleteCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = DeleteAsync(env, args, ARGS_TWO, deleteCB); - } else { - ret = DeletePromise(env, deleteCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &deleteCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DeleteExecuteCB, - DeleteAsyncCompleteCB, - (void *)deleteCB, - &deleteCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - deleteCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DeleteExecuteCB, - DeletePromiseCompleteCB, - (void *)deleteCB, - &deleteCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void DeleteExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Delete, worker pool thread execute."); - DSHelperDeleteCB *deleteCB = static_cast(data); - if (deleteCB->dataShareHelper != nullptr) { - deleteCB->execResult = INVALID_PARAMETER; - if (!deleteCB->uri.empty()) { - OHOS::Uri uri(deleteCB->uri); - deleteCB->result = deleteCB->dataShareHelper->Delete(uri, deleteCB->predicates); - deleteCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_Delete, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Delete, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Delete, worker pool thread execute end."); -} - -void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Delete, main event thread complete."); - DSHelperDeleteCB *DeleteCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, DeleteCB->execResult); - napi_create_int32(env, DeleteCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (DeleteCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); - delete DeleteCB; - DeleteCB = nullptr; - HILOG_INFO("NAPI_Delete, main event thread complete end."); -} - -void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Delete, main event thread complete."); - DSHelperDeleteCB *DeleteCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, DeleteCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); - delete DeleteCB; - DeleteCB = nullptr; - HILOG_INFO("NAPI_Delete, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Update(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperUpdateCB *updateCB = new (std::nothrow) DSHelperUpdateCB; - if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, updateCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - updateCB->cbBase.cbInfo.env = env; - updateCB->cbBase.asyncWork = nullptr; - updateCB->cbBase.deferred = nullptr; - updateCB->cbBase.ability = nullptr; - - napi_value ret = UpdateWrap(env, info, updateCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (updateCB != nullptr) { - delete updateCB; - updateCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_FOUR; - const size_t argcPromise = ARGS_THREE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); - } - - updateCB->valueBucket.Clear(); - AnalysisValuesBucket(updateCB->valueBucket, env, args[PARAM1]); - UnwrapDataAbilityPredicates(updateCB->predicates, env, args[PARAM2]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - updateCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = UpdateAsync(env, args, ARGS_THREE, updateCB); - } else { - ret = UpdatePromise(env, updateCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || updateCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &updateCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - UpdateExecuteCB, - UpdateAsyncCompleteCB, - (void *)updateCB, - &updateCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - updateCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - UpdateExecuteCB, - UpdatePromiseCompleteCB, - (void *)updateCB, - &updateCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void UpdateExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Update, worker pool thread execute."); - DSHelperUpdateCB *updateCB = static_cast(data); - if (updateCB->dataShareHelper != nullptr) { - updateCB->execResult = INVALID_PARAMETER; - if (!updateCB->uri.empty()) { - OHOS::Uri uri(updateCB->uri); - updateCB->result = updateCB->dataShareHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); - updateCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_Update, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Update, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Update, worker pool thread execute end."); -} - -void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Update, main event thread complete."); - DSHelperUpdateCB *updateCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, updateCB->execResult); - napi_create_int32(env, updateCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (updateCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); - delete updateCB; - updateCB = nullptr; - HILOG_INFO("NAPI_Update, main event thread complete end."); -} - -void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Update, main event thread complete."); - DSHelperUpdateCB *updateCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, updateCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); - delete updateCB; - updateCB = nullptr; - HILOG_INFO("NAPI_Update, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOpenFileCB *openFileCB = new (std::nothrow) DSHelperOpenFileCB; - if (openFileCB == nullptr) { - HILOG_ERROR("%{public}s, openFileCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - openFileCB->cbBase.cbInfo.env = env; - openFileCB->cbBase.asyncWork = nullptr; - openFileCB->cbBase.deferred = nullptr; - openFileCB->cbBase.ability = nullptr; - - napi_value ret = OpenFileWrap(env, info, openFileCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (openFileCB != nullptr) { - delete openFileCB; - openFileCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, openFileCB->uri.c_str()); - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - openFileCB->mode = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,mode=%{public}s", __func__, openFileCB->mode.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - openFileCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = OpenFileAsync(env, args, ARGS_TWO, openFileCB); - } else { - ret = OpenFilePromise(env, openFileCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || openFileCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &openFileCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - OpenFileExecuteCB, - OpenFileAsyncCompleteCB, - (void *)openFileCB, - &openFileCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (openFileCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - openFileCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - OpenFileExecuteCB, - OpenFilePromiseCompleteCB, - (void *)openFileCB, - &openFileCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void OpenFileExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - if (OpenFileCB->dataShareHelper != nullptr) { - OpenFileCB->execResult = INVALID_PARAMETER; - if (!OpenFileCB->uri.empty()) { - OHOS::Uri uri(OpenFileCB->uri); - OpenFileCB->result = OpenFileCB->dataShareHelper->OpenFile(uri, OpenFileCB->mode); - OpenFileCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_OpenFile, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_OpenFile, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_OpenFile, worker pool thread execute end."); -} - -void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_OpenFile, main event thread complete."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, OpenFileCB->execResult); - napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (OpenFileCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, OpenFileCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); - delete OpenFileCB; - OpenFileCB = nullptr; - HILOG_INFO("NAPI_OpenFile, main event thread complete end."); -} - -void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_OpenFileCB, main event thread complete."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, OpenFileCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, OpenFileCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); - delete OpenFileCB; - OpenFileCB = nullptr; - HILOG_INFO("NAPI_OpenFileCB, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperBatchInsertCB *BatchInsertCB = new (std::nothrow) DSHelperBatchInsertCB; - if (BatchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, BatchInsertCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - BatchInsertCB->cbBase.cbInfo.env = env; - BatchInsertCB->cbBase.asyncWork = nullptr; - BatchInsertCB->cbBase.deferred = nullptr; - BatchInsertCB->cbBase.ability = nullptr; - - napi_value ret = BatchInsertWrap(env, info, BatchInsertCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (BatchInsertCB != nullptr) { - delete BatchInsertCB; - BatchInsertCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -std::vector NapiValueObject(napi_env env, napi_value param) -{ - HILOG_INFO("%{public}s,called", __func__); - std::vector result; - UnwrapArrayObjectFromJS(env, param, result); - return result; -} - -bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value) -{ - HILOG_INFO("%{public}s,called", __func__); - uint32_t arraySize = 0; - napi_value jsValue = nullptr; - std::string strValue = ""; - - if (!IsArrayForNapiValue(env, param, arraySize)) { - HILOG_INFO("%{public}s, IsArrayForNapiValue is false", __func__); - return false; - } - - value.clear(); - for (uint32_t i = 0; i < arraySize; i++) { - jsValue = nullptr; - if (napi_get_element(env, param, i, &jsValue) != napi_ok) { - HILOG_INFO("%{public}s, napi_get_element is false", __func__); - return false; - } - - NativeRdb::ValuesBucket valueBucket; - valueBucket.Clear(); - AnalysisValuesBucket(valueBucket, env, jsValue); - - value.push_back(valueBucket); - } - HILOG_INFO("%{public}s,end", __func__); - return true; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - batchInsertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, batchInsertCB->uri.c_str()); - } - - batchInsertCB->values = NapiValueObject(env, args[PARAM1]); - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - batchInsertCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = BatchInsertAsync(env, args, ARGS_TWO, batchInsertCB); - } else { - ret = BatchInsertPromise(env, batchInsertCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value BatchInsertAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || batchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &batchInsertCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - BatchInsertExecuteCB, - BatchInsertAsyncCompleteCB, - (void *)batchInsertCB, - &batchInsertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (batchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - batchInsertCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - BatchInsertExecuteCB, - BatchInsertPromiseCompleteCB, - (void *)batchInsertCB, - &batchInsertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void BatchInsertExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); - DSHelperBatchInsertCB *batchInsertCB = static_cast(data); - if (batchInsertCB->dataShareHelper != nullptr) { - batchInsertCB->execResult = INVALID_PARAMETER; - if (!batchInsertCB->uri.empty()) { - OHOS::Uri uri(batchInsertCB->uri); - batchInsertCB->result = batchInsertCB->dataShareHelper->BatchInsert(uri, batchInsertCB->values); - batchInsertCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_BatchInsert, dataShareHelper uri is empyt"); - } - } else { - HILOG_ERROR("NAPI_BatchInsert, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_BatchInsert, worker pool thread execute end."); -} - -void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_BatchInsert, main event thread complete."); - DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, BatchInsertCB->execResult); - napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (BatchInsertCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, BatchInsertCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); - delete BatchInsertCB; - BatchInsertCB = nullptr; - HILOG_INFO("NAPI_BatchInsert, main event thread complete end."); -} - -void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_BatchInsertCB, main event thread complete."); - DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, BatchInsertCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, BatchInsertCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); - delete BatchInsertCB; - BatchInsertCB = nullptr; - HILOG_INFO("NAPI_BatchInsertCB, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Query(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperQueryCB *QueryCB = new (std::nothrow) DSHelperQueryCB; - if (QueryCB == nullptr) { - HILOG_ERROR("%{public}s, QueryCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - QueryCB->cbBase.cbInfo.env = env; - QueryCB->cbBase.asyncWork = nullptr; - QueryCB->cbBase.deferred = nullptr; - QueryCB->cbBase.ability = nullptr; - - napi_value ret = QueryWrap(env, info, QueryCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (QueryCB != nullptr) { - delete QueryCB; - QueryCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_FOUR; - const size_t argcPromise = ARGS_THREE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); - } - - std::vector result; - bool arrayStringbool = false; - arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); - if (!arrayStringbool) { - HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); - } - queryCB->columns = result; - for (size_t i = 0; i < queryCB->columns.size(); i++) { - HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); - } - - UnwrapDataAbilityPredicates(queryCB->predicates, env, args[PARAM2]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo", __func__); - queryCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = QueryAsync(env, args, ARGS_THREE, queryCB); - } else { - ret = QueryPromise(env, queryCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || queryCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &queryCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - QueryExecuteCB, - QueryAsyncCompleteCB, - (void *)queryCB, - &queryCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (queryCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - queryCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - QueryExecuteCB, - QueryPromiseCompleteCB, - (void *)queryCB, - &queryCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete."); - DSHelperQueryCB *QueryCB = static_cast(data); - napi_value result = nullptr; - result = WrapResultSet(env, QueryCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); - delete QueryCB; - QueryCB = nullptr; - HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete end."); -} - -void QueryExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Query, worker pool thread execute."); - DSHelperQueryCB *queryCB = static_cast(data); - if (queryCB->dataShareHelper != nullptr) { - queryCB->execResult = INVALID_PARAMETER; - if (!queryCB->uri.empty()) { - OHOS::Uri uri(queryCB->uri); - auto resultset = queryCB->dataShareHelper->Query(uri, queryCB->columns, queryCB->predicates); - if (resultset != nullptr) { - queryCB->result = resultset; - queryCB->execResult = NO_ERROR; - } else { - HILOG_INFO("NAPI_Query, resultset == nullptr."); - } - } else { - HILOG_ERROR("NAPI_Query, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Query, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Query, worker pool thread execute end."); -} - -void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Query, main event thread complete."); - DSHelperQueryCB *queryCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, queryCB->execResult); - result[PARAM1] = WrapResultSet(env, queryCB->result); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (queryCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); - delete queryCB; - queryCB = nullptr; - HILOG_INFO("NAPI_Query, main event thread complete end."); -} - -napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet) -{ - HILOG_INFO("%{public}s,called", __func__); - if (resultSet == nullptr) { - HILOG_ERROR("%{public}s, input parameter resultSet is nullptr", __func__); - return WrapVoidToJS(env); - } - - return RdbJsKit::ResultSetProxy::NewInstance(env, resultSet); -} - -napi_value NAPI_Release(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperReleaseCB *releaseCB = new (std::nothrow) DSHelperReleaseCB; - if (releaseCB == nullptr) { - HILOG_ERROR("%{public}s, releaseCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - releaseCB->cbBase.cbInfo.env = env; - releaseCB->cbBase.asyncWork = nullptr; - releaseCB->cbBase.deferred = nullptr; - - napi_value ret = ReleaseWrap(env, info, releaseCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (releaseCB != nullptr) { - delete releaseCB; - releaseCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_ONE; - const size_t argcPromise = ARGS_ZERO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("DataShareHelper ReleaseWrap objectInfo"); - releaseCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = ReleaseAsync(env, args, PARAM0, releaseCB); - } else { - ret = ReleasePromise(env, releaseCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || releaseCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &releaseCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - ReleaseExecuteCB, - ReleaseAsyncCompleteCB, - (void *)releaseCB, - &releaseCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (releaseCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - releaseCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - ReleaseExecuteCB, - ReleasePromiseCompleteCB, - (void *)releaseCB, - &releaseCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void ReleaseExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Release, worker pool thread execute."); - DSHelperReleaseCB *releaseCB = static_cast(data); - if (releaseCB->dataShareHelper != nullptr) { - releaseCB->result = releaseCB->dataShareHelper->Release(); - } else { - HILOG_ERROR("NAPI_Release, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Release, worker pool thread execute end."); -} - -void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Release, main event thread complete."); - DSHelperReleaseCB *releaseCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, releaseCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_get_boolean(env, releaseCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (releaseCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, releaseCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); - delete releaseCB; - releaseCB = nullptr; - HILOG_INFO("NAPI_Release, main event thread complete end."); -} - -void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Release, main event thread complete."); - DSHelperReleaseCB *releaseCB = static_cast(data); - napi_value result = nullptr; - napi_get_boolean(env, releaseCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, releaseCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); - delete releaseCB; - releaseCB = nullptr; - HILOG_INFO("NAPI_Release, main event thread complete end."); -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h deleted file mode 100644 index 4cbaeafaf18..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H -#define OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H -#include "data_ability_observer_stub.h" -#include "data_share_common.h" - -namespace OHOS { -namespace AppExecFwk { -class NAPIDataShareObserver : public AAFwk::DataAbilityObserverStub { -public: - void OnChange() override; - void SetEnv(const napi_env &env); - void SetCallbackRef(const napi_ref &ref); - void ReleaseJSCallback(); - - void SetAssociatedObject(DSHelperOnOffCB* object); - const DSHelperOnOffCB* GetAssociatedObject(void); - - void ChangeWorkPre(); - void ChangeWorkRun(); - void ChangeWorkInt(); - void ChangeWorkPreDone(); - void ChangeWorkRunDone(); - int GetWorkPre(); - int GetWorkRun(); - int GetWorkInt(); - -private: - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; - DSHelperOnOffCB* onCB_ = nullptr; - int workPre_ = 0; - int workRun_ = 0; - int intrust_ = 0; - std::mutex mutex_; -}; - -/** - * @brief DataShareHelper NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value DataShareHelperInit(napi_env env, napi_value exports); -napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info); - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Insert(napi_env env, napi_callback_info info); - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB); - -/** - * @brief Insert Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB); - -/** - * @brief Insert Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB); - -/** - * @brief Insert asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : notifyChange. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info); - -/** - * @brief NotifyChange processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangeExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : on. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Register(napi_env env, napi_callback_info info); - -/** - * @brief On processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); - -/** - * @brief On Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); - -/** - * @brief On asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void RegisterExecuteCB(napi_env env, void *data); -void RegisterCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : off. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_UnRegister(napi_env env, napi_callback_info info); - -/** - * @brief Off processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); - -/** - * @brief Off Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); - -/** - * @brief Off asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void UnRegisterExecuteCB(napi_env env, void *data); -void UnRegisterCompleteCB(napi_env env, napi_status status, void *data); -void FindRegisterObs(napi_env env, DSHelperOnOffCB *data); -/** - * @brief Parse the ValuesBucket parameters. - * - * @param param Indicates the want parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args); - -static std::vector registerInstances_; -napi_value NAPI_Release(napi_env env, napi_callback_info info); - -napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB); - -napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB); - -napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB); - -void ReleaseExecuteCB(napi_env env, void *data); - -void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_GetType(napi_env env, napi_callback_info info); -napi_value NAPI_GetType(napi_env env, napi_callback_info info); -napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB); -napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB); -napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB); -void GetTypeExecuteCB(napi_env env, void *data); -void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data); -void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); -napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB); -napi_value GetFileTypesAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB); -napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB); -void GetFileTypesExecuteCB(napi_env env, void *data); -void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data); -void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data); -napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB); - -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); -napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB); -napi_value NormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB); -napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB); -void NormalizeUriExecuteCB(napi_env env, void *data); -void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); -void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); -napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB); -napi_value DenormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB); -napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB); -void DenormalizeUriExecuteCB(napi_env env, void *data); -void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); -void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_Delete(napi_env env, napi_callback_info info); - -napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB); -napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB); - -napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB); - -void DeleteExecuteCB(napi_env env, void *data); - -void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_Update(napi_env env, napi_callback_info info); - -napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB); -napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB); - -napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB); - -void UpdateExecuteCB(napi_env env, void *data); - -void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_OpenFile(napi_env env, napi_callback_info info); - -napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB); -napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB); - -napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB); - -void OpenFileExecuteCB(napi_env env, void *data); - -void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info); - -napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB); -napi_value BatchInsertAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB); - -napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB); - -void BatchInsertExecuteCB(napi_env env, void *data); - -void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data); - -std::vector NapiValueObject(napi_env env, napi_value param); - -bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value); - -napi_value NAPI_Query(napi_env env, napi_callback_info info); - -napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB); - -napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB); - -napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB); - -void QueryExecuteCB(napi_env env, void *data); - -void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet); - -void AnalysisValuesBucket(NativeRdb::ValuesBucket &value, const napi_env &env, const napi_value &arg); -void SetValuesBucketObject( - NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value); - -void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value); -} // namespace AppExecFwk -} // namespace OHOS -#endif /* OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H */ diff --git a/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp b/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp deleted file mode 100644 index 078fee397f3..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "napi_datashare_helper.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace AppExecFwk { -EXTERN_C_START -/* - * The module initialization. - */ -static napi_value Init(napi_env env, napi_value exports) -{ - DataShareHelperInit(env, exports); - return exports; -} -EXTERN_C_END - -/* - * The module definition. - */ -static napi_module _module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.dataShare", - .nm_priv = ((void *)0), - .reserved = {0} -}; - -/* - * The module registration. - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn deleted file mode 100644 index 4cf1996aa54..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") - -#################################group######################################### -group("unittest") { - testonly = true - deps = [] - - deps += [ "unittest:unittest" ] -} -############################################################################### diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn deleted file mode 100644 index a73139a8541..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (C) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") - -module_output_path = "ability_runtime/datashare" - -ohos_js_unittest("DataShareJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - - if (is_standard_system) { - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" - } else { - deps = [ "//test/developertest/adapter/examples/app_info/test/common/main:get_app_info_test_lib" ] - entry_app_dep = [ "//test/developertest/adapter/examples/app_info/test/common/shell:build_shell_execute" ] - } -} - -group("unittest") { - testonly = true - # deps = [ ":DataShareJsTest" ] -} diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js b/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js deleted file mode 100644 index 65a03a220c3..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js +++ /dev/null @@ -1,1081 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import dataShare from '@ohos.data.dataShare'; -import dataAbility from '@ohos.data.dataAbility'; - -const TAG = "[DATASHARE_JSKITS_TEST]" -const URI = ("datashare:///com.samples.datasharetest.DataShare"); -let dseWant = { - "bundleName": "com.examples.datasharetest.service", - "abilityName": "DataShareExtAbility", -} - -describe('dataShareTest', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll') - }) - - beforeEach(function () { - console.info(TAG + 'beforeEach') - }) - - afterEach(function () { - console.info(TAG + 'afterEach') - }) - - afterAll(async function () { - console.info(TAG + 'afterAll') - }) - - console.log(TAG + "*************Unit Test Begin*************"); - - function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); - } - - /** - * @tc.name data share createDataShareHelper test - * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0000 - * @tc.desc data share createDataShareHelper test - */ - it('createDataShareHelper_0000', 0, async function (done) { - console.log(TAG + ":createDataShareHelper_0000 start"); - try { - let helper = dataShare.createDataShareHelper(this.context, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":createDataShareHelper_0000 end"); - }) - - /** - * @tc.name data share createDataShareHelper test - * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0010 - * @tc.desc data share createDataShareHelper test - */ - it('createDataShareHelper_0010', 0, async function (done) { - console.log(TAG + ":createDataShareHelper_0010 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":createDataShareHelper_0010 end"); - }) - - /** - * @tc.name data share createDataShareHelper test - * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0011 - * @tc.desc data share createDataShareHelper test - */ - it('createDataShareHelper_0011', 0, async function (done) { - console.log(TAG + ":createDataShareHelper_0011 start"); - try { - let helper = dataShare.createDataShareHelper(this.context, null, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":createDataShareHelper_0011 end"); - }) - - /** - * @tc.name data share createDataShareHelper test - * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0012 - * @tc.desc data share createDataShareHelper test - */ - it('createDataShareHelper_0012', 0, async function (done) { - console.log(TAG + ":createDataShareHelper_0012 start"); - try { - let helper = dataShare.createDataShareHelper(this.context, dseWant, null); - console.log(TAG + ":DataShareHelper helper:" + helper); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":createDataShareHelper_0012 end"); - }) - - /** - * @tc.name data share onEvent test - * @tc.number SUB_DDM_DataShare_JS_on_0020 - * @tc.desc data share onEvent test - */ - it('on_0020', 0, async function (done) { - console.log(TAG + ":on_0020 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.on( - "dataChange", - URI, - onChangeNotify - ) - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":on_0020 end"); - }) - - /** - * @tc.name data share onEvent test - * @tc.number SUB_DDM_DataShare_JS_on_0021 - * @tc.desc data share onEvent test - */ - it('on_0021', 0, async function (done) { - console.log(TAG + ":on_0021 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.on( - "dataChange", - null, - onChangeNotify - ) - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":on_0021 end"); - }) - - /** - * @tc.name data share offEvent test - * @tc.number SUB_DDM_DataShare_JS_off_0030 - * @tc.desc data share offEvent test - */ - it('off_0030', 0, async function (done) { - console.log(TAG + ":off_0030 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.off( - "dataChange", - URI, - ) - helper.off( - "dataChange", - URI, - onChangeNotify - ) - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":off_0030 end"); - }) - - /** - * @tc.name data share offEvent test - * @tc.number SUB_DDM_DataShare_JS_off_0031 - * @tc.desc data share offEvent test - */ - it('off_0031', 0, async function (done) { - console.log(TAG + ":off_0031 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.off( - "dataChange", - null, - onChangeNotify - ) - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":off_0031 end"); - }) - - /** - * @tc.name data share getType_callback test - * @tc.number SUB_DDM_DataShare_getType_0040 - * @tc.desc data share getType_callback test - */ - it('getType_callback_0040', 0, async function (done) { - console.log(TAG + ":getType_callback_0040 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.getType( - URI, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":getType_callback_0040 end"); - }) - - /** - * @tc.name data share getType_promise test - * @tc.number SUB_DDM_DataShare_JS_getType_promise_0041 - * @tc.desc data share getType_promise test - */ - it('getType_promise_0041', 0, async function (done) { - console.log(TAG + ":getType_promise_0041 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.getType( - URI - ).then((data) => { - console.info("==========================>getTypeCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":getType_promise_0041 end"); - }) - - /** - * @tc.name data share getFileType_callback test - * @tc.number SUB_DDM_DataShare_JS_getFileType_callback_0050 - * @tc.desc data share getFileType_callback test - */ - it('getFileType_callback_0050', 0, async function (done) { - console.log(TAG + ":getFileType_callback_0050 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.getFileTypes( - URI, - "image/*", - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":getFileType_callback_0050 end"); - }) - - /** - * @tc.name data share getFileType_promise test - * @tc.number SUB_DDM_DataShare_JS_getFileType_promise_0051 - * @tc.desc data share getFileType_promise test - */ - it('getFileType_promise_0051', 0, async function (done) { - console.log(TAG + ":getFileType_promise_0051 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.getFileTypes( - URI, - "image/*" - ).then((data) => { - console.info("==========================>getFileTypesCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":getFileType_promise_0051 end"); - }) - - /** - * @tc.name data share getFileType_callback test - * @tc.number SUB_DDM_DataShare_JS_getFileType_callback_0052 - * @tc.desc data share getFileType_callback test - */ - it('getFileType_callback_0052', 0, async function (done) { - console.log(TAG + ":getFileType_callback_0052 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.getFileTypes( - null, - "image/*", - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":getFileType_callback_0052 end"); - }) - - /** - * @tc.name data share normalizeUri_callback test - * @tc.number SUB_DDM_DataShare_JS_normalizeUri_0060 - * @tc.desc data share normalizeUri_callback test - */ - it('normalizeUri_callback_0060', 0, async function (done) { - console.log(TAG + ":normalizeUri_callback_0060 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.normalizeUri( - URI, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":normalizeUri_callback_0060 end"); - }) - - /** - * @tc.name data share normalizeUri_promise test - * @tc.number SUB_DDM_DataShare_JS_normalizeUri_promise_0061 - * @tc.desc data share normalizeUri_promise test - */ - it('normalizeUri_promise_0061', 0, async function (done) { - console.log(TAG + ":normalizeUri_promise_0061 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.normalizeUri( - URI, - ).then((data) => { - console.info("==========================>normalizeUriCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":normalizeUri_promise_0061 end"); - }) - - /** - * @tc.name data share normalizeUri_callback test - * @tc.number SUB_DDM_DataShare_JS_normalizeUri_0062 - * @tc.desc data share normalizeUri_callback test - */ - it('normalizeUri_callback_0062', 0, async function (done) { - console.log(TAG + ":normalizeUri_callback_0062 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.normalizeUri( - null, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":normalizeUri_callback_0062 end"); - }) - - /** - * @tc.name data share denormalizeUri_callback test - * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_callback_0060 - * @tc.desc data share denormalizeUri_callback test - */ - it('denormalizeUri_callback_0070', 0, async function (done) { - console.log(TAG + ":denormalizeUri_callback_0070 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.denormalizeUri( - URI, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":denormalizeUri_callback_0070 end"); - }) - - /** - * @tc.name data share denormalizeUri_promise test - * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_promise_0061 - * @tc.desc data share denormalizeUri_promise test - */ - it('denormalizeUri_promise_0071', 0, async function (done) { - console.log(TAG + ":denormalizeUri_promise_0071 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.denormalizeUri( - URI, - ).then((data) => { - console.info("==========================>denormalizeUriCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":denormalizeUri_promise_0071 end"); - }) - - /** - * @tc.name data share denormalizeUri_callback test - * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_callback_0072 - * @tc.desc data share denormalizeUri_callback test - */ - it('denormalizeUri_callback_0072', 0, async function (done) { - console.log(TAG + ":denormalizeUri_callback_0072 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.denormalizeUri( - null, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":denormalizeUri_callback_0072 end"); - }) - - /** - * @tc.name data share notifyChange_callback test - * @tc.number SUB_DDM_DataShare_JS_notifyChange_callback_0080 - * @tc.desc data share notifyChange_callback test - */ - it('notifyChange_callback_0080', 0, async function (done) { - console.log(TAG + ":notifyChange_callback_0080 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.notifyChange( - URI, - (err) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":notifyChange_callback_0080 end"); - }) - - /** - * @tc.name data share notifyChange_promise test - * @tc.number SUB_DDM_DataShare_JS_notifyChange_promise_0081 - * @tc.desc data share notifyChange_promise test - */ - it('notifyChange_promise_0081', 0, async function (done) { - console.log(TAG + ":notifyChange_promise_0081 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.notifyChange( - URI, - ).then(() => { - console.info("==========================>notifyChangeCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":notifyChange_promise_0081 end"); - }) - - /** - * @tc.name data share notifyChange_callback test - * @tc.number SUB_DDM_DataShare_JS_notifyChange_callback_0082 - * @tc.desc data share notifyChange_callback test - */ - it('notifyChange_callback_0082', 0, async function (done) { - console.log(TAG + ":notifyChange_callback_0082 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - helper.notifyChange( - null, - (err) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":notifyChange_callback_0082 end"); - }) - - /** - * @tc.name data share insert_callback test - * @tc.number SUB_DDM_DataShare_JS_insert_callback_0090 - * @tc.desc data share insert_callback test - */ - it('insert_callback_0090', 0, async function (done) { - console.log(TAG + ":insert_callback_0090 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, - "blobType": u8, - } - helper.insert( - URI, - valueBucket, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":insert_callback_0090 end"); - }) - - /** - * @tc.name data share insert_promise test - * @tc.number SUB_DDM_DataShare_JS_insert_promise_0091 - * @tc.desc data share insert_promise test - */ - it('insert_promise_0091', 0, async function (done) { - console.log(TAG + ":insert_promise_0081 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const valueBucket = { - "name": "rose1", - "age": 221, - "salary": 20.5, - "blobType": u8, - } - helper.insert( - URI, - valueBucket - ).then((data) => { - console.info("==========================>insertCallback=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":insert_promise_0091 end"); - }) - - /** - * @tc.name data share insert_callback test - * @tc.number SUB_DDM_DataShare_JS_insert_callback_0092 - * @tc.desc data share insert_callback test - */ - it('insert_callback_0092', 0, async function (done) { - console.log(TAG + ":insert_callback_0092 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, - "blobType": u8, - } - helper.insert( - null, - valueBucket, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":insert_callback_0092 end"); - }) - - /** - * @tc.name data share batchInsert_callback test - * @tc.number SUB_DDM_DataShare_JS_batchInsert_callback_0090 - * @tc.desc data share batchInsert_callback test - */ - it('batchInsert_callback_0100', 0, async function (done) { - console.log(TAG + ":batchInsert_callback_0100 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) - helper.batchInsert( - URI, - cars, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":batchInsert_callback_0100 end"); - }) - - /** - * @tc.name data share batchInsert_promise test - * @tc.number SUB_DDM_DataShare_JS_batchInsert_promise_0101 - * @tc.desc data share createDataShareHelper test - */ - it('batchInsert_promise_0101', 0, async function (done) { - console.log(TAG + ":batchInsert_promise_0101 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) - helper.batchInsert( - URI, - cars - ).then((data) => { - console.info("==========================>batchInsertCallback=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":batchInsert_promise_0101 end"); - }) - - /** - * @tc.name data share batchInsert_callback test - * @tc.number SUB_DDM_DataShare_JS_batchInsert_callback_0102 - * @tc.desc data share batchInsert_callback test - */ - it('batchInsert_callback_0102', 0, async function (done) { - console.log(TAG + ":batchInsert_callback_0102 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) - helper.batchInsert( - null, - cars, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":batchInsert_callback_0102 end"); - }) - - /** - * @tc.name data share delete_callback test - * @tc.number SUB_DDM_DataShare_JS_delete_callback_0110 - * @tc.desc data share delete_callback test - */ - it('delete_callback_0110', 0, async function (done) { - console.log(TAG + ":delete_callback_0110 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.delete( - URI, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":delete_callback_0110 end"); - }) - - /** - * @tc.name data share delete_promise test - * @tc.number SUB_DDM_DataShare_JS_delete_promise_0111 - * @tc.desc data share delete_promise test - */ - it('delete_promise_0111', 0, async function (done) { - console.log(TAG + ":delete_promise_0111 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.delete( - URI, - da - ).then((data) => { - console.info("==========================>deleteCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":delete_promise_0111 end"); - }) - - /** - * @tc.name data share delete_callback test - * @tc.number SUB_DDM_DataShare_JS_delete_callback_0112 - * @tc.desc data share delete_callback test - */ - it('delete_callback_0112', 0, async function (done) { - console.log(TAG + ":delete_callback_0112 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.delete( - null, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":delete_callback_0112 end"); - }) - - /** - * @tc.name data share delete_callback test - * @tc.number SUB_DDM_DataShare_JS_delete_callback_0113 - * @tc.desc data share delete_callback test - */ - it('delete_callback_0113', 0, async function (done) { - console.log(TAG + ":delete_callback_0113 start"); - try { - let helper = dataShare.createDataShareHelper(this.context, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.delete( - URI, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":delete_callback_0113 end"); - }) - - /** - * @tc.name data share update_callback test - * @tc.number SUB_DDM_DataShare_JS_update_callback_0120 - * @tc.desc data share update_callback test - */ - it('update_callback_0120', 0, async function (done) { - console.log(TAG + ":update_callback_0120 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": u8, - } - let da = new dataAbility.DataAbilityPredicates() - helper.update( - URI, - va, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":update_callback_0120 end"); - }) - - /** - * @tc.name data share update_promise test - * @tc.number SUB_DDM_DataShare_JS_update_promise_0121 - * @tc.desc data share update_promise test - */ - it('update_promise_0121', 0, async function (done) { - console.log(TAG + ":update_promise_0121 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": u8, - } - let da = new dataAbility.DataAbilityPredicates() - helper.update( - URI, - va, - da - ).then((data) => { - console.info("==========================>updateCallback=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":update_promise_0121 end"); - }) - - /** - * @tc.name data share update_callback test - * @tc.number SUB_DDM_DataShare_JS_update_callback_0122 - * @tc.desc data share update_callback test - */ - it('update_callback_0122', 0, async function (done) { - console.log(TAG + ":update_callback_0122 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": u8, - } - let da = new dataAbility.DataAbilityPredicates() - helper.update( - null, - va, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(false).assertTrue(); - } catch (err) { - expect(true).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":update_callback_0122 end"); - }) - - /** - * @tc.name data share update_callback test - * @tc.number SUB_DDM_DataShare_JS_update_callback_0123 - * @tc.desc data share update_callback test - */ - it('update_callback_0123', 0, async function (done) { - console.log(TAG + ":update_callback_0123 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.update( - URI, - null, - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":update_callback_0123 end"); - }) - - /** - * @tc.name data share query_callback test - * @tc.number SUB_DDM_DataShare_JS_query_callback_0130 - * @tc.desc data share query_callback test - */ - it('query_callback_0130', 0, async function (done) { - console.log(TAG + ":query_callback_0130 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.query( - URI, - ["*"], - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":query_callback_0130 end"); - }) - - /** - * @tc.name data share query_promise test - * @tc.number SUB_DDM_DataShare_JS_query_promise_0131 - * @tc.desc data share query_promise test - */ - it('query_promise_0131', 0, async function (done) { - console.log(TAG + ":query_promise_0131 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.query( - URI, - ["*"], - da - ).then((data) => { - console.info("==========================>queryCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":query_promise_0131 end"); - }) - - /** - * @tc.name data share query_callback test - * @tc.number SUB_DDM_DataShare_JS_query_callback_0132 - * @tc.desc data share query_callback test - */ - it('query_callback_0132', 0, async function (done) { - console.log(TAG + ":query_callback_0132 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.query( - null, - ["*"], - da, - (err, data) => { - console.info("==========================>Called=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":query_callback_0130 end"); - }) - - /** - * @tc.name data share query_promise test - * @tc.number SUB_DDM_DataShare_JS_query_promise_0133 - * @tc.desc data share query_promise test - */ - it('query_promise_0133', 0, async function (done) { - console.log(TAG + ":query_promise_0133 start"); - try { - let helper = dataShare.createDataShareHelper(null, dseWant, URI); - console.log(TAG + ":DataShareHelper helper:" + helper); - let da = new dataAbility.DataAbilityPredicates() - helper.query( - URI, - null, - da - ).then((data) => { - console.info("==========================>queryCallback=======================>"); - }); - expect(true).assertTrue(); - } catch (err) { - expect(false).assertTrue(); - console.log(TAG + ":DataShareHelper catch err:" + err); - } - done(); - console.log(TAG + ":query_promise_0133 end"); - }) - - console.log(TAG + "*************Unit Test End*************"); -}) diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json b/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json deleted file mode 100644 index c5d82560491..00000000000 --- a/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "visible": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "MyApplication", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } -} diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn deleted file mode 100644 index b6f58ee3e56..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//ark/ts2abc/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") - -ts2abc_gen_abc("gen_datashare_ext_ability_abc") { - src_js = rebase_path("datashare_ext_ability.js") - dst_file = rebase_path(target_out_dir + "/datashare_ext_ability.abc") - in_puts = [ "datashare_ext_ability.js" ] - out_puts = [ target_out_dir + "/datashare_ext_ability.abc" ] - extra_args = [ "--module" ] -} - -gen_js_obj("datashare_ext_ability_js") { - input = "datashare_ext_ability.js" - output = target_out_dir + "/datashare_ext_ability.o" -} - -gen_js_obj("datashare_ext_ability_abc") { - input = get_label_info(":gen_datashare_ext_ability_abc", "target_out_dir") + - "/datashare_ext_ability.abc" - output = target_out_dir + "/datashare_ext_ability_abc.o" - dep = ":gen_datashare_ext_ability_abc" -} - -ohos_shared_library("datashareextensionability_napi") { - sources = [ "datashare_ext_ability_module.cpp" ] - - deps = [ - ":datashare_ext_ability_abc", - ":datashare_ext_ability_js", - ] - - external_deps = [ "napi:ace_napi" ] - - relative_install_dir = "module/application" - subsystem_name = "aafwk" - part_name = "ability_runtime" -} diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js deleted file mode 100644 index 3ab00cd1480..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class DataShareExtensionAbility { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - - getFileTypes(uri, mimeTypeFilter) { - console.log('getFileTypes, uri:' + uri); - } - - openFile(uri, mode) { - console.log('openFile, uri:' + uri); - } - - openRawFile(uri, mode) { - console.log('openRawFile, uri:' + uri); - } - - insert(uri, value) { - console.log('insert, uri:' + uri); - } - - update(uri, value, predicates) { - console.log('update, uri:' + uri); - } - - delete(uri, predicates) { - console.log('delete, uri:' + uri); - } - - query(uri, columns, predicates) { - console.log('query, uri:' + uri); - } - - getType(uri) { - console.log('getType, uri:' + uri); - } - - batchInsert(uri, values) { - console.log('batchInsert, uri:' + uri); - } - - normalizeUri(uri) { - console.log('normalizeUri, uri:' + uri); - } - - denormalizeUri(uri) { - console.log('denormalizeUri, uri:' + uri); - } -} - -export default DataShareExtensionAbility \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp deleted file mode 100644 index 9e0d46b7a17..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "native_engine/native_engine.h" - -extern const char _binary_datashare_ext_ability_js_start[]; -extern const char _binary_datashare_ext_ability_js_end[]; -extern const char _binary_datashare_ext_ability_abc_start[]; -extern const char _binary_datashare_ext_ability_abc_end[]; - -extern "C" __attribute__((constructor)) -void NAPI_application_DataShareExtensionAbility_AutoRegister() -{ - auto moduleManager = NativeModuleManager::GetInstance(); - NativeModule newModuleInfo = { - .name = "application.DataShareExtensionAbility", - .fileName = "application/libdatashareextensionability_napi.so/DataShareExtensionAbility.js", - }; - - moduleManager->Register(&newModuleInfo); -} - -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbility_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_datashare_ext_ability_js_end - _binary_datashare_ext_ability_js_start; - } -} - -// datashare extension ability JS register -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbility_GetABCCode(const char **buf, int *buflen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_abc_start; - } - if (buflen != nullptr) { - *buflen = _binary_datashare_ext_ability_abc_end - _binary_datashare_ext_ability_abc_start; - } -} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn deleted file mode 100644 index fc18df9c428..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//ark/ts2abc/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") - -ts2abc_gen_abc("gen_datashare_ext_ability_context_abc") { - src_js = rebase_path("datashare_ext_ability_context.js") - dst_file = rebase_path(target_out_dir + "/datashare_ext_ability_context.abc") - in_puts = [ "datashare_ext_ability_context.js" ] - out_puts = [ target_out_dir + "/datashare_ext_ability_context.abc" ] - extra_args = [ "--module" ] -} - -gen_js_obj("datashare_ext_ability_context_js") { - input = "datashare_ext_ability_context.js" - output = target_out_dir + "/datashare_ext_ability_context.o" -} - -gen_js_obj("datashare_ext_ability_context_abc") { - input = - get_label_info(":gen_datashare_ext_ability_context_abc", - "target_out_dir") + "/datashare_ext_ability_context.abc" - output = target_out_dir + "/datashare_ext_ability_context_abc.o" - dep = ":gen_datashare_ext_ability_context_abc" -} - -ohos_shared_library("datashareextensionabilitycontext_napi") { - sources = [ "datashare_ext_ability_context_module.cpp" ] - - deps = [ - ":datashare_ext_ability_context_abc", - ":datashare_ext_ability_context_js", - ] - - external_deps = [ "napi:ace_napi" ] - - relative_install_dir = "module/application" - subsystem_name = "aafwk" - part_name = "ability_runtime" -} diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js deleted file mode 100644 index 68ddf9c897f..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -var ExtensionContext = requireNapi("application.ExtensionContext") - -class DataShareExtensionAbilityContext extends ExtensionContext { - constructor(obj) { - super(obj); - } -} - -export default DataShareExtensionAbilityContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp deleted file mode 100644 index 145456c2d85..00000000000 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "native_engine/native_engine.h" - -extern const char _binary_datashare_ext_ability_context_js_start[]; -extern const char _binary_datashare_ext_ability_context_js_end[]; -extern const char _binary_datashare_ext_ability_context_abc_start[]; -extern const char _binary_datashare_ext_ability_context_abc_end[]; - -extern "C" __attribute__((constructor)) -void NAPI_application_DataShareExtensionAbilityContext_AutoRegister() -{ - auto moduleManager = NativeModuleManager::GetInstance(); - NativeModule newModuleInfo = { - .name = "application.DataShareExtensionAbilityContext", - .fileName = "application/libdatashareextensionabilitycontext_napi.so/DataShareExtensionAbilityContext.js", - }; - - moduleManager->Register(&newModuleInfo); -} - -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbilityContext_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_context_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_datashare_ext_ability_context_js_end - _binary_datashare_ext_ability_context_js_start; - } -} - -// datashare extension ability context JS register -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbilityContext_GetABCCode(const char **buf, int *buflen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_context_abc_start; - } - if (buflen != nullptr) { - *buflen = _binary_datashare_ext_ability_context_abc_end - _binary_datashare_ext_ability_context_abc_start; - } -} -- Gitee