diff --git a/bundle.json b/bundle.json index de58f375c789c1037f09c35d63552c0f33216007..4beffc32716c48eb24250f05d2bccbcb8fd6e68f 100644 --- a/bundle.json +++ b/bundle.json @@ -90,6 +90,7 @@ "init", "eventhandler", "c_utils", + "runtime_core", "i18n", "device_manager", "kv_store", @@ -120,7 +121,8 @@ "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification", - "//base/notification/distributed_notification_service/frameworks/reminder:reminder_client" + "//base/notification/distributed_notification_service/frameworks/reminder:reminder_client", + "//base/notification/distributed_notification_service/frameworks/ets:ani_packages" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", diff --git a/frameworks/ans/test/unittest/notification_do_not_disturb_profile_test.cpp b/frameworks/ans/test/unittest/notification_do_not_disturb_profile_test.cpp index 0212181c0d7469bdd7b98219e0cc1397ea47dc9b..27a74851633faf3d25ed11a050dfbb9ae6a856bd 100644 --- a/frameworks/ans/test/unittest/notification_do_not_disturb_profile_test.cpp +++ b/frameworks/ans/test/unittest/notification_do_not_disturb_profile_test.cpp @@ -109,28 +109,6 @@ HWTEST_F(NotificationDoNotDisturbProfileTest, Marshalling_0100, TestSize.Level1) EXPECT_EQ(res, true); } -/** - * @tc.name: ReadFromParcel_0100 - * @tc.desc: test it when trustlist_ emplace success. - * @tc.type: FUNC - */ -HWTEST_F(NotificationDoNotDisturbProfileTest, ReadFromParcel_0100, TestSize.Level1) -{ - int32_t id = 1; - std::string name = "name"; - std::vector trustlist; - NotificationBundleOption bundleOption; - trustlist.emplace_back(bundleOption); - auto rrc = std::make_shared(id, name, trustlist); - - Parcel parcel; - parcel.WriteUint32(10); - auto res = rrc->ReadFromParcel(parcel); - sptr notification = new (std::nothrow) NotificationBundleOption(); - parcel.WriteParcelable(notification); - EXPECT_EQ(res, true); -} - /** * @tc.name: ReadFromParcel_0200 * @tc.desc: test it when trustlist_ emplace success. diff --git a/frameworks/ans/test/unittest/notification_test.cpp b/frameworks/ans/test/unittest/notification_test.cpp index 17937fcd66451b3dea1a008f19bbde6117a6f254..7346ad2392d2a7a5f568e55f9b9235d5e0bce224 100644 --- a/frameworks/ans/test/unittest/notification_test.cpp +++ b/frameworks/ans/test/unittest/notification_test.cpp @@ -323,8 +323,7 @@ HWTEST_F(NotificationTest, Dump_00001, Function | SmallTest | Level1) "notificationBundleOption = null, agentBundle = null, creatorUserId = -1, ownerUserId = -1, " "receiverUserId = -1, updateDeadLine = 0, finishDeadLine = 0, sound = , distributed = 0: " "flag: 0, unifiedGroupInfo_ = null }, postTime = 0, " - "sound = nullptr, vibrationStyle = [], updateTimer = 0, finishTimer = 0, archiveTimer = 0, " - "isPrivileged = false }"; + "sound = nullptr, vibrationStyle = [], updateTimer = 0, finishTimer = 0, archiveTimer = 0 }"; EXPECT_EQ(rrc->Dump(), ret); } diff --git a/frameworks/ets/BUILD.gn b/frameworks/ets/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..37059d00d2882cd157c9a6243d06de83d16e36d5 --- /dev/null +++ b/frameworks/ets/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2025 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("//base/notification/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +group("ani_packages") { + deps = [ + "./ets:ets_files", + "./ani:notification_manager_ani", + "./ani:notification_subscribe_ani", + ] +} \ No newline at end of file diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..46336e3a10f08cac02050894918af79048deadd1 --- /dev/null +++ b/frameworks/ets/ani/BUILD.gn @@ -0,0 +1,192 @@ +# Copyright (c) 2025 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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//base/notification/distributed_notification_service/notification.gni") + +ohos_shared_library("notification_manager_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + + include_dirs = [ + "./include", + "./include/manager", + "${core_path}/common/include", + "${inner_api_path}", + "${frameworks_path}/cj/ffi/include", + ] + + sources = [ + "./src/sts_common.cpp", + "./src/sts_convert_other.cpp", + "./src/sts_bundle_option.cpp", + "./src/sts_notification_flag.cpp", + "./src/sts_user_input.cpp", + "./src/sts_action_button.cpp", + "./src/sts_notification_manager.cpp", + "./src/sts_slot.cpp", + "./src/sts_disturb_mode.cpp", + "./src/sts_notification_content.cpp", + "./src/sts_template.cpp", + "./src/sts_request.cpp", + "./src/sts_subscribe.cpp", + "./src/sts_subscriber.cpp", + "./src/sts_sorting_map.cpp", + "./src/sts_subscribe_info.cpp", + "./src/sts_sorting.cpp", + "./src/manager/ani_local_live_view.cpp", + "./src/manager/ani_publish.cpp", + "./src/manager/ani_display_badge.cpp", + "./src/manager/ani_slot.cpp", + "./src/manager/ani_cance.cpp", + "./src/manager/ani_notification_enable.cpp", + "./src/manager/ani_do_not_disturb_profile.cpp", + "./src/manager/ani_do_not_disturb_date.cpp", + "./src/manager/ani_get_active.cpp", + "./src/manager/ani_manager.cpp", + "./src/manager/ani_request_enable.cpp", + "./src/manager/ani_ans_dialog_callback.cpp", + "./src/manager/ani_on.cpp", + "./src/manager/ani_push_callback.cpp", + "./src/manager/ani_support_template.cpp", + "./src/manager/ani_distributed_enable.cpp", + "./src/manager/ani_remove_group.cpp", + "./src/manager/ani_open_settings.cpp", + "./src/manager/ani_sync_config.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_path}/cj/ffi:cj_notification_manager_ffi", + ] + + defines = [] + + if (distributed_notification_service_feature_local_liveview) { + defines += [ "ANS_FEATURE_LIVEVIEW_LOCAL_LIVEVIEW" ] + } + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "runtime_core:ani", + "ipc:ipc_core", + "ability_base:zuri", + "ability_runtime:ani_common", + "ability_runtime:ani_wantagent_common", + "ability_runtime:wantagent_innerkits", + "ability_runtime:runtime", + "napi:ace_napi", + "image_framework:image_native", + "image_framework:image_ani", + "resource_management:global_resmgr", + "ability_runtime:ani_base_context", + "ability_runtime:ability_context_native", + "ability_runtime:abilitykit_native", + "ability_runtime:app_context", + "ace_engine:ace_uicontent", + "access_token:libtokenid_sdk", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_shared_library("notification_subscribe_ani") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + + include_dirs = [ + "./include", + "./include/subscribe", + "${core_path}/common/include", + "${inner_api_path}", + "${frameworks_path}/cj/ffi/include", + ] + + configs = [ + "${frameworks_module_ans_path}:ans_innerkits_public_config", + ] + + sources = [ + "./src/sts_common.cpp", + "./src/sts_convert_other.cpp", + "./src/sts_bundle_option.cpp", + "./src/sts_notification_flag.cpp", + "./src/sts_user_input.cpp", + "./src/sts_action_button.cpp", + "./src/sts_notification_manager.cpp", + "./src/sts_slot.cpp", + "./src/sts_disturb_mode.cpp", + "./src/sts_notification_content.cpp", + "./src/sts_template.cpp", + "./src/sts_request.cpp", + "./src/sts_sorting.cpp", + "./src/sts_subscribe.cpp", + "./src/sts_subscriber.cpp", + "./src/sts_sorting_map.cpp", + "./src/sts_subscribe_info.cpp", + "./src/subscribe/ani_remove.cpp", + "./src/subscribe/ani_subscribe.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_path}/cj/ffi:cj_notification_manager_ffi", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "runtime_core:ani", + "ipc:ipc_core", + "ability_base:zuri", + "ability_base:want", + "image_framework:image", + "ability_runtime:wantagent_innerkits", + "ability_runtime:ani_common", + "ability_runtime:runtime", + "napi:ace_napi", + "ability_runtime:ani_common", + "ability_runtime:ani_wantagent_common", + "image_framework:image_native", + "image_framework:image_ani", + "resource_management:global_resmgr", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h b/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h new file mode 100755 index 0000000000000000000000000000000000000000..9559747e895ee020853bb0ca509c8f48f0e19ccc --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_ANS_DIALOG_CALLBACK_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_ANS_DIALOG_CALLBACK_H +#include +#include "ani.h" +#include "ani_base_context.h" +#include "ans_dialog_host_client.h" +#include "ability.h" +#include "ability_context.h" +#include "ui_content.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace Notification; + +struct EnableNotificationInfo { + int32_t errorCode = ANI_OK; + std::string bundleName {""}; + bool stageMode = false; + ani_resolver resolver {}; + std::shared_ptr context = nullptr; + sptr callerToken = nullptr; +}; + +using StsAnsDialogCallbackComplete = void(ani_env *env, std::shared_ptr info); +class StsAnsDialogCallback final : public AnsDialogCallbackNativeInterface { +public: + StsAnsDialogCallback() = default; + ~StsAnsDialogCallback() override = default; + DISALLOW_COPY_AND_MOVE(StsAnsDialogCallback); + + bool Init(ani_env *env, + std::shared_ptr info, + StsAnsDialogCallbackComplete *complete); + void ProcessDialogStatusChanged(const DialogStatusData& data) override; + +private: + ani_vm *vm_ = nullptr; + std::shared_ptr info_ = nullptr; + StsAnsDialogCallbackComplete *complete_ = nullptr; + static int32_t GetErrCodeFromStatus(EnabledDialogStatus status); +}; + +class ModalExtensionCallback { +public: + ModalExtensionCallback(); + ~ModalExtensionCallback(); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string &message); + void OnRemoteReady(const std::shared_ptr &uiProxy); + void OnDestroy(); + void SetSessionId(int32_t sessionId); + void SetBundleName(std::string bundleName); + void SetAbilityContext(std::shared_ptr abilityContext); + void ReleaseOrErrorHandle(int32_t code); + +private: + int32_t sessionId_ = 0; + std::string bundleName_; + std::shared_ptr abilityContext_; +}; + +} +} + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_ANS_DIALOG_CALLBACK_H \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_cance.h b/frameworks/ets/ani/include/manager/ani_cance.h new file mode 100644 index 0000000000000000000000000000000000000000..485c27fa7feb912326e53cc5559ef0106537b73b --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_cance.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_CANCEL_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_CANCEL_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniCancelAll(ani_env* env); +void AniCancelWithId(ani_env* env, ani_double id); +void AniCancelWithIdLabel(ani_env* env, ani_double id, ani_string label); +void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_double id); +void AniCancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string label); +void AniCancelAsBundle(ani_env *env, ani_double id, ani_string representativeBundle, ani_double userId); +void AniCancelAsBundleWithBundleOption(ani_env *env, ani_object representativeBundle, ani_double id); +void AniCancelGroup(ani_env *env, ani_string groupName); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_display_badge.h b/frameworks/ets/ani/include/manager/ani_display_badge.h new file mode 100644 index 0000000000000000000000000000000000000000..a292920bfbab2b1d55cc648bd023ac3086857c21 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_display_badge.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DISPLAY_BADGE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DISPLAY_BADGE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniDisplayBadge(ani_env *env, ani_object obj, ani_boolean enable); +ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj); +void AniSetBadgeNumber(ani_env *env, ani_double badgeNumber); +void AniSetBadgeNumberByBundle(ani_env *env, ani_object obj, ani_double badgeNumber); +} +} +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_distributed_enable.h b/frameworks/ets/ani/include/manager/ani_distributed_enable.h new file mode 100755 index 0000000000000000000000000000000000000000..385c801ac758916f36e3efe9d5347a8e50ee52cb --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_distributed_enable.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DISTRIBUTED_ENBLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DISTRIBUTED_ENBLE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +const int32_t DISTURB_DEFAULT_FLAG = 13; + +ani_boolean AniIsDistributedEnabled(ani_env* env); +ani_boolean AniIsDistributedEnabledByBundle(ani_env* env, ani_object obj); +ani_boolean AniIsDistributedEnabledByBundleType(ani_env* env, ani_object obj, ani_string deviceType); +void AniSetDistributedEnable(ani_env* env, ani_boolean enabled); +void AniSetDistributedEnableByBundle(ani_env *env, ani_object obj, ani_boolean enable); +void AniSetDistributedEnableByBundleAndType(ani_env *env, ani_object obj, ani_string deviceType, ani_boolean enable); +void AniSetTargetDeviceStatus(ani_env* env, ani_string deviceType, ani_double status); +ani_boolean AniIsSmartReminderEnabled(ani_env *env, ani_string deviceType); +void AniSetSmartReminderEnable(ani_env *env, ani_string deviceType, ani_boolean enable); +void AniSetDistributedEnableBySlot(ani_env *env, ani_enum_item slot, ani_string deviceType, ani_boolean enable); +ani_boolean AniIsDistributedEnabledBySlot(ani_env *env, ani_enum_item slot, ani_string deviceType); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_do_not_disturb_date.h b/frameworks/ets/ani/include/manager/ani_do_not_disturb_date.h new file mode 100644 index 0000000000000000000000000000000000000000..721ba1d523602e14576322ac06efb5e16de73520 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_do_not_disturb_date.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DO_NOT_DISTURB_DATA_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DO_NOT_DISTURB_DATA_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniSetDoNotDisturbDate(ani_env *env, ani_object date); +void AniSetDoNotDisturbDateWithId(ani_env *env, ani_object date, ani_double userId); +ani_object AniGetDoNotDisturbDate(ani_env *env); +ani_object AniGetDoNotDisturbDateWithId(ani_env *env, ani_double userId); +ani_boolean AniIsSupportDoNotDisturbMode(ani_env *env); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h b/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..c5e9b03c1852126ee277b0bdc2b61a4a76e8d0cf --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DO_NOT_DISTURB_PROFILE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DO_NOT_DISTURB_PROFILE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniAddDoNotDisturbProfile(ani_env *env, ani_object obj); +void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj); +ani_object AniGetDoNotDisturbProfile(ani_env *env, ani_double id); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_get_active.h b/frameworks/ets/ani/include/manager/ani_get_active.h new file mode 100644 index 0000000000000000000000000000000000000000..3d8861090ad05acd61b3b09e194dbd8df996b339 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_get_active.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_GET_ACTIVE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_GET_ACTIVE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_double AniGetActiveNotificationCount(ani_env *env); +ani_object AniGetAllActiveNotifications(ani_env *env); +ani_object AniGetActiveNotifications(ani_env *env); +ani_object AniGetActiveNotificationByFilter(ani_env *env, ani_object obj); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_local_live_view.h b/frameworks/ets/ani/include/manager/ani_local_live_view.h new file mode 100644 index 0000000000000000000000000000000000000000..35cb1275ec5fae32c20cfca0867134494f8fb2dc --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_local_live_view.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_LOCAL_LIVE_VIEW_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_LOCAL_LIVE_VIEW_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniTriggerSystemLiveView( + ani_env *env, ani_object bundleOptionObj, ani_double notificationId, ani_object buttonOptionsObj); +void AniSubscribeSystemLiveView(ani_env *env, ani_object subscriberObj); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_manager.h b/frameworks/ets/ani/include/manager/ani_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..fd52141fa1307b5cf833f3e24fa717172aa4248c --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_manager.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_MANAGER_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniNotificationManagerRegistryInit(ani_env *env); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_notification_enable.h b/frameworks/ets/ani/include/manager/ani_notification_enable.h new file mode 100644 index 0000000000000000000000000000000000000000..bb657a6e239da1362e1b72077b12874c8211205e --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_ENABLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_ENABLE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_boolean AniIsNotificationEnabled(ani_env *env); +ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_double userId); +ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bundleOption); +void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean enable); +void AniSetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId, ani_boolean enabled); +ani_boolean AniIsNotificationEnabledSync(ani_env *env); +ani_boolean AniGetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId); +ani_object AniGetAllNotificationEnabledBundles(ani_env *env); +void AniDisableNotificationFeature(ani_env *env, ani_boolean disabled, ani_object bundleList); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_on.h b/frameworks/ets/ani/include/manager/ani_on.h new file mode 100755 index 0000000000000000000000000000000000000000..911d45fd82d0d120adcc18f871814d1929e35041 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_on.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_ON_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_ON_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_int AniOn(ani_env *env, ani_string type, ani_fn_object fn, ani_object checkRequestObj); +ani_int AniOff(ani_env *env, ani_string type, ani_fn_object fn); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_open_settings.h b/frameworks/ets/ani/include/manager/ani_open_settings.h new file mode 100644 index 0000000000000000000000000000000000000000..1617ec391c70a5acd47828ecc4e62b7b3e9c2041 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_open_settings.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_OPEN_SETTINGS_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_OPEN_SETTINGS_H + +#include "ani.h" +#include "ani_base_context.h" +#include "ans_dialog_host_client.h" +#include "ability.h" +#include "ability_context.h" +#include "ui_content.h" + +namespace OHOS { +namespace NotificationManagerSts { +class SettingsModalExtensionCallback; +struct OpenSettingsInfo { + int32_t errorCode = ANI_OK; + std::shared_ptr context = nullptr; + ani_resolver resolver {}; +}; + +ani_object AniOpenNotificationSettings(ani_env *env, ani_object content); +bool GetOpenSettingsInfo(ani_env *env, ani_object content, std::shared_ptr &info); +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName, + ani_env *env, std::shared_ptr &info); +void StsAsyncCompleteCallbackOpenSettings(ani_env *env, std::shared_ptr info); + +using StsSettingsModalExtensionCallbackComplete = void(ani_env *env, std::shared_ptr info); +void ProcessStatusChanged(int32_t code); +bool CreateUiExtCallback(ani_env *env, std::shared_ptr& uiExtCallback, + Ace::ModalUIExtensionCallbacks& uiExtensionCallbacks, std::shared_ptr &info, + std::shared_ptr& abilityContext, std::string &bundleName); +class SettingsModalExtensionCallback { +public: + SettingsModalExtensionCallback(); + ~SettingsModalExtensionCallback(); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string &message); + void OnRemoteReady(const std::shared_ptr &uiProxy); + void OnDestroy(); + void SetSessionId(int32_t sessionId); + void SetBundleName(std::string bundleName); + void SetAbilityContext(std::shared_ptr abilityContext); + void ReleaseOrErrorHandle(int32_t code); + bool Init(ani_env *env, std::shared_ptr info, + StsSettingsModalExtensionCallbackComplete *complete); + void ProcessStatusChanged(int32_t code, bool isAsync); +private: + int32_t sessionId_ = 0; + std::string bundleName_; + std::shared_ptr abilityContext_; + ani_vm *vm_ = nullptr; + std::shared_ptr info_ = nullptr; + StsSettingsModalExtensionCallbackComplete *complete_ = nullptr; +}; +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_publish.h b/frameworks/ets/ani/include/manager/ani_publish.h new file mode 100644 index 0000000000000000000000000000000000000000..33a018c6aa3a14c25c66f3f91786a508b0cb2626 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_publish.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_PUBLISH_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_PUBLISH_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniPublish(ani_env *env, ani_object obj); +void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId); +void AniPublishAsBundle(ani_env *env, ani_object request, ani_string representativeBundle, ani_double userId); +void AniPublishAsBundleWithBundleOption(ani_env *env, ani_object representativeBundle, ani_object request); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_push_callback.h b/frameworks/ets/ani/include/manager/ani_push_callback.h new file mode 100755 index 0000000000000000000000000000000000000000..fcaf53782ec62ab0afa68cd848be72d9d31d95a2 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_push_callback.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_PUSH_CALLBACK_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_PUSH_CALLBACK_H +#include +#include +#include "ani.h" +#include "push_callback_stub.h" +#include "notification_constant.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; +class StsPushCallBack : public PushCallBackStub { +public: + struct ResultParam { + int32_t code = -1; + std::string msg = ""; + }; + + StsPushCallBack(ani_env *env); + virtual ~StsPushCallBack(); + int32_t OnCheckNotification( + const std::string ¬ificationData, const std::shared_ptr &pushCallBackParam) override; + void SetJsPushCallBackObject(ani_env *env, NotificationConstant::SlotType slotType, ani_ref pushCallBackObject); + void HandleCheckCallback( + ani_env *env, ani_fn_object fn, ani_object value, const std::shared_ptr &pushCallBackParam); + +private: + int32_t CheckNotification( + ani_env *env, + const std::string ¬ificationData, + const std::shared_ptr &pushCallBackParam); + static bool WarpFunctionResult(ani_env *env, ani_object funcResult, ResultParam &result); + ani_vm *vm_ = nullptr; + std::map pushCallBackObjects_; + std::mutex mutexlock; +}; + +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_remove_group.h b/frameworks/ets/ani/include/manager/ani_remove_group.h new file mode 100644 index 0000000000000000000000000000000000000000..1ec3dbe0865779d0a7958cecdb4adf0b5537e340 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_remove_group.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REMOVE_GROUP_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REMOVE_GROUP_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniRemoveGroupByBundle(ani_env *env, ani_object bundleOption, ani_string groupName); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_request_enable.h b/frameworks/ets/ani/include/manager/ani_request_enable.h new file mode 100755 index 0000000000000000000000000000000000000000..3e4592c6abcca0482001f9552cbb829ee7eea164 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_request_enable.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REQUEST_ENABLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REQUEST_ENABLE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_object AniRequestEnableNotification(ani_env *env, ani_object content); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h new file mode 100644 index 0000000000000000000000000000000000000000..eecf03272219636acbc2e1099e75a32c8ca50c57 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SLOT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SLOT_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj); +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj, ani_double slotFlags); + +ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption); +ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type); +void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable); +void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, + ani_boolean enable, ani_boolean isForceControl); +void AniAddSlotByNotificationSlot(ani_env *env, ani_object notificationSlotObj); +void AniAddSlotBySlotType(ani_env *env, ani_enum_item enumObj); +void AniAddSlots(ani_env *env, ani_object notificationSlotArrayObj); +ani_object AniGetSlot(ani_env *env, ani_enum_item enumObj); +ani_object AniGetSlots(ani_env *env); +void AniRemoveSlot(ani_env *env, ani_enum_item enumObj); +void AniRemoveAllSlots(ani_env *env); +void AniSetSlotByBundle(ani_env *env, ani_object bundleOptionObj, ani_object slotObj); +ani_double AniGetSlotNumByBundle(ani_env *env, ani_object bundleOption); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + diff --git a/frameworks/ets/ani/include/manager/ani_support_template.h b/frameworks/ets/ani/include/manager/ani_support_template.h new file mode 100755 index 0000000000000000000000000000000000000000..5be565d995c1793687386b5ce4ef383727abae38 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_support_template.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SUPPORT_TEMPLATE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SUPPORT_TEMPLATE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_boolean AniIsSupportTemplate(ani_env* env, ani_string templateName); +ani_object AniGetDeviceRemindType(ani_env *env); + +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/manager/ani_sync_config.h b/frameworks/ets/ani/include/manager/ani_sync_config.h new file mode 100644 index 0000000000000000000000000000000000000000..a337aed87ef81cedbccd6be725c5f3eeae8991b4 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_sync_config.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SYNC_CONFIG_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_SYNC_CONFIG_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_double AniSetAdditionalConfig(ani_env *env, ani_string key, ani_string value); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_action_button.h b/frameworks/ets/ani/include/sts_action_button.h new file mode 100644 index 0000000000000000000000000000000000000000..3a690d2d62e16b87c207cdb1f12015e1d68914a9 --- /dev/null +++ b/frameworks/ets/ani/include/sts_action_button.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_ACTION_BUTTON_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_ACTION_BUTTON_H +#include "ani.h" +#include "pixel_map.h" +#include "want_params.h" +#include "want_agent.h" +#include "notification_constant.h" +#include "notification_user_input.h" +#include "notification_action_button.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using SemanticActionButton = OHOS::Notification::NotificationConstant::SemanticActionButton; +using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; +using NotificationUserInput = OHOS::Notification::NotificationUserInput; +using NotificationActionButton = OHOS::Notification::NotificationActionButton; + +struct StsActionButton { + std::shared_ptr icon; + std::string title; + std::shared_ptr wantAgent; + std::shared_ptr extras = {}; + SemanticActionButton semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + bool autoCreatedReplies = true; + std::vector> mimeTypeOnlyInputs = {}; + std::shared_ptr userInput = {}; + bool isContextual = false; +}; + +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, + StsActionButton &actionButton); +ani_object WrapNotificationActionButton(ani_env* env, + const std::shared_ptr &actionButton); + +ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, + const char *name, std::vector> &res); +ani_object GetAniArrayNotificationActionButton(ani_env* env, + const std::vector> &actionButtons); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_bundle_option.h b/frameworks/ets/ani/include/sts_bundle_option.h new file mode 100644 index 0000000000000000000000000000000000000000..5bda338dd90f47bcb45d2a2706874f5f4d980bbf --- /dev/null +++ b/frameworks/ets/ani/include/sts_bundle_option.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_BUNDLE_OPTION_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_BUNDLE_OPTION_H +#include "ani.h" +#include "notification_bundle_option.h" + +using BundleOption = OHOS::Notification::NotificationBundleOption; +namespace OHOS { +namespace NotificationSts { +bool UnwrapBundleOption(ani_env *env, ani_object param, BundleOption& option); +bool WrapBundleOption(ani_env* env, + const std::shared_ptr &bundleOption, ani_object &bundleObject); + +bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector& options); +ani_object GetAniArrayBundleOption(ani_env* env, const std::vector &bundleOptions); +} +} + +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h new file mode 100644 index 0000000000000000000000000000000000000000..8bfe1dac6b764c903707eecd6a959dcac813a7ce --- /dev/null +++ b/frameworks/ets/ani/include/sts_common.h @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_COMMON_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_COMMON_H + +#include "ani.h" +#include +#include +#include +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace NotificationSts { +bool IsUndefine(ani_env *env, const ani_object &obj); +ani_object CreateBoolean(ani_env *env, bool value); +ani_object CreateDouble(ani_env *env, ani_double value); +ani_object CreateInt(ani_env *env, int32_t value); +bool CreateDate(ani_env *env, int64_t time, ani_object &outObj); +ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string &aniStr); +ani_status GetStringByAniString(ani_env *env, ani_string str, std::string &res); +bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector &stdVString); +ani_object GetAniStringArrayByVectorString(ani_env *env, std::vector &strs); +ani_object newArrayClass(ani_env *env, int length); +ani_object newRecordClass(ani_env *env); +ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values); + +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, std::string &outStr); +ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, + ani_boolean isUndefined, bool outvalue); +ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, ani_double &outvalue); +ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, ani_ref &outRef); +ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res); +ani_status GetPropertyNumberArray(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res); + +bool SetFieldString(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, const std::string value); +bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, bool value); +bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, double value); +bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const std::vector &values); + +// property +bool SetPropertyOptionalByBoolean(ani_env *env, ani_object object, const char *name, bool value); +bool SetPropertyOptionalByDouble(ani_env *env, ani_object object, const char *name, double value); +bool SetPropertyOptionalByString(ani_env *env, ani_object object, const char *name, const std::string value); +bool SetPropertyOptionalByInt(ani_env *env, ani_object object, const char *name, int32_t value); +bool SetPropertyByRef(ani_env *env, ani_object object, const char *name, ani_ref value); + +bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj); + +inline bool AniBooleanToBool(ani_boolean value) +{ + return value == ANI_TRUE; +} + +inline ani_boolean BoolToAniBoolean(bool value) +{ + return value ? ANI_TRUE : ANI_FALSE; +} + +template +static bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) +{ + if (env == nullptr || cls == nullptr || object == nullptr) { + return false; + } + std::string setterName(""); + setterName.append(propertyName); + ani_method setter; + ani_status status = env->Class_FindMethod(cls, setterName.c_str(), nullptr, &setter); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod %{public}s failed %{public}d", propertyName, status); + return false; + } + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v) { + status = env->Object_CallMethod_Void(object, setter, static_cast(value)); + } else { + status = env->Object_CallMethod_Void(object, setter, value); + } + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethod_Void %{public}s failed %{public}d", propertyName, status); + return false; + } + return true; +} + +[[maybe_unused]]static bool CallSetterNull(ani_env* env, ani_class cls, ani_object object, const char* propertyName) +{ + ani_ref nullRef = nullptr; + ani_status status = env->GetNull(&nullRef); + if (status != ANI_OK) { + ANS_LOGE("GetNull %{public}s failed %{public}d", propertyName, status); + return false; + } + return CallSetter(env, cls, object, propertyName, nullRef); +} + +template +static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &result) +{ + ani_status status = ANI_ERROR; + if constexpr (std::is_enum::value || std::is_integral::value) { + ani_int intValue{}; + status = env->EnumItem_GetValue_Int(enumItem, &intValue); + if (ANI_OK != status) { + ANS_LOGD("EnumConvert_StsToNative failed, status : %{public}d", status); + return false; + } + result = static_cast(intValue); + return true; + } else if constexpr (std::is_same::value) { + ani_string strValue{}; + status = env->EnumItem_GetValue_String(enumItem, &strValue); + if (ANI_OK != status) { + ANS_LOGD("EnumItem_GetValue_String failed, status : %{public}d", status); + return false; + } + status = GetStdString(env, strValue, result); + if (ANI_OK != status) { + ANS_LOGD("EnumConvertAniToNative GetStdString failed, status : %{public}d", status); + return false; + } + } else { + ANS_LOGD("Enum convert failed: type not supported"); + return false; + } +} + +template +void deletePoint(T &result) +{ + delete result; + result = nullptr; +} + +template +void deleteVectorWithPoints(std::vector &results) +{ + for (auto result : results) { + deletePoint(result); + } + results.clear(); +} + +template +void deleteVectorWithSpPoints(std::vector> &results) +{ + for (auto result : results) { + result = nullptr; + } + results.clear(); +} + +template +void deleteVectorWithArraySpPoints(std::map>> &results) +{ + for (auto it = results.begin(); it != results.end(); ++it) { + auto vt = static_cast>>(it -> second); + for (auto pt : vt) { + pt = nullptr; + } + vt.clear(); + } + results.clear(); +} + +template +static bool EnumConvertAniToNative(ani_env *env, ani_object enumItem, T &result) +{ + return EnumConvertAniToNative(env, static_cast(enumItem), result); +} + +template +static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T enumValue, ani_enum_item &result) +{ + ani_enum aniEnum{}; + ani_status status = env->FindEnum(enumName, &aniEnum); + if (ANI_OK != status) { + ANS_LOGD("Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); + return false; + } + constexpr int32_t loopMaxNum = 1000; + for (int32_t index = 0U; index < loopMaxNum; index++) { + ani_enum_item enumItem{}; + status = env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem); + if (ANI_OK != status) { + ANS_LOGD( + "Enum_GetEnumItemByIndex failed: enumName:%{public}s index:%{public}d, status:%{public}d", + enumName, index, status); + return false; + } + // compare value + T tmpValue{}; + if (EnumConvertAniToNative(env, enumItem, tmpValue) && tmpValue == enumValue) { + result = enumItem; + return true; + } + } + ANS_LOGD("EnumConvert_NativeToSts failed enumName: %{public}s", enumName); + return false; +} + +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_convert_other.h b/frameworks/ets/ani/include/sts_convert_other.h new file mode 100644 index 0000000000000000000000000000000000000000..2c32dcb836ecd38d95d7353d4fc5b1749ac6042d --- /dev/null +++ b/frameworks/ets/ani/include/sts_convert_other.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONVERT_OTHER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONVERT_OTHER_H +#include "ani.h" +#include "resource_manager.h" +#include "pixel_map.h" +#include "want_agent.h" +#include "ani_common_want_agent.h" + +using ResourceManager = OHOS::Global::Resource::ResourceManager; +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::Media; +using namespace OHOS::AbilityRuntime::WantAgent; + +std::shared_ptr UnwrapWantAgent(ani_env *env, ani_object agent); +ani_object WarpWantAgent(ani_env *env, std::shared_ptr wantAgent); +ani_object GetAniWantAgentArray(ani_env *env, std::vector> wantAgents); + +ani_object CreateAniPixelMap(ani_env* env, std::shared_ptr pixelMap); +std::shared_ptr GetPixelMapFromEnvSp(ani_env* env, ani_object obj); +// ani_object to vector +ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector> &pixelMaps); +// ani_object to vector +ani_status GetPixelMapArray(ani_env *env, + ani_object param, const char *name, std::vector> &pixelMaps); +// map ro AniRecord +bool GetAniPictrueInfo(ani_env *env, std::map>> pictureMap, + ani_object &pictureInfoObj); +// AniRecord to map +ani_status GetMapOfPictureInfo(ani_env *env, ani_object obj, + std::map>> pictureMap); +// vector to AniArray +ani_object GetAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps); + +ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource); +ani_status GetResourceArray(ani_env *env, + ani_object param, const char *name, std::vector &res); +ani_object GetAniResource(ani_env *env, const std::shared_ptr &resource); +ani_object GetAniArrayResource(ani_env *env, + const std::vector> &resources); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_disturb_mode.h b/frameworks/ets/ani/include/sts_disturb_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..491450d9fcebf2771a166c2c3b53b103d2ec7615 --- /dev/null +++ b/frameworks/ets/ani/include/sts_disturb_mode.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_DISTURB_MODE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_DISTURB_MODE_H +#include "ani.h" +#include "notification_do_not_disturb_profile.h" + +using NotificationDoNotDisturbProfile = OHOS::Notification::NotificationDoNotDisturbProfile; +namespace OHOS { +namespace NotificationSts { +bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, + sptr &profile); +bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, + std::vector> &profiles); +bool WrapDoNotDisturbProfile(ani_env* env, sptr profile, ani_object& outObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_notification_content.h b/frameworks/ets/ani/include/sts_notification_content.h new file mode 100644 index 0000000000000000000000000000000000000000..cd6051dbca083526a88ea27fff0162ede2a32c2c --- /dev/null +++ b/frameworks/ets/ani/include/sts_notification_content.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONVERT_NOTIFICATION_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONVERT_NOTIFICATION_H +#include "ani.h" + +#include "notification_progress.h" +#include "notification_time.h" +#include "notification_icon_button.h" +#include "notification_local_live_view_button.h" +#include "notification_capsule.h" + +#include "notification_content.h" +#include "notification_basic_content.h" +#include "notification_normal_content.h" +#include "notification_long_text_content.h" +#include "notification_multiline_content.h" +#include "notification_picture_content.h" +#include "notification_live_view_content.h" +#include "notification_local_live_view_content.h" + +using LiveViewStatus = OHOS::Notification::NotificationLiveViewContent::LiveViewStatus; +using LiveViewTypes = OHOS::Notification::NotificationLocalLiveViewContent::LiveViewTypes; +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::Notification; + +enum STSLiveViewStatus { + LIVE_VIEW_CREATE = 0, + LIVE_VIEW_INCREMENTAL_UPDATE = 1, + LIVE_VIEW_END = 2, + LIVE_VIEW_FULL_UPDATE = 3 +}; + +class StsLiveViewStatusUtils { +public: +static bool StsToC(const STSLiveViewStatus inType, LiveViewStatus &outType); +static bool CToSts(const LiveViewStatus inType, STSLiveViewStatus &outType); +}; + +bool LiveViewStatusEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewStatus &liveViewStatus); +bool LiveViewStatusCToEts(ani_env *env, LiveViewStatus liveViewStatus, ani_enum_item &enumItem); + +bool LiveViewTypesEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewTypes &liveViewTypes); +bool LiveViewTypesCToEts(ani_env *env, LiveViewTypes liveViewTypes, ani_enum_item &enumItem); + +void UnWarpNotificationProgress(ani_env *env, ani_object obj, NotificationProgress ¬ificationProgress); +bool WarpNotificationProgress(ani_env *env, const NotificationProgress &progress, ani_object &progressObject); + +void UnWarpNotificationTime(ani_env *env, ani_object obj, NotificationTime ¬ificationTime); +bool WarpNotificationTime(ani_env *env, const NotificationTime &time, bool isInitialTimeExist, ani_object &timeObject); + +ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, + NotificationIconButton &iconButton); +ani_object WarpNotificationIconButton(ani_env *env, const NotificationIconButton &button); +ani_status GetIconButtonArray(ani_env *env, + ani_object param, const char *name, std::vector &res); +ani_object GetAniIconButtonArray(ani_env *env, const std::vector buttons); + +void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, + NotificationLocalLiveViewButton &button); +bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLiveViewButton &button, + ani_object &buttonObject); + +void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule &capsule); +bool WarpNotificationCapsule(ani_env *env, const NotificationCapsule &capsule, ani_object &capsuleObject); + +ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, + std::shared_ptr basicContent); + +ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, + std::shared_ptr &normalContent); +ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, + std::shared_ptr &longTextContent); +ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, + std::shared_ptr &multiLineContent); +ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, + std::shared_ptr &pictureContent); +ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent); +ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent); + +bool SetNotificationContent(ani_env* env, std::shared_ptr ncContent, ani_object &ncObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_notification_flag.h b/frameworks/ets/ani/include/sts_notification_flag.h new file mode 100644 index 0000000000000000000000000000000000000000..33b3e72385ded699a31c117c8bfa347e85bd60ca --- /dev/null +++ b/frameworks/ets/ani/include/sts_notification_flag.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_NOTIFICATION_FLAG_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_NOTIFICATION_FLAG_H +#include "ani.h" +#include "notification_flags.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationFlags = OHOS::Notification::NotificationFlags; +bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, + ani_object &flagsObject); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_notification_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f2d72b257cf02e81b5dfa3b12ab0833c9518ca00 --- /dev/null +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_NOTIFICATION_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_NOTIFICATION_MANAGER_H +#include "ani.h" +#include "notification_constant.h" +#include "notification_content.h" +#include "notification_do_not_disturb_date.h" +#include "notification_slot.h" +#include "notification_button_option.h" +#include "notification_local_live_view_subscriber.h" +#include "sts_runtime.h" +#include "notification_check_info.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationLocalLiveViewSubscriber = OHOS::Notification::NotificationLocalLiveViewSubscriber; +using SlotType = OHOS::Notification::NotificationConstant::SlotType; +using SlotLevel = OHOS::Notification::NotificationSlot::NotificationLevel; +using ContentType = OHOS::Notification::NotificationContent::Type; +using ButtonOption = OHOS::Notification::NotificationButtonOption; +using NotificationDoNotDisturbDate = OHOS::Notification::NotificationDoNotDisturbDate; +using RemindType = OHOS::Notification::NotificationConstant::RemindType; +using NotificationConstant = OHOS::Notification::NotificationConstant; + +enum STSDoNotDisturbType { + TYPE_NONE = 0, + TYPE_ONCE = 1, + TYPE_DAILY = 2, + TYPE_CLEARLY = 3, +}; + +enum STSSlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + LIVE_VIEW = 4, + CUSTOMER_SERVICE = 5, + EMERGENCY_INFORMATION = 10, + OTHER_TYPES = 0xFFFF, +}; + +enum STSSlotLevel { + LEVEL_NONE = 0, + LEVEL_MIN = 1, + LEVEL_LOW = 2, + LEVEL_DEFAULT = 3, + LEVEL_HIGH = 4, +}; + +enum STSContentType { + NOTIFICATION_CONTENT_BASIC_TEXT, + NOTIFICATION_CONTENT_LONG_TEXT, + NOTIFICATION_CONTENT_PICTURE, + NOTIFICATION_CONTENT_CONVERSATION, + NOTIFICATION_CONTENT_MULTILINE, + NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW, + NOTIFICATION_CONTENT_LIVE_VIEW, +}; + +enum class STSRemindType { + IDLE_DONOT_REMIND, + IDLE_REMIND, + ACTIVE_DONOT_REMIND, + ACTIVE_REMIND +}; + +class StsDoNotDisturbTypeUtils { +public: +static bool StsToC(const STSDoNotDisturbType inType, + OHOS::Notification::NotificationConstant::DoNotDisturbType &outType); +}; + +class StsSlotTypeUtils { +public: +static bool StsToC(const STSSlotType inType, SlotType &outType); +static bool CToSts(const SlotType inType, STSSlotType &outType); +}; + +class StsSlotLevelUtils { +public: +static bool StsToC(const STSSlotLevel inType, SlotLevel &outType); +static bool CToSts(const SlotLevel inLevel, STSSlotLevel &outLevel); +}; + +class StsContentTypeUtils { +public: +static bool StsToC(const STSContentType inType, ContentType &outType); +static bool CToSts(const ContentType inType, STSContentType &outType); +}; + +class StsRemindTypeUtils { +public: +static bool StsToC(const STSRemindType inType, RemindType &outType); +static bool CToSts(const RemindType inType, STSRemindType &outType); +}; + +class StsNotificationLocalLiveViewSubscriber : public NotificationLocalLiveViewSubscriber { +public: + StsNotificationLocalLiveViewSubscriber(); + virtual ~StsNotificationLocalLiveViewSubscriber(); + + /** + * @brief Called back when a notification is canceled. + * + */ + virtual void OnConnected() override; + + /** + * @brief Called back when the subscriber is disconnected from the ANS. + * + */ + virtual void OnDisconnected() override; + + virtual void OnResponse(int32_t notificationId, sptr buttonOption) override; + + /** + * @brief Called back when connection to the ANS has died. + * + */ + virtual void OnDied() override; + + /** + * @brief Sets the callback information by type. + * + * @param env Indicates the environment that the API is invoked under. + * @param type Indicates the type of callback. + * @param ref Indicates the napi_ref of callback. + */ + void SetStsNotificationLocalLiveViewSubscriber(ani_env *env, ani_object &localLiveViewSubscriberObj); + + std::unique_ptr &GetStsNotificationLocalLiveViewSubscriber() + { + return stsSubscriber_; + } +private: + ani_env* GetAniEnv(); +private: + ani_vm* vm_ = nullptr; + std::unique_ptr stsSubscriber_ = nullptr; +}; + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType); +bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem); + +bool SlotLevelEtsToC(ani_env *env, ani_enum_item enumItem, SlotLevel &slotLevel); +bool SlotLevelCToEts(ani_env *env, SlotLevel slotLevel, ani_enum_item &enumItem); + +bool ContentTypeEtsToC(ani_env *env, ani_enum_item enumItem, ContentType &contentType); +bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enumItem); + +bool DeviceRemindTypeCToEts(ani_env *env, RemindType remindType, ani_enum_item &enumItem); +bool DeviceRemindTypeEtsToC(ani_env *env, ani_enum_item enumItem, RemindType &remindType); + +ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonOptionObj, + ButtonOption &buttonOption); +ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption); + +bool UnWarpNotificationDoNotDisturbDate(ani_env* env, const ani_object doNotDisturbDateObj, + NotificationDoNotDisturbDate& doNotDisturbDate); +bool WarpNotificationDoNotDisturbDate( + ani_env *env, const std::shared_ptr &date, ani_object &outObj); + +bool WarpNotificationCheckInfo( + ani_env *env, const std::shared_ptr &data, ani_object &outObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_request.h b/frameworks/ets/ani/include/sts_request.h new file mode 100644 index 0000000000000000000000000000000000000000..c35fee773d5eed331e3e3d0efdf19ade94d5345e --- /dev/null +++ b/frameworks/ets/ani/include/sts_request.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_REQUEST_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_REQUEST_H +#include "ani.h" +#include "notification.h" +#include "notification_request.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::Notification; +using NotificationSts = OHOS::Notification::Notification; + +struct StsDistributedOptions { + bool isDistributed = false; + std::vector supportDisplayDevices = {}; + std::vector supportOperateDevices = {}; + int32_t remindType = -1; +}; + +void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions); +bool WarpNotificationUnifiedGroupInfo(ani_env* env, + const std::shared_ptr &groupInfo, ani_object &groupInfoObject); + +ani_status UnWarpNotificationRequest( + ani_env *env, ani_object obj, std::shared_ptr ¬ificationRequest); +bool WarpNotificationRequest( + ani_env *env, const NotificationRequest *notificationRequest, ani_class &cls, ani_object &outAniObj); +ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests); +ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vector> requests); + +bool UnWarpNotificationCheckRequest(ani_env *env, ani_object obj, sptr &checkRequest); +bool UnWarpNotificationFilter(ani_env *env, ani_object obj, LiveViewFilter& filter); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_slot.h b/frameworks/ets/ani/include/sts_slot.h new file mode 100644 index 0000000000000000000000000000000000000000..2c4da3de6ef8f6a2398637633471154a34ceb0b2 --- /dev/null +++ b/frameworks/ets/ani/include/sts_slot.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SLOT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SLOT_H +#include "ani.h" +#include "notification_constant.h" +#include "notification_slot.h" + +namespace OHOS { +namespace NotificationSts { +using SlotType = OHOS::Notification::NotificationConstant::SlotType; +using SlotLevel = OHOS::Notification::NotificationSlot::NotificationLevel; +using NotificationSlot = OHOS::Notification::NotificationSlot; + +constexpr const char* NOTIFICATION_SOLT_CLASSNAME = "Lnotification/notificationSlot/NotificationSlotInner;"; +bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, + const SlotType value); +bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, + const SlotLevel value); +bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj); +bool WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, + ani_object &outAniObj); +bool ParseNotificationSlotByBasicType(ani_env *env, ani_object notificationSlotObj, + NotificationSlot &slot); +bool UnwrapNotificationSlot(ani_env *env, ani_object notificationSlotObj, NotificationSlot &slot); +bool UnwrapNotificationSlotArrayByAniObj(ani_env *env, ani_object notificationSlotArrayObj, + std::vector &slots); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_sorting.h b/frameworks/ets/ani/include/sts_sorting.h new file mode 100644 index 0000000000000000000000000000000000000000..9c77a26002973115d674d46895696e2076573fdb --- /dev/null +++ b/frameworks/ets/ani/include/sts_sorting.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H +#include "ani.h" +#include "notification_sorting.h" + +namespace OHOS { +namespace NotificationSts { +bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting &sorting, ani_object &outObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_sorting_map.h b/frameworks/ets/ani/include/sts_sorting_map.h new file mode 100644 index 0000000000000000000000000000000000000000..f8708c9966ff7c5d8584178b5b83dabca3e1a46c --- /dev/null +++ b/frameworks/ets/ani/include/sts_sorting_map.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_MAP_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_MAP_H +#include "ani.h" +#include "notification_sorting_map.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationSortingMap = OHOS::Notification::NotificationSortingMap; + +bool WarpNotificationSortingMap(ani_env *env, + const std::shared_ptr &sortingMap, ani_object &outObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_subscribe.h b/frameworks/ets/ani/include/sts_subscribe.h new file mode 100644 index 0000000000000000000000000000000000000000..bfa5abf0745482bc9385e45de8cca119aeb04d91 --- /dev/null +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SUBSCRIBE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SUBSCRIBE_H +#include "ani.h" +#include "notification_request.h" +#include "notification_operation_info.h" +#include "ans_operation_callback_stub.h" +#include "notification_subscriber.h" +#include "notification_do_not_disturb_date.h" + +#include "sts_notification_manager.h" +#include "sts_subscriber.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationKey = OHOS::Notification::NotificationKey; +using StsNotificationOperationInfo = OHOS::Notification::NotificationOperationInfo; + +class StsDistributedOperationCallback : public OHOS::Notification::OperationCallbackStub { +public: + explicit StsDistributedOperationCallback(ani_object promise, ani_resolver resolver); + ~StsDistributedOperationCallback() override {}; + void OnOperationCallback(const int32_t operationResult) override; + void OnStsOperationCallback(ani_env *env, const int32_t operationResult); + void SetVm(ani_vm *vm); +private: + ani_vm *etsVm_; + ani_resolver resolver_; + bool isCall_ = false; + std::mutex lock_; +}; + +class StsSubscriberInstance : public OHOS::Notification::NotificationSubscriber { +public: + StsSubscriberInstance(); + virtual ~StsSubscriberInstance(); + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int32_t deleteReason) override; + + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override; + + virtual void OnUpdate(const std::shared_ptr &sortingMap) override; + + virtual void OnConnected() override; + + virtual void OnDisconnected() override; + + virtual void OnDied() override; + + virtual void OnDoNotDisturbDateChange(const std::shared_ptr &date) override; + + void onDoNotDisturbChanged(const std::shared_ptr &date); + + virtual void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override; + + void OnBadgeChanged(const std::shared_ptr &badgeData) override; + + void OnBadgeEnabledChanged(const sptr &callbackData) override; + + virtual void OnBatchCanceled(const std::vector> &requestList, + const std::shared_ptr &sortingMap, int32_t deleteReason) override; + + virtual bool HasOnBatchCancelCallback() override; + + bool SetObject(ani_env *env, ani_object obj); + bool IsInit(); + bool Compare(ani_env *env, ani_object obj); + bool Compare(std::shared_ptr instance); + +private: + bool CallFunction(ani_env *env, const char* func, std::vector &parm); + +private: + ani_ref ref_ = nullptr; + ani_object obj_ = nullptr; + ani_vm *vm_ = nullptr; + std::mutex lock_; +}; + +class SubscriberInstanceManager { +public: + static SubscriberInstanceManager* GetInstance() + { + static SubscriberInstanceManager instance; + return &instance; + } + ~SubscriberInstanceManager() = default; + + bool HasNotificationSubscriber( + ani_env *env, ani_object value, std::shared_ptr &subscriberInfo); + bool AddSubscriberInstancesInfo(ani_env *env, std::shared_ptr &subscriberInfo); + bool DelSubscriberInstancesInfo(ani_env *env, ani_object obj); + + bool AddDeletingSubscriber(std::shared_ptr subscriber); + void DelDeletingSubscriber(std::shared_ptr subscriber); + + bool Subscribe(ani_env *env, ani_object subscriber, ani_object info); + bool SubscribeSelf(ani_env *env, ani_object subscriber); + bool UnSubscribe(ani_env *env, ani_object subscriber); +private: + SubscriberInstanceManager() {} + + bool GetNotificationSubscriber( + ani_env *env, ani_object value, std::shared_ptr &subscriberInfo); + +private: + std::mutex mutex_; + std::vector> subscriberInstances_; + std::mutex delMutex_; + std::vector> DeletingSubscriber; +}; + +bool IsValidRemoveReason(int32_t reasonType); +bool UnWarpReasonEnum(ani_env *env, const ani_object enumItem, int32_t &outEnum); +bool UnWarpNotificationKey(ani_env *env, const ani_object obj, NotificationKey &OutObj); +bool UnwarpOperationInfo(ani_env *env, const ani_object obj, StsNotificationOperationInfo &outObj); +sptr GetOperationInfoForDistributeOperation( + ani_env *env, ani_string hashcode, ani_object operationInfo, bool &noWithOperationInfo); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_subscribe_info.h b/frameworks/ets/ani/include/sts_subscribe_info.h new file mode 100644 index 0000000000000000000000000000000000000000..5342188b8f488620623f94e672027254fe6edefc --- /dev/null +++ b/frameworks/ets/ani/include/sts_subscribe_info.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H +#include "ani.h" +#include "notification_subscribe_info.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationSubscribeInfo = OHOS::Notification::NotificationSubscribeInfo; + +bool UnwarpNotificationSubscribeInfo(ani_env *env, ani_object value, NotificationSubscribeInfo &info); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_subscriber.h b/frameworks/ets/ani/include/sts_subscriber.h new file mode 100644 index 0000000000000000000000000000000000000000..2999c285db39a7a5ba1fb53f1a15e2ac9b9f0acf --- /dev/null +++ b/frameworks/ets/ani/include/sts_subscriber.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SUBSCRIBER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SUBSCRIBER_H +#include "ani.h" +#include "sts_request.h" +#include "enabled_notification_callback_data.h" +#include "badge_number_callback_data.h" +#include "sts_sorting_map.h" + +namespace OHOS { +namespace NotificationSts { +using EnabledNotificationCallbackData = OHOS::Notification::EnabledNotificationCallbackData; +using BadgeNumberCallbackData = OHOS::Notification::BadgeNumberCallbackData; + +bool WarpSubscribeCallbackData( + ani_env *env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int32_t deleteReason, + ani_object &outObj); +bool WarpSubscribeCallbackDataArray( + ani_env *env, + const std::vector> &requestList, + const std::shared_ptr &sortingMap, + int32_t deleteReason, + ani_object &outObj); +bool WarpEnabledNotificationCallbackData( + ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj); +bool WarpBadgeNumberCallbackData( + ani_env *env, const std::shared_ptr &badgeData, ani_object &outObj); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_template.h b/frameworks/ets/ani/include/sts_template.h new file mode 100644 index 0000000000000000000000000000000000000000..fd9431cb408951e4c975ec2c899f24798fd278b9 --- /dev/null +++ b/frameworks/ets/ani/include/sts_template.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_TEMPLATE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_TEMPLATE_H +#include "ani.h" +#include "notification_template.h" + +namespace OHOS { +namespace NotificationSts { +using NotificationTemplate = OHOS::Notification::NotificationTemplate; +ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, NotificationTemplate& tmplate); +ani_object WrapNotificationTemplate(ani_env* env, const std::shared_ptr &templ); +} // namespace NotificationSts +} // OHOS +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/sts_throw_erro.h b/frameworks/ets/ani/include/sts_throw_erro.h new file mode 100644 index 0000000000000000000000000000000000000000..642ed3b429369ce88195eab551f1f03a6e42ac10 --- /dev/null +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONTENT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_CONTENT_H +#include "ani.h" +#include +#include +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "sts_error_utils.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::Notification; +static const std::unordered_map ERROR_CODE_TO_MESSAGE { + {ERROR_PERMISSION_DENIED, "Permission denied"}, + {ERROR_NOT_SYSTEM_APP, "The application isn't system application"}, + {ERROR_PARAM_INVALID, "Invalid parameter"}, + {ERROR_SYSTEM_CAP_ERROR, "SystemCapability not found"}, + {ERROR_INTERNAL_ERROR, "Internal error"}, + {ERROR_IPC_ERROR, "Marshalling or unmarshalling error"}, + {ERROR_SERVICE_CONNECT_ERROR, "Failed to connect to the service"}, + {ERROR_NOTIFICATION_CLOSED, "Notification disabled"}, + {ERROR_SLOT_CLOSED, "Notification slot disabled"}, + {ERROR_NOTIFICATION_UNREMOVABLE, "Notification deletion disabled"}, + {ERROR_NOTIFICATION_NOT_EXIST, "The notification does not exist"}, + {ERROR_USER_NOT_EXIST, "The user does not exist"}, + {ERROR_OVER_MAX_NUM_PER_SECOND, "The notification sending frequency reaches the upper limit"}, + {ERROR_DISTRIBUTED_OPERATION_FAILED, "Distributed operation failed"}, + {ERROR_READ_TEMPLATE_CONFIG_FAILED, "Failed to read the template configuration"}, + {ERROR_NO_MEMORY, "No memory space"}, + {ERROR_BUNDLE_NOT_FOUND, "The specified bundle name was not found"}, + {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, + {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, + {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, + {ERROR_NO_PROFILE_TEMPLATE, "Not exit noNotDisturb profile template"}, + {ERROR_REPEAT_SET, "Repeat create or end"}, + {ERROR_NO_RIGHT, "No permission"}, + {ERROR_EXPIRED_NOTIFICATION, "Low update version"}, + {ERROR_NETWORK_UNREACHABLE, "Network unreachable"}, + {ERROR_REJECTED_WITH_DISABLE_NOTIFICATION, + "The application is not allowed to publish notifications due to permission control settings"}, + {ERROR_DISTRIBUTED_OPERATION_TIMEOUT, "Distributed operation timeout"}, +}; + +inline std::string FindAnsErrMsg(const int32_t errCode) +{ + auto findMsg = ERROR_CODE_TO_MESSAGE.find(errCode); + if (findMsg == ERROR_CODE_TO_MESSAGE.end()) { + ANS_LOGE("FindAnsErrMsg Inner error."); + return "Inner error."; + } + return findMsg->second; +} + +inline void ThrowStsErroWithMsg(ani_env *env, std::string logMsg) +{ + ANS_LOGE("%{public}s", logMsg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); +} + +inline void ThrowStsErrorWithCode(ani_env *env, const int32_t errCode, std::string msg = "") +{ + if (env == nullptr) return; + OHOS::AbilityRuntime::ThrowStsError(env, errCode, msg.empty() ? FindAnsErrMsg(errCode) : msg); +} + +inline void ThrowStsErrorWithInvalidParam(ani_env *env) +{ + ThrowStsErrorWithCode(env, ERROR_PARAM_INVALID); +} + +} // namespace NotificationSts +} // OHOS +#endif + diff --git a/frameworks/ets/ani/include/sts_user_input.h b/frameworks/ets/ani/include/sts_user_input.h new file mode 100644 index 0000000000000000000000000000000000000000..9aebd240411ded957e23fd27a349b7f7b91b013a --- /dev/null +++ b/frameworks/ets/ani/include/sts_user_input.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_USER_INPUT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_USER_INPUT_H + +#include "ani.h" + +#include "notification_user_input.h" + +namespace OHOS { +namespace NotificationSts { +ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, + std::shared_ptr &userInput); +ani_object WarpUserInput(ani_env *env, std::shared_ptr userInput); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/subscribe/ani_remove.h b/frameworks/ets/ani/include/subscribe/ani_remove.h new file mode 100644 index 0000000000000000000000000000000000000000..5b7680a876645227d41956ac49e73a84c5619682 --- /dev/null +++ b/frameworks/ets/ani/include/subscribe/ani_remove.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REMOVE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_REMOVE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationSubScribeSts { +void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notificationKey, ani_object reasonEnum); +void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEnum); +void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reasonEnum); +void AniRemoveAllForUserId(ani_env *env, ani_double userId); +void AniRemoveAllForBundle(ani_env *env, ani_object bundle); +void AniRemoveAll(ani_env *env); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/include/subscribe/ani_subscribe.h b/frameworks/ets/ani/include/subscribe/ani_subscribe.h new file mode 100644 index 0000000000000000000000000000000000000000..5f7859b29c2366bb1e27c64457e11ba35ffcbd76 --- /dev/null +++ b/frameworks/ets/ani/include/subscribe/ani_subscribe.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_SUBSCRIBE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_NOTIFICATION_SUBSCRIBE_H +#include "ani.h" +#include + +namespace OHOS { +namespace NotificationSubScribeSts { +ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo); +void AniSubScribeRegistryInit(ani_env *env); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp b/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp new file mode 100755 index 0000000000000000000000000000000000000000..b288966f2b1e6d246b08f8f58f9fd5cecf87accf --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2025 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 "ani_ans_dialog_callback.h" +#include "ans_log_wrapper.h" +#include "inner_errors.h" +#include "notification_helper.h" + +namespace OHOS { +namespace NotificationManagerSts { + +bool StsAnsDialogCallback::Init( + ani_env *env, std::shared_ptr info, StsAnsDialogCallbackComplete *complete) +{ + if (env == nullptr || info == nullptr || complete == nullptr) { + ANS_LOGE("invalid data"); + return false; + } + ani_status status = ANI_OK; + if ((status = env->GetVM(&vm_)) != ANI_OK) { + ANS_LOGD("GetVM faild. status %{public}d", status); + return false; + } + info_ = info; + complete_ = complete; + return true; +} + +void StsAnsDialogCallback::ProcessDialogStatusChanged(const DialogStatusData &data) +{ + ANS_LOGD("enter"); + if (vm_ == nullptr || info_ == nullptr || complete_ == nullptr) { + ANS_LOGE("invalid data"); + AnsDialogHostClient::Destroy(); + return; + } + info_->errorCode = StsAnsDialogCallback::GetErrCodeFromStatus( + static_cast(data.GetStatus())); + + ani_env* env; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + if (complete_) { + complete_(env, info_); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } +} + +int32_t StsAnsDialogCallback::GetErrCodeFromStatus(EnabledDialogStatus status) +{ + switch (static_cast(status)) { + case EnabledDialogStatus::ALLOW_CLICKED: + return ERR_OK; + case EnabledDialogStatus::DENY_CLICKED: + return CJSystemapi::Notification::ERR_ANS_NOT_ALLOWED; + case EnabledDialogStatus::CRASHED: + return CJSystemapi::Notification::ERROR_INTERNAL_ERROR; + default: + return CJSystemapi::Notification::ERROR_INTERNAL_ERROR; + } + return CJSystemapi::Notification::ERROR_INTERNAL_ERROR; +} + +ModalExtensionCallback::ModalExtensionCallback() +{} + +ModalExtensionCallback::~ModalExtensionCallback() +{} + + +/* + * when UIExtensionAbility use terminateSelfWithResult + */ +void ModalExtensionCallback::OnResult(int32_t resultCode, const AAFwk::Want& result) +{ + ANS_LOGD("OnResult"); +} + +/* + * when UIExtensionAbility send message to UIExtensionComponent + */ +void ModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) +{ + ANS_LOGD("OnReceive"); +} + +/* + * when UIExtensionAbility disconnect or use terminate or process die + * releaseCode is 0 when process normal exit + */ +void ModalExtensionCallback::OnRelease(int32_t releaseCode) +{ + ANS_LOGI("OnRelease"); + ReleaseOrErrorHandle(releaseCode); +} + +/* + * when UIExtensionComponent init or turn to background or destroy UIExtensionAbility occur error + */ +void ModalExtensionCallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ANS_LOGE("OnError, name = %{public}s, message = %{public}s", name.c_str(), message.c_str()); + ReleaseOrErrorHandle(code); + NotificationHelper::RemoveEnableNotificationDialog(); +} + +/* + * when UIExtensionComponent connect to UIExtensionAbility, ModalUIExtensionProxy will init, + * UIExtensionComponent can send message to UIExtensionAbility by ModalUIExtensionProxy + */ +void ModalExtensionCallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ANS_LOGD("OnRemoteReady"); +} + +/* + * when UIExtensionComponent destructed + */ +void ModalExtensionCallback::OnDestroy() +{ + ANS_LOGD("OnDestroy"); +} + + +void ModalExtensionCallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void ModalExtensionCallback::SetBundleName(std::string bundleName) +{ + this->bundleName_ = bundleName; +} + +void ModalExtensionCallback::SetAbilityContext(std::shared_ptr abilityContext) +{ + this->abilityContext_ = abilityContext; +} + +void ModalExtensionCallback::ReleaseOrErrorHandle(int32_t code) +{ + ANS_LOGD("ReleaseOrErrorHandle start"); + Ace::UIContent* uiContent = this->abilityContext_->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return; + } + uiContent->CloseModalUIExtension(this->sessionId_); + ANS_LOGD("ReleaseOrErrorHandle end"); + return; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_cance.cpp b/frameworks/ets/ani/src/manager/ani_cance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..600558eff0052d46de28f884795021bc72bc3f8b --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_cance.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2025 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 "ani_cance.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniCancelAll(ani_env* env) +{ + ANS_LOGD("AniCancelAll notifications call"); + int returncode = Notification::NotificationHelper::CancelAllNotifications(); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniCancelAll -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniCancelAll notifications end"); +} + +void AniCancelWithId(ani_env* env, ani_double id) +{ + ANS_LOGD("AniCancelWithId call,id : %{public}lf", id); + int returncode = Notification::NotificationHelper::CancelNotification(static_cast(id)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniCancelWithId -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniCancelWithId notifications end"); +} + +void AniCancelWithIdLabel(ani_env* env, ani_double id, ani_string label) +{ + ANS_LOGD("AniCancelWithIdLabel call"); + std::string labelStr; + if (ANI_OK != NotificationSts::GetStringByAniString(env, label, labelStr)) { + NotificationSts::ThrowStsErroWithMsg(env, "Label parse failed!"); + return; + } + + ANS_LOGD("Cancel by label id:%{public}lf label:%{public}s", id, labelStr.c_str()); + int returncode = Notification::NotificationHelper::CancelNotification(labelStr, static_cast(id)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniCancelWithIdLabel -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniCancelWithIdLabel end"); +} + +void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_double id) +{ + ANS_LOGD("AniCancelWithBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleObj, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "BundleOption parse failed!"); + return; + } + + ANS_LOGD("Cancel by bundle:%{public}s id:%{public}lf", + option.GetBundleName().c_str(), id); + int returncode = Notification::NotificationHelper::CancelAsBundle(option, static_cast(id)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniCancelWithBundle -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniCancelWithBundle end"); +} + +void AniCancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string label) +{ + ANS_LOGD("sts AniCancelWithIdOptinalLabel call, id:%{public}lf", id); + ani_boolean isUndefined = ANI_FALSE; + env->Reference_IsUndefined(label, &isUndefined); + int32_t ret = -1; + if (isUndefined) { + ANS_LOGE("sts AniCancelWithIdOptinalLabel the label is undefined"); + ret = Notification::NotificationHelper::CancelNotification(static_cast(id)); + } else { + std::string labelStr; + if (ANI_OK != NotificationSts::GetStringByAniString(env, label, labelStr)) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts AniCancelWithIdOptinalLabel ERROR_INTERNAL_ERROR"); + return; + } + ANS_LOGD("sts AniCancelWithIdOptinalLabel id:%{public}lf label:%{public}s", id, labelStr.c_str()); + ret = Notification::NotificationHelper::CancelNotification(labelStr, id); + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("sts AniCancelWithIdOptinalLabel error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts AniCancelWithIdOptinalLabel end, externalCode: %{public}d", externalCode); +} + +void AniCancelAsBundle(ani_env *env, ani_double id, ani_string representativeBundle, ani_double userId) +{ + ANS_LOGD("AniCancelAsBundle enter"); + int32_t convertedId = static_cast(id); + int32_t UserId = static_cast(userId); + std::string bundleStr; + + if (ANI_OK != NotificationSts::GetStringByAniString(env, representativeBundle, bundleStr)) { + ANS_LOGE("AniCancelAsBundle:: representativeBundle parse failed!"); + NotificationSts::ThrowStsErroWithMsg(env, "representativeBundle parse failed!"); + return; + } + ANS_LOGD("AniCancelAsBundle, convertedId: %{public}d, UserId: %{public}d, bundleStr: %{public}s", + convertedId, UserId, bundleStr.c_str()); + + int returncode = Notification::NotificationHelper::CancelAsBundle(convertedId, bundleStr, UserId); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniCancelAsBundle: CancelAsBundle retern erro. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + + ANS_LOGD("AniCancelAsBundle end"); +} + +void AniCancelAsBundleWithBundleOption(ani_env *env, ani_object representativeBundle, ani_double id) +{ + ANS_LOGD("AniCancelAsBundleWithBundleOption enter"); + int32_t idTest = static_cast(id); + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, representativeBundle, option) != true) { + ANS_LOGE("AniPublishAsBundleWithBundleOption BundleOption parse failed!"); + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishAsBundleWithBundleOption BundleOption parse failed!"); + return; + } + + ANS_LOGD("AniPublishAsBundleWithBundleOption: bundle %{public}s, uid: %{public}d, id: %{public}d", + option.GetBundleName().c_str(), option.GetUid(), idTest); + + int returncode = Notification::NotificationHelper::CancelAsBundle(option, idTest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("CancelAsBundle retern error. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + + ANS_LOGD("AniCancelAsBundleWithBundleOption end"); +} + +void AniCancelGroup(ani_env *env, ani_string groupName) +{ + ANS_LOGD("AniCancelGroup enter"); + + std::string groupNameStr; + if (ANI_OK != NotificationSts::GetStringByAniString(env, groupName, groupNameStr)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniCancelGroup: groupName parse failed!"); + return; + } + ANS_LOGD("AniCancelGroup groupNameStr: %{public}s", groupNameStr.c_str()); + int returncode = Notification::NotificationHelper::CancelGroup(groupNameStr); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniCancelGroup: CancelAsBundle retern erro. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniCancelGroup end"); +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_display_badge.cpp b/frameworks/ets/ani/src/manager/ani_display_badge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed01c043a4b222fc50caf9a261a80602b443a487 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_display_badge.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2025 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 "ani_display_badge.h" + +#include "ans_log_wrapper.h" +#include "sts_bundle_option.h" +#include "sts_throw_erro.h" +#include "sts_error_utils.h" +#include "sts_common.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "notification_bundle_option.h" + + +namespace OHOS { +namespace NotificationManagerSts { +void AniDisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) +{ + ANS_LOGD("DisplayBadgeAni call"); + int returncode = 0; + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, obj, option)) { + returncode = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, + NotificationSts::AniBooleanToBool(enable)); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts DisplayBadge ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("sts DisplayBadge error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("DisplayBadgeAni end, ret: %{public}d", externalCode); +} + +ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts IsBadgeDisplayed call"); + int returncode = 0; + bool isDisplayed = false; + if (obj == nullptr) { + returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); + } else { + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, obj, option)) { + returncode = Notification::NotificationHelper::GetShowBadgeEnabledForBundle(option, isDisplayed); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts IsBadgeDisplayed ERROR_INTERNAL_ERROR"); + return NotificationSts::BoolToAniBoolean(false); + } + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("sts IsBadgeDisplayed error, errorCode: %{public}d", externalCode); + return NotificationSts::BoolToAniBoolean(false); + } + ANS_LOGD("sts IsBadgeDisplayed end, isDisplayed: %{public}d, returncode: %{public}d", isDisplayed, + externalCode); + return NotificationSts::BoolToAniBoolean(isDisplayed); +} + +void AniSetBadgeNumber(ani_env *env, ani_double badgeNumber) +{ + ANS_LOGD("sts AniSetBadgeNumber call, BadgeNumber: %{public}lf", badgeNumber); + int returncode = Notification::NotificationHelper::SetBadgeNumber(static_cast(badgeNumber)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("sts AniSetBadgeNumber error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("sts AniSetBadgeNumber end"); +} + +void AniSetBadgeNumberByBundle(ani_env *env, ani_object obj, ani_double badgeNumber) +{ + ANS_LOGD("AniSetBadgeNumberByBundle call, badgeNumber: %{public}lf", badgeNumber); + int returncode = ERR_OK; + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, obj, option)) { + returncode = Notification::NotificationHelper::SetBadgeNumberByBundle(option, + static_cast(badgeNumber)); + } else { + ANS_LOGE("sts AniSetBadgeNumberByBundle ERROR_INTERNAL_ERROR"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("sts AniSetBadgeNumberByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniSetBadgeNumberByBundle end, ret: %{public}d", externalCode); +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_distributed_enable.cpp b/frameworks/ets/ani/src/manager/ani_distributed_enable.cpp new file mode 100755 index 0000000000000000000000000000000000000000..4beb262fdb52a70724074698553c58605e17a8d1 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_distributed_enable.cpp @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2025 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 "ani_distributed_enable.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniSetDistributedEnable(ani_env* env, ani_boolean enabled) +{ + ANS_LOGD("AniSetDistributedEnable call,enable : %{public}d", enabled); + int returncode = Notification::NotificationHelper::EnableDistributed(NotificationSts::AniBooleanToBool(enabled)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetDistributedEnable -> error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("AniSetDistributedEnable end"); +} + +ani_boolean AniIsDistributedEnabled(ani_env* env) +{ + ANS_LOGD("AniIsDistributedEnabled call"); + bool enabled = false; + int returncode = Notification::NotificationHelper::IsDistributedEnabled(enabled); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsDistributedEnabled -> error, errorCode: %{public}d", externalCode); + return NotificationSts::BoolToAniBoolean(false); + } + ANS_LOGD("AniIsDistributedEnabled end, enabled: %{public}d, returncode: %{public}d", enabled, externalCode); + return NotificationSts::BoolToAniBoolean(enabled); +} + +ani_boolean AniIsDistributedEnabledByBundle(ani_env* env, ani_object obj) +{ + ANS_LOGD("AniIsDistributedEnabledByBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniIsDistributedEnabledByBundle : erro arguments."); + return NotificationSts::BoolToAniBoolean(false); + } + bool enabled = false; + int returncode = Notification::NotificationHelper::IsDistributedEnableByBundle(option, enabled); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsDistributedEnabledByBundle -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniIsDistributedEnabledByBundle end, enabled: %{public}d, returncode: %{public}d", enabled, externalCode); + return NotificationSts::BoolToAniBoolean(enabled); +} + +ani_boolean AniIsDistributedEnabledByBundleType(ani_env* env, ani_object obj, ani_string deviceType) +{ + ANS_LOGD("AniIsDistributedEnabledByBundleType call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniIsDistributedEnabledByBundleType : erro arguments."); + return NotificationSts::BoolToAniBoolean(false); + } + std::string deviceTypeStr; + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + NotificationSts::ThrowStsErroWithMsg(env, "deviceType parse failed!"); + return NotificationSts::BoolToAniBoolean(false); + } + ANS_LOGD("Cancel by deviceType:%{public}s", deviceTypeStr.c_str()); + + bool enabled = false; + int returncode = Notification::NotificationHelper::IsDistributedEnabledByBundle(option, deviceTypeStr, enabled); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsDistributedEnabledByBundle -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniIsDistributedEnabledByBundle end, enabled: %{public}d, returncode: %{public}d", enabled, externalCode); + return NotificationSts::BoolToAniBoolean(enabled); +} + +void AniSetDistributedEnableByBundle(ani_env *env, ani_object obj, ani_boolean enable) +{ + ANS_LOGD("setDistributedEnableByBundle call"); + int returncode = ERR_OK; + Notification::NotificationBundleOption option; + bool bFlag = NotificationSts::UnwrapBundleOption(env, obj, option); + if (bFlag) { + returncode = Notification::NotificationHelper::EnableDistributedByBundle( + option, NotificationSts::AniBooleanToBool(enable)); + } else { + ANS_LOGE("sts setDistributedEnableByBundle ERROR_INTERNAL_ERROR"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("sts setDistributedEnableByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("sts setDistributedEnableByBundle end, ret: %{public}d", externalCode); +} + +void AniSetDistributedEnableByBundleAndType(ani_env *env, + ani_object obj, ani_string deviceType, ani_boolean enable) +{ + ANS_LOGD("sts setDistributedEnabledByBundle call"); + std::string deviceTypeStr; + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + int returncode = ERR_OK; + Notification::NotificationBundleOption option; + bool bFlag = NotificationSts::UnwrapBundleOption(env, obj, option); + if (bFlag) { + returncode = Notification::NotificationHelper::SetDistributedEnabledByBundle(option, + deviceTypeStr, NotificationSts::AniBooleanToBool(enable)); + } else { + ANS_LOGE("sts setDistributedEnabledByBundle ERROR_INTERNAL_ERROR"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("sts setDistributedEnabledByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("sts setDistributedEnabledByBundle end, ret: %{public}d", externalCode); +} + +void AniSetTargetDeviceStatus(ani_env* env, ani_string deviceType, ani_double status) +{ + ANS_LOGD("sts setTargetDeviceStatus call, id:%{public}lf", status); + std::string deviceTypeStr; + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + ANS_LOGD("sts setTargetDeviceStatus id:%{public}lf deviceType:%{public}s", status, deviceTypeStr.c_str()); + int32_t ret = Notification::NotificationHelper::SetTargetDeviceStatus(deviceTypeStr, status, DISTURB_DEFAULT_FLAG); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + ANS_LOGE("sts setTargetDeviceStatus error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("sts setTargetDeviceStatus end, externalCode: %{public}d", externalCode); +} + +ani_boolean AniIsSmartReminderEnabled(ani_env *env, ani_string deviceType) +{ + ANS_LOGD("isSmartReminderEnabled call"); + bool allowed = false; + std::string deviceTypeStr; + if (env == nullptr || deviceType == nullptr) { + ANS_LOGE("Invalid env or deviceType is null"); + return ANI_FALSE; + } + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return ANI_FALSE; + } + int returncode = Notification::NotificationHelper::IsSmartReminderEnabled(deviceTypeStr, allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("isSmartReminderEnabled -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("isSmartReminderEnabled end"); + return NotificationSts::BoolToAniBoolean(allowed); +} + + +void AniSetSmartReminderEnable(ani_env *env, ani_string deviceType, ani_boolean enable) +{ + ANS_LOGD("setSmartReminderEnabled call"); + std::string deviceTypeStr; + if (env == nullptr || deviceType == nullptr) { + ANS_LOGE("Invalid env or deviceType is null"); + return; + } + + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + int returncode = Notification::NotificationHelper::SetSmartReminderEnabled(deviceTypeStr, + NotificationSts::AniBooleanToBool(enable)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("setSmartReminderEnabled -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("setSmartReminderEnabled end"); +} + +void AniSetDistributedEnableBySlot(ani_env *env, ani_enum_item slot, ani_string deviceType, ani_boolean enable) +{ + ANS_LOGD("setDistributedEnabledBySlot enter "); + std::string deviceTypeStr; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, slot, slotType)) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("SlotTypeEtsToC failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + if (env == nullptr || deviceType == nullptr) { + ANS_LOGE("Invalid env or deviceType is null"); + return; + } + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + int returncode = ERR_OK; + returncode = Notification::NotificationHelper::SetDistributedEnabledBySlot(slotType, + deviceTypeStr, NotificationSts::AniBooleanToBool(enable)); + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("setDistributedEnabledBySlot error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } +} + +ani_boolean AniIsDistributedEnabledBySlot(ani_env *env, ani_enum_item slot, ani_string deviceType) +{ + ANS_LOGD("isDistributedEnabledBySlot enter"); + std::string deviceTypeStr; + + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, slot, slotType)) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("SlotTypeEtsToC failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return ANI_FALSE; + } + if (env == nullptr || deviceType == nullptr) { + ANS_LOGE("Invalid env or deviceType is null"); + return ANI_FALSE; + } + if (NotificationSts::GetStringByAniString(env, deviceType, deviceTypeStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return ANI_FALSE; + } + bool isEnable = false; + int returncode = Notification::NotificationHelper::IsDistributedEnabledBySlot(slotType, deviceTypeStr, isEnable); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("isDistributedEnabledBySlot -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + return isEnable ? ANI_TRUE : ANI_FALSE; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_do_not_disturb_date.cpp b/frameworks/ets/ani/src/manager/ani_do_not_disturb_date.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d09b4241994f9483982910f0c727640172de5e9 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_date.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2025 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 "ani_do_not_disturb_date.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" +#include "sts_notification_manager.h" +#include "sts_request.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniSetDoNotDisturbDate(ani_env *env, ani_object date) +{ + ANS_LOGD("AniSetDoNotDisturbDate enter"); + Notification::NotificationDoNotDisturbDate doNotDisturbDate; + if (NotificationSts::UnWarpNotificationDoNotDisturbDate(env, date, doNotDisturbDate)) { + ANS_LOGE("AniSetDoNotDisturbDate UnWarpNotificationDoNotDisturbDate ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "UnWarpNotificationDoNotDisturbDate ERROR_INTERNAL_ERROR"); + return; + } + + int returncode = Notification::NotificationHelper::SetDoNotDisturbDate(doNotDisturbDate); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("SetDoNotDisturbDate error. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniSetDoNotDisturbDate end"); +} + +void AniSetDoNotDisturbDateWithId(ani_env *env, ani_object date, ani_double userId) +{ + ANS_LOGD("AniSetDoNotDisturbDateWithId enter"); + Notification::NotificationDoNotDisturbDate doNotDisturbDate; + if (NotificationSts::UnWarpNotificationDoNotDisturbDate(env, date, doNotDisturbDate)) { + ANS_LOGE("AniSetDoNotDisturbDateWithId UnWarpNotificationDoNotDisturbDate ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "UnWarpNotificationDoNotDisturbDate ERROR_INTERNAL_ERROR"); + return; + } + + const int32_t id = static_cast(userId); + int returncode = Notification::NotificationHelper::SetDoNotDisturbDate(id, doNotDisturbDate); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("SetDoNotDisturbDate erro. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + + ANS_LOGD("AniSetDoNotDisturbDateWithId end"); +} + +ani_object AniGetDoNotDisturbDate(ani_env *env) +{ + ani_object data = nullptr; + Notification::NotificationDoNotDisturbDate doNotDisturbDate; + + ANS_LOGD("AniGetDoNotDisturbDate enter"); + int returncode = Notification::NotificationHelper::GetDoNotDisturbDate(doNotDisturbDate); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("GetDoNotDisturbDate retern erro. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return data; + } + + auto datePtr = std::make_shared(doNotDisturbDate); + if (NotificationSts::WarpNotificationDoNotDisturbDate(env, datePtr, data) == false) { + ANS_LOGE("WarpNotificationDoNotDisturbDate faild"); + NotificationSts::ThrowStsErroWithMsg(env, "AniGetDoNotDisturbDate ERROR_INTERNAL_ERROR"); + } + + ANS_LOGD("AniGetDoNotDisturbDate end"); + return data; +} + +ani_object AniGetDoNotDisturbDateWithId(ani_env *env, ani_double userId) +{ + ani_object data = nullptr; + Notification::NotificationDoNotDisturbDate doNotDisturbDate; + + ANS_LOGD("AniGetDoNotDisturbDateWithId enter"); + + const int32_t id = static_cast(userId); + int returncode = Notification::NotificationHelper::GetDoNotDisturbDate(id, doNotDisturbDate); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("GetDoNotDisturbDate erro. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return data; + } + + auto datePtr = std::make_shared(doNotDisturbDate); + if (NotificationSts::WarpNotificationDoNotDisturbDate(env, datePtr, data) == false) { + ANS_LOGE("AniGetDoNotDisturbDateWithId WarpNotificationDoNotDisturbDate faild"); + } + + ANS_LOGD("AniGetDoNotDisturbDateWithId end"); + return data; +} + +ani_boolean AniIsSupportDoNotDisturbMode(ani_env *env) +{ + bool supportDoNotDisturbMode = false; + ANS_LOGD("AniIsSupportDoNotDisturbMode enter"); + int returncode = Notification::NotificationHelper::DoesSupportDoNotDisturbMode(supportDoNotDisturbMode); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("DoesSupportDoNotDisturbMode error. returncode: %{public}d, externalCode: %{public}d", + returncode, externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return ANI_FALSE; + } + ANS_LOGD("DoesSupportDoNotDisturbMode returncode: %{public}d", supportDoNotDisturbMode); + ANS_LOGD("AniIsSupportDoNotDisturbMode end"); + return NotificationSts::BoolToAniBoolean(supportDoNotDisturbMode); +} + +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71f94dd19d0b5ff4389d983e3687d5fa71b177a4 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2025 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 "ani_do_not_disturb_profile.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_common.h" +#include "sts_throw_erro.h" +#include "sts_disturb_mode.h" +#include "sts_bundle_option.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniAddDoNotDisturbProfile(ani_env *env, ani_object obj) +{ + ANS_LOGD("AniAddDoNotDisturbProfile call"); + int returncode = 0; + std::vector> profiles; + if (NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { + returncode = Notification::NotificationHelper::AddDoNotDisturbProfiles(profiles); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniAddDoNotDisturbProfile failed : ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniAddDoNotDisturbProfile error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniAddDoNotDisturbProfile end"); +} + +void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj) +{ + ANS_LOGD("AniRemoveDoNotDisturbProfile call"); + int returncode = 0; + std::vector> profiles; + if (NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { + returncode = Notification::NotificationHelper::RemoveDoNotDisturbProfiles(profiles); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniRemoveDoNotDisturbProfile failed : ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniRemoveDoNotDisturbProfile error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniRemoveDoNotDisturbProfile end"); +} + +ani_object AniGetDoNotDisturbProfile(ani_env *env, ani_double id) +{ + ani_object profile; + ANS_LOGD("AniGetDoNotDisturbProfile enter"); + + sptr doNotDisturbProfile = new (std::nothrow) NotificationDoNotDisturbProfile(); + if (doNotDisturbProfile == nullptr) { + ANS_LOGE("Failed to create NotificationDoNotDisturbProfile."); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + return nullptr; + } + + int32_t idTest = static_cast(id); + ANS_LOGD("AniGetDoNotDisturbProfile: idTest: %{public}d", idTest); + int returncode = Notification::NotificationHelper::GetDoNotDisturbProfile(idTest, doNotDisturbProfile); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniSetDoNotDisturbDateWithId error, errorCode: %{public}d, returncode: %{public}d", + externalCode, returncode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + + if (!NotificationSts::WrapDoNotDisturbProfile(env, doNotDisturbProfile, profile)) { + ANS_LOGE("AniGetDoNotDisturbProfile WrapDoNotDisturbProfile failed"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + return nullptr; + } + + ANS_LOGD("AniGetDoNotDisturbProfile end"); + return profile; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_get_active.cpp b/frameworks/ets/ani/src/manager/ani_get_active.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93c02e57210c57e14c623bc6b71a00719444e6a3 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025 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 "ani_get_active.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_request.h" +#include "sts_common.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_double AniGetActiveNotificationCount(ani_env *env) +{ + ANS_LOGD("sts GetActiveNotificationCount call"); + uint64_t num = 0; + int returncode = OHOS::Notification::NotificationHelper::GetActiveNotificationNums(num); + ANS_LOGD("sts GetActiveNotificationCount end, num: %{public}llu", num); + ani_double retNum = static_cast(num); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + return 0; + } + return retNum; +} + +ani_object AniGetAllActiveNotifications(ani_env *env) +{ + ANS_LOGD("sts AniGetAllActiveNotifications call"); + std::vector> notifications; + int returncode = OHOS::Notification::NotificationHelper::GetAllActiveNotifications(notifications); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniGetAllActiveNotifications error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_object arrayRequestObj; + if (notifications.size() == 0) { + arrayRequestObj = NotificationSts::newArrayClass(env, 0); + } else { + arrayRequestObj = NotificationSts::GetAniNotificationRequestArrayByNotifocations(env, notifications); + } + if (arrayRequestObj == nullptr) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniGetAllActiveNotifications ERROR_INTERNAL_ERROR"); + } + ANS_LOGD("sts AniGetAllActiveNotifications end"); + return arrayRequestObj; +} + +ani_object AniGetActiveNotifications(ani_env *env) +{ + ANS_LOGD("sts AniGetActiveNotifications call"); + std::vector> requests; + int returncode = OHOS::Notification::NotificationHelper::GetActiveNotifications(requests); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniGetActiveNotifications error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_object arrayRequestObj; + if (requests.size() == 0) { + arrayRequestObj = NotificationSts::newArrayClass(env, 0); + } else { + arrayRequestObj = NotificationSts::GetAniNotificationRequestArray(env, requests); + } + if (arrayRequestObj == nullptr) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniGetActiveNotifications ERROR_INTERNAL_ERROR"); + } + ANS_LOGD("sts AniGetActiveNotifications end"); + return arrayRequestObj; +} + +ani_object AniGetActiveNotificationByFilter(ani_env *env, ani_object obj) +{ + ANS_LOGD("AniGetActiveNotificationByFilter call"); + Notification::LiveViewFilter filter; + if (!OHOS::NotificationSts::UnWarpNotificationFilter(env, obj, filter)) { + NotificationSts::ThrowStsErroWithMsg(env, "sts UnWarpNotificationFilter ERROR_INTERNAL_ERROR"); + return nullptr; + } + sptr notificationRequest = nullptr; + int returncode = Notification::NotificationHelper::GetActiveNotificationByFilter(filter, notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniGetActiveNotificationByFilter -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return nullptr; + } + + ani_object requestObj = nullptr; + ani_class requestCls; + if (!NotificationSts::WarpNotificationRequest(env, notificationRequest.GetRefPtr(), requestCls, requestObj) + || requestObj == nullptr) { + NotificationSts::ThrowStsErroWithMsg(env, "sts UnWarpNotificationFilter ERROR_INTERNAL_ERROR"); + ANS_LOGE("AniGetActiveNotificationByFilter WarpNotificationRequest faild"); + return nullptr; + } + ANS_LOGD("AniGetActiveNotificationByFilter end"); + return requestObj; +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_local_live_view.cpp b/frameworks/ets/ani/src/manager/ani_local_live_view.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3c4203c80ad7bc0013b2d147039627e8d24cc14 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_local_live_view.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 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 "ani_local_live_view.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniTriggerSystemLiveView( + ani_env *env, ani_object bundleOptionObj, ani_double notificationId, ani_object buttonOptionsObj) +{ + ANS_LOGD("AniTriggerSystemLiveView call"); + BundleOption bundleOption; + if (!NotificationSts::UnwrapBundleOption(env, bundleOptionObj, bundleOption)) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniTriggerSystemLiveView bundleOption ERROR_INTERNAL_ERROR"); + return; + } + NotificationSts::ButtonOption buttonOption; + if (NotificationSts::UnWarpNotificationButtonOption(env, buttonOptionsObj, buttonOption) != ANI_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("AniTriggerSystemLiveView buttonOption ERROR_INTERNAL_ERROR"); + return; + } + int returncode = OHOS::Notification::NotificationHelper::TriggerLocalLiveView(bundleOption, + static_cast(notificationId), buttonOption); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniTriggerSystemLiveView error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniTriggerSystemLiveView end"); +} + +void AniSubscribeSystemLiveView(ani_env *env, ani_object subscriberObj) +{ + ANS_LOGD("AniSubscribeSystemLiveView call"); + NotificationSts::StsNotificationLocalLiveViewSubscriber *localLiveViewSubscriber + = new (std::nothrow)NotificationSts::StsNotificationLocalLiveViewSubscriber(); + localLiveViewSubscriber->SetStsNotificationLocalLiveViewSubscriber(env, subscriberObj); + int returncode + = OHOS::Notification::NotificationHelper::SubscribeLocalLiveViewNotification(*localLiveViewSubscriber, false); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSubscribeSystemLiveView error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniSubscribeSystemLiveView end"); +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cecd702155edb49de00b2480c098c4eb3328a38 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2025 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 "ani_manager.h" + +#include "ans_log_wrapper.h" +#include "ani_display_badge.h" +#include "ani_slot.h" +#include "ani_cance.h" +#include "ani_notification_enable.h" +#include "ani_do_not_disturb_date.h" +#include "ani_do_not_disturb_profile.h" +#include "ani_get_active.h" +#include "ani_publish.h" +#include "ani_local_live_view.h" +#include "ani_request_enable.h" +#include "ani_on.h" +#include "ani_support_template.h" +#include "ani_distributed_enable.h" +#include "ani_remove_group.h" +#include "ani_open_settings.h" +#include "ani_sync_config.h" + +namespace OHOS { +namespace NotificationManagerSts { +static std::array kitManagerFunctions = { + ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, + ani_native_function {"nativeCancelWithIdOptionalLabel", nullptr, + reinterpret_cast(AniCancelWithIdOptinalLabel)}, + ani_native_function {"nativeCancelWithId", nullptr, reinterpret_cast(AniCancelWithId)}, + ani_native_function {"nativeCancelWithIdLabel", nullptr, reinterpret_cast(AniCancelWithIdLabel)}, + ani_native_function {"nativeCancelWithBundle", nullptr, reinterpret_cast(AniCancelWithBundle)}, + ani_native_function {"nativeDisplayBadge", nullptr, reinterpret_cast(AniDisplayBadge)}, + ani_native_function {"nativeIsBadgeDisplayed", nullptr, reinterpret_cast(AniIsBadgeDisplayed)}, + ani_native_function {"nativeGetActiveNotificationCount", ":D", + reinterpret_cast(AniGetActiveNotificationCount)}, + ani_native_function {"nativeGetActiveNotifications", nullptr, + reinterpret_cast(AniGetActiveNotifications)}, + ani_native_function {"nativeGetAllActiveNotifications", nullptr, + reinterpret_cast(AniGetAllActiveNotifications)}, + ani_native_function {"nativeAddDoNotDisturbProfile", nullptr, + reinterpret_cast(AniAddDoNotDisturbProfile)}, + ani_native_function {"nativeRemoveDoNotDisturbProfile", nullptr, + reinterpret_cast(AniRemoveDoNotDisturbProfile)}, + ani_native_function {"nativeSubscribeSystemLiveView", nullptr, + reinterpret_cast(AniSubscribeSystemLiveView)}, + ani_native_function {"nativeTriggerSystemLiveView", nullptr, + reinterpret_cast(AniTriggerSystemLiveView)}, + ani_native_function {"nativePublishWithUserId", nullptr, reinterpret_cast(AniPublishWithId)}, + ani_native_function {"nativePublish", nullptr, reinterpret_cast(AniPublish)}, + ani_native_function {"nativeGetSlotFlagsByBundle", nullptr, reinterpret_cast(AniGetSlotFlagsByBundle)}, + ani_native_function {"nativeSetSlotFlagsByBundle", nullptr, reinterpret_cast(AniSetSlotFlagsByBundle)}, + ani_native_function {"nativeGetSlotsByBundle", nullptr, reinterpret_cast(AniGetSlotsByBundle)}, + ani_native_function {"nativeIsNotificationSlotEnabled", nullptr, + reinterpret_cast(AniIsNotificationSlotEnabled)}, + ani_native_function {"nativeSetNotificationEnableSlot", nullptr, + reinterpret_cast(AniSetNotificationEnableSlot)}, + ani_native_function {"nativeSetNotificationEnableSlotWithForce", nullptr, + reinterpret_cast(AniSetNotificationEnableSlotWithForce)}, + ani_native_function {"nativeIsNotificationEnabled", nullptr, + reinterpret_cast(AniIsNotificationEnabled)}, + ani_native_function {"nativeIsNotificationEnabledWithId", nullptr, + reinterpret_cast(AniIsNotificationEnabledWithId)}, + ani_native_function {"nativeIsNotificationEnabledWithBundleOption", nullptr, + reinterpret_cast(AniIsNotificationEnabledWithBundleOption)}, + ani_native_function {"nativeSetNotificationEnable", + nullptr, reinterpret_cast(AniSetNotificationEnable)}, + ani_native_function {"nativeRequestEnableNotification", + "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", + reinterpret_cast(AniRequestEnableNotification)}, + ani_native_function {"nativePublishAsBundle", nullptr, reinterpret_cast(AniPublishAsBundle)}, + ani_native_function {"nativePublishAsBundleWithBundleOption", nullptr, + reinterpret_cast(AniPublishAsBundleWithBundleOption)}, + ani_native_function {"nativeCancelAsBundle", nullptr, reinterpret_cast(AniCancelAsBundle)}, + ani_native_function {"nativeCancelAsBundleWithBundleOption", nullptr, + reinterpret_cast(AniCancelAsBundleWithBundleOption)}, + ani_native_function {"nativeCancelGroup", nullptr, reinterpret_cast(AniCancelGroup)}, + ani_native_function {"nativeSetDoNotDisturbDate", nullptr, reinterpret_cast(AniSetDoNotDisturbDate)}, + ani_native_function {"nativeSetDoNotDisturbDateWithId", nullptr, + reinterpret_cast(AniSetDoNotDisturbDateWithId)}, + ani_native_function {"nativeGetDoNotDisturbDate", nullptr, reinterpret_cast(AniGetDoNotDisturbDate)}, + ani_native_function {"nativeGetDoNotDisturbDateWithId", nullptr, + reinterpret_cast(AniGetDoNotDisturbDateWithId)}, + ani_native_function {"nativeIsSupportDoNotDisturbMode", nullptr, + reinterpret_cast(AniIsSupportDoNotDisturbMode)}, + ani_native_function {"nativeGetDoNotDisturbProfile", nullptr, reinterpret_cast(AniGetDoNotDisturbProfile)}, + ani_native_function {"nativeOn", + "Lstd/core/String;" + "Lstd/core/Function1;" + "Lnotification/notificationRequest/NotificationCheckRequest;" + ":I", + reinterpret_cast(AniOn)}, + ani_native_function {"nativeOff", "Lstd/core/String;Lstd/core/Function1;:I", reinterpret_cast(AniOff)}, + ani_native_function {"nativeGetAllNotificationEnabledBundles", nullptr, + reinterpret_cast(AniGetAllNotificationEnabledBundles)}, + ani_native_function {"nativeIsNotificationEnabledSync", nullptr, + reinterpret_cast(AniIsNotificationEnabledSync)}, + ani_native_function {"nativeSetBadgeNumber", "D:V", + reinterpret_cast(AniSetBadgeNumber)}, + ani_native_function {"nativeSetBadgeNumberByBundle", nullptr, + reinterpret_cast(AniSetBadgeNumberByBundle)}, + ani_native_function {"nativeGetActiveNotificationByFilter", nullptr, + reinterpret_cast(AniGetActiveNotificationByFilter)}, + ani_native_function {"nativeRemoveGroupByBundle", nullptr, + reinterpret_cast(AniRemoveGroupByBundle)}, + ani_native_function {"nativeAddSlotByNotificationSlot", nullptr, + reinterpret_cast(AniAddSlotByNotificationSlot)}, + ani_native_function {"nativeAddSlotBySlotType", nullptr, + reinterpret_cast(AniAddSlotBySlotType)}, + ani_native_function {"nativeAddSlots", nullptr, + reinterpret_cast(AniAddSlots)}, + ani_native_function {"nativeGetSlot", nullptr, + reinterpret_cast(AniGetSlot)}, + ani_native_function {"nativeGetSlots", nullptr, + reinterpret_cast(AniGetSlots)}, + ani_native_function {"nativeRemoveSlot", nullptr, + reinterpret_cast(AniRemoveSlot)}, + ani_native_function {"nativeRemoveAllSlots", nullptr, + reinterpret_cast(AniRemoveAllSlots)}, + ani_native_function {"nativeSetSlotByBundle", nullptr, + reinterpret_cast(AniSetSlotByBundle)}, + ani_native_function {"nativeGetSlotNumByBundle", nullptr, + reinterpret_cast(AniGetSlotNumByBundle)}, + ani_native_function {"nativeOpenNotificationSettings", + "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", + reinterpret_cast(AniOpenNotificationSettings)}, + ani_native_function {"nativesetTargetDeviceStatus", nullptr, + reinterpret_cast(AniSetTargetDeviceStatus)}, + ani_native_function {"nativesetDistributedEnabledByBundle", nullptr, + reinterpret_cast(AniSetDistributedEnableByBundleAndType)}, + ani_native_function {"nativesetSmartReminderEnabled", nullptr, + reinterpret_cast(AniSetSmartReminderEnable)}, + ani_native_function {"nativeisSmartReminderEnabled", nullptr, + reinterpret_cast(AniIsSmartReminderEnabled)}, + ani_native_function {"nativesetDistributedEnabledBySlot", nullptr, + reinterpret_cast(AniSetDistributedEnableBySlot)}, + ani_native_function {"nativeisDistributedEnabledBySlot", nullptr, + reinterpret_cast(AniIsDistributedEnabledBySlot)}, + ani_native_function {"nativesetAdditionalConfig", nullptr, + reinterpret_cast(AniSetAdditionalConfig)}, + ani_native_function {"nativesetDistributedEnableByBundle", nullptr, + reinterpret_cast(AniSetDistributedEnableByBundle)}, + ani_native_function {"nativedisableNotificationFeature", nullptr, + reinterpret_cast(AniDisableNotificationFeature)}, + ani_native_function {"nativeIsSupportTemplate", nullptr, reinterpret_cast(AniIsSupportTemplate)}, + ani_native_function {"nativeSetDistributedEnable", nullptr, reinterpret_cast(AniSetDistributedEnable)}, + ani_native_function {"nativeIsDistributedEnabled", nullptr, reinterpret_cast(AniIsDistributedEnabled)}, + ani_native_function {"nativeIsDistributedEnabledByBundle", nullptr, + reinterpret_cast(AniIsDistributedEnabledByBundle)}, + ani_native_function {"nativeIsDistributedEnabledByBundleType", nullptr, + reinterpret_cast(AniIsDistributedEnabledByBundleType)}, + ani_native_function {"nativeGetDeviceRemindType", nullptr, reinterpret_cast(AniGetDeviceRemindType)}, + ani_native_function {"nativeGetSyncNotificationEnabledWithoutApp", nullptr, + reinterpret_cast(AniGetSyncNotificationEnabledWithoutApp)}, + ani_native_function {"nativeSetSyncNotificationEnabledWithoutApp", nullptr, + reinterpret_cast(AniSetSyncNotificationEnabledWithoutApp)}, +}; + +void AniNotificationManagerRegistryInit(ani_env *env) +{ + ANS_LOGD("StsNotificationManagerRegistryInit call"); + ani_status status = ANI_ERROR; + if (env->ResetError() != ANI_OK) { + ANS_LOGD("ResetError failed"); + } + ani_namespace ns; + status = env->FindNamespace("L@ohos/notificationManager/notificationManager;", &ns); + if (status != ANI_OK) { + ANS_LOGE("FindNamespace notificationManager failed status : %{public}d", status); + return; + } + status = env->Namespace_BindNativeFunctions(ns, kitManagerFunctions.data(), kitManagerFunctions.size()); + if (status != ANI_OK) { + ANS_LOGD("Namespace_BindNativeFunctions failed status : %{public}d", status); + } + if (env->ResetError() != ANI_OK) { + ANS_LOGD("ResetError failed"); + } + ANS_LOGD("StsNotificationManagerRegistryInit end"); +} +} // namespace NotificationManagerSts +} // namespace OHOS + +extern "C" { +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + ANS_LOGD("ANI_Constructor"); + ani_env *env = nullptr; + ani_status status = ANI_ERROR; + status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + ANS_LOGE("GetEnv failed status : %{public}d", status); + return ANI_NOT_FOUND; + } + + OHOS::NotificationManagerSts::AniNotificationManagerRegistryInit(env); + *result = ANI_VERSION_1; + ANS_LOGD("ANI_Constructor finish"); + return ANI_OK; +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba521c2dc6bbd809d11a3c9f535f9c6e9513c2e4 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2025 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 "ani_notification_enable.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_boolean AniIsNotificationEnabled(ani_env *env) +{ + ANS_LOGD("AniIsNotificationEnabled call"); + bool allowed = false; + int returncode = Notification::NotificationHelper::IsAllowedNotifySelf(allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsNotificationEnabled -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniIsNotificationEnabled end"); + return NotificationSts::BoolToAniBoolean(allowed); +} + +ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_double userId) +{ + ANS_LOGD("AniIsNotificationEnabledWithId call"); + bool allowed = false; + int returncode = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsNotificationEnabledWithId -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniIsNotificationEnabledWithId end"); + return NotificationSts::BoolToAniBoolean(allowed); +} + +ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bundleOption) +{ + ANS_LOGD("AniIsNotificationEnabledWithBundleOption call"); + int returncode = ERR_OK; + bool allowed = false; + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + returncode = Notification::NotificationHelper::IsAllowedNotify(option, allowed); + } else { + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return ANI_FALSE; + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsNotificationEnabledWithBundleOption -> error, errorCode: %{public}d", externalCode); + return ANI_FALSE; + } + ANS_LOGD("AniIsNotificationEnabledWithBundleOption end"); + return NotificationSts::BoolToAniBoolean(allowed); +} + +void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean enable) +{ + ANS_LOGD("AniSetNotificationEnable call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return ; + } + std::string deviceId {""}; + int returncode = Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(option, deviceId, + NotificationSts::AniBooleanToBool(enable)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetNotificationEnable -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniSetNotificationEnable end"); +} + +ani_object AniGetAllNotificationEnabledBundles(ani_env *env) +{ + ANS_LOGD("AniGetAllNotificationEnabledBundles call"); + std::vector bundleOptions = {}; + int returncode = Notification::NotificationHelper::GetAllNotificationEnabledBundles(bundleOptions); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniGetAllNotificationEnabledBundles -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return nullptr; + } + ani_object arrayBundles = NotificationSts::GetAniArrayBundleOption(env, bundleOptions); + if (arrayBundles == nullptr) { + ANS_LOGE("GetAniArrayBundleOption filed,arrayBundles is nullptr"); + NotificationSts::ThrowStsErroWithMsg(env, "GetAniArrayBundleOption ERROR_INTERNAL_ERROR"); + return nullptr; + } + return arrayBundles; +} + +ani_boolean AniIsNotificationEnabledSync(ani_env *env) +{ + ANS_LOGD("AniIsNotificationEnabledSync call"); + bool allowed = false; + int returncode = Notification::NotificationHelper::IsAllowedNotifySelf(allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniIsNotificationEnabledSync -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return NotificationSts::BoolToAniBoolean(false); + } + return NotificationSts::BoolToAniBoolean(allowed); +} + +ani_boolean AniGetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId) +{ + ANS_LOGD("AniGetSyncNotificationEnabledWithoutApp call"); + bool enabled = false; + int returncode = Notification::NotificationHelper::GetSyncNotificationEnabledWithoutApp( + static_cast(userId), enabled); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniGetSyncNotificationEnabledWithoutApp -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return NotificationSts::BoolToAniBoolean(false); + } + ANS_LOGD("End success, enabled: %{public}d, returncode: %{public}d", enabled, externalCode); + return NotificationSts::BoolToAniBoolean(enabled); +} + +void AniSetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId, ani_boolean enabled) +{ + ANS_LOGD("AniSetSyncNotificationEnabledWithoutApp call,enable : %{public}d", enabled); + int returncode = Notification::NotificationHelper::SetSyncNotificationEnabledWithoutApp( + static_cast(userId), NotificationSts::AniBooleanToBool(enabled)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniSetSyncNotificationEnabledWithoutApp -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniSetSyncNotificationEnabledWithoutApp end"); +} + +void AniDisableNotificationFeature(ani_env *env, ani_boolean disabled, ani_object bundleList) +{ + ANS_LOGD("AniDisableNotificationFeature enter"); + std::vector bundleListStd; + if (!NotificationSts::GetStringArrayByAniObj(env, bundleList, bundleListStd)) { + std::string msg = "Invalid bundleList: must be an array of strings."; + ANS_LOGE("GetStringArrayByAniObj failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return; + } + Notification::NotificationDisable param; + param.SetDisabled(NotificationSts::AniBooleanToBool(disabled)); + param.SetBundleList(bundleListStd); + + int returncode = ERR_OK; + returncode = Notification::NotificationHelper::DisableNotificationFeature(param); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniDisableNotificationFeature error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_on.cpp b/frameworks/ets/ani/src/manager/ani_on.cpp new file mode 100755 index 0000000000000000000000000000000000000000..8d4da2c647407f2a08a84dfccce730c0254e44fd --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_on.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2025 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 "ani_on.h" +#include "ans_log_wrapper.h" +#include "sts_common.h" +#include "sts_throw_erro.h" +#include "sts_request.h" +#include "ani_push_callback.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" +#include "notification_helper.h" +#include "inner_errors.h" + +constexpr const char* TYPE_STRING = "checkNotification"; +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; + +bool CheckCallerIsSystemApp() +{ + auto selfToken = IPCSkeleton::GetSelfTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken)) { + ANS_LOGE("current app is not system app, not allow."); + return false; + } + return true; +} + +ani_int AniOn(ani_env *env, ani_string type, ani_fn_object fn, ani_object checkRequestObj) +{ + ANS_LOGD("enter"); +#ifdef ANS_FEATURE_LIVEVIEW_LOCAL_LIVEVIEW + std::string typeStr = ""; + ani_status status = OHOS::NotificationSts::GetStringByAniString(env, type, typeStr); + if (status != ANI_OK || typeStr.compare(TYPE_STRING)) { + ANS_LOGE("InvalidParam 'type'"); + int32_t errCode = OHOS::Notification::ERROR_PARAM_INVALID; + OHOS::NotificationSts::ThrowStsErrorWithInvalidParam(env); + return errCode; + } + if (OHOS::NotificationSts::IsUndefine(env, checkRequestObj)) { + ANS_LOGI("Old function param, don't need register."); + return ERR_OK; + } + sptr checkRequest = new NotificationCheckRequest(); + if (!OHOS::NotificationSts::UnWarpNotificationCheckRequest(env, checkRequestObj, checkRequest)) { + ANS_LOGE("InvalidParam 'checkRequest'"); + int32_t errCode = OHOS::Notification::ERROR_PARAM_INVALID; + OHOS::NotificationSts::ThrowStsErrorWithInvalidParam(env); + return errCode; + } + if (!CheckCallerIsSystemApp()) { + OHOS::NotificationSts::ThrowStsErrorWithCode(env, ERROR_NOT_SYSTEM_APP); + return ERROR_NOT_SYSTEM_APP; + } + + sptr stsPushCallBack_ = new (std::nothrow) StsPushCallBack(env); + if (stsPushCallBack_ == nullptr) { + ANS_LOGE("new stsPushCallBack_ failed"); + OHOS::NotificationSts::ThrowStsErrorWithCode(env, ERROR_INTERNAL_ERROR); + return ERROR_INTERNAL_ERROR; + } + NotificationConstant::SlotType outSlotType = checkRequest->GetSlotType(); + stsPushCallBack_->SetJsPushCallBackObject(env, outSlotType, fn); + auto result = NotificationHelper::RegisterPushCallback(stsPushCallBack_->AsObject(), checkRequest); + if (result != ERR_OK) { + int32_t externalCode = ERR_OK ? ERR_OK : CJSystemapi::Notification::ErrorToExternal(result); + ANS_LOGE("Register failed, result is %{public}d", externalCode); + OHOS::NotificationSts::ThrowStsErrorWithCode(env, externalCode); + return externalCode; + } + ANS_LOGD("done"); + return result; +#else + int32_t errCode = OHOS::Notification::ERROR_SYSTEM_CAP_ERROR; + OHOS::NotificationSts::ThrowStsErrorWithCode(env, errCode); + return errCode; +#endif +} + +ani_int AniOff(ani_env *env, ani_string type, ani_fn_object fn) +{ + ANS_LOGD("enter"); +#ifdef ANS_FEATURE_LIVEVIEW_LOCAL_LIVEVIEW + std::string typeStr = ""; + ani_status status = OHOS::NotificationSts::GetStringByAniString(env, type, typeStr); + if (status != ANI_OK || typeStr.compare(TYPE_STRING)) { + ANS_LOGE("InvalidParam 'type'"); + int32_t errCode = OHOS::Notification::ERROR_PARAM_INVALID; + OHOS::NotificationSts::ThrowStsErrorWithInvalidParam(env); + return errCode; + } + if (!CheckCallerIsSystemApp()) { + OHOS::NotificationSts::ThrowStsErrorWithCode(env, ERROR_NOT_SYSTEM_APP); + return ERROR_NOT_SYSTEM_APP; + } + if (!OHOS::NotificationSts::IsUndefine(env, fn)) { + int32_t errCode = OHOS::Notification::ERROR_PARAM_INVALID; + OHOS::NotificationSts::ThrowStsErrorWithInvalidParam(env); + return errCode; + } + int32_t ret = NotificationHelper::UnregisterPushCallback(); + ANS_LOGD("done. ret %{public}d", ret); + return ERR_OK; +#else + int32_t errCode = OHOS::Notification::ERROR_SYSTEM_CAP_ERROR; + OHOS::NotificationSts::ThrowStsErrorWithCode(env, errCode); + return errCode; +#endif +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_open_settings.cpp b/frameworks/ets/ani/src/manager/ani_open_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..962e28e777d05847e7d45c3f18981a5cf92df7d4 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_open_settings.cpp @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2025 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 "ani_open_settings.h" + +#include "ans_log_wrapper.h" +#include "sts_error_utils.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "ani_common_util.h" +#include "sts_throw_erro.h" +#include "ani_ans_dialog_callback.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; +static std::atomic isExist = false; +const int32_t ERR__INVALID_WANT = 1011; +bool GetOpenSettingsInfo(ani_env *env, ani_object content, std::shared_ptr &info) +{ + ANS_LOGD("enter"); + + ani_status status = ANI_OK; + ani_boolean stageMode = ANI_FALSE; + status = OHOS::AbilityRuntime::IsStageContext(env, content, stageMode); + ANS_LOGD("status %{public}d, stageMode %{public}d", status, stageMode); + if (ANI_OK != status || stageMode != ANI_TRUE) { + ANS_LOGE("Only support stage mode"); + std::string msg = "Incorrect parameter types.Only support stage mode."; + ANS_LOGE("sts GetOpenSettingsInfo ERROR_PARAM_INVALID"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return false; + } + info->context = OHOS::AbilityRuntime::GetStageModeContext(env, content); + return true; +} + +bool CreateUiExtCallback(ani_env *env, std::shared_ptr& uiExtCallback, + Ace::ModalUIExtensionCallbacks& uiExtensionCallbacks, std::shared_ptr &info, + std::shared_ptr& abilityContext, std::string &bundleName) +{ + if (!uiExtCallback->Init(env, info, StsAsyncCompleteCallbackOpenSettings)) { + ANS_LOGE("error"); + info->errorCode = OHOS::Notification::ERROR_INTERNAL_ERROR; + StsAsyncCompleteCallbackOpenSettings(env, info); + return false; + } + uiExtCallback->SetAbilityContext(abilityContext); + uiExtCallback->SetBundleName(bundleName); + uiExtensionCallbacks = { + .onRelease = + std::bind(&SettingsModalExtensionCallback::OnRelease, uiExtCallback, std::placeholders::_1), + .onResult = std::bind(&SettingsModalExtensionCallback::OnResult, uiExtCallback, + std::placeholders::_1, std::placeholders::_2), + .onReceive = + std::bind(&SettingsModalExtensionCallback::OnReceive, uiExtCallback, std::placeholders::_1), + .onError = std::bind(&SettingsModalExtensionCallback::OnError, uiExtCallback, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), + .onRemoteReady = + std::bind(&SettingsModalExtensionCallback::OnRemoteReady, uiExtCallback, std::placeholders::_1), + .onDestroy = std::bind(&SettingsModalExtensionCallback::OnDestroy, uiExtCallback), + }; + return true; +} + +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName, + ani_env *env, std::shared_ptr &info) +{ + if (context == nullptr) { + ANS_LOGE("Get context failed"); + return false; + } + + std::shared_ptr abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (abilityContext == nullptr) { + ANS_LOGE("abilityContext is null"); + return false; + } + auto uiContent = abilityContext->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return false; + } + + AAFwk::Want want; + std::string targetBundleName = "com.ohos.sceneboard"; + std::string targetAbilityName = "NotificationManangerUIExtensionAbility"; + want.SetElementName(targetBundleName, targetAbilityName); + + std::string typeKey = "ability.want.params.uiExtensionType"; + std::string typeValue = "sys/commonUI"; + want.SetParam(typeKey, typeValue); + + auto uiExtCallback = std::make_shared(); + Ace::ModalUIExtensionCallbacks uiExtensionCallbacks; + if (!CreateUiExtCallback(env, uiExtCallback, uiExtensionCallbacks, info, abilityContext, + bundleName)) { + ANS_LOGE("CreateUiExtCallback fail"); + return false; + } + + Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + ANS_LOGI("Create end, sessionId: %{public}d", sessionId); + if (sessionId == 0) { + ANS_LOGE("Create component failed, sessionId is 0"); + return false; + } + uiExtCallback->SetSessionId(sessionId); + return true; +} + +void StsAsyncCompleteCallbackOpenSettings(ani_env *env, std::shared_ptr info) +{ + ANS_LOGD("enter"); + if (env == nullptr) { + ANS_LOGD("env is null"); + return; + } + ani_status status; + int32_t errorCode = ERR_OK; + if (info->errorCode == OHOS::Notification::ERROR_SETTING_WINDOW_EXIST) { + errorCode = OHOS::Notification::ERROR_SETTING_WINDOW_EXIST; + } else if (info->errorCode == ERR__INVALID_WANT) { + errorCode = ERR__INVALID_WANT; + } else { + errorCode = info->errorCode == + ERR_OK ? ERR_OK : CJSystemapi::Notification::ErrorToExternal(info->errorCode); + } + + if (errorCode == ERR_OK) { + ANS_LOGD("Resolve. errorCode %{public}d", errorCode); + ani_object ret = OHOS::AppExecFwk::createInt(env, errorCode); + if (ret == nullptr) { + ANS_LOGD("createInt faild"); + NotificationSts::ThrowStsErroWithMsg(env, ""); + return; + } + if (ANI_OK != (status = env->PromiseResolver_Resolve(info->resolver, static_cast(ret)))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + NotificationSts::ThrowStsErroWithMsg(env, ""); + } + } else { + std::string errMsg = OHOS::NotificationSts::FindAnsErrMsg(errorCode); + ANS_LOGD("reject. errorCode %{public}d errMsg %{public}s", errorCode, errMsg.c_str()); + ani_error rejection = static_cast(OHOS::AbilityRuntime::CreateStsError(env, errorCode, errMsg)); + if (ANI_OK != (status = env->PromiseResolver_Reject(info->resolver, rejection))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + NotificationSts::ThrowStsErroWithMsg(env, ""); + } + } +} + +ani_object AniOpenNotificationSettings(ani_env *env, ani_object content) +{ + ANS_LOGD("sts AniOpenNotificationSettings call"); + std::shared_ptr info = std::make_shared(); + if (!GetOpenSettingsInfo(env, content, info)) { + ANS_LOGE("sts AniOpenNotificationSettings GetOpenSettingsInfo fail"); + return nullptr; + } + if (info->context == nullptr) { + ANS_LOGE("sts AniOpenNotificationSettings context is null"); + NotificationSts::ThrowStsErroWithMsg(env, ""); + return nullptr; + } + std::string bundleName {""}; + if (isExist.exchange(true)) { + ANS_LOGE("sts AniOpenNotificationSettings ERROR_SETTING_WINDOW_EXIST"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_SETTING_WINDOW_EXIST, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_SETTING_WINDOW_EXIST)); + return nullptr; + } + ani_object aniPromise {}; + ani_resolver aniResolver {}; + if (ANI_OK != env->Promise_New(&aniResolver, &aniPromise)) { + ANS_LOGD("Promise_New faild"); + return nullptr; + } + info->resolver = aniResolver; + bool success = CreateSettingsUIExtension(info->context, bundleName, env, info); + if (success) { + info->errorCode = OHOS::Notification::ERR_ANS_DIALOG_POP_SUCCEEDED; + } else { + info->errorCode = OHOS::Notification::ERROR_INTERNAL_ERROR; + } + if (info->errorCode != ERR_ANS_DIALOG_POP_SUCCEEDED) { + ANS_LOGE("error, code is %{public}d.", info->errorCode); + StsAsyncCompleteCallbackOpenSettings(env, info); + isExist.store(false); + return nullptr; + } + ANS_LOGD("sts AniOpenNotificationSettings end"); + + return aniPromise; +} + +SettingsModalExtensionCallback::SettingsModalExtensionCallback() +{} + +SettingsModalExtensionCallback::~SettingsModalExtensionCallback() +{} + +bool SettingsModalExtensionCallback::Init(ani_env *env, std::shared_ptr info, + StsSettingsModalExtensionCallbackComplete *complete) +{ + if (env == nullptr || info == nullptr || complete == nullptr) { + ANS_LOGE("invalid data"); + return false; + } + ani_status status = ANI_OK; + if ((status = env->GetVM(&vm_)) != ANI_OK) { + ANS_LOGD("GetVM faild. status %{public}d", status); + return false; + } + info_ = info; + complete_ = complete; + return true; +} + +void SettingsModalExtensionCallback::ProcessStatusChanged(int32_t code, bool isAsync) +{ + ANS_LOGD("enter"); + if (vm_ == nullptr || info_ == nullptr || complete_ == nullptr) { + ANS_LOGE("invalid data"); + AnsDialogHostClient::Destroy(); + return; + } + info_->errorCode = code; + + ani_env* env; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + if (isAsync) { + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env); + } else { + aniResult = vm_->GetEnv(ANI_VERSION_1, &env); + } + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + if (complete_) { + complete_(env, info_); + } + if (isAsync && (aniResult = vm_->DetachCurrentThread()) != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } +} + +/* + * when UIExtensionAbility use terminateSelfWithResult + */ +void SettingsModalExtensionCallback::OnResult(int32_t resultCode, const AAFwk::Want& result) +{ + ANS_LOGD("OnResult"); +} + +/* + * when UIExtensionAbility send message to UIExtensionComponent + */ +void SettingsModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) +{ + ANS_LOGD("OnReceive"); +} + +/* + * when UIExtensionAbility disconnect or use terminate or process die + * releaseCode is 0 when process normal exit + */ +void SettingsModalExtensionCallback::OnRelease(int32_t releaseCode) +{ + ANS_LOGD("OnRelease"); + ReleaseOrErrorHandle(releaseCode); +} + +/* + * when UIExtensionComponent init or turn to background or destroy UIExtensionAbility occur error + */ +void SettingsModalExtensionCallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ANS_LOGE("OnError, code = %{public}d,name = %{public}s, message = %{public}s", code, name.c_str(), message.c_str()); + ReleaseOrErrorHandle(code); + ProcessStatusChanged(code, false); +} + +/* + * when UIExtensionComponent connect to UIExtensionAbility, ModalUIExtensionProxy will init, + * UIExtensionComponent can send message to UIExtensionAbility by ModalUIExtensionProxy + */ +void SettingsModalExtensionCallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ANS_LOGI("OnRemoteReady"); + ProcessStatusChanged(0, true); +} + +/* + * when UIExtensionComponent destructed + */ +void SettingsModalExtensionCallback::OnDestroy() +{ + ANS_LOGI("OnDestroy"); + isExist.store(false); +} + + +void SettingsModalExtensionCallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void SettingsModalExtensionCallback::SetBundleName(std::string bundleName) +{ + this->bundleName_ = bundleName; +} + +void SettingsModalExtensionCallback::SetAbilityContext( + std::shared_ptr abilityContext) +{ + this->abilityContext_ = abilityContext; +} + +void SettingsModalExtensionCallback::ReleaseOrErrorHandle(int32_t code) +{ + ANS_LOGD("ReleaseOrErrorHandle start"); + Ace::UIContent* uiContent = this->abilityContext_->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return; + } + uiContent->CloseModalUIExtension(this->sessionId_); + ANS_LOGD("ReleaseOrErrorHandle end"); + return; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_publish.cpp b/frameworks/ets/ani/src/manager/ani_publish.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba7f1f4f8889111e2e523c072dcc0a5ee0c3222a --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025 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 "ani_publish.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_bundle_option.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_request.h" +#include "notification_request.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; + +void AniPublish(ani_env *env, ani_object obj) +{ + ANS_LOGD("AniPublish call"); + std::shared_ptr notificationRequest = std::make_shared(); + if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { + ANS_LOGE("UnWarpNotificationRequest failed"); + NotificationSts::ThrowStsErroWithMsg(env, "AniPublish ERROR_INTERNAL_ERROR"); + return; + } + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniPublish end"); +} + +void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId) +{ + ANS_LOGD("AniPublishWithId start"); + //NotificationRequest request; + std::shared_ptr notificationRequest = std::make_shared(); + if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishWithId ERROR_INTERNAL_ERROR"); + return; + } + notificationRequest->SetOwnerUserId(static_cast(userId)); + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniPublishWithId error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniPublishWithId end"); +} + +void AniPublishAsBundle(ani_env *env, ani_object request, ani_string representativeBundle, ani_double userId) +{ + ANS_LOGD("AniPublishAsBundle enter"); + std::string bundleStr; + if (ANI_OK != NotificationSts::GetStringByAniString(env, representativeBundle, bundleStr)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishAsBundle ERROR_INTERNAL_ERROR"); + return; + } + + std::shared_ptr notificationRequest = std::make_shared(); + if (NotificationSts::UnWarpNotificationRequest(env, request, notificationRequest) != ANI_OK) { + ANS_LOGE("AniPublishAsBundle failed"); + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishAsBundle ERROR_INTERNAL_ERROR"); + return; + } + notificationRequest->SetOwnerUserId(static_cast(userId)); + notificationRequest->SetOwnerBundleName(bundleStr); + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniPublishAsBundle: PublishNotificationerror, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + + ANS_LOGD("AniPublishAsBundle end"); +} + +void AniPublishAsBundleWithBundleOption(ani_env *env, ani_object representativeBundle, ani_object request) +{ + ANS_LOGE("AniPublishAsBundleWithBundleOption enter"); + std::shared_ptr notificationRequest = std::make_shared(); + if (NotificationSts::UnWarpNotificationRequest(env, request, notificationRequest) != ANI_OK) { + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishAsBundleWithBundleOption ERROR_INTERNAL_ERROR"); + return; + } + + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, representativeBundle, option) != true) { + NotificationSts::ThrowStsErroWithMsg(env, "UnwrapBundleOption ERROR_INTERNAL_ERROR"); + return; + } + + ANS_LOGD("AniPublishAsBundleWithBundleOption: bundle %{public}s uid: %{public}d", + option.GetBundleName().c_str(), option.GetUid()); + notificationRequest->SetOwnerBundleName(option.GetBundleName()); + notificationRequest->SetOwnerUid(option.GetUid()); + notificationRequest->SetIsAgentNotification(true); + + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniPublishAsBundleWithBundleOption error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniPublishAsBundleWithBundleOption end"); +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_push_callback.cpp b/frameworks/ets/ani/src/manager/ani_push_callback.cpp new file mode 100755 index 0000000000000000000000000000000000000000..b20c33fbd4d7d51d4bf3db96f6834e3b1d4ebe3a --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_push_callback.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2025 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 "ani_push_callback.h" +#include "ans_log_wrapper.h" +#include "sts_notification_manager.h" +#include "sts_common.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; +using namespace OHOS::NotificationSts; +StsPushCallBack::StsPushCallBack(ani_env *env) +{ + if (env == nullptr || env->GetVM(&vm_) != ANI_OK) { + ANS_LOGE("InvalidParam 'env'"); + } +} + +StsPushCallBack::~StsPushCallBack() +{ +} + +int32_t StsPushCallBack::OnCheckNotification( + const std::string ¬ificationData, const std::shared_ptr &pushCallBackParam) +{ + ANS_LOGD("enter"); + std::lock_guard l(mutexlock); + if (vm_ == nullptr || pushCallBackParam == nullptr) { + ANS_LOGE("InvalidParam"); + return ERR_INVALID_STATE; + } + ani_env* env; + ani_status aniResult = ANI_ERROR; + if (ANI_OK != (aniResult = vm_->GetEnv(ANI_VERSION_1, &env))) { + ANS_LOGD("GetEnv error. result: %{public}d.", aniResult); + return ERR_INVALID_STATE; + } + return CheckNotification(env, notificationData, pushCallBackParam); +} + +void StsPushCallBack::SetJsPushCallBackObject( + ani_env *env, NotificationConstant::SlotType slotType, ani_ref pushCallBackObject) +{ + ANS_LOGD("enter"); + if (env == nullptr || pushCallBackObject == nullptr) { + ANS_LOGE("InvalidParam"); + return; + } + ani_ref pushCheckObject; + ani_status status = ANI_OK; + if (ANI_OK != (status = env->GlobalReference_Create(pushCallBackObject, &pushCheckObject))) { + ANS_LOGE("GlobalReference_Create pushCallBackObject faild. status %{public}d", status); + return; + } + pushCallBackObjects_.insert_or_assign(slotType, pushCheckObject); +} + +void StsPushCallBack::HandleCheckCallback( + ani_env *env, ani_fn_object fn, ani_object value, const std::shared_ptr &pushCallBackParam) +{ + ANS_LOGD("enter"); + if (env == nullptr || fn == nullptr || value == nullptr || pushCallBackParam == nullptr) { + ANS_LOGE("pushCallBackObjects is nullptr"); + return; + } + std::vector vec; + vec.push_back(value); + ani_ref funcResult; + ani_status status = ANI_OK; + if (ANI_OK != (status = env->FunctionalObject_Call(fn, vec.size(), vec.data(), &funcResult))) { + ANS_LOGE("FunctionalObject_Call faild. status %{public}d", status); + return; + } + ResultParam result; + if (!WarpFunctionResult(env, static_cast(funcResult), result)) { + ANS_LOGE("WarpFunctionResult faild"); + return; + } + std::unique_lock uniqueLock(pushCallBackParam->callBackMutex); + pushCallBackParam->result = result.code; + pushCallBackParam->ready = true; + pushCallBackParam->callBackCondition.notify_all(); + ANS_LOGD("done"); +} + +int32_t StsPushCallBack::CheckNotification( + ani_env *env, + const std::string ¬ificationData, + const std::shared_ptr &pushCallBackParam) +{ + ANS_LOGD("enter"); + auto checkInfo = std::make_shared(); + checkInfo->ConvertJsonStringToValue(notificationData); + NotificationConstant::SlotType outSlotType = static_cast(checkInfo->GetSlotType()); + if (pushCallBackObjects_.find(outSlotType) == pushCallBackObjects_.end()) { + ANS_LOGE("pushCallBackObjects is nullptr"); + return ERR_INVALID_STATE; + } + ani_object checkInfoObj; + if (!WarpNotificationCheckInfo(env, checkInfo, checkInfoObj) || checkInfoObj == nullptr) { + ANS_LOGE("WarpNotificationCheckInfo faild"); + return ERR_INVALID_STATE; + } + HandleCheckCallback( + env, static_cast(pushCallBackObjects_[outSlotType]), checkInfoObj, pushCallBackParam); + return ERR_OK; +} + +bool StsPushCallBack::WarpFunctionResult(ani_env *env, ani_object obj, ResultParam &result) +{ + ANS_LOGD("enter"); + if (env == nullptr || obj == nullptr) return false; + ani_status status = ANI_OK; + ani_double code; + ani_ref msg; + std::string message = ""; + if (ANI_OK != (status = env->Object_GetPropertyByName_Double(obj, "code", &code))) { + ANS_LOGE("WarpFunctionResult. code faild. status %{public}d", status); + return false; + } + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(obj, "message", &msg))) { + ANS_LOGE("WarpFunctionResult. message faild. status %{public}d", status); + return false; + } + if (ANI_OK != (status = GetStringByAniString(env, static_cast(msg), message))) { + ANS_LOGE("GetStringByAniString faild. status %{public}d", status); + return false; + } + result.code = code; + result.msg = message; + ANS_LOGD("WarpFunctionResult: code %{public}d message %{public}s", result.code, result.msg.c_str()); + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_remove_group.cpp b/frameworks/ets/ani/src/manager/ani_remove_group.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b916af19792811694c73495821becb706b13e46b --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_remove_group.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 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 "ani_remove_group.h" + +#include "ans_log_wrapper.h" +#include "sts_error_utils.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "sts_common.h" +#include "sts_throw_erro.h" +#include "sts_bundle_option.h" +#include "notification_helper.h" + +namespace OHOS { +namespace NotificationManagerSts { + +void AniRemoveGroupByBundle(ani_env *env, ani_object bundleOption, ani_string groupName) +{ + ANS_LOGD("AniRemoveGroupByBundle call"); + OHOS::Notification::NotificationBundleOption option; + if (!OHOS::NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "sts AniRemoveGroupByBundle ERROR_INTERNAL_ERROR"); + return ; + } + std::string groupNameStr = ""; + ani_status status = NotificationSts::GetStringByAniString(env, groupName, groupNameStr); + if (status != ANI_OK) { + NotificationSts::ThrowStsErroWithMsg(env, "sts AniRemoveGroupByBundle ERROR_INTERNAL_ERROR"); + return ; + } + int returncode = OHOS::Notification::NotificationHelper::RemoveGroupByBundle(option, groupNameStr); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + ANS_LOGE("AniRemoveGroupByBundle -> error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniRemoveGroupByBundle end"); +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_request_enable.cpp b/frameworks/ets/ani/src/manager/ani_request_enable.cpp new file mode 100755 index 0000000000000000000000000000000000000000..910cac486064a992279034197f35b2b263ac4eb1 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_request_enable.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2025 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 "ani_request_enable.h" + +#include "ani_ans_dialog_callback.h" +#include "ans_log_wrapper.h" +#include "sts_error_utils.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "ani_common_util.h" +#include "sts_throw_erro.h" + +namespace OHOS { +namespace NotificationManagerSts { +using namespace OHOS::Notification; +bool GetEnableNotificationInfo(ani_env *env, ani_object content, std::shared_ptr &info) +{ + ANS_LOGD("enter"); + if (content == nullptr) { + ANS_LOGD("content is null"); + return true; + } + ani_status status = ANI_OK; + ani_boolean stageMode = ANI_FALSE; + status = OHOS::AbilityRuntime::IsStageContext(env, content, stageMode); + ANS_LOGD("status %{public}d, stageMode %{public}d", status, stageMode); + if (ANI_OK != status || stageMode != ANI_TRUE) { + ANS_LOGE("Only support stage mode"); + std::string msg = "Incorrect parameter types.Only support stage mode."; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return false; + } + info->stageMode = true; + info->context = OHOS::AbilityRuntime::GetStageModeContext(env, content); + if (info->context != nullptr) { + info->callerToken = info->context->GetToken(); + } + return true; +} + +void RequestEnableExecute(std::shared_ptr &info) +{ + ANS_LOGD("enter"); + sptr client = nullptr; + AnsDialogHostClient::CreateIfNullptr(client); + if (client == nullptr) { + ANS_LOGD("create client fail"); + info->errorCode = ERROR_INTERNAL_ERROR; + return; + } + if (info->context != nullptr) { + ANS_LOGD("stage mode"); + bool canPop = false; + std::string bundleName = ""; + ErrCode errCode = NotificationHelper::CanPopEnableNotificationDialog(client, canPop, bundleName); + ANS_LOGI("CanPopEnableNotificationDialog result , errCode = %{public}d , canPop = %{public}d", + errCode, canPop); + if (canPop == false) { + info->errorCode = errCode; + return; + } + info->bundleName = bundleName; + } else { + ANS_LOGD("un stage mode"); + std::string deviceId {""}; + info->errorCode = NotificationHelper::RequestEnableNotification(deviceId, client, info->callerToken); + } + ANS_LOGI("ipcCall done, code is %{public}d.", info->errorCode); +} + +void StsAsyncCompleteCallbackRequestEnableNotification(ani_env *env, std::shared_ptr info) +{ + ANS_LOGD("enter"); + if (env == nullptr || info == nullptr) return; + ani_status status; + int32_t errorCode = info->errorCode == + ERR_OK ? ERR_OK : CJSystemapi::Notification::ErrorToExternal(info->errorCode); + if (errorCode == ERR_OK) { + ANS_LOGD("Resolve. errorCode %{public}d", errorCode); + ani_object ret = OHOS::AppExecFwk::createInt(env, errorCode); + if (ret == nullptr) { + ANS_LOGD("createInt faild"); + return; + } + if (ANI_OK != (status = env->PromiseResolver_Resolve(info->resolver, static_cast(ret)))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + } + } else { + std::string errMsg = OHOS::NotificationSts::FindAnsErrMsg(errorCode); + ANS_LOGD("reject. errorCode %{public}d errMsg %{public}s", errorCode, errMsg.c_str()); + ani_error rejection = static_cast(OHOS::AbilityRuntime::CreateStsError(env, errorCode, errMsg)); + if (ANI_OK != (status = env->PromiseResolver_Reject(info->resolver, rejection))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + } + } +} + +bool CreateUIExtension(std::shared_ptr &info) +{ + ANS_LOGD("enter"); + if (info->context == nullptr) { + ANS_LOGE("Get context failed"); + return false; + } + std::shared_ptr abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(info->context); + if (abilityContext == nullptr) { + ANS_LOGE("abilityContext is null"); + return false; + } + auto uiContent = abilityContext->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return false; + } + AAFwk::Want want; + std::string targetBundleName = "com.ohos.notificationdialog"; + std::string targetAbilityName = "EnableNotificationDialog"; + want.SetElementName(targetBundleName, targetAbilityName); + std::string typeKey = "ability.want.params.uiExtensionType"; + std::string typeValue = "sysDialog/common"; + want.SetParam(typeKey, typeValue); + auto uiExtCallback = std::make_shared(); + uiExtCallback->SetAbilityContext(abilityContext); + uiExtCallback->SetBundleName(info->bundleName); + OHOS::Ace::ModalUIExtensionCallbacks uiExtensionCallbacks = { + .onRelease = std::bind(&ModalExtensionCallback::OnRelease, uiExtCallback, std::placeholders::_1), + .onResult = std::bind(&ModalExtensionCallback::OnResult, uiExtCallback, + std::placeholders::_1, std::placeholders::_2), + .onReceive = std::bind(&ModalExtensionCallback::OnReceive, uiExtCallback, std::placeholders::_1), + .onError = std::bind(&ModalExtensionCallback::OnError, uiExtCallback, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), + .onRemoteReady = std::bind(&ModalExtensionCallback::OnRemoteReady, uiExtCallback, std::placeholders::_1), + .onDestroy = std::bind(&ModalExtensionCallback::OnDestroy, uiExtCallback), + }; + OHOS::Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + ANS_LOGI("Create end, sessionId: %{public}d", sessionId); + if (sessionId == 0) { + ANS_LOGE("Create component failed, sessionId is 0"); + return false; + } + uiExtCallback->SetSessionId(sessionId); + return true; +} + +void RequestEnableComplete(ani_env *env, std::shared_ptr &info) +{ + ANS_LOGD("enter"); + if (!info->bundleName.empty()) { + bool success = CreateUIExtension(info); + if (success) { + info->errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; + } else { + info->errorCode = ERROR_INTERNAL_ERROR; + NotificationHelper::RemoveEnableNotificationDialog(); + } + } + if (info->errorCode != ERR_ANS_DIALOG_POP_SUCCEEDED) { + ANS_LOGE("error, code is %{public}d.", info->errorCode); + StsAsyncCompleteCallbackRequestEnableNotification(env, info); + return; + } + // Dialog is popped + auto StsCallback = std::make_unique(); + if (!StsCallback->Init(env, info, StsAsyncCompleteCallbackRequestEnableNotification) || + !AnsDialogHostClient::SetDialogCallbackInterface(std::move(StsCallback)) + ) { + ANS_LOGE("error"); + info->errorCode = ERROR_INTERNAL_ERROR; + StsAsyncCompleteCallbackRequestEnableNotification(env, info); + return; + } +} + +ani_object AniRequestEnableNotification(ani_env *env, ani_object content) +{ + ANS_LOGD("enter"); + std::shared_ptr info = std::make_shared(); + if (!GetEnableNotificationInfo(env, content, info)) { + ANS_LOGD("GetEnableNotificationInfo"); + return nullptr; + } + ani_object aniPromise {}; + ani_resolver aniResolver {}; + if (ANI_OK != env->Promise_New(&aniResolver, &aniPromise)) { + ANS_LOGD("Promise_New faild"); + return nullptr; + } + info->resolver = aniResolver; + RequestEnableExecute(info); + RequestEnableComplete(env, info); + ANS_LOGD("RequestEnableNotification done"); + return aniPromise; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8790b0a3b2e5b837c91ddfae05963ce4bfceefea --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2025 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 "ani_slot.h" + +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_error_utils.h" +#include "sts_common.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "sts_bundle_option.h" +#include "sts_slot.h" +#include "notification_slot.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationManagerSts { +namespace { +constexpr int32_t RETURN_EXCEPTION_VALUE = -1; +} // namespace + +ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) +{ + ANS_LOGD("sts GetSlotsByBundle enter"); + int returncode = CJSystemapi::Notification::SUCCESS_CODE; + std::vector> slots; + BundleOption option; + if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + returncode = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); + } else { + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return nullptr; + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("sts GetSlotsByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return nullptr; + } + ani_object outAniObj; + if (!NotificationSts::WrapNotificationSlotArray(env, slots, outAniObj)) { + NotificationSts::ThrowStsErroWithMsg(env, "GetSlotsByBundle:failed to WrapNotificationSlotArray"); + return nullptr; + } + ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", externalCode); + return outAniObj; +} + +void AniAddSlots(ani_env *env, ani_object notificationSlotArrayObj) +{ + ANS_LOGD("AniAddSlots enter"); + std::vector slots; + if (!NotificationSts::UnwrapNotificationSlotArrayByAniObj(env, notificationSlotArrayObj, slots)) { + ANS_LOGE("UnwrapNotificationSlotArrayByAniObj failed"); + NotificationSts::ThrowStsErroWithMsg(env, "sts AddSlots ERROR_INTERNAL_ERROR"); + return; + } + int returncode = Notification::NotificationHelper::AddNotificationSlots(slots); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniAddSlots -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniAddSlots leave"); +} + +void AniAddSlotByNotificationSlot(ani_env *env, ani_object notificationSlotObj) +{ + ANS_LOGD("AniAddSlotByNotificationSlot enter"); + int returncode = CJSystemapi::Notification::SUCCESS_CODE; + Notification::NotificationSlot slot; + if (NotificationSts::UnwrapNotificationSlot(env, notificationSlotObj, slot)) { + returncode = Notification::NotificationHelper::AddNotificationSlot(slot); + } else { + NotificationSts::ThrowStsErroWithMsg(env, "sts AddSlot ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("sts AddSlot error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniAddSlotByNotificationSlot leave"); +} + +void AniAddSlotBySlotType(ani_env *env, ani_enum_item enumObj) +{ + ANS_LOGD("AniAddSlotBySlotType enter"); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, enumObj, slotType)) { + NotificationSts::ThrowStsErroWithMsg(env, "AddSlotByType ERROR_INTERNAL_ERROR"); + return; + } + int returncode = Notification::NotificationHelper::AddSlotByType(slotType); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniAddSlotBySlotType -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + ANS_LOGD("AniAddSlotBySlotType leave"); + return; +} + +ani_object AniGetSlot(ani_env *env, ani_enum_item enumObj) +{ + ANS_LOGD("AniGetSlot enter"); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, enumObj, slotType)) { + ANS_LOGE("SlotTypeEtsToC failed"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlot ERROR_INTERNAL_ERROR"); + return nullptr; + } + sptr slot = nullptr; + int returncode = Notification::NotificationHelper::GetNotificationSlot(slotType, slot); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniGetSlot -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + if (slot == nullptr) { + ANS_LOGD("AniGetSlot -> slot is nullptr"); + AbilityRuntime::ThrowStsError(env, RETURN_EXCEPTION_VALUE, "slot is null"); + return nullptr; + } + ani_object slotObj; + if (!NotificationSts::WrapNotificationSlot(env, slot, slotObj)) { + ANS_LOGE("WrapNotificationSlot faild"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlot ERROR_INTERNAL_ERROR"); + return nullptr; + } + ANS_LOGD("AniGetSlot leave"); + return slotObj; +} + +ani_object AniGetSlots(ani_env *env) +{ + ANS_LOGD("AniGetSlots enter"); + std::vector> slots; + int returncode = Notification::NotificationHelper::GetNotificationSlots(slots); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniGetSlots -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return nullptr; + } + ani_object outAniObj; + if (!NotificationSts::WrapNotificationSlotArray(env, slots, outAniObj)) { + ANS_LOGE("WrapNotificationSlotArray faild"); + NotificationSts::ThrowStsErroWithMsg(env, "AniGetSlots:failed to WrapNotificationSlotArray"); + return nullptr; + } + ANS_LOGD("AniGetSlots leave"); + return outAniObj; +} + +void AniRemoveSlot(ani_env *env, ani_enum_item enumObj) +{ + ANS_LOGD("AniRemoveSlot enter"); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, enumObj, slotType)) { + ANS_LOGE("SlotTypeEtsToC failed"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlot ERROR_INTERNAL_ERROR"); + return; + } + int returncode = Notification::NotificationHelper::RemoveNotificationSlot(slotType); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniRemoveSlot -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniRemoveSlot leave"); +} + +void AniRemoveAllSlots(ani_env *env) +{ + ANS_LOGD("AniRemoveAllSlots enter"); + int returncode = Notification::NotificationHelper::RemoveAllSlots(); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniRemoveAllSlots -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniRemoveAllSlots leave"); +} + +void AniSetSlotByBundle(ani_env *env, ani_object bundleOptionObj, ani_object slotObj) +{ + ANS_LOGD("AniSetSlotByBundle enter"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleOptionObj, option)) { + ANS_LOGE("UnwrapBundleOption failed"); + NotificationSts::ThrowStsErroWithMsg(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); + return; + } + + Notification::NotificationSlot slot; + if (!NotificationSts::UnwrapNotificationSlot(env, slotObj, slot)) { + ANS_LOGE("UnwrapNotificationSlot failed"); + NotificationSts::ThrowStsErroWithMsg(env, "sts SetSlotByBundle ERROR_INTERNAL_ERROR"); + return; + } + + std::vector> slotsVct; + sptr slotPtr = new (std::nothrow) Notification::NotificationSlot(slot); + if (slotPtr == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr"); + NotificationSts::ThrowStsErroWithMsg(env, "sts AniSetSlotByBundle ERROR_INTERNAL_ERROR"); + return; + } + slotsVct.emplace_back(slotPtr); + + int returncode = Notification::NotificationHelper::UpdateNotificationSlots(option, slotsVct); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("sts SetSlotByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniSetSlotByBundle leave"); +} + +ani_double AniGetSlotNumByBundle(ani_env *env, ani_object bundleOption) +{ + ANS_LOGD("AniGetSlotNumByBundle enter"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + ANS_LOGE("UnwrapBundleOption failed"); + NotificationSts::ThrowStsErroWithMsg(env, "AniGetSlotNumByBundle ERROR_INTERNAL_ERROR"); + return RETURN_EXCEPTION_VALUE; + } + uint64_t num = 0; + int returncode = Notification::NotificationHelper::GetNotificationSlotNumAsBundle(option, num); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("sts GetSlotNumByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return RETURN_EXCEPTION_VALUE; + } + ani_double retNum = static_cast(num); + ANS_LOGD("AniGetSlotNumByBundle leave"); + return retNum; +} +void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) +{ + ANS_LOGD("AniSetNotificationEnableSlot enter "); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); + return; + } + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, type, slotType)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); + return; + } + int returncode = 0; + bool isForceControl = false; + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, + NotificationSts::AniBooleanToBool(enable), isForceControl); + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniSetNotificationEnableSlot error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return; + } + ANS_LOGD("AniSetNotificationEnableSlot end"); +} + +void AniSetNotificationEnableSlotWithForce(ani_env *env, + ani_object bundleOption, ani_enum_item type, ani_boolean enable, ani_boolean isForceControl) +{ + ANS_LOGD("AniSetNotificationEnableSlotWithForce enter "); + Notification::NotificationBundleOption option; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!(NotificationSts::SlotTypeEtsToC(env, type, slotType)) + || !(NotificationSts::UnwrapBundleOption(env, bundleOption, option))) { + NotificationSts::ThrowStsErroWithMsg(env, "SetNotificationEnableSlotWithForce ERROR_INTERNAL_ERROR"); + return; + } + int returncode = 0; + + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, + NotificationSts::AniBooleanToBool(enable), NotificationSts::AniBooleanToBool(isForceControl)); + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } +} + +ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type) +{ + ANS_LOGD("IsNotificationSlotEnabled enter"); + Notification::NotificationBundleOption option; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option) + || !NotificationSts::SlotTypeEtsToC(env, type, slotType)) { + NotificationSts::ThrowStsErroWithMsg(env, "IsNotificationSlotEnabled : erro arguments."); + return ANI_FALSE; + } + + bool isEnable = false; + int returncode = Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("IsNotificationSlotEnabled -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + return isEnable ? ANI_TRUE : ANI_FALSE; +} + +ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts getSlotFlagsByBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniGetSlotFlagsByBundle : erro arguments."); + return ANI_FALSE; + } + uint32_t slotFlags = 0; + int returncode = Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniGetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } + return slotFlags; +} + +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj, ani_double slotFlags) +{ + ANS_LOGD("sts setSlotFlagsByBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniSetSlotFlagsByBundle : erro arguments."); + return; + } + int returncode = + Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, static_cast(slotFlags)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("AniSetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + } +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_support_template.cpp b/frameworks/ets/ani/src/manager/ani_support_template.cpp new file mode 100755 index 0000000000000000000000000000000000000000..461787a311d9499426b499443acdceef19fd10f1 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_support_template.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 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 "ani_support_template.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_boolean AniIsSupportTemplate(ani_env* env, ani_string templateName) +{ + ANS_LOGD("AniIsSupportTemplate call"); + std::string templateNameStr; + if (NotificationSts::GetStringByAniString(env, templateName, templateNameStr) != ANI_OK) { + NotificationSts::ThrowStsErroWithMsg(env, "templateName parse failed!"); + return NotificationSts::BoolToAniBoolean(false); + } + + ANS_LOGD("AniIsSupportTemplate by templateName:%{public}s", templateNameStr.c_str()); + bool support = false; + int returncode = Notification::NotificationHelper::IsSupportTemplate(templateNameStr, support); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniIsSupportTemplate -> error, errorCode: %{public}d", externalCode); + return NotificationSts::BoolToAniBoolean(false); + } + ANS_LOGD("AniIsSupportTemplate end, support: %{public}d, returncode: %{public}d", support, externalCode); + return NotificationSts::BoolToAniBoolean(support); +} + +ani_object AniGetDeviceRemindType(ani_env *env) +{ + ANS_LOGD("AniGetDeviceRemindType enter"); + + Notification::NotificationConstant::RemindType remindType = + Notification::NotificationConstant::RemindType::DEVICE_IDLE_REMIND; + int returncode = Notification::NotificationHelper::GetDeviceRemindType(remindType); + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniGetDeviceRemindType error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_enum_item remindTypeItem {}; + if (!NotificationSts::DeviceRemindTypeCToEts(env, remindType, remindTypeItem)) { + NotificationSts::ThrowStsErroWithMsg(env, "AniGetDeviceRemindType:failed to WrapNotificationSlotArray"); + return nullptr; + } + ANS_LOGD("AniGetDeviceRemindType end, ret: %{public}d", externalCode); + return remindTypeItem; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/manager/ani_sync_config.cpp b/frameworks/ets/ani/src/manager/ani_sync_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a05c28f7a8507c08cd5fd2af4ad70e0fb1108a8 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_sync_config.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 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 "ani_sync_config.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_bundle_option.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationManagerSts { +const double RESULT_OK = 0.0; +const double RESULT_FAILED = 1.0; + +ani_double AniSetAdditionalConfig(ani_env *env, ani_string key, ani_string value) +{ + ANS_LOGD("sts setAdditionalConfig call"); + if (env == nullptr || key == nullptr) { + ANS_LOGE("Invalid env or key is null"); + return RESULT_FAILED; + } + std::string keyStr; + if (NotificationSts::GetStringByAniString(env, key, keyStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return RESULT_FAILED; + } + std::string valueStr; + if (NotificationSts::GetStringByAniString(env, value, valueStr) != ANI_OK) { + std::string msg = "Parameter verification failed"; + ANS_LOGE("GetStringByAniString failed. msg: %{public}s", msg.c_str()); + OHOS::AbilityRuntime::ThrowStsError(env, Notification::ERROR_PARAM_INVALID, msg); + return RESULT_FAILED; + } + int returncode = Notification::NotificationHelper::SetAdditionConfig(keyStr, valueStr); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { + ANS_LOGE("setAdditionalConfig -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + return RESULT_FAILED; + } + return RESULT_OK; +} +} // namespace NotificationManagerSts +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26968f75212054c1f282168c47704b7abc5b803d --- /dev/null +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2025 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 "sts_action_button.h" + +#include "sts_common.h" +#include "sts_convert_other.h" +#include "ani_common_want.h" +#include "ans_log_wrapper.h" +#include "sts_user_input.h" + + +namespace OHOS { +namespace NotificationSts { +void GetStsActionButtonByOther(StsActionButton &actionButton) +{ + ANS_LOGD("GetStsActionButtonByOther call"); + actionButton.icon = nullptr; + actionButton.semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + actionButton.autoCreatedReplies = true; + actionButton.mimeTypeOnlyInputs = {}; + actionButton.isContextual = false; + ANS_LOGD("GetStsActionButtonByOther end"); +} +ani_status GetStsActionButtonByWantAgent(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ANS_LOGD("GetStsActionButtonByWantAgent call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("GetStsActionButtonByWantAgent fail, has nullptr"); + return ANI_ERROR; + } + ani_boolean isUndefind = ANI_TRUE; + ani_ref wantAgentRef; + if (ANI_OK != GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) || isUndefind == ANI_TRUE) { + ANS_LOGE("GetStsActionButtonByWantAgent: GetPropertyRef wantAgent failed"); + return ANI_INVALID_ARGS; + } + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + if (wantAgent == nullptr) { + ANS_LOGE("GetStsActionButtonByWantAgent: wantAgent is nullptr"); + return ANI_INVALID_ARGS; + } + actionButton.wantAgent = wantAgent; + ANS_LOGD("GetStsActionButtonByWantAgent end"); + return ANI_OK; +} + +ani_status GetStsActionButtonByWantParams(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ANS_LOGD("GetStsActionButtonByWantParams call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("GetStsActionButtonByWantParams fail, has nullptr"); + return ANI_ERROR; + } + ani_boolean isUndefind = ANI_TRUE; + WantParams wantParams = {}; + ani_ref extrasRef; + if (ANI_OK == GetPropertyRef(env, param, "extras", isUndefind, extrasRef) && isUndefind == ANI_FALSE) { + UnwrapWantParams(env, extrasRef, wantParams); + } else { + ANS_LOGE("GetStsActionButtonByWantParams: GetPropertyRef extras failed"); + return ANI_INVALID_ARGS; + } + std::shared_ptr extras = std::make_shared(wantParams); + actionButton.extras = extras; + ANS_LOGD("GetStsActionButtonByWantParams end"); + return ANI_OK; +} +ani_status GetStsActionButtonByUserInput(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ANS_LOGD("GetStsActionButtonByUserInput call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("GetStsActionButtonByUserInput fail, has nullptr"); + return ANI_ERROR; + } + ani_boolean isUndefind = ANI_TRUE; + std::shared_ptr userInput = nullptr; + ani_ref userInputRef; + if (ANI_OK == GetPropertyRef(env, param, "userInput", isUndefind, userInputRef) && isUndefind == ANI_FALSE) { + UnwrapNotificationUserInput(env, static_cast(userInputRef), userInput); + } else { + ANS_LOGD("GetStsActionButtonByUserInput : GetPropertyRef userInput failed"); + } + if (userInput == nullptr) { + ANS_LOGD("GetStsActionButtonByUserInput : userInput is nullptr"); + userInput = {}; + } + actionButton.userInput = userInput; + ANS_LOGD("GetStsActionButtonByUserInput end"); + return ANI_OK; +} + +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ANS_LOGD("UnwrapNotificationActionButton call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("UnwrapNotificationActionButton fail, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefind = ANI_TRUE; + std::string title; + if ((status = GetPropertyString(env, param, "title", isUndefind, title)) != ANI_OK || isUndefind == ANI_TRUE) { + ANS_LOGE("UnwrapNotificationActionButton : Get title failed"); + return ANI_INVALID_ARGS; + } + actionButton.title = title; + if (ANI_OK != GetStsActionButtonByWantAgent(env, param, actionButton)) { + ANS_LOGE("UnwrapNotificationActionButton : GetStsActionButtonByWantAgent failed"); + return ANI_INVALID_ARGS; + } + if (ANI_OK != GetStsActionButtonByWantParams(env, param, actionButton)) { + ANS_LOGE("UnwrapNotificationActionButton : GetStsActionButtonByWantParams failed"); + return ANI_INVALID_ARGS; + } + GetStsActionButtonByOther(actionButton); + ANS_LOGD("UnwrapNotificationActionButton end"); + return status; +} + +bool SetNotificationActionButtonByRequiredParameter( + ani_env *env, + ani_class iconButtonCls, + ani_object &iconButtonObject, + const std::shared_ptr &actionButton) +{ + ANS_LOGD("SetActionButtonByRequiredParameter call"); + if (env == nullptr || iconButtonCls == nullptr || iconButtonObject == nullptr || actionButton == nullptr) { + ANS_LOGE("SetActionButtonByRequiredParameter fail, has nullptr"); + return ANI_ERROR; + } + ani_string stringValue; + // title: string; + if (ANI_OK != GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { + ANS_LOGE("SetActionButtonByRequiredParameter: Get title failed"); + return false; + } + if (!CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)) { + ANS_LOGE("SetActionButtonByRequiredParameter: Set title failed"); + return false; + } + // wantAgent: WantAgent; + std::shared_ptr agent = actionButton->GetWantAgent(); + if (agent == nullptr) { + ANS_LOGE("SetActionButtonByRequiredParameter:agent is null"); + return false; + } else { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + if (wantAgent == nullptr) { + ANS_LOGE("SetActionButtonByRequiredParameter: wantAgent is nullptr"); + return false; + } + if (!CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)) { + ANS_LOGE("SetActionButtonByRequiredParameter: Set wantAgent failed"); + return false; + } + } + ANS_LOGD("SetActionButtonByRequiredParameter end"); + return true; +} + +void SetNotificationActionButtonByOptionalParameter( + ani_env *env, + ani_class iconButtonCls, + ani_object &iconButtonObject, + const std::shared_ptr &actionButton) +{ + ANS_LOGD("SetActionButtonByOptionalParameter call"); + if (env == nullptr || iconButtonCls == nullptr || iconButtonObject == nullptr || actionButton == nullptr) { + ANS_LOGE("SetActionButtonByOptionalParameter fail, has nullptr"); + return; + } + // extras?: Record + ani_ref extras = WrapWantParams(env, *(actionButton->GetAdditionalData().get())); + if (!CallSetter(env, iconButtonCls, iconButtonObject, "extras", extras)) { + ANS_LOGD("SetActionButtonByOptionalParameter : Set extras failed"); + } + // userInput?: NotificationUserInput + ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); + if (!CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)) { + ANS_LOGD("SetActionButtonByOptionalParameter : Set userInput failed"); + } + ANS_LOGD("SetActionButtonByOptionalParameter end"); +} + +ani_object WrapNotificationActionButton(ani_env* env, + const std::shared_ptr &actionButton) +{ + ANS_LOGD("WrapNotificationActionButton call"); + if (env == nullptr || actionButton == nullptr) { + ANS_LOGE("WrapNotificationActionButton failed, has nullptr"); + return nullptr; + } + ani_object iconButtonObject = nullptr; + ani_class iconButtonCls = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)) { + ANS_LOGE("WrapNotificationActionButton : CreateClassObjByClassName failed"); + return nullptr; + } + if (!SetNotificationActionButtonByRequiredParameter(env, iconButtonCls, iconButtonObject, actionButton)) { + ANS_LOGE("WrapNotificationActionButton : SetRequiredParameter failed"); + return nullptr; + } + SetNotificationActionButtonByOptionalParameter(env, iconButtonCls, iconButtonObject, actionButton); + ANS_LOGE("WrapNotificationActionButton end"); + return iconButtonObject; +} + +ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, + const char *name, std::vector> &res) +{ + ANS_LOGD("GetActionButtonArray call"); + if (env == nullptr || param == nullptr || name == nullptr) { + ANS_LOGE("GetActionButtonArray failed, has nullptr"); + return ANI_ERROR; + } + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + StsActionButton actionButton; + if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("GetActionButtonArray: GetPropertyRef name = %{public}s, status = %{public}d", name, status); + return ANI_INVALID_ARGS; + } + if (ANI_OK!= (status = GetPropertyDouble(env, static_cast(arrayObj), "length", isUndefined, length))) { + ANS_LOGE("GetActionButtonArray: GetPropertyDouble name = %{public}s, status = %{public}d", name, status); + return status; + } + for (int i = 0; i < static_cast(length); i++) { + ani_ref buttonRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i))) { + ANS_LOGE("GetActionButtonArray: get ref failed, status = %{public}d, index = %{public}d", status, i); + return status; + } + if (ANI_OK + != (status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton))) { + ANS_LOGE("GetActionButtonArray: UnwrapActionButton failed, status = %{public}d, index = %{public}d", + status, i); + return status; + } + std::shared_ptr button + = NotificationActionButton::Create(actionButton.icon, + actionButton.title, actionButton.wantAgent, actionButton.extras, + actionButton.semanticActionButton, actionButton.autoCreatedReplies, actionButton.mimeTypeOnlyInputs, + actionButton.userInput, actionButton.isContextual); + res.push_back(button); + } + ANS_LOGD("GetActionButtonArray end"); + return status; +} + +ani_object GetAniArrayNotificationActionButton(ani_env* env, + const std::vector> &actionButtons) +{ + ANS_LOGD("GetAniArrayActionButton call"); + if (env == nullptr || actionButtons.empty()) { + ANS_LOGE("GetAniArrayActionButton failed, has nullptr"); + return nullptr; + } + ani_object arrayObj = newArrayClass(env, actionButtons.size()); + if (arrayObj == nullptr) { + ANS_LOGE("GetAniArrayActionButton: arrayObj is nullptr"); + return nullptr; + } + ani_size index = 0; + for (auto &button : actionButtons) { + ani_object item = WrapNotificationActionButton(env, button); + if (item == nullptr) { + ANS_LOGE("GetAniArrayActionButton: item is nullptr"); + return nullptr; + } + if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { + ANS_LOGE("GetAniArrayActionButton: Object_CallMethodByName_Void failed"); + return nullptr; + } + index ++; + } + ANS_LOGD("GetAniArrayActionButton end"); + return arrayObj; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cf67a9bfdc0d15f84516fed7a0abe1baab43ed9 --- /dev/null +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2025 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 "sts_bundle_option.h" + +#include "ans_log_wrapper.h" +#include "sts_common.h" + +namespace OHOS { +namespace NotificationSts { +bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::NotificationBundleOption& option) +{ + ANS_LOGD("UnwrapBundleOption call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnwrapBundleOption failed, has nullptr"); + return false; + } + std::string bundleName; + ani_boolean isUndefined = ANI_TRUE; + if (GetPropertyString(env, obj, "bundle", isUndefined, bundleName) !=ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("UnwrapBundleOption Get bundle failed"); + return false; + } + option.SetBundleName(bundleName); + ani_double result = 0.0; + if (GetPropertyDouble(env, obj, "uid", isUndefined, result) == ANI_OK && isUndefined == ANI_FALSE) { + int32_t uid = static_cast(result); + option.SetUid(uid); + } else { + ANS_LOGD("UnwrapBundleOption get uid failed"); + } + ANS_LOGD("UnwrapBundleOption end"); + return true; +} + +ani_object GetAniArrayBundleOption(ani_env* env, + const std::vector &bundleOptions) +{ + ANS_LOGD("GetAniArrayActionButton call"); + if (env == nullptr) { + ANS_LOGE("GetAniArrayActionButton failed, has nullptr"); + return nullptr; + } + ani_object arrayObj = newArrayClass(env, bundleOptions.size()); + if (arrayObj == nullptr) { + ANS_LOGE("GetAniArrayActionButton: arrayObj is nullptr"); + return nullptr; + } + int32_t index = 0; + for (auto &option : bundleOptions) { + std::shared_ptr optSp = std::make_shared(option); + ani_object item; + if (!WrapBundleOption(env, optSp, item) || item == nullptr) { + ANS_LOGE("GetAniArrayActionButton: item is nullptr"); + return nullptr; + } + if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { + ANS_LOGE("GetAniArrayActionButton: Object_CallMethodByName_Void failed"); + return nullptr; + } + index ++; + } + ANS_LOGD("GetAniArrayActionButton end"); + return arrayObj; +} + +bool UnwrapArrayBundleOption(ani_env *env, + ani_ref arrayObj, std::vector& options) +{ + ANS_LOGD("UnwrapArrayBundleOption call"); + if (env == nullptr || arrayObj == nullptr) { + ANS_LOGE("UnwrapArrayBundleOption failed, has nullptr"); + return false; + } + ani_status status; + ani_double length; + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGE("UnwrapArrayBundleOption: get length failed, status = %{public}d", status); + return false; + } + Notification::NotificationBundleOption option; + for (int32_t i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &optionRef, i); + if (status != ANI_OK) { + ANS_LOGE("UnwrapArrayBundleOption: get bundleOptionRef failed, status = %{public}d", status); + return false; + } + if (!UnwrapBundleOption(env, static_cast(optionRef), option)) { + ANS_LOGE("UnwrapArrayBundleOption: get option status = %{public}d, index = %{public}d", status, i); + return false; + } + options.push_back(option); + } + ANS_LOGD("UnwrapArrayBundleOption end"); + return true; +} + +bool WrapBundleOption(ani_env* env, + const std::shared_ptr &bundleOption, ani_object &bundleObject) +{ + ANS_LOGD("WrapBundleOption call"); + if (env == nullptr || bundleOption == nullptr) { + ANS_LOGE("WrapBundleOption failed, has nullptr"); + return false; + } + ani_class bundleCls = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject) + || bundleCls == nullptr || bundleObject == nullptr) { + ANS_LOGE("WrapBundleOption: create BundleOption failed"); + return false; + } + // bundle: string; + ani_string stringValue = nullptr; + if (ANI_OK != GetAniStringByString(env, bundleOption->GetBundleName(), stringValue) + || !CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { + ANS_LOGE("WrapBundleOption: set bundle failed"); + return false; + } + // uid?: number; + uint32_t uid = bundleOption->GetUid(); + SetPropertyOptionalByDouble(env, bundleObject, "uid", uid); + ANS_LOGD("WrapBundleOption end"); + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31f5b6b53d4e6574e2fdd594774d542179648f96 --- /dev/null +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -0,0 +1,721 @@ +/* + * Copyright (c) 2025 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 "sts_common.h" + +#include "ans_log_wrapper.h" +#include "ani_common_util.h" + +namespace OHOS { +namespace NotificationSts { +constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; +constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; +constexpr const char* CLASSNAME_INT = "Lstd/core/Int;"; + +bool IsUndefine(ani_env *env, const ani_object &obj) +{ + if (env == nullptr || obj == nullptr) { + ANS_LOGE("IsUndefine fail, has nullptr"); + return true; + } + ani_boolean isUndefined; + if (ANI_OK != env->Reference_IsUndefined(obj, &isUndefined)) { + ANS_LOGE("Reference_IsUndefined faild"); + return true; + } + return (isUndefined == ANI_TRUE) ? true : false; +} + +ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& aniStr) +{ + if (env == nullptr) { + ANS_LOGE("GetAniStringByString fail, env is nullptr"); + return ANI_INVALID_ARGS; + } + ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); + if (status != ANI_OK) { + ANS_LOGE("String_NewUTF8 failed %{public}d", status); + return status; + } + return status; +} + +ani_status GetStringByAniString(ani_env *env, ani_string str, std::string &res) +{ + if (str == nullptr || env == nullptr) { + ANS_LOGE("GetStringByAniString fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ani_size sz {}; + ani_status status = ANI_ERROR; + if ((status = env->String_GetUTF8Size(str, &sz)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return status; + } + res.resize(sz + 1); + if ((status = env->String_GetUTF8SubString(str, 0, sz, res.data(), res.size(), &sz)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return status; + } + res.resize(sz); + return status; +} + +bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector &stdVString) +{ + if (env == nullptr || ani_obj == nullptr) { + ANS_LOGE("GetStringArrayByAniObj fail, has nullptr"); + return false; + } + ani_double length; + ani_status status = env->Object_GetPropertyByName_Double(ani_obj, "length", &length); + if (status != ANI_OK) { + ANS_LOGE("Object_GetPropertyByName_Double faild. status %{public}d", status); + return false; + } + for (int i = 0; i < int(length); i++) { + ani_ref stringEntryRef; + status = env->Object_CallMethodByName_Ref(ani_obj, + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + std::string std_string; + if (ANI_OK != (status = GetStringByAniString(env, static_cast(stringEntryRef), std_string))) { + ANS_LOGE("GetStdString faild. status %{public}d", status); + return false; + } + stdVString.emplace_back(std_string); + } + return true; +} + +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, std::string &outStr) +{ + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyString fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetPropertyString: %{public}s", name); + ani_status status = ANI_ERROR; + ani_ref strRef; + if ((status =env->Object_GetPropertyByName_Ref(obj, name, &strRef)) != ANI_OK) { + ANS_LOGE("Object_GetField_Ref bundle fail, status: %{public}d", status); + return status; + } + status = env->Reference_IsUndefined(strRef, &isUndefined); + if (status != ANI_OK) { + ANS_LOGE("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + return status; + } + if (isUndefined == ANI_TRUE) { + ANS_LOGE("%{public}s is undefined", name); + return status; + } + if ((status = GetStringByAniString(env, reinterpret_cast(strRef), outStr)) != ANI_OK) { + ANS_LOGE("GetStdString failed"); + return status; + } + return status; +} + +ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, + ani_boolean isUndefined, bool outvalue) +{ + ANS_LOGD("GetPropertyBool start"); + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyBool fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetPropertyBool: %{public}s", name); + ani_ref refObj = nullptr; + ani_status status = ANI_ERROR; + status = env->Object_GetPropertyByName_Ref(obj, name, &refObj); + if (ANI_OK != status) { + ANS_LOGE("Object_GetPropertyByName_Ref fail, status: %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(refObj, &isUndefined)) != ANI_OK) { + ANS_LOGE("Reference_IsUndefined failed, status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGD("%{public}s is undefined", name); + return ANI_INVALID_ARGS; + } + ani_boolean result = ANI_FALSE; + if ((status = env->Object_CallMethodByName_Boolean(static_cast(refObj), + "unboxed", ":Z", &result)) != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + return status; + } + outvalue = (result == ANI_TRUE); + return status; +} + +ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, ani_double &outvalue) +{ + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyDouble fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetPropertyDouble: %{public}s", name); + ani_status status = ANI_ERROR; + ani_ref refObj; + status = GetPropertyRef(env, obj, name, isUndefined, refObj); + if (status != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("%{public}s is undefined", name); + return ANI_INVALID_ARGS; + } + if ((status = env->Object_CallMethodByName_Double(static_cast(refObj), + "unboxed", ":D", &outvalue)) != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + return status; + } + ANS_LOGD("Object_CallMethodByName_Double sucess, status: %{public}f", outvalue); + return status; +} + +ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_boolean &isUndefined, ani_ref &outRef) +{ + ANS_LOGD("GetPropertyRef call"); + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyRef fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetPropertyRef: %{public}s", name); + ani_status status = env->Object_GetPropertyByName_Ref(obj, name, &outRef); + if (status != ANI_OK) { + ANS_LOGE("Failed to get property '%{public}s', status: %{public}d", name, status); + return status; + } + if (outRef == nullptr) { + ANS_LOGE("get Ref fialed, outRef is nullptr"); + return ANI_ERROR; + } + status = env->Reference_IsUndefined(outRef, &isUndefined); + if (status != ANI_OK) { + ANS_LOGE("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + } + ANS_LOGD("GetPropertyRef end"); + return status; +} + +ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res) +{ + if (env == nullptr || param == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyStringArray fail, has nullptr"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetPropertyStringArray: %{public}s", name); + ani_ref arrayObj = nullptr; + ani_status status; + ani_double length; + if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("GetPropertyRef fail, status = %{public}d, isUndefind = %{public}d", status, isUndefined); + return ANI_INVALID_ARGS; + } + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return status; + } + std::string str = ""; + for (int i = 0; i < static_cast(length); i++) { + ani_ref stringEntryRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d, index: %{public}d", status, i); + return status; + } + status = GetStringByAniString(env, static_cast(stringEntryRef), str); + if (status != ANI_OK) { + ANS_LOGE("GetStdString failed, index: %{public}d", i); + return status; + } + res.push_back(str); + ANS_LOGD("GetStdString index: %{public}d %{public}s", i, str.c_str()); + } + return status; +} + +ani_status GetPropertyNumberArray(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res) +{ + ANS_LOGD("GetPropertyNumberArray enter"); + ani_ref arrayObj = nullptr; + ani_status status; + ani_double length; + if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref numEntryRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &numEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + ani_double doubleValue = 0.0; + status = env->Object_CallMethodByName_Double(static_cast(numEntryRef), "unboxed", + ":D", &doubleValue); + if (status != ANI_OK) { + ANS_LOGI("Object_CallMethodByName_Double uid fail, status: %{public}d", status); + return status; + } + res.push_back(static_cast(doubleValue)); + } + ANS_LOGD("GetPropertyNumberArray leave"); + return status; +} + +ani_object GetAniStringArrayByVectorString(ani_env *env, std::vector &strs) +{ + if (env == nullptr || strs.empty()) { + ANS_LOGE("GetAniStringArrayByVectorString fail, env is nullptr or strs is empty"); + return nullptr; + } + int length = strs.size(); + ani_object arrayObj = newArrayClass(env, length); + if (arrayObj == nullptr) { + return nullptr; + } + ani_size i = 0; + for (auto &str : strs) { + ani_string aniStr; + if ((GetAniStringByString(env, str, aniStr) != ANI_OK) || aniStr == nullptr) { + ANS_LOGE("GetAniStringByString faild"); + return nullptr; + } + ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", + i, aniStr); + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + return arrayObj; +} + +bool SetFieldString(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, const std::string value) +{ + if (env == nullptr || cls == nullptr || object == nullptr || fieldName.empty()) { + ANS_LOGE("SetFieldString fail, has nullptr or fieldName is empty"); + return false; + } + ani_field field = nullptr; + ani_string string = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + ANS_LOGD("SetFieldString fieldName : %{public}s", fieldName.c_str()); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("SetFieldString status : %{public}d", status); + return false; + } + if (value.empty()) { + ani_ref nullRef = nullptr; + if ((status = env->GetNull(&nullRef)) != ANI_OK) { + ANS_LOGE("SetFieldString GetNull fail status : %{public}d", status); + return false; + } + if ((status = env->Object_SetField_Ref(object, field, nullRef)) != ANI_OK) { + ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + return false; + } + return true; + } + if ((status = env->String_NewUTF8(value.c_str(), value.size(), &string)) != ANI_OK) { + ANS_LOGE("SetFieldString String_NewUTF8 fail status : %{public}d", status); + return false; + } + if ((status = env->Object_SetField_Ref(object, field, string)) != ANI_OK) { + ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + return false; + } + return true; +} + +bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, bool value) +{ + if (env == nullptr || cls == nullptr || object == nullptr || fieldName.empty()) { + ANS_LOGE("SetOptionalFieldBoolean fail, has nullptr or fieldName is empty"); + return false; + } + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_object boolObj = CreateBoolean(env, BoolToAniBoolean(value)); + if (boolObj == nullptr) { + return false; + } + status = env->Object_SetField_Ref(object, field, boolObj); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, + const std::string fieldName, double value) +{ + if (env == nullptr || cls == nullptr || object == nullptr || fieldName.empty()) { + ANS_LOGE("SetOptionalFieldDouble fail, has nullptr or fieldName is empty"); + return false; + } + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_object doubleObj = CreateDouble(env, value); + if (doubleObj == nullptr) { + return false; + } + status = env->Object_SetField_Ref(object, field, doubleObj); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +ani_object CreateBoolean(ani_env *env, bool value) +{ + ani_class persion_cls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_BOOLEAN, &persion_cls)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_method personInfoCtor; + if ((status = env->Class_FindMethod(persion_cls, "", "Z:V", &personInfoCtor)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_object personInfoObj; + if ((status = env->Object_New(persion_cls, personInfoCtor, &personInfoObj, value ? ANI_TRUE : ANI_FALSE)) + != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + return personInfoObj; +} +ani_object CreateDouble(ani_env *env, double value) +{ + if (env == nullptr) { + ANS_LOGE("CreateDouble fail, env is nullptr"); + return nullptr; + } + ani_class doubleCls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_DOUBLE, &doubleCls)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_method doubleCtor; + if ((status = env->Class_FindMethod(doubleCls, "", "D:V", &doubleCtor)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_object doubleObj; + if ((status = env->Object_New(doubleCls, doubleCtor, &doubleObj, static_cast(value))) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + return doubleObj; +} + +ani_object newArrayClass(ani_env *env, int length) +{ + ANS_LOGD("newArrayClass call"); + if (env == nullptr || length < 0) { + ANS_LOGE("CreateDouble fail, env is nullptr or length is less than zero"); + return nullptr; + } + ani_class arrayCls = nullptr; + if (ANI_OK != env->FindClass("Lescompat/Array;", &arrayCls)) { + ANS_LOGE("FindClass Lescompat/Array; Failed"); + return nullptr; + } + ani_method arrayCtor; + if (ANI_OK != env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor)) { + ANS_LOGE("Class_FindMethod Failed"); + return nullptr; + } + ani_object arrayObj = nullptr; + if (ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)) { + ANS_LOGE("Object_New Array Faild"); + return nullptr; + } + ANS_LOGD("newArrayClass end"); + return arrayObj; +} + +ani_object newRecordClass(ani_env *env) +{ + ANS_LOGD("newRecordClass call"); + if (env == nullptr) { + ANS_LOGE("newRecordClass fail, env is nullptr"); + return nullptr; + } + ani_status status = ANI_ERROR; + ani_class recordCls; + if (ANI_OK != (status = env->FindClass("Lescompat/Record;", &recordCls))) { + ANS_LOGE("newRecordClass fail, FindClass status = %{public}d", status); + return nullptr; + } + ani_method ctor; + if (ANI_OK != (status = env->Class_FindMethod(recordCls, "", nullptr, &ctor))) { + ANS_LOGE("newRecordClass fail, Class_FindMethod status = %{public}d", status); + return nullptr; + } + ani_object recordObj = {}; + if (ANI_OK != (status = env->Object_New(recordCls, ctor, &recordObj))) { + ANS_LOGE("newRecordClass fail, Object_New status = %{public}d", status); + return nullptr; + } + ANS_LOGD("newRecordClass end"); + return recordObj; +} + +ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values) +{ + if (env == nullptr) { + ANS_LOGE("ConvertArrayDoubleToAniObj fail, env is nullptr"); + return nullptr; + } + ani_object arrayObj = newArrayClass(env, values.size()); + if (arrayObj == nullptr) { + return nullptr; + } + for (size_t i = 0; i < values.size(); i++) { + ani_object intObj = CreateDouble(env, static_cast(values[i])); + if (intObj == nullptr) { + ANS_LOGE("null intObj"); + return nullptr; + } + ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, intObj); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + } + return arrayObj; +} + +bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const std::vector &values) +{ + if (env == nullptr || cls == nullptr || object == nullptr || fieldName.empty()) { + ANS_LOGE("SetOptionalFieldArrayDouble fail, has nullptr or fieldName is empty"); + return false; + } + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + ani_object arrayObj = ConvertArrayDoubleToAniObj(env, values); + if (arrayObj == nullptr) { + ANS_LOGE("arrayObj is nullptr."); + return false; + } + status = env->Object_SetField_Ref(object, field, arrayObj); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + return true; +} + +bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj) +{ + if (env == nullptr || className == nullptr) { + ANS_LOGE("CreateClassObjByClassName fail, has nullptr"); + return false; + } + if (ANI_OK != env->FindClass(className, &cls)) { + ANS_LOGE("FindClass fail"); + return false; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + ANS_LOGE("FindMethod fail"); + return false; + } + outAniObj = {}; + if (ANI_OK != env->Object_New(cls, ctor, &outAniObj)) { + ANS_LOGE("Object_New fail"); + return false; + } + return true; +} + +bool CreateDate(ani_env *env, int64_t time, ani_object &outObj) +{ + if (env == nullptr || time < 0) { + ANS_LOGE("CreateDate fail, env is nullptr or time is invalid value"); + return false; + } + ani_class cls; + ani_status status; + if (ANI_OK != (status = env->FindClass("Lescompat/Date;", &cls))) { + ANS_LOGD("error. not find class name 'Lescompat/Date;'. status %{public}d", status); + return false; + } + ani_method ctor; + if (ANI_OK != (status = env->Class_FindMethod(cls, "", "Lstd/core/Object;:V", &ctor))) { + ANS_LOGD("error. not find method name ''. status %{public}d", status); + return false; + } + ani_object timeObj = CreateDouble(env, static_cast(time)); + if (timeObj == nullptr) { + ANS_LOGD("createDouble faild"); + return false; + } + if (ANI_OK != (status = env->Object_New(cls, ctor, &outObj, timeObj))) { + ANS_LOGD("Object_New faild. status %{public}d", status); + return false; + } + return true; +} + +ani_object CreateInt(ani_env *env, int32_t value) +{ + ani_class cls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_INT, &cls)) != ANI_OK) { + ANS_LOGE("FindClass '%{public}s' faild. status %{public}d", CLASSNAME_INT, status); + return nullptr; + } + ani_method ctor; + if ((status = env->Class_FindMethod(cls, "", "I:V", &ctor)) != ANI_OK) { + ANS_LOGE("Class_FindMethod '%{public}s' faild. status %{public}d", CLASSNAME_INT, status); + return nullptr; + } + ani_object outObj; + if ((status = env->Object_New(cls, ctor, &outObj, value)) != ANI_OK) { + ANS_LOGE("Object_New '%{public}s' faild. status %{public}d", CLASSNAME_INT, status); + return nullptr; + } + return outObj; +} + +bool SetPropertyOptionalByBoolean(ani_env *env, ani_object object, const char *name, bool value) +{ + ANS_LOGD("enter SetPropertyOptionalByBoolean"); + if (env == nullptr || object == nullptr || name == nullptr) { + ANS_LOGE("The parameter is invalid."); + return false; + } + ani_ref boolObj = CreateBoolean(env, value); + if (boolObj == nullptr) { + ANS_LOGE("CreateBoolean faild"); + return false; + } + return SetPropertyByRef(env, object, name, boolObj); +} + +bool SetPropertyOptionalByDouble(ani_env *env, ani_object object, const char *name, double value) +{ + ANS_LOGD("enter SetPropertyOptionalByDouble"); + if (env == nullptr || object == nullptr || name == nullptr) { + ANS_LOGE("The parameter is invalid."); + return false; + } + ani_ref doubleObj = CreateDouble(env, value); + if (doubleObj == nullptr) { + ANS_LOGE("CreateDouble faild"); + return false; + } + return SetPropertyByRef(env, object, name, doubleObj); +} + +bool SetPropertyOptionalByString(ani_env *env, ani_object object, const char *name, const std::string value) +{ + ANS_LOGD("enter SetPropertyOptionalByString"); + if (env == nullptr || object == nullptr || name == nullptr) { + ANS_LOGE("The parameter is invalid."); + return false; + } + ani_string stringObj; + ani_status status = ANI_OK; + if (ANI_OK != (status = GetAniStringByString(env, value, stringObj))) { + ANS_LOGE("GetAniStringByString faild. status %{public}d", status); + return false; + } + if (stringObj == nullptr) { + ANS_LOGE("CreateString faild"); + return false; + } + return SetPropertyByRef(env, object, name, static_cast(stringObj)); +} + +bool SetPropertyOptionalByInt(ani_env *env, ani_object object, const char *name, int32_t value) +{ + ANS_LOGD("enter SetPropertyOptionalByInt"); + if (env == nullptr || object == nullptr || name == nullptr) { + ANS_LOGE("The parameter is invalid."); + return false; + } + ani_ref IntObj = CreateInt(env, value); + if (IntObj == nullptr) { + ANS_LOGE("CreateInt faild"); + return false; + } + return SetPropertyByRef(env, object, name, IntObj); +} + +bool SetPropertyByRef(ani_env *env, ani_object object, const char *name, ani_ref value) +{ + ANS_LOGD("enter SetPropertyByRef"); + ani_status status = ANI_OK; + if (env == nullptr || object == nullptr || name == nullptr || value == nullptr) { + ANS_LOGE("The parameter is invalid."); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(object, name, value))) { + ANS_LOGE("set '%{public}s' faild. status %{public}d", name, status); + return false; + } + return true; +} + +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b316a48594fa7bf8090eed59351f212da8b2b151 --- /dev/null +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -0,0 +1,524 @@ +/* + * Copyright (c) 2025 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 "sts_convert_other.h" + +#include "sts_common.h" +#include "pixel_map_ani.h" + +namespace OHOS { +namespace NotificationSts { +std::shared_ptr UnwrapWantAgent(ani_env *env, ani_object agent) +{ + ANS_LOGD("UnwrapWantAgent called"); + if (env == nullptr || agent == nullptr) { + ANS_LOGE("UnwrapWantAgent failed, has nullPtr"); + return nullptr; + } + ani_status status = ANI_ERROR; + ani_long nativeObj {}; + if ((status = env->Object_GetFieldByName_Long(agent, "nativeObj", &nativeObj)) != ANI_OK) { + ANS_LOGI("UnwrapWantAgent Object_GetField_Long fetch failed, status = %{public}d", status); + return nullptr; + } + WantAgent* wantAgent = reinterpret_cast(nativeObj); + if (wantAgent == nullptr) { + ANS_LOGI("UnwrapWantAgent wantAgent nullptr"); + return nullptr; + } + std::shared_ptr wantAgentSp = std::make_shared(*wantAgent); + deletePoint(wantAgent); + ANS_LOGD("UnwrapWantAgent end"); + return wantAgentSp; +} + +ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource) +{ + ANS_LOGD("UnwrapResource called"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnwrapResource failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + std::string bundleName = ""; + ani_boolean isUndefined = ANI_TRUE; + if ((status = GetPropertyString(env, obj, "bundleName", isUndefined, bundleName)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + resource.bundleName = bundleName; + + std::string moduleName = ""; + if ((status = GetPropertyString(env, obj, "moduleName", isUndefined, moduleName)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + resource.moduleName = moduleName; + + ani_double idAni = 0.0; + if ((status = GetPropertyDouble(env, obj, "id", isUndefined, idAni)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + resource.id = static_cast(idAni); + ANS_LOGD("UnwrapResource end"); + return status; +} + +ani_object CreateAniPixelMap(ani_env* env, std::shared_ptr pixelMap) +{ + ANS_LOGD("CreateAniPixelMap call"); + if (env == nullptr || pixelMap == nullptr) { + ANS_LOGE("CreateAniPixelMap failed, has nullPtr"); + return nullptr; + } + return PixelMapAni::CreatePixelMap(env, pixelMap); +} + +std::shared_ptr GetPixelMapFromEnvSp(ani_env* env, ani_object obj) +{ + ANS_LOGD("GetPixelMapFromEnvSp call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("GetPixelMapFromEnvSp failed, has nullPtr"); + return nullptr; + } + ani_status ret; + ani_long nativeObj {}; + if ((ret = env->Object_GetFieldByName_Long(obj, "nativeObj", &nativeObj)) != ANI_OK) { + ANS_LOGI("GetPixelMapFromEnvSp Object_GetField_Long fetch failed"); + return nullptr; + } + PixelMap* pixelmap = reinterpret_cast(nativeObj); + if (pixelmap == nullptr) { + ANS_LOGI("GetPixelMapFromEnvSp pixelmap nullptr"); + return nullptr; + } + std::shared_ptr pixelmapSp = std::make_shared(*pixelmap); + deletePoint(pixelmap); + return pixelmapSp; +} + +ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector> &pixelMaps) +{ + ANS_LOGD("GetPixelMapArrayByRef call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("GetPixelMapArrayByRef failed, has nullPtr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_double length; + status = env->Object_GetPropertyByName_Double(static_cast(param), "length", &length); + if (status != ANI_OK) { + ANS_LOGE("GetPixelMapArrayByRef: status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref pixelMapRef; + status = env->Object_CallMethodByName_Ref(static_cast(param), + "$_get", "I:Lstd/core/Object;", &pixelMapRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGE("GetPixelMapArrayByRef:status : %{public}d, index: %{public}d", status, i); + pixelMaps.clear(); + return status; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pixelMapRef)); + if (pixelMap == nullptr) { + ANS_LOGE("GetPixelMapArrayByRef: GetPixelMapFromEnvSp failed."); + pixelMaps.clear(); + return ANI_INVALID_ARGS; + } + pixelMaps.push_back(pixelMap); + } + ANS_LOGD("GetPixelMapArrayByRef end"); + return status; +} + +ani_status GetPixelMapArray(ani_env *env, + ani_object param, const char *name, std::vector> &pixelMaps) +{ + ANS_LOGD("GetPixelMapArray call"); + if (env == nullptr || param == nullptr || name == nullptr) { + ANS_LOGE("GetPixelMapArray failed, has nullPtr"); + return ANI_ERROR; + } + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = ANI_TRUE; + ani_status status = ANI_ERROR; + if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + + if ((status = GetPixelMapArrayByRef(env, arrayObj, pixelMaps)) != ANI_OK) { + pixelMaps.clear(); + return status; + } + ANS_LOGD("GetPixelMapArray end"); + return status; +} + +ani_status GetResourceArray(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + ANS_LOGD("GetResourceArray call"); + if (env == nullptr || param == nullptr || name == nullptr) { + ANS_LOGE("GetResourceArray failed, has nullPtr"); + return ANI_ERROR; + } + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("GetResourceArray failed, status : %{public}d", status); + return ANI_INVALID_ARGS; + } + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGE("GetResourceArray : status : %{public}d", status); + return status; + } + for (int i = 0; i < static_cast(length); i++) { + ani_ref iconRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &iconRef, (ani_int)i); + if (status != ANI_OK) { + res.clear(); + ANS_LOGE("GetResourceArray: status = %{public}d, index = %{public}d", status, i); + return status; + } + ResourceManager::Resource resource; + if (ANI_OK != UnwrapResource(env, static_cast(iconRef), resource)) { + ANS_LOGE("GetResourceArray : status = %{public}d, index= %{public}d", status, i); + res.clear(); + return status; + } + res.push_back(resource); + } + ANS_LOGD("GetResourceArray end"); + return status; +} + +ani_status GetKeyString(ani_env *env, ani_object obj, int index, ani_string &str) +{ + ANS_LOGD("GetKeyString call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("GetKeyString failed, has nullPtr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_ref stringEntryRef; + status = env->Object_CallMethodByName_Ref(obj, + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)index); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d, index: %{public}d", status, index); + return status; + } + str = static_cast(stringEntryRef); + ANS_LOGD("GetKeyString end"); + return status; +} + +ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vector keys, + std::map>> &pictureMap) +{ + ANS_LOGD("GetPixelMapByKeys call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("GetPixelMapByKeys failed, has nullPtr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + for (auto anikey : keys) { + ani_ref picturesArrayRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(obj, "$_get", nullptr, &picturesArrayRef, anikey))) { + ANS_LOGE("GetPixelMapByKeys : Object_CallMethodByName_Ref failed"); + deleteVectorWithArraySpPoints(pictureMap); + return status; + } + std::vector> pixelMaps = {}; + if ((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { + ANS_LOGE("GetPixelMapByKeys : GetPixelMapArrayByRef failed"); + deleteVectorWithSpPoints(pixelMaps); + deleteVectorWithArraySpPoints(pictureMap); + return status; + } + std::string str = ""; + if ((status = GetStringByAniString(env, anikey, str)) != ANI_OK) { + ANS_LOGE("GetPixelMapByKeys : GetStringByAniString failed"); + deleteVectorWithSpPoints(pixelMaps); + deleteVectorWithArraySpPoints(pictureMap); + return status; + } + pictureMap[str] = pixelMaps; + } + ANS_LOGD("GetPixelMapByKeys end"); + return status; +} + +ani_status GetPixelMapByRef( + ani_env *env, ani_object obj, ani_ref keysStrArrayRef, + std::map>> &pictureMap) +{ + ANS_LOGD("GetPixelMapByRef call"); + if (env == nullptr || obj == nullptr || keysStrArrayRef == nullptr) { + ANS_LOGE("GetPixelMapByRef failed, has nullPtr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_double length; + if (ANI_OK != + (status = env->Object_GetPropertyByName_Double(static_cast(keysStrArrayRef), "length", &length))) { + ANS_LOGE("GetPixelMapByRef : Object_GetPropertyByName_Double status = %{public}d", status); + return status; + } + ani_string strAni = {}; + std::vector keys = {}; + for (int i = 0; i < static_cast(length); i++) { + if ((status = GetKeyString(env, static_cast(keysStrArrayRef), i, strAni)) != ANI_OK) { + ANS_LOGE("GetPixelMapByRef : GetKeyString status = %{public}d", status); + keys.clear(); + return status; + } + keys.push_back(strAni); + } + status = GetPixelMapByKeys(env, obj, keys, pictureMap); + ANS_LOGD("GetPixelMapByRef end"); + return status; +} + +ani_status GetMapOfPictureInfo(ani_env *env, ani_object obj, + std::map>> pictureMap) +{ + ANS_LOGD("GetMapOfPictureInfo call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("GetMapOfPictureInfo failed, has nullPtr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + if (ANI_OK != (status = env->FindClass("Lnotification/notificationContent/RecordTools;", &cls))) { + ANS_LOGE("GetMapOfPictureInfo : FindClass status = %{public}d", status); + return status; + } + if (cls == nullptr) { + ANS_LOGE("GetMapOfPictureInfo : cls is nullptr"); + return ANI_INVALID_TYPE; + } + ani_static_method keysMethod = nullptr; + if (ANI_OK != (status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod))) { + ANS_LOGE("GetMapOfPictureInfo : Class_FindStaticMethod status = %{public}d", status); + return status; + } + ani_ref keysStrArrayRef = nullptr; + if (ANI_OK != (status = env->Class_CallStaticMethod_Ref(cls, keysMethod, &keysStrArrayRef, obj))) { + ANS_LOGE("GetMapOfPictureInfo : Class_CallStaticMethod_Ref status = %{public}d", status); + return status; + } + if (IsUndefine(env, static_cast(keysStrArrayRef))) { + ANS_LOGE("GetMapOfPictureInfo : keysStrArrayRef IsUndefined"); + return ANI_INVALID_ARGS; + } + if (ANI_OK != (status = GetPixelMapByRef(env, obj, keysStrArrayRef, pictureMap))) { + deleteVectorWithArraySpPoints(pictureMap); + ANS_LOGE("GetMapOfPictureInfo : GetPixelMapByRef status = %{public}d", status); + } + ANS_LOGD("GetMapOfPictureInfo end"); + return status; +} + +ani_object GetAniResource(ani_env *env, const std::shared_ptr &resource) +{ + ANS_LOGD("GetAniResource call"); + if (env == nullptr || resource == nullptr) { + ANS_LOGE("GetAniResource failed, has nullPtr"); + return nullptr; + } + ani_status status = ANI_ERROR; + ani_class resourceCls = nullptr; + ani_object resourceObject = nullptr; + if (!CreateClassObjByClassName(env, + "Lglobal/resourceInner/ResourceInner;", resourceCls, resourceObject)) { + ANS_LOGE("GetAniResource : CreateClassObjByClassName failed"); + return nullptr; + } + ani_string stringValue = nullptr; + if (ANI_OK != (status = GetAniStringByString(env, resource->bundleName, stringValue)) + || !CallSetter(env, resourceCls, resourceObject, "bundleName", stringValue)) { + ANS_LOGE("GetAniResource : set bundleName failed, status = %{public}d", status); + return nullptr; + } + if (ANI_OK != (status = GetAniStringByString(env, resource->moduleName, stringValue)) + || !CallSetter(env, resourceCls, resourceObject, "moduleName", stringValue)) { + ANS_LOGE("GetAniResource : set moduleName failed, status = %{public}d", status); + return nullptr; + } + if (!CallSetter(env, resourceCls, resourceObject, "id", resource->id)) { + ANS_LOGE("GetAniResource : set moduleName failed, status = %{public}d", status); + } + ANS_LOGD("GetAniResource end"); + return resourceObject; +} + +ani_object GetAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps) +{ + ANS_LOGD("GetAniArrayPixelMap call"); + if (env == nullptr || pixelMaps.empty()) { + ANS_LOGE("GetAniArrayPixelMap failed, env is nullPtr or pixelMaps is empty"); + return nullptr; + } + ani_size length = pixelMaps.size(); + ani_object arrayObj = newArrayClass(env, length); + if (arrayObj == nullptr) { + ANS_LOGE("GetAniArrayPixelMap : arrayObj is nullptr"); + return nullptr; + } + ani_size i = 0; + for (auto &pixelMap : pixelMaps) { + ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, pixelMap); + if (pixelMapObject == nullptr) { + ANS_LOGE("GetAniArrayPixelMap : pixelMapObject is nullptr"); + return nullptr; + } + ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", + i, pixelMapObject); + if (status != ANI_OK) { + ANS_LOGE("GetAniArrayPixelMap : Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + ANS_LOGD("GetAniArrayPixelMap end"); + return arrayObj; +} + +ani_object GetAniArrayResource(ani_env *env, + const std::vector> &resources) +{ + ANS_LOGD("GetAniArrayResource call"); + if (env == nullptr || resources.empty()) { + ANS_LOGE("GetAniArrayResource failed, env is nullPtr or resources is empty"); + return nullptr; + } + ani_size length = resources.size(); + ani_object arrayObj = newArrayClass(env, length); + if (arrayObj == nullptr) { + ANS_LOGE("GetAniArrayResource : arrayObj is nullPtr"); + return nullptr; + } + ani_size i = 0; + for (auto &resource : resources) { + ani_object resourceObject = GetAniResource(env, resource); + if (resourceObject == nullptr) { + ANS_LOGE("GetAniArrayResource : resourceObject is nullPtr"); + return nullptr; + } + ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", + i, resourceObject); + if (status != ANI_OK) { + ANS_LOGE("GetAniArrayResource : Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + ANS_LOGD("GetAniArrayResource end"); + return arrayObj; +} + +bool GetAniPictrueInfo(ani_env *env, std::map>> pictureMap, + ani_object &pictureInfoObj) +{ + ANS_LOGD("GetAniPictrueInfo call"); + if (env == nullptr || pictureMap.empty()) { + ANS_LOGE("GetAniPictrueInfo failed, env is nullPtr or pictureMap is empty"); + return false; + } + pictureInfoObj = newRecordClass(env); + if (pictureInfoObj == nullptr) { + ANS_LOGE("GetAniPictrueInfo failed, pictureInfoObj is nullPtr"); + return false; + } + for (const auto& [key, value] : pictureMap) { + ani_string aniKey; + if (GetAniStringByString(env, key, aniKey) != ANI_OK || aniKey == nullptr) { + ANS_LOGE("GetAniPictrueInfo : GetAniStringByString failed"); + return false; + } + ani_object aniPictrueArray = GetAniArrayPixelMap(env, value); + if (aniPictrueArray == nullptr) { + ANS_LOGE("GetAniPictrueInfo : GetAniArrayPixelMap failed"); + return false; + } + if (ANI_OK != env->Object_CallMethodByName_Void(pictureInfoObj, + "$_set", "Lstd/core/Object;Lstd/core/Object;:V", aniKey, aniPictrueArray)) { + ANS_LOGE("GetAniPictrueInfo : Object_CallMethodByName_Void failed"); + return false; + } + } + ANS_LOGD("GetAniPictrueInfo end"); + return true; +} + +ani_object WarpWantAgent(ani_env *env, std::shared_ptr wantAgent) +{ + ANS_LOGD("WarpWantAgent call"); + if (wantAgent == nullptr) { + ANS_LOGE("WarpWantAgent failed, wantAgent is nullptr"); + return nullptr; + } + ani_object wantAgentObj = AppExecFwk::WrapWantAgent(env, wantAgent.get()); + if (wantAgentObj == nullptr) { + ANS_LOGE("WarpWantAgent : wantAgentObj is nullptr"); + } + ANS_LOGD("WarpWantAgent end"); + return wantAgentObj; +} + +ani_object GetAniWantAgentArray(ani_env *env, std::vector> wantAgents) +{ + ANS_LOGD("GetAniWantAgentArray call"); + if (env == nullptr || wantAgents.empty()) { + ANS_LOGE("GetAniWantAgentArray failed, env is nullptr or wantAgents is empty"); + return nullptr; + } + ani_status status = ANI_ERROR; + ani_class arrayCls = nullptr; + if (ANI_OK != (status = env->FindClass("Lescompat/Array;", &arrayCls))) { + ANS_LOGE("GetAniWantAgentArray : FindClass status = %{public}d", status); + return nullptr; + } + ani_method arrayCtor; + if (ANI_OK != (status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor))) { + ANS_LOGE("GetAniWantAgentArray : Class_FindMethod status = %{public}d", status); + return nullptr; + } + ani_object arrayObj; + if (ANI_OK != (status = env->Object_New(arrayCls, arrayCtor, &arrayObj, wantAgents.size()))) { + ANS_LOGE("GetAniWantAgentArray : Object_New status = %{public}d", status); + return nullptr; + } + ani_size index = 0; + for (auto &wantAgent : wantAgents) { + ani_object item = WarpWantAgent(env, wantAgent); + if (item == nullptr + || ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { + ANS_LOGE("GetAniWantAgentArray : set WantAgent failed"); + return nullptr; + } + index ++; + } + ANS_LOGD("GetAniWantAgentArray end"); + return arrayObj; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1cc2f7c285f947b872331c17355a377d1f02140e --- /dev/null +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2025 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 "sts_disturb_mode.h" + +#include "sts_bundle_option.h" +#include "sts_common.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace NotificationSts { +bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, + sptr &profile) +{ + ANS_LOGD("UnwrapDoNotDisturbProfile call"); + if (env == nullptr || param == nullptr) { + ANS_LOGE("UnwrapDoNotDisturbProfile fail, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_double idAni = 0.0; + if (ANI_OK != env->Object_GetPropertyByName_Double(param, "id", &idAni)) { + ANS_LOGE("UnwrapDoNotDisturbProfile: get id failed"); + return false; + } + profile->SetProfileId(static_cast(idAni)); + std::string nameStr = ""; + if (ANI_OK != GetPropertyString(env, param, "name", isUndefined, nameStr) || isUndefined == ANI_TRUE) { + ANS_LOGE("UnwrapDoNotDisturbProfile: get name failed"); + return false; + } + profile->SetProfileName(nameStr); + ani_ref trustlistRef; + if (ANI_OK != GetPropertyRef(env, param, "trustlist", isUndefined, trustlistRef) || isUndefined == ANI_TRUE) { + ANS_LOGE("UnwrapDoNotDisturbProfile: get trustlist failed"); + } else { + std::vector trustlist = {}; + UnwrapArrayBundleOption(env, static_cast(trustlistRef), trustlist); + if (!trustlist.empty()) { + profile->SetProfileTrustList(trustlist); + } + } + ANS_LOGD("UnwrapDoNotDisturbProfile end"); + return true; +} + +bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, + std::vector> &profiles) +{ + ANS_LOGD("UnwrapArrayDoNotDisturbProfile call"); + if (env == nullptr || arrayObj == nullptr) { + ANS_LOGE("UnwrapArrayDoNotDisturbProfile fail, has nullptr"); + return false; + } + ani_status status; + ani_double length; + status = env->Object_GetPropertyByName_Double(arrayObj, "length", &length); + if (status != ANI_OK) { + ANS_LOGD("UnwrapArrayDoNotDisturbProfile: status = %{public}d", status); + return false; + } + for (int i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", + "I:Lstd/core/Object;", &optionRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGE("UnwrapArrayDoNotDisturbProfile: status : %{public}d, index: %{public}d", status, i); + return false; + } + sptr profile = new (std::nothrow)NotificationDoNotDisturbProfile(); + if (!UnwrapDoNotDisturbProfile(env, static_cast(optionRef), profile)) { + ANS_LOGE("Get profile failed, index: %{public}d", i); + return false; + } + profiles.push_back(profile); + } + ANS_LOGD("UnwrapArrayDoNotDisturbProfile end"); + return true; +} + +bool WrapProfileTrustList(ani_env* env, sptr profile, + ani_object &outObj) +{ + ani_status status = ANI_OK; + const auto& trustList = profile->GetProfileTrustList(); + if (trustList.empty()) { + ANS_LOGE("WrapProfileTrustList trustlist is nullptr"); + return true; + } + ani_object arrayObj = newArrayClass(env, trustList.size()); + if (arrayObj == nullptr) { + ANS_LOGE("WrapProfileTrustList Failed to create trustlist array"); + return false; + } + + int32_t index = 0; + for (const auto& bundle : trustList) { + auto bundlePtr = std::make_shared(bundle); + ani_object bundleObj = nullptr; + if (!WrapBundleOption(env, bundlePtr, bundleObj)) { + ANS_LOGE("WrapProfileTrustList WrapBundleOption failed"); + return false; + } + if (ANI_OK != (status = env->Object_CallMethodByName_Void(arrayObj, "$_set", + "ILstd/core/Object;:V", index, bundleObj))) { + ANS_LOGE("WrapProfileTrustList set object faild. index %{public}d status %{public}d", + index, status); + return false; + } + index++; + } + ani_ref arrayRef = arrayObj; + if (!SetPropertyByRef(env, outObj, "trustlist", arrayRef)) { + ANS_LOGE("WrapProfileTrustList Failed to set trustlist property"); + return false; + } + return true; +} + +bool WrapDoNotDisturbProfile(ani_env* env, sptr profile, + ani_object &outObj) +{ + ani_status status = ANI_OK; + ani_class cls = nullptr; + if (env == nullptr) { + ANS_LOGE("WrapDoNotDisturbProfile: Invalid input parameters"); + return false; + } + const char* className = "L@ohos/notificationManager/notificationManager/DoNotDisturbProfileInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj) || outObj == nullptr) { + ANS_LOGE("WrapDoNotDisturbProfile: Failed to create profile class object"); + return false; + } + ani_double id = static_cast(profile->GetProfileId()); + if (ANI_OK != (status = env->Object_SetPropertyByName_Double(outObj, "id", id))) { + ANS_LOGE("WrapDoNotDisturbProfile : set reason faild. status %{public}d", status); + return false; + } + if (!SetPropertyOptionalByString(env, outObj, "name", profile->GetProfileName())) { + ANS_LOGE("WrapDoNotDisturbProfile: set name failed"); + return false; + } + if (!WrapProfileTrustList(env, profile, outObj)) { + ANS_LOGE("WrapDoNotDisturbProfile: set trustList failed"); + return false; + } + return true; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3aa635f9f0594c9b5abd4d43187bba6c0389a64 --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -0,0 +1,1513 @@ +/* + * Copyright (c) 2025 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 "sts_notification_content.h" + +#include "sts_common.h" +#include "sts_convert_other.h" +#include "want_params.h" +#include "ani_common_want.h" +#include "sts_notification_manager.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using NotificationBasicContent = OHOS::Notification::NotificationBasicContent; + +bool StsLiveViewStatusUtils::StsToC(const STSLiveViewStatus inType, LiveViewStatus &outType) +{ + ANS_LOGD("StsLiveViewStatusUtils::StsToC inType = %{public}d", static_cast(inType)); + switch (inType) { + case STSLiveViewStatus::LIVE_VIEW_CREATE: + outType = LiveViewStatus::LIVE_VIEW_CREATE; + break; + case STSLiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE: + outType = LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; + break; + case STSLiveViewStatus::LIVE_VIEW_END: + outType = LiveViewStatus::LIVE_VIEW_END; + break; + case STSLiveViewStatus::LIVE_VIEW_FULL_UPDATE: + outType = LiveViewStatus::LIVE_VIEW_FULL_UPDATE; + break; + default: + ANS_LOGE("LiveViewStatus %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsLiveViewStatusUtils::CToSts(const LiveViewStatus inType, STSLiveViewStatus &outType) +{ + ANS_LOGD("StsLiveViewStatusUtils::CToSts:inType = %{public}d", static_cast(inType)); + switch (inType) { + case LiveViewStatus::LIVE_VIEW_CREATE: + outType = STSLiveViewStatus::LIVE_VIEW_CREATE; + break; + case LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE: + outType = STSLiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; + break; + case LiveViewStatus::LIVE_VIEW_END: + outType = STSLiveViewStatus::LIVE_VIEW_END; + break; + case LiveViewStatus::LIVE_VIEW_FULL_UPDATE: + outType = STSLiveViewStatus::LIVE_VIEW_FULL_UPDATE; + break; + default: + ANS_LOGE("LiveViewStatus %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool LiveViewStatusEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewStatus &liveViewStatus) +{ + ANS_LOGD("LiveViewStatusEtsToC call"); + if (env == nullptr) { + ANS_LOGE("LiveViewStatusEtsToC failed, env is nullptr"); + return false; + } + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + if (!EnumConvertAniToNative(env, enumItem, stsLiveViewStatus) + || !StsLiveViewStatusUtils::StsToC(stsLiveViewStatus, liveViewStatus)) { + ANS_LOGE("LiveViewStatusEtsToC failed"); + return false; + } + ANS_LOGD("LiveViewStatusEtsToC end"); + return true; +} + +bool LiveViewStatusCToEts(ani_env *env, LiveViewStatus liveViewStatus, ani_enum_item &enumItem) +{ + ANS_LOGD("LiveViewStatusCToEts call"); + if (env == nullptr) { + ANS_LOGE("LiveViewStatusCToEts failed, env is nullptr"); + return false; + } + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + if (!StsLiveViewStatusUtils::CToSts(liveViewStatus, stsLiveViewStatus) + || !EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewStatus", stsLiveViewStatus, enumItem)) { + ANS_LOGE("LiveViewStatusCToEts failed"); + return false; + } + ANS_LOGD("LiveViewStatusCToEts end"); + return true; +} + +bool LiveViewTypesEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewTypes &liveViewTypes) +{ + ANS_LOGD("LiveViewTypesEtsToC call"); + return EnumConvertAniToNative(env, enumItem, liveViewTypes); +} + +bool LiveViewTypesCToEts(ani_env *env, LiveViewTypes liveViewTypes, ani_enum_item &enumItem) +{ + ANS_LOGD("LiveViewTypesCToEts call"); + return EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewTypes", liveViewTypes, enumItem); +} + +void UnWarpNotificationProgress(ani_env *env, ani_object obj, NotificationProgress ¬ificationProgress) +{ + ANS_LOGD("UnWarpNotificationProgress call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationProgress failed, has nullptr"); + return; + } + ani_double maxValueAni = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if (GetPropertyDouble(env, obj, "maxValue", isUndefined, maxValueAni) == ANI_OK + && isUndefined == ANI_FALSE) { + notificationProgress.SetMaxValue(static_cast(maxValueAni)); + } else { + ANS_LOGD("UnWarpNotificationProgress: get maxValue failed"); + } + ani_double currentValueAni = 0.0; + if (GetPropertyDouble(env, obj, "currentValue", isUndefined, currentValueAni) == ANI_OK + && isUndefined == ANI_FALSE) { + notificationProgress.SetCurrentValue(static_cast(currentValueAni)); + } else { + ANS_LOGD("UnWarpNotificationProgress: get currentValue failed"); + } + bool isPercentage = true; + if (ANI_OK == GetPropertyBool(env, obj, "isPercentage", isUndefined, isPercentage) + && isUndefined == ANI_FALSE) { + notificationProgress.SetIsPercentage(isPercentage); + } else { + ANS_LOGD("UnWarpNotificationProgress: get isPercentage failed"); + } + ANS_LOGD("UnWarpNotificationProgress end"); +} + +bool WarpNotificationProgress(ani_env *env, const NotificationProgress &progress, ani_object &progressObject) +{ + ANS_LOGD("WarpNotificationProgress call"); + if (env == nullptr) { + ANS_LOGE("WarpNotificationProgress failed, env is nullptr"); + return false; + } + ani_class progressClass = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationProgressInner;", progressClass, progressObject) + || progressObject == nullptr) { + ANS_LOGE("WarpNotificationProgress: create class failed"); + return false; + } + // maxValue?: number; + if (!SetPropertyOptionalByDouble(env, progressObject, "maxValue", progress.GetMaxValue())) { + ANS_LOGD("WarpNotificationProgress: set maxValue failed"); + } + // currentValue?: number; + if (!SetPropertyOptionalByDouble(env, progressObject, "currentValue", progress.GetCurrentValue())) { + ANS_LOGD("WarpNotificationProgress: set currentValue failed"); + } + // isPercentage?: boolean; + if (!SetPropertyOptionalByBoolean(env, progressObject, "isPercentage", progress.GetIsPercentage())) { + ANS_LOGD("WarpNotificationProgress: set currentValue failed"); + } + ANS_LOGD("WarpNotificationProgress end"); + return true; +} + +void UnWarpNotificationTime(ani_env *env, ani_object obj, + NotificationTime ¬ificationTime) +{ + ANS_LOGD("UnWarpNotificationTime call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationTime failed, has nullptr"); + return; + } + ani_boolean isUndefined = ANI_TRUE; + ani_double initialTime = 0.0; + if (GetPropertyDouble(env, obj, "version", isUndefined, initialTime) == ANI_OK + && isUndefined == ANI_FALSE) { + notificationTime.SetInitialTime(static_cast(initialTime)); + } else { + ANS_LOGD("UnWarpNotificationTime: get version failed"); + } + bool isCountDown = true; + if (ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, isCountDown) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsCountDown(isCountDown); + } else { + ANS_LOGD("UnWarpNotificationTime: get isCountDown failed"); + } + bool isPaused = true; + if (ANI_OK == GetPropertyBool(env, obj, "isPaused", isUndefined, isPaused) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsPaused(isPaused); + } else { + ANS_LOGD("UnWarpNotificationTime: get isPaused failed"); + } + bool isInTitle = true; + isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyBool(env, obj, "isInTitle", isUndefined, isInTitle) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsInTitle(isInTitle); + } else { + ANS_LOGD("UnWarpNotificationTime: get isInTitle failed"); + } + ANS_LOGD("UnWarpNotificationTime end"); +} + +bool WarpNotificationTime(ani_env *env, const NotificationTime &time, bool isInitialTimeExist, ani_object &timeObject) +{ + ANS_LOGD("WarpNotificationTime call"); + if (env == nullptr) { + ANS_LOGE("WarpNotificationTime failed, env is nullptr"); + return false; + } + ani_class timeClass = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationTimeInner;", timeClass, timeObject) + || timeObject == nullptr) { + ANS_LOGE("WarpNotificationTime: create class failed"); + return false; + } + // initialTime?: number; + if (isInitialTimeExist) { + if (!SetPropertyOptionalByDouble(env, timeObject, "initialTime", time.GetInitialTime())) { + ANS_LOGD("WarpNotificationTime: set initialTime failed"); + } + } + // isCountDown?: boolean; + if (!SetPropertyOptionalByBoolean(env, timeObject, "isCountDown", time.GetIsCountDown())) { + ANS_LOGD("WarpNotificationTime: set isCountDown failed"); + } + // isPaused?: boolean; + if (!SetPropertyOptionalByBoolean(env, timeObject, "isPaused", time.GetIsPaused())) { + ANS_LOGD("WarpNotificationTime: set isPaused failed"); + } + // isInTitle?: boolean; + if (!SetPropertyOptionalByBoolean(env, timeObject, "isInTitle", time.GetIsInTitle())) { + ANS_LOGD("WarpNotificationTime: set isInTitle failed"); + } + ANS_LOGD("WarpNotificationTime end"); + return true; +} + +ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, NotificationIconButton &iconButton) +{ + ANS_LOGD("UnWarpNotificationIconButton call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationIconButton failed, env is nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; + std::string name = ""; + if ((status = GetPropertyString(env, obj, "name", isUndefined, name)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationIconButton: get name failed, status = %{public}d", status); + return ANI_INVALID_ARGS; + } + iconButton.SetName(name); + ani_ref iconRef = {}; + if ((status = GetPropertyRef(env, obj, "iconResource", isUndefined, iconRef)) != ANI_OK + || isUndefined == ANI_TRUE || iconRef == nullptr) { + ANS_LOGE("UnWarpNotificationIconButton: get iconResource failed, status = %{public}d", status); + return ANI_INVALID_ARGS; + } + ResourceManager::Resource resource; + if (ANI_OK == UnwrapResource(env, static_cast(iconRef), resource)) { + iconButton.SetIconResource(std::make_shared(resource)); + } else { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap == nullptr) { + ANS_LOGE("UnWarpNotificationIconButton: get iconResource failed"); + return ANI_INVALID_ARGS; + } + iconButton.SetIconImage(pixelMap); + } + std::string text = ""; + if (GetPropertyString(env, obj, "text", isUndefined, text) == ANI_OK && isUndefined == ANI_FALSE) { + iconButton.SetName(text); + } else { + ANS_LOGD("UnWarpNotificationIconButton: get text failed"); + } + bool hidePanel = true; + if (ANI_OK == GetPropertyBool(env, obj, "hidePanel", isUndefined, hidePanel) + && isUndefined == ANI_FALSE) { + iconButton.SetHidePanel(hidePanel); + } else { + ANS_LOGD("UnWarpNotificationIconButton: get hidePanel failed"); + } + ANS_LOGD("UnWarpNotificationIconButton end"); + return status; +} + +ani_status GetIconButtonArray(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + ANS_LOGD("GetIconButtonArray call"); + if (env == nullptr || param == nullptr || name == nullptr) { + ANS_LOGE("GetIconButtonArray failed, has nullptr"); + return ANI_ERROR; + } + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status = ANI_ERROR; + ani_double length; + if (((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK) || isUndefined == ANI_TRUE) { + ANS_LOGI("get param failed, may be %{public}s : undefined", name); + return ANI_INVALID_ARGS; + } + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + for (int i = 0; i < static_cast(length); i++) { + ani_ref buttonRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + NotificationIconButton button; + if (UnWarpNotificationIconButton(env, static_cast(buttonRef), button) == ANI_OK) { + res.push_back(button); + } else { + ANS_LOGE("GetIconButtonArray: UnWarpNotificationIconButton failed"); + return ANI_INVALID_ARGS; + } + } + ANS_LOGD("GetIconButtonArray end"); + return status; +} + +void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, + NotificationLocalLiveViewButton &button) +{ + ANS_LOGD("UnWarpNotificationLocalLiveViewButton call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationLocalLiveViewButton failed, has nullptr"); + return; + } + std::vector names = {}; + ani_boolean isUndefined = ANI_TRUE; + // names?: Array + if (GetPropertyStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { + for (auto name: names) { + button.addSingleButtonName(name); + } + } else { + ANS_LOGD("UnWarpNotificationLocalLiveViewButton get names failed."); + } + // icons?: Array + std::vector> icons = {}; + if (ANI_OK == GetPixelMapArray(env, obj, "icons", icons)) { + for (auto icon : icons) { + button.addSingleButtonIcon(icon); + } + } else { + ANS_LOGD("UnWarpNotificationLocalLiveViewButton get icons failed."); + } + // iconsResource?: Array + std::vector resources = {}; + if (ANI_OK == GetResourceArray(env, obj, "iconsResource", resources)) { + for (auto res : resources) { + std::shared_ptr pRes = std::make_shared(res); + button.addSingleButtonIconResource(pRes); + } + } else { + ANS_LOGD("UnWarpNotificationLocalLiveViewButton get iconsResource failed."); + } + ANS_LOGD("UnWarpNotificationLocalLiveViewButton end"); +} + +bool WarpNotificationLocalLiveViewButton( + ani_env *env, const NotificationLocalLiveViewButton &button, ani_object &buttonObject) +{ + ANS_LOGD("WarpNotificationLocalLiveViewButton call"); + if (env == nullptr) { + ANS_LOGE("WarpNotificationLocalLiveViewButton failed, env is nullptr"); + return false; + } + ani_class buttonClass = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationButtonInner;", buttonClass, buttonObject) + || buttonObject == nullptr) { + ANS_LOGE("WarpNotificationLocalLiveViewButton: create class failed"); + return false; + } + // names?: Array; + std::vector names = button.GetAllButtonNames(); + ani_object namesObjectArray = GetAniStringArrayByVectorString(env, names); + if (namesObjectArray == nullptr) { + ANS_LOGE("namesObjectArray is nullptr"); + return false; + } + if (!SetPropertyByRef(env, buttonObject, "names", namesObjectArray)) { + ANS_LOGE("Set names failed"); + return false; + } + // icons?: Array; + std::vector> icons = button.GetAllButtonIcons(); + ani_object iconsObjectArray = GetAniArrayPixelMap(env, icons); + if (iconsObjectArray == nullptr) { + ANS_LOGE("iconsObjectArray is nullptr"); + return false; + } + if (!SetPropertyByRef(env, buttonObject, "icons", iconsObjectArray)) { + ANS_LOGE("Set icons failed"); + return false; + } + // iconsResource?: Array; + std::vector> iconsResource = button.GetAllButtonIconResource(); + ani_object resourceObjectArray = GetAniArrayResource(env, iconsResource); + if (resourceObjectArray == nullptr) { + ANS_LOGE("resourceObjectArray is nullptr"); + return false; + } + if (!SetPropertyByRef(env, buttonObject, "iconsResource", resourceObjectArray)) { + ANS_LOGE("Set iconsResource failed"); + return false; + } + ANS_LOGD("WarpNotificationLocalLiveViewButton end"); + return true; +} + +void UnWarpNotificationCapsuleByOther(ani_env *env, ani_object obj, NotificationCapsule &capsule) +{ + ANS_LOGD("UnWarpNotificationCapsuleByOther call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationCapsuleByOther failed, has nullptr"); + return; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref iconRef = {}; + if (GetPropertyRef(env, obj, "icon", isUndefined, iconRef) != ANI_OK + || isUndefined == ANI_TRUE || iconRef == nullptr) { + ANS_LOGD("UnWarpNotificationCapsule: get icon ref failed"); + } else { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap != nullptr) { + capsule.SetIcon(pixelMap); + } else { + ANS_LOGD("UnWarpNotificationCapsule: get icon failed"); + } + } + std::vector iconButtons = {}; + if (GetIconButtonArray(env, obj, "capsuleButtons", iconButtons) == ANI_OK && !(iconButtons.empty())) { + capsule.SetCapsuleButton(iconButtons); + } else { + ANS_LOGD("UnWarpNotificationCapsule: get capsuleButtons failed"); + } +} + +void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule &capsule) +{ + ANS_LOGD("UnWarpNotificationCapsule call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationCapsule failed, has nullptr"); + return; + } + ani_boolean isUndefined = ANI_TRUE; + std::string title = ""; + if (GetPropertyString(env, obj, "title", isUndefined, title) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetTitle(title); + } else { + ANS_LOGE("UnWarpNotificationCapsule: get title failed"); + } + std::string backgroundColor = ""; + isUndefined = ANI_TRUE; + if (GetPropertyString(env, obj, "backgroundColor", isUndefined, backgroundColor) == ANI_OK + && isUndefined == ANI_FALSE) { + capsule.SetBackgroundColor(backgroundColor); + } else { + ANS_LOGE("UnWarpNotificationCapsule: get backgroundColor failed"); + } + std::string content = ""; + isUndefined = ANI_TRUE; + if (GetPropertyString(env, obj, "content", isUndefined, content) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetContent(content); + } else { + ANS_LOGE("UnWarpNotificationCapsule: get content failed"); + } + ani_double time = 0.0; + if (GetPropertyDouble(env, obj, "time", isUndefined, time) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetTime(static_cast(time)); + } else { + ANS_LOGE("UnWarpNotificationCapsule: get time failed"); + } + UnWarpNotificationCapsuleByOther(env, obj, capsule); + ANS_LOGD("UnWarpNotificationCapsule end"); +} + +ani_object WarpNotificationIconButton(ani_env *env, const NotificationIconButton &button) +{ + ANS_LOGD("WarpNotificationIconButton call"); + if (env == nullptr) { + ANS_LOGE("WarpNotificationIconButton failed, env is nullptr"); + return nullptr; + } + ani_class iconButtonCls = nullptr; + ani_object iconButtonObject = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationIconButtonInner;", iconButtonCls, iconButtonObject) + || iconButtonObject == nullptr) { + ANS_LOGE("WarpNotificationIconButton: create class failed"); + return nullptr; + } + // name: string + if (!SetPropertyOptionalByString(env, iconButtonObject, "name", button.GetName())) { + ANS_LOGE("WarpNotificationIconButton: set name failed"); + return nullptr; + } + // iconResource: IconType; type IconType = Resource | image.PixelMap; + std::shared_ptr icon = button.GetIconImage(); + if (icon) { + ani_object pixelMapObject = CreateAniPixelMap(env, icon); + if (pixelMapObject == nullptr) { + ANS_LOGE("WarpNotificationIconButton: pixelMapObject is nullptr"); + return nullptr; + } + if (!SetPropertyByRef(env, iconButtonObject, "iconResource", pixelMapObject)) { + ANS_LOGE("WarpNotificationIconButton: set iconResource failed"); + return nullptr; + } + } else { + ani_object resourceObject = GetAniResource(env, button.GetIconResource()); + if (resourceObject == nullptr) { + ANS_LOGE("WarpNotificationIconButton: resourceObject is nullptr"); + return nullptr; + } + if (!SetPropertyByRef(env, iconButtonObject, "iconResource", resourceObject)) { + ANS_LOGE("WarpNotificationIconButton: set iconResource failed"); + return nullptr; + } + } + // text?: string; + SetPropertyOptionalByString(env, iconButtonObject, "text", button.GetText()); + // hidePanel?: boolean; + SetPropertyOptionalByBoolean(env, iconButtonObject, "hidePanel", button.GetHidePanel()); + ANS_LOGD("WarpNotificationIconButton end"); + return iconButtonObject; +} + +ani_object GetAniIconButtonArray(ani_env *env, const std::vector buttons) +{ + ANS_LOGD("GetAniIconButtonArray start"); + if (env == nullptr || buttons.empty()) { + ANS_LOGE("GetAniIconButtonArray failed, env is nullptr or buttons is empty"); + return nullptr; + } + ani_object arrayObj = newArrayClass(env, buttons.size()); + if (arrayObj == nullptr) { + ANS_LOGE("GetAniIconButtonArray failed, arrayObj is nullptr"); + return nullptr; + } + ani_size index = 0; + for (auto &button : buttons) { + ani_object item = WarpNotificationIconButton(env, button); + if (item == nullptr) { + ANS_LOGE("GetAniIconButtonArray: item is nullptr"); + return nullptr; + } + if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { + ANS_LOGE("GetAniIconButtonArray: add item failed"); + return nullptr; + } + index ++; + } + ANS_LOGE("GetAniIconButtonArray end"); + return arrayObj; +} + +bool WarpNotificationCapsule(ani_env *env, const NotificationCapsule &capsule, ani_object &capsuleObject) +{ + ANS_LOGD("WarpNotificationCapsule start"); + if (env == nullptr) { + ANS_LOGE("GetAniIconButtonArray failed, env is nullptr"); + return false; + } + ani_class capsuleClass = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationCapsuleInner;", capsuleClass, capsuleObject) + || capsuleObject == nullptr) { + ANS_LOGE("GetAniIconButtonArray: create class failed"); + return false; + } + // title?: string; + SetPropertyOptionalByString(env, capsuleObject, "title", capsule.GetTitle()); + // icon?: image.PixelMap; + std::shared_ptr icon = capsule.GetIcon(); + if (icon) { + ani_object pixelMapObject = CreateAniPixelMap(env, icon); + if (pixelMapObject == nullptr) { + ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); + } else { + SetPropertyByRef(env, capsuleObject, "icon", pixelMapObject); + } + } + // backgroundColor?: string; + if (!SetPropertyOptionalByString(env, capsuleObject, "backgroundColor", capsule.GetBackgroundColor())) { + ANS_LOGD("WarpNotificationCapsule: set backgroundColor failed"); + } + //content?: string; + if (!SetPropertyOptionalByString(env, capsuleObject, "content", capsule.GetContent())) { + ANS_LOGD("WarpNotificationCapsule: set content failed"); + } + // time?: number; + if (!SetPropertyOptionalByDouble(env, capsuleObject, "time", capsule.GetTime())) { + ANS_LOGD("WarpNotificationCapsule: set time failed"); + } + // capsuleButtons?: Array; + std::vector buttons = capsule.GetCapsuleButton(); + ani_object buttonsObjectArray = GetAniIconButtonArray(env, buttons); + if (buttonsObjectArray == nullptr + || SetPropertyByRef(env, capsuleObject, "capsuleButtons", buttonsObjectArray)) { + ANS_LOGD("WarpNotificationCapsule: set capsuleButtons failed"); + } + ANS_LOGD("WarpNotificationCapsule end"); + return true; +} + +ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, + std::shared_ptr basicContent) +{ + ANS_LOGD("UnWarpNotificationBasicContent call"); + if (env == nullptr || obj == nullptr || basicContent == nullptr) { + ANS_LOGE("UnWarpNotificationBasicContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; + std::string title; + if ((status = GetPropertyString(env, obj, "title", isUndefined, title)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationBasicContent: get title failed, status = %{public}d", status); + return ANI_INVALID_ARGS; + } + basicContent->SetTitle(title); + std::string text; + if ((status = GetPropertyString(env, obj, "text", isUndefined, text)) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationBasicContent: get text failed, status = %{public}d", status); + return ANI_INVALID_ARGS; + } + basicContent->SetText(text); + std::string additionalText; + if (GetPropertyString(env, obj, "additionalText", isUndefined, additionalText) == ANI_OK + && isUndefined == ANI_FALSE) { + basicContent->SetAdditionalText(additionalText); + } else { + ANS_LOGD("UnWarpNotificationBasicContent: get additionalText failed"); + } + ani_ref lockscreenPictureRef = {}; + if (env->Object_GetPropertyByName_Ref(obj, "lockscreenPicture", &lockscreenPictureRef) != ANI_OK + || lockscreenPictureRef == nullptr) { + ANS_LOGD("UnWarpNotificationBasicContent: get lockscreenPicture failed"); + } else { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(lockscreenPictureRef)); + if (pixelMap != nullptr) { + basicContent->SetLockScreenPicture(pixelMap); + } else { + ANS_LOGD("UnWarpNotificationBasicContent: get lockscreenPicture by pixelMap failed"); + } + } + ANS_LOGD("UnWarpNotificationBasicContent end"); + return status; +} + +ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, + std::shared_ptr &normalContent) +{ + ANS_LOGD("UnWarpNotificationNormalContent call"); + if (env == nullptr || obj == nullptr || normalContent == nullptr) { + ANS_LOGE("UnWarpNotificationNormalContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, normalContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationNormalContent failed"); + return status; + } + ANS_LOGE("UnWarpNotificationNormalContent end"); + return status; +} + +ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, + std::shared_ptr &longTextContent) +{ + ANS_LOGD("UnWarpNotificationLongTextContent call"); + if (env == nullptr || obj == nullptr || longTextContent == nullptr) { + ANS_LOGE("UnWarpNotificationLongTextContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, longTextContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationLongTextContent:get BasicContent failed"); + return status; + } + ani_boolean isUndefined = ANI_TRUE; + std::string longText; + if ((status = GetPropertyString(env, obj, "longText", isUndefined, longText)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationLongTextContent:get longText failed"); + return ANI_INVALID_ARGS; + } + longTextContent->SetLongText(longText); + std::string briefText; + if ((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationLongTextContent:get briefText failed"); + return ANI_INVALID_ARGS; + } + longTextContent->SetBriefText(briefText); + std::string expandedTitle; + if ((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationLongTextContent:get expandedTitle failed"); + return ANI_INVALID_ARGS; + } + longTextContent->SetExpandedTitle(expandedTitle); + ANS_LOGD("UnWarpNotificationLongTextContent end"); + return status; +} + +ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, + std::shared_ptr &multiLineContent) +{ + ANS_LOGD("UnWarpNotificationMultiLineContent call"); + if (env == nullptr || obj == nullptr || multiLineContent == nullptr) { + ANS_LOGE("UnWarpNotificationMultiLineContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, multiLineContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationMultiLineContent: get BasicContent failed"); + return status; + } + ani_boolean isUndefined = ANI_TRUE; + std::string longTitle; + if ((status = GetPropertyString(env, obj, "longTitle", isUndefined, longTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationMultiLineContent: get longTitle failed"); + return ANI_INVALID_ARGS; + } + multiLineContent->SetExpandedTitle(longTitle); + + std::string briefText; + isUndefined = ANI_TRUE; + if ((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationMultiLineContent: get briefText failed"); + return ANI_INVALID_ARGS; + } + multiLineContent->SetBriefText(briefText); + + std::vector lines = {}; + isUndefined = ANI_TRUE; + if ((status = GetPropertyStringArray(env, obj, "lines", isUndefined, lines)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationMultiLineContent: get lines failed"); + return ANI_INVALID_ARGS; + } + for (auto line : lines) { + multiLineContent->AddSingleLine(line); + } + ANS_LOGD("UnWarpNotificationMultiLineContent end"); + return status; +} + +ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, + std::shared_ptr &pictureContent) +{ + ANS_LOGD("UnWarpNotificationPictureContent call"); + if (env == nullptr || obj == nullptr || pictureContent == nullptr) { + ANS_LOGE("UnWarpNotificationPictureContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, pictureContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationPictureContent: get BasicContent failed"); + return status; + } + std::string expandedTitle; + ani_boolean isUndefined = ANI_TRUE; + if ((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationPictureContent: get expandedTitle failed"); + return ANI_INVALID_ARGS; + } + pictureContent->SetExpandedTitle(expandedTitle); + + std::string briefText; + if ((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationPictureContent: get briefText failed"); + return ANI_INVALID_ARGS; + } + pictureContent->SetBriefText(briefText); + ani_ref pictureRef = {}; + if ((status = GetPropertyRef(env, obj, "picture", isUndefined, pictureRef)) != ANI_OK + || isUndefined == ANI_TRUE || pictureRef == nullptr) { + ANS_LOGE("UnWarpNotificationPictureContent: get briefText failed"); + return ANI_INVALID_ARGS; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pictureRef)); + if (pixelMap == nullptr) { + ANS_LOGE("UnWarpNotificationPictureContent: get briefText by pixelMap failed"); + return ANI_INVALID_ARGS; + } + pictureContent->SetBigPicture(pixelMap); + ANS_LOGD("UnWarpNotificationPictureContent end"); + return status; +} + +bool CheckAniLiveViewContentParam( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) +{ + if (env == nullptr) { + ANS_LOGE("env is null"); + return false; + } + if (obj == nullptr) { + ANS_LOGE("obj is null"); + return false; + } + if (liveViewContent == nullptr) { + ANS_LOGE("liveViewContent is null"); + return false; + } + return true; +} + +void GetAniLiveViewContentVersion( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) +{ + if (!CheckAniLiveViewContentParam(env, obj, liveViewContent)) { + ANS_LOGD("CheckAniLiveViewContentParam faild"); + return; + } + ani_double versionAni = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if (GetPropertyDouble(env, obj, "version", isUndefined, versionAni) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get version failed"); + return; + } + liveViewContent->SetVersion(static_cast(versionAni)); +} + +void GetAniLiveViewContentExtraInfo( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) +{ + if (!CheckAniLiveViewContentParam(env, obj, liveViewContent)) { + ANS_LOGD("CheckAniLiveViewContentParam faild"); + return; + } + ani_status status = ANI_OK; + ani_ref extraInfoRef; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK != (status = GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef)) + || isUndefined == ANI_TRUE || extraInfoRef == nullptr) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo failed. status %{public}d", status); + return; + } + AAFwk::WantParams wantParams = {}; + if (!UnwrapWantParams(env, extraInfoRef, wantParams)) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo by ref failed"); + return; + } + std::shared_ptr extraInfo = std::make_shared(wantParams); + liveViewContent->SetExtraInfo(extraInfo); +} + +void GetAniLiveViewContentPictureInfo( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) +{ + if (!CheckAniLiveViewContentParam(env, obj, liveViewContent)) { + ANS_LOGD("CheckAniLiveViewContentParam faild"); + return; + } + ani_ref pictureInfoRef; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK != GetPropertyRef(env, obj, "pictureInfo", isUndefined, pictureInfoRef) + || isUndefined == ANI_TRUE || pictureInfoRef == nullptr) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); + return; + } + std::map>> pictureMap; + if (GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) != ANI_OK) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo by ref failed"); + return; + } + liveViewContent->SetPicture(pictureMap); +} + +void GetAniLiveViewContentIsLocalUpdateOnly( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) +{ + if (!CheckAniLiveViewContentParam(env, obj, liveViewContent)) { + ANS_LOGD("CheckAniLiveViewContentParam faild"); + return; + } + ani_status status = ANI_OK; + bool isLocalUpdateOnly = true; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK != (status = GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly))) { + ANS_LOGD("get 'isLocalUpdateOnly' faild. status %{public}d", status); + return; + } + if (isUndefined == ANI_TRUE) { + ANS_LOGD("'isLocalUpdateOnly' is Undefined"); + return; + } + liveViewContent->SetIsOnlyLocalUpdate(isLocalUpdateOnly); +} + +void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent) +{ + ANS_LOGD("UnWarpNotificationLiveViewContentByOther call"); + if (!CheckAniLiveViewContentParam(env, obj, liveViewContent)) { + ANS_LOGD("CheckAniLiveViewContentParam faild"); + return; + } + GetAniLiveViewContentVersion(env, obj, liveViewContent); + GetAniLiveViewContentExtraInfo(env, obj, liveViewContent); + GetAniLiveViewContentPictureInfo(env, obj, liveViewContent); + GetAniLiveViewContentIsLocalUpdateOnly(env, obj, liveViewContent); + ANS_LOGD("UnWarpNotificationLiveViewContentByOther end"); +} + +ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent) +{ + ANS_LOGD("UnWarpNotificationLiveViewContent call"); + if (env == nullptr || obj == nullptr || liveViewContent == nullptr) { + ANS_LOGE("UnWarpNotificationLiveViewContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationLiveViewContent: get BasicContent failed"); + return status; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref statusRef; + if ((status = GetPropertyRef(env, obj, "status", isUndefined, statusRef)) != ANI_OK + || isUndefined == ANI_TRUE || statusRef == nullptr) { + ANS_LOGE("UnWarpNotificationLiveViewContent: get status failed"); + return ANI_INVALID_ARGS; + } + LiveViewStatus liveViewStatus = LiveViewStatus::LIVE_VIEW_CREATE; + if (!LiveViewStatusEtsToC(env, static_cast(statusRef), liveViewStatus)) { + ANS_LOGE("UnWarpNotificationLiveViewContent: get status by ref failed"); + return ANI_INVALID_ARGS; + } + liveViewContent->SetLiveViewStatus(liveViewStatus); + UnWarpNotificationLiveViewContentByOther(env, obj, liveViewContent); + ANS_LOGD("UnWarpNotificationLiveViewContent end"); + return status; +} + +void GetLocalLiveViewContentByOne(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent) +{ + ANS_LOGD("GetLocalLiveViewContentByOne call"); + if (env == nullptr || obj == nullptr || localLiveViewContent == nullptr) { + ANS_LOGE("GetLocalLiveViewContentByOne failed, has nullptr"); + return; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref capsuleRef = {}; + if (GetPropertyRef(env, obj, "capsule", isUndefined, capsuleRef) == ANI_OK + && isUndefined == ANI_FALSE && capsuleRef != nullptr) { + NotificationCapsule capsule; + UnWarpNotificationCapsule(env, static_cast(capsuleRef), capsule); + localLiveViewContent->SetCapsule(capsule); + } else { + ANS_LOGD("GetLocalLiveViewContentByOne: get capsule failed"); + } + ani_ref buttonRef = {}; + if (GetPropertyRef(env, obj, "button", isUndefined, buttonRef) == ANI_OK + && isUndefined == ANI_FALSE && buttonRef != nullptr) { + NotificationLocalLiveViewButton button; + UnWarpNotificationLocalLiveViewButton(env, static_cast(buttonRef), button); + localLiveViewContent->SetButton(button); + } else { + ANS_LOGD("GetLocalLiveViewContentByOne: get button failed"); + } + std::vector buttons = {}; + if (GetIconButtonArray(env, obj, "cardButtons", buttons) == ANI_OK) { + localLiveViewContent->SetCardButton(buttons); + } else { + ANS_LOGD("GetLocalLiveViewContentByOne: get cardButtons failed"); + } + ANS_LOGD("GetLocalLiveViewContentByOne end"); +} + +void GetLocalLiveViewContentByTwo(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent) +{ + ANS_LOGD("GetLocalLiveViewContentByTwo call"); + if (env == nullptr || obj == nullptr || localLiveViewContent == nullptr) { + ANS_LOGE("GetLocalLiveViewContentByTwo failed, has nullptr"); + return; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref timeRef = {}; + if (GetPropertyRef(env, obj, "time", isUndefined, timeRef) == ANI_OK + && isUndefined == ANI_FALSE && timeRef != nullptr) { + NotificationTime notificationTime; + UnWarpNotificationTime(env, static_cast(timeRef), notificationTime); + localLiveViewContent->SetTime(notificationTime); + } else { + ANS_LOGD("GetLocalLiveViewContentByTwo: get time failed"); + } + ani_ref progressRef = {}; + if (GetPropertyRef(env, obj, "progress", isUndefined, progressRef) == ANI_OK + && isUndefined == ANI_FALSE && progressRef != nullptr) { + NotificationProgress notificationProgress; + UnWarpNotificationProgress(env, static_cast(progressRef), notificationProgress); + localLiveViewContent->SetProgress(notificationProgress); + } else { + ANS_LOGD("GetLocalLiveViewContentByTwo: get progress failed"); + } + ani_ref liveViewTypeRef = {}; + if (GetPropertyRef(env, obj, "liveViewType", isUndefined, liveViewTypeRef) == ANI_OK + && isUndefined == ANI_FALSE && liveViewTypeRef != nullptr) { + LiveViewTypes types = LiveViewTypes::LIVE_VIEW_ACTIVITY; + if (LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), types)) { + localLiveViewContent->SetLiveViewType(types); + } else { + ANS_LOGD("GetLocalLiveViewContentByTwo: get liveViewType by ref failed"); + } + } else { + ANS_LOGD("GetLocalLiveViewContentByTwo: get liveViewType failed"); + } + ANS_LOGD("GetLocalLiveViewContentByTwo end"); +} + +ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent) +{ + ANS_LOGD("UnWarpNotificationLocalLiveViewContent call"); + if (env == nullptr || obj == nullptr || localLiveViewContent == nullptr) { + ANS_LOGE("UnWarpNotificationLocalLiveViewContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + if ((status = UnWarpNotificationBasicContent(env, obj, localLiveViewContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationLocalLiveViewContent: get BasicContent failed"); + return status; + } + ani_double typeCode = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if ((status = GetPropertyDouble(env, obj, "typeCode", isUndefined, typeCode)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationLocalLiveViewContent: get typeCode failed"); + return ANI_INVALID_ARGS; + } + localLiveViewContent->SetType(static_cast(typeCode)); + GetLocalLiveViewContentByOne(env, obj, localLiveViewContent); + GetLocalLiveViewContentByTwo(env, obj, localLiveViewContent); + ANS_LOGD("UnWarpNotificationLocalLiveViewContent end"); + return status; +} + +bool SetNotificationBasicContent( + ani_env* env, const NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("SetNotificationBasicContent call"); + if (env == nullptr || basicContent == nullptr || object == nullptr) { + ANS_LOGE("SetNotificationBasicContent failed, has nullptr"); + return false; + } + if (!SetPropertyOptionalByString(env, object, "title", basicContent->GetTitle())) { + ANS_LOGE("SetNotificationBasicContent: set title failed"); + return false; + } + if (!SetPropertyOptionalByString(env, object, "text", basicContent->GetText())) { + ANS_LOGE("SetNotificationBasicContent: set text failed"); + return false; + } + if (!SetPropertyOptionalByString(env, object, "additionalText", basicContent->GetAdditionalText())) { + ANS_LOGD("SetNotificationBasicContent: set additionalText failed"); + } + ani_ref lockScreenPicObj = CreateAniPixelMap(env, basicContent->GetLockScreenPicture()); + if (lockScreenPicObj == nullptr || !SetPropertyByRef(env, object, "lockScreenPicture", lockScreenPicObj)) { + ANS_LOGD("SetNotificationBasicContent: set lockScreenPicture failed"); + } + ANS_LOGD("SetNotificationBasicContent end"); + return true; +} + +bool SetNotificationNormalContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationNormalContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationNormalContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationBasicContentInner;", contentCls, contentObj) + || contentCls == nullptr || contentObj == nullptr) { + ANS_LOGE("SetNotificationNormalContent: create class failed"); + return false; + } + std::shared_ptr basicContent = nContent->GetNotificationContent(); + if (basicContent == nullptr) { + ANS_LOGE("SetNotificationNormalContent: get basicContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, basicContent.get(), contentObj)) { + ANS_LOGE("SetNotificationNormalContent: set basicContent failed"); + return false; + } + if (!SetPropertyByRef(env, ncObj, "normal", contentObj)) { + ANS_LOGE("SetNotificationNormalContent: set normal to ncObj failed"); + return false; + } + return true; +} + +bool SetNotificationLongTextContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationLongTextContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationLongTextContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationLongTextContentInner;", contentCls, contentObj) + || contentObj == nullptr) { + ANS_LOGE("SetNotificationLongTextContent: create class failed"); + return false; + } + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationLongTextContent: get LongTextContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationLongTextContent: set BasicContent failed"); + return false; + } + if (!SetPropertyOptionalByString(env, contentObj, "longText", content->GetLongText())) { + ANS_LOGE("SetNotificationLongTextContent: set longText failed"); + return false; + } + if (!SetPropertyOptionalByString(env, contentObj, "briefText", content->GetBriefText())) { + ANS_LOGE("SetNotificationLongTextContent: set briefText failed"); + return false; + } + if (!SetPropertyOptionalByString(env, contentObj, "expandedTitle", content->GetExpandedTitle())) { + ANS_LOGE("SetNotificationLongTextContent: set expandedTitle failed"); + return false; + } + return SetPropertyByRef(env, ncObj, "longText", contentObj); +} + +bool SetNotificationPictureContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationPictureContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationPictureContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationPictureContentInner;", contentCls, contentObj) + || contentObj == nullptr) { + ANS_LOGE("SetNotificationPictureContent: create class failed"); + return false; + } + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationPictureContent: get PictureContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationPictureContent: set BasicContent failed"); + return false; + } + if (!SetPropertyOptionalByString(env, contentObj, "briefText", content->GetBriefText())) { + ANS_LOGD("SetNotificationPictureContent: set briefText failed"); + } + if (!SetPropertyOptionalByString(env, contentObj, "expandedTitle", content->GetExpandedTitle())) { + ANS_LOGD("SetNotificationPictureContent: set expandedTitle failed"); + } + ani_object pictureObj = CreateAniPixelMap(env, content->GetBigPicture()); + if (pictureObj == nullptr || !SetPropertyByRef(env, contentObj, "picture", pictureObj)) { + ANS_LOGD("SetNotificationPictureContent: set picture failed"); + } + return SetPropertyByRef(env, ncObj, "picture", contentObj); +} + +bool SetNotificationMultiLineContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationMultiLineContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationMultiLineContentInner;", contentCls, contentObj) + || contentObj == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent: create class failed"); + return false; + } + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent: get MultiLineContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationMultiLineContent: set BasicContent failed"); + return false; + } + if (!SetPropertyOptionalByString(env, contentObj, "briefText", content->GetBriefText())) { + ANS_LOGD("SetNotificationMultiLineContent: set briefText failed"); + } + if (!SetPropertyOptionalByString(env, contentObj, "longTitle", content->GetExpandedTitle())) { + ANS_LOGD("SetNotificationMultiLineContent: set briefText failed"); + } + std::vector allLines = content->GetAllLines(); + ani_object allLinesObject = GetAniStringArrayByVectorString(env, allLines); + if (allLinesObject == nullptr || !SetPropertyByRef(env, contentObj, "lines", allLinesObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set lines failed"); + } + return SetPropertyByRef(env, ncObj, "multiLine", contentObj); +} + +void SetCapsule(ani_env *env, std::shared_ptr &content, ani_object &contentObj) +{ + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { + ani_object capsuleObject = nullptr; + if (!WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) + || capsuleObject == nullptr || !SetPropertyByRef(env, contentObj, "capsule", capsuleObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set capsule failed"); + } + } +} + +void SetButton(ani_env *env, std::shared_ptr &content, ani_object &contentObj) +{ + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::BUTTON)) { + ani_object buttonObject = nullptr; + if (!WarpNotificationLocalLiveViewButton(env, content->GetButton(), buttonObject) + || buttonObject == nullptr || !SetPropertyByRef(env, contentObj, "button", buttonObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set button failed"); + } + } +} + +void SetCardButtons(ani_env *env, std::shared_ptr &content, ani_object &contentObj) +{ + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CARD_BUTTON)) { + std::vector buttons = content->GetCardButton(); + ani_object buttonsObjectArray = GetAniIconButtonArray(env, buttons); + if (buttonsObjectArray == nullptr || !SetPropertyByRef(env, contentObj, "cardButtons", buttonsObjectArray)) { + ANS_LOGD("SetNotificationMultiLineContent: set cardButtons failed"); + } + } +} + +void SetProgress(ani_env *env, std::shared_ptr &content, ani_object &contentObj) +{ + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::PROGRESS)) { + ani_object progressObject = nullptr; + if (!WarpNotificationProgress(env, content->GetProgress(), progressObject) + || progressObject == nullptr || !SetPropertyByRef(env, contentObj, "progress", progressObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set progress failed"); + } + } +} + +void SetTime(ani_env *env, std::shared_ptr &content, ani_object &contentObj) +{ + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::TIME)) { + bool flag = content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::INITIAL_TIME); + ani_object timeObject = nullptr; + if (!WarpNotificationTime(env, content->GetTime(), flag, timeObject) + || timeObject == nullptr || !SetPropertyByRef(env, contentObj, "time", timeObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set time failed"); + } + } +} + +bool WarpLocalLiveViewContentWithFalg( + ani_env* env, std::shared_ptr nContent, ani_object &contentObj) +{ + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent: get LocalLiveViewContent failed"); + return false; + } + SetCapsule(env, content, contentObj); + SetButton(env, content, contentObj); + SetCardButtons(env, content, contentObj); + SetProgress(env, content, contentObj); + SetTime(env, content, contentObj); + return true; +} + + +bool WarpNotificationLocalLiveViewContent( + ani_env* env, std::shared_ptr nContent, ani_object &contentObj) +{ + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent: get LocalLiveViewContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationMultiLineContent: set BasicContent failed"); + return false; + } + if (!SetPropertyOptionalByInt(env, contentObj, "typeCode", content->GetType())) { + ANS_LOGD("SetNotificationMultiLineContent: set typeCode failed"); + } + ani_enum_item enumItem = nullptr; + if (!LiveViewTypesCToEts(env, content->GetLiveViewType(), enumItem) + || enumItem == nullptr || !SetPropertyByRef(env, contentObj, "liveViewType", enumItem)) { + ANS_LOGD("SetNotificationMultiLineContent: set liveViewType failed"); + } + if (!WarpLocalLiveViewContentWithFalg(env, nContent, contentObj)) { + ANS_LOGE("WarpLocalLiveViewContentWithFalg faild"); + return false; + } + return true; +} + +bool SetNotificationLocalLiveViewContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationMultiLineContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", contentCls, contentObj) + || contentObj == nullptr) { + ANS_LOGE("SetNotificationMultiLineContent: create class failed"); + return false; + } + if (!WarpNotificationLocalLiveViewContent(env, nContent, contentObj)) { + ANS_LOGE("WarpNotificationLocalLiveViewContent faild"); + return false; + } + return SetPropertyByRef(env, ncObj, "systemLiveView", contentObj); +} + +bool WarpLiveViewContentBasicContent( + ani_env *env, std::shared_ptr nContent, ani_object &contentObj) +{ + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationLiveViewContent: get LiveViewContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationLiveViewContent: set BasicContent failed"); + return false; + } + return true; +} + +bool WarpNotificationLiveViewContent( + ani_env *env, std::shared_ptr nContent, ani_object &contentObj) +{ + if (!WarpLiveViewContentBasicContent(env, nContent, contentObj)) { + ANS_LOGE("WarpLiveViewContentBasicContent faild"); + return false; + } + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); + if (content == nullptr) { + ANS_LOGE("SetNotificationLiveViewContent: get LiveViewContent failed"); + return false; + } + ani_object lockScreenPicObj = CreateAniPixelMap(env, content->GetLockScreenPicture()); + if (lockScreenPicObj == nullptr || !SetPropertyByRef(env, contentObj, "lockScreenPicture", lockScreenPicObj)) { + ANS_LOGD("SetNotificationLiveViewContent: set lockScreenPicture failed"); + } + ani_enum_item enumItem = nullptr; + if (!LiveViewStatusCToEts(env, content->GetLiveViewStatus(), enumItem) + || enumItem == nullptr || !SetPropertyByRef(env, contentObj, "status", enumItem)) { + ANS_LOGD("SetNotificationLiveViewContent: set status failed"); + } + if (!SetPropertyOptionalByInt(env, contentObj, "version", static_cast(content->GetVersion()))) { + ANS_LOGD("SetNotificationLiveViewContent: set version failed"); + } + std::shared_ptr extraInfoData = content->GetExtraInfo(); + if (extraInfoData == nullptr) { + ANS_LOGD("SetNotificationLiveViewContent: set extraInfo failed"); + } else { + ani_ref extraInfoObj = WrapWantParams(env, *extraInfoData); + if (extraInfoObj == nullptr || !SetPropertyByRef(env, contentObj, "extraInfo", extraInfoObj)) { + ANS_LOGD("SetNotificationLiveViewContent: set extraInfo by ref failed"); + } + } + ani_object pictureInfoObj = nullptr; + if (!GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) + || pictureInfoObj == nullptr || SetPropertyByRef(env, contentObj, "pictureInfo", pictureInfoObj)) { + ANS_LOGD("SetNotificationLiveViewContent: set pictureInfo failed"); + } + return true; +} + +bool SetNotificationLiveViewContent( + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationLiveViewContent call"); + if (env == nullptr || nContent == nullptr || ncObj == nullptr) { + ANS_LOGE("SetNotificationLiveViewContent failed, has nullptr"); + return false; + } + ani_class contentCls; + ani_object contentObj; + if (!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", + contentCls, contentObj) || contentObj == nullptr) { + ANS_LOGE("SetNotificationLiveViewContent: create class failed"); + return false; + } + if (!WarpNotificationLiveViewContent(env, nContent, contentObj)) { + ANS_LOGE("WarpNotificationLiveViewContent faild"); + return false; + } + return SetPropertyByRef(env, ncObj, "liveView", contentObj); +} + +bool SetNotificationContent(ani_env* env, std::shared_ptr ncContent, ani_object &ncObj) +{ + ANS_LOGD("SetNotificationContent call"); + if (env == nullptr || ncContent == nullptr) { + ANS_LOGE("SetNotificationContent failed, has nullptr"); + return false; + } + ani_class ncCls; + if (!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationContentInner;", + ncCls, ncObj) || ncObj == nullptr) { + ANS_LOGE("SetNotificationContent: create class failed"); + return false; + } + ContentType contentType = ncContent->GetContentType(); + ani_enum_item contentTypeItem {}; + if (!ContentTypeCToEts(env, contentType, contentTypeItem) + || !SetPropertyByRef(env, ncObj, "notificationContentType", contentTypeItem)) { + ANS_LOGE("SetNotificationContent: set notificationContentType failed"); + return false; + } + bool result = true; + ANS_LOGD("SetNotificationContent: contentType = %{public}d", static_cast(contentType)); + switch (contentType) { + case ContentType::BASIC_TEXT: // normal?: NotificationBasicContent + result = SetNotificationNormalContent(env, ncContent, ncObj); + break; + case ContentType::LONG_TEXT: // longText?: NotificationLongTextContent + result = SetNotificationLongTextContent(env, ncContent, ncObj); + break; + case ContentType::PICTURE: // picture?: NotificationPictureContent + result = SetNotificationPictureContent(env, ncContent, ncObj); + break; + case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent + result = SetNotificationMultiLineContent(env, ncContent, ncObj); + break; + case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent + result = SetNotificationLocalLiveViewContent(env, ncContent, ncObj); + break; + case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent + result = SetNotificationLiveViewContent(env, ncContent, ncObj); + break; + default: + result = false; + break; + } + if (!result) { + ANS_LOGE("SetNotificationContent failed"); + } + ANS_LOGD("SetNotificationContent end"); + return result; +} +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef7771fbd600ce262ffe4e62c5fb918533cef25d --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 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 "sts_notification_flag.h" +#include "sts_common.h" + +namespace OHOS { +namespace NotificationSts { +bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, + ani_object &flagsObject) +{ + ANS_LOGD("WarpNotificationFlags call"); + if (flags == nullptr) { + ANS_LOGE("flags is null"); + return false; + } + ani_class flagsCls = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationFlags/NotificationFlagsInner;", flagsCls, flagsObject) || + flagsObject == nullptr) { + ANS_LOGE("Create faild"); + return false; + } + // readonly soundEnabled?: NotificationFlagStatus; + int32_t soundEnabled = static_cast(flags->IsSoundEnabled()); + ani_enum_item enumItem = nullptr; + if (!EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + soundEnabled, enumItem)) { + ANS_LOGE("EnumConvertNativeToAni 'soundEnabled' faild"); + return false; + } + if (!SetPropertyByRef(env, flagsObject, "soundEnabled", enumItem)) { + ANS_LOGE("WarpNotificationFlags set 'soundEnabled' faild"); + return false; + } + // readonly vibrationEnabled?: NotificationFlagStatus; + int32_t vibrationEnabled = static_cast(flags->IsVibrationEnabled()); + if (!EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + vibrationEnabled, enumItem)) { + ANS_LOGE("EnumConvertNativeToAni 'vibrationEnabled' faild"); + return false; + } + if (!SetPropertyByRef(env, flagsObject, "vibrationEnabled", enumItem)) { + ANS_LOGE("WarpNotificationFlags set 'vibrationEnabled' faild"); + return false; + } + // readonly reminderFlags?: number; + uint32_t reminderFlags = flags->GetReminderFlags(); + if (!SetPropertyOptionalByDouble(env, flagsObject, "reminderFlags", reminderFlags)) { + ANS_LOGD("WarpNotificationFlags set 'reminderFlags' faild"); + } + return true; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb011638169efb21a1ab19def7c9c11a1879cf00 --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -0,0 +1,770 @@ +/* + * Copyright (c) 2025 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 "sts_notification_manager.h" +#include "sts_common.h" +#include "ani_common_util.h" +#include "ani_common_want.h" + +namespace OHOS { +namespace NotificationSts { +bool SetDate(ani_env *env, ani_object obj, const char *name, int64_t time) +{ + ANS_LOGD("SetDate call"); + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("SetDate failed, has nullptr"); + return false; + } + ani_object timeObj; + if (!CreateDate(env, time, timeObj)) { + ANS_LOGE("CreateDate faild."); + return false; + } + if (!SetPropertyByRef(env, obj, name, timeObj)) { + ANS_LOGE("set '%{public}s' faild.", name); + return false; + } + ANS_LOGD("SetDate end"); + return true; +} + +bool StsSlotTypeUtils::StsToC(const STSSlotType inType, SlotType &outType) +{ + switch (inType) { + case STSSlotType::SOCIAL_COMMUNICATION: + outType = SlotType::SOCIAL_COMMUNICATION; + break; + case STSSlotType::SERVICE_INFORMATION: + outType = SlotType::SERVICE_REMINDER; + break; + case STSSlotType::CONTENT_INFORMATION: + outType = SlotType::CONTENT_INFORMATION; + break; + case STSSlotType::LIVE_VIEW: + outType = SlotType::LIVE_VIEW; + break; + case STSSlotType::CUSTOMER_SERVICE: + outType = SlotType::CUSTOMER_SERVICE; + break; + case STSSlotType::EMERGENCY_INFORMATION: + outType = SlotType::EMERGENCY_INFORMATION; + break; + case STSSlotType::UNKNOWN_TYPE: + case STSSlotType::OTHER_TYPES: + outType = SlotType::OTHER; + break; + default: + ANS_LOGE("SlotType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsSlotTypeUtils::CToSts(const SlotType inType, STSSlotType &outType) +{ + switch (inType) { + case SlotType::CUSTOM: + outType = STSSlotType::UNKNOWN_TYPE; + break; + case SlotType::SOCIAL_COMMUNICATION: + outType = STSSlotType::SOCIAL_COMMUNICATION; + break; + case SlotType::SERVICE_REMINDER: + outType = STSSlotType::SERVICE_INFORMATION; + break; + case SlotType::CONTENT_INFORMATION: + outType = STSSlotType::CONTENT_INFORMATION; + break; + case SlotType::LIVE_VIEW: + outType = STSSlotType::LIVE_VIEW; + break; + case SlotType::CUSTOMER_SERVICE: + outType = STSSlotType::CUSTOMER_SERVICE; + break; + case SlotType::EMERGENCY_INFORMATION: + outType = STSSlotType::EMERGENCY_INFORMATION; + break; + case SlotType::OTHER: + outType = STSSlotType::OTHER_TYPES; + break; + default: + ANS_LOGE("SlotType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsContentTypeUtils::StsToC(const STSContentType inType, ContentType &outType) +{ + switch (inType) { + case STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT: + outType = ContentType::BASIC_TEXT; + break; + case STSContentType::NOTIFICATION_CONTENT_LONG_TEXT: + outType = ContentType::LONG_TEXT; + break; + case STSContentType::NOTIFICATION_CONTENT_MULTILINE: + outType = ContentType::MULTILINE; + break; + case STSContentType::NOTIFICATION_CONTENT_PICTURE: + outType = ContentType::PICTURE; + break; + case STSContentType::NOTIFICATION_CONTENT_CONVERSATION: + outType = ContentType::CONVERSATION; + break; + case STSContentType::NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW: + outType = ContentType::LOCAL_LIVE_VIEW; + break; + case STSContentType::NOTIFICATION_CONTENT_LIVE_VIEW: + outType = ContentType::LIVE_VIEW; + break; + default: + ANS_LOGE("ContentType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsContentTypeUtils::CToSts(const ContentType inType, STSContentType &outType) +{ + switch (inType) { + case ContentType::BASIC_TEXT: + outType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + break; + case ContentType::LONG_TEXT: + outType = STSContentType::NOTIFICATION_CONTENT_LONG_TEXT; + break; + case ContentType::MULTILINE: + outType = STSContentType::NOTIFICATION_CONTENT_MULTILINE; + break; + case ContentType::PICTURE: + outType = STSContentType::NOTIFICATION_CONTENT_PICTURE; + break; + case ContentType::CONVERSATION: + outType = STSContentType::NOTIFICATION_CONTENT_CONVERSATION; + break; + case ContentType::LOCAL_LIVE_VIEW: + outType = STSContentType::NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW; + break; + case ContentType::LIVE_VIEW: + outType = STSContentType::NOTIFICATION_CONTENT_LIVE_VIEW; + break; + default: + ANS_LOGE("ContentType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsSlotLevelUtils::CToSts(const SlotLevel inLevel, STSSlotLevel &outLevel) +{ + switch (inLevel) { + case SlotLevel::LEVEL_NONE: + case SlotLevel::LEVEL_UNDEFINED: + outLevel = STSSlotLevel::LEVEL_NONE; + break; + case SlotLevel::LEVEL_MIN: + outLevel = STSSlotLevel::LEVEL_MIN; + break; + case SlotLevel::LEVEL_LOW: + outLevel = STSSlotLevel::LEVEL_LOW; + break; + case SlotLevel::LEVEL_DEFAULT: + outLevel = STSSlotLevel::LEVEL_DEFAULT; + break; + case SlotLevel::LEVEL_HIGH: + outLevel = STSSlotLevel::LEVEL_HIGH; + break; + default: + ANS_LOGE("SlotLevel %{public}d is an invalid value", inLevel); + return false; + } + return true; +} + +bool StsSlotLevelUtils::StsToC(const STSSlotLevel inLevel, SlotLevel &outLevel) +{ + switch (inLevel) { + case STSSlotLevel::LEVEL_NONE: + outLevel = SlotLevel::LEVEL_NONE; + break; + case STSSlotLevel::LEVEL_MIN: + outLevel = SlotLevel::LEVEL_MIN; + break; + case STSSlotLevel::LEVEL_LOW: + outLevel = SlotLevel::LEVEL_LOW; + break; + case STSSlotLevel::LEVEL_DEFAULT: + outLevel = SlotLevel::LEVEL_DEFAULT; + break; + case STSSlotLevel::LEVEL_HIGH: + outLevel = SlotLevel::LEVEL_HIGH; + break; + default: + ANS_LOGE("SlotLevel %{public}d is an invalid value", inLevel); + return false; + } + return true; +} + +bool StsDoNotDisturbTypeUtils::StsToC(const STSDoNotDisturbType inType, + OHOS::Notification::NotificationConstant::DoNotDisturbType &outType) +{ + switch (inType) { + case STSDoNotDisturbType::TYPE_NONE: + outType = Notification::NotificationConstant::DoNotDisturbType::NONE; + break; + case STSDoNotDisturbType::TYPE_ONCE: + outType = Notification::NotificationConstant::DoNotDisturbType::ONCE; + break; + case STSDoNotDisturbType::TYPE_DAILY: + outType = Notification::NotificationConstant::DoNotDisturbType::DAILY; + break; + case STSDoNotDisturbType::TYPE_CLEARLY: + outType = Notification::NotificationConstant::DoNotDisturbType::CLEARLY; + break; + default: + ANS_LOGE("STSDoNotDisturbType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsRemindTypeUtils::StsToC(const STSRemindType inType, RemindType &outType) +{ + switch (inType) { + case STSRemindType::IDLE_DONOT_REMIND: + outType = RemindType::DEVICE_IDLE_DONOT_REMIND; + break; + case STSRemindType::IDLE_REMIND: + outType = RemindType::DEVICE_IDLE_REMIND; + break; + case STSRemindType::ACTIVE_DONOT_REMIND: + outType = RemindType::DEVICE_ACTIVE_DONOT_REMIND; + break; + case STSRemindType::ACTIVE_REMIND: + outType = RemindType::DEVICE_ACTIVE_REMIND; + break; + default: + ANS_LOGE("STSRemindType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsRemindTypeUtils::CToSts(const RemindType inType, STSRemindType &outType) +{ + switch (inType) { + case RemindType::NONE: + case RemindType::DEVICE_IDLE_DONOT_REMIND: + outType = STSRemindType::IDLE_DONOT_REMIND; + break; + case RemindType::DEVICE_IDLE_REMIND: + outType = STSRemindType::IDLE_REMIND; + break; + case RemindType::DEVICE_ACTIVE_DONOT_REMIND: + outType = STSRemindType::ACTIVE_DONOT_REMIND; + break; + case RemindType::DEVICE_ACTIVE_REMIND: + outType = STSRemindType::ACTIVE_REMIND; + break; + default: + ANS_LOGE("RemindType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +StsNotificationLocalLiveViewSubscriber::StsNotificationLocalLiveViewSubscriber() +{} + +StsNotificationLocalLiveViewSubscriber::~StsNotificationLocalLiveViewSubscriber() +{} + +void StsNotificationLocalLiveViewSubscriber::OnConnected() +{} + +void StsNotificationLocalLiveViewSubscriber::OnDisconnected() +{} + +void StsNotificationLocalLiveViewSubscriber::OnDied() +{} + +void StsNotificationLocalLiveViewSubscriber::OnResponse(int32_t notificationId, sptr buttonOption) +{ + ANS_LOGD("OnResponse call"); + std::string functionName = "OnResponse"; + ani_env *env = GetAniEnv(); + if (env == nullptr || stsSubscriber_ == nullptr) { + ANS_LOGE("null env or stsSubscriber_"); + return; + } + ani_status status = ANI_OK; + ani_object stsSubscriberObj = reinterpret_cast(stsSubscriber_->aniRef); + ani_ref funRef; + ani_boolean isUndefined = ANI_TRUE; + status = GetPropertyRef(env, stsSubscriberObj, functionName.c_str(), isUndefined, funRef); + if (status != ANI_OK || isUndefined == ANI_TRUE || funRef == nullptr) { + ANS_LOGE("Object_GetField_Ref failed"); + return; + } + ani_object notificationIdAni = CreateDouble(env, notificationId); + ani_object buttonOptionObj = WarpNotificationButtonOption(env, buttonOption); + if (notificationIdAni == nullptr || buttonOptionObj == nullptr) { + ANS_LOGE("null args"); + return; + } + ani_fn_object onFn = reinterpret_cast(funRef); + ani_ref resutlt; + std::vector argv; + argv.push_back(notificationIdAni); + argv.push_back(buttonOptionObj); + if ((status = env->FunctionalObject_Call(onFn, argv.size(), argv.data(), &resutlt)) != ANI_OK) { + ANS_LOGE("FunctionalObject_Call failed, status: %{public}d", status); + return; + } +} + +void StsNotificationLocalLiveViewSubscriber::SetStsNotificationLocalLiveViewSubscriber( + ani_env *env, ani_object &localLiveViewSubscriberObj) +{ + ANS_LOGD("SetStsNotificationLocalLiveViewSubscriber call"); + if (env == nullptr) { + ANS_LOGE("Set failed, env is nullptr"); + return; + } + stsSubscriber_ = std::make_unique(); + if (stsSubscriber_ == nullptr) { + ANS_LOGE("stsSubscriber_ is nullptr"); + return; + } + ani_ref objRef = nullptr; + if (env->GlobalReference_Create(localLiveViewSubscriberObj, &objRef) != ANI_OK) { + ANS_LOGE("create ref failed"); + return; + } + ani_vm *aniVM = nullptr; + if (env->GetVM(&aniVM) != ANI_OK) { + ANS_LOGE("GetVM failed"); + return; + } + vm_ = aniVM; + stsSubscriber_->aniObj = localLiveViewSubscriberObj; + stsSubscriber_->aniRef = objRef; +} + +ani_env* StsNotificationLocalLiveViewSubscriber::GetAniEnv() +{ + ANS_LOGD("GetAniEnv call"); + if (vm_ == nullptr) { + ANS_LOGE("vm_ is nullptr"); + return nullptr; + } + ani_env* aniEnv = nullptr; + if (vm_->GetEnv(ANI_VERSION_1, &aniEnv) != ANI_OK) { + ANS_LOGE("get env failed"); + return nullptr; + } + return aniEnv; +} + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType) +{ + ANS_LOGD("SlotTypeEtsToC call"); + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + if (!EnumConvertAniToNative(env, enumItem, stsSlotType) || !StsSlotTypeUtils::StsToC(stsSlotType, slotType)) { + ANS_LOGE("SlotTypeEtsToC failed"); + return false; + } + return true; +} + +bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem) +{ + ANS_LOGD("SlotTypeCToEts call"); + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + if (!StsSlotTypeUtils::CToSts(slotType, stsSlotType) + || !EnumConvertNativeToAni( + env, "L@ohos/notificationManager/notificationManager/SlotType;", stsSlotType, enumItem)) { + ANS_LOGE("SlotTypeCToEts failed"); + return false; + } + return true; +} + +bool SlotLevelEtsToC(ani_env *env, ani_enum_item enumItem, SlotLevel &slotLevel) +{ + ANS_LOGD("SlotLevelEtsToC call"); + STSSlotLevel stsSlotLevel = STSSlotLevel::LEVEL_NONE; + if (!EnumConvertAniToNative(env, enumItem, stsSlotLevel) + || !StsSlotLevelUtils::StsToC(stsSlotLevel, slotLevel)) { + ANS_LOGE("SlotLevelEtsToC failed"); + return false; + } + return true; +} +bool SlotLevelCToEts(ani_env *env, SlotLevel slotLevel, ani_enum_item &enumItem) +{ + ANS_LOGD("SlotLevelCToEts call"); + STSSlotLevel stsSlotLevel = STSSlotLevel::LEVEL_NONE; + if (!StsSlotLevelUtils::CToSts(slotLevel, stsSlotLevel) || !EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/SlotLevel;", stsSlotLevel, enumItem)) { + ANS_LOGE("SlotLevelCToEts failed"); + return false; + } + return true; +} + +bool ContentTypeEtsToC(ani_env *env, ani_enum_item enumItem, ContentType &contentType) +{ + ANS_LOGD("ContentTypeEtsToC call"); + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + if (!EnumConvertAniToNative(env, enumItem, stsContentType) + || !StsContentTypeUtils::StsToC(stsContentType, contentType)) { + ANS_LOGE("ContentTypeEtsToC failed"); + return false; + } + return true; +} + +bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enumItem) +{ + ANS_LOGD("ContentTypeCToEts call"); + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + if (!StsContentTypeUtils::CToSts(contentType, stsContentType) + || !EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/ContentType;", stsContentType, enumItem)) { + ANS_LOGE("ContentTypeCToEts failed"); + return false; + } + return true; +} + +bool DoNotDisturbTypeEtsToC(ani_env *env, ani_enum_item enumItem, + Notification::NotificationConstant::DoNotDisturbType &doNotDisturbType) +{ + ANS_LOGD("DoNotDisturbTypeEtsToC call"); + STSDoNotDisturbType stsDoNotDisturbType = TYPE_NONE; + if (!EnumConvertAniToNative(env, enumItem, stsDoNotDisturbType) + || !StsDoNotDisturbTypeUtils::StsToC(stsDoNotDisturbType, doNotDisturbType)) { + ANS_LOGE("DoNotDisturbTypeEtsToC failed"); + return false; + } + return true; +} + +bool DeviceRemindTypeCToEts(ani_env *env, RemindType remindType, ani_enum_item &enumItem) +{ + STSRemindType stsRemindType = STSRemindType::IDLE_DONOT_REMIND; + StsRemindTypeUtils::CToSts(remindType, stsRemindType); + EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/RemindType;", stsRemindType, enumItem); + return true; +} + +bool DeviceRemindTypeEtsToC(ani_env *env, ani_enum_item enumItem, RemindType &remindType) +{ + STSRemindType stsRemindType = STSRemindType::IDLE_DONOT_REMIND; + if (EnumConvertAniToNative(env, enumItem, stsRemindType)) { + StsRemindTypeUtils::StsToC(stsRemindType, remindType); + return true; + } + return false; +} + +ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonOptionObj, + ButtonOption &buttonOption) +{ + ANS_LOGD("UnWarpNotificationButtonOption call"); + if (env == nullptr || buttonOptionObj == nullptr) { + ANS_LOGE("UnWarpNotificationButtonOption failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefind = ANI_TRUE; + std::string buttonName = ""; + if ((status = GetPropertyString(env, buttonOptionObj, "buttonName", isUndefind, buttonName)) != ANI_OK + || isUndefind == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationButtonOption: get buttonName failed"); + return ANI_INVALID_ARGS; + } + buttonOption.SetButtonName(buttonName); + ANS_LOGD("UnWarpNotificationButtonOption end"); + return status; +} + +ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption) +{ + ANS_LOGD("WarpNotificationButtonOption call"); + if (env == nullptr || buttonOption == nullptr) { + ANS_LOGE("WarpNotificationButtonOption failed, has nullptr"); + return nullptr; + } + ani_object optObj = nullptr; + ani_class optCls = nullptr; + if (!CreateClassObjByClassName(env, + "L@ohos/notificationManager/notificationManager/ButtonOptionsInner;", optCls, optObj) || optObj == nullptr) { + ANS_LOGE("WarpNotificationButtonOption: create class failed"); + return nullptr; + } + // title: string; + if (!SetPropertyOptionalByString(env, optObj, "buttonName", buttonOption->GetButtonName())) { + ANS_LOGE("WarpNotificationButtonOption: set buttonName failed"); + return nullptr; + } + ANS_LOGD("WarpNotificationButtonOption end"); + return optObj; +} + +bool WarpNotificationDoNotDisturbDate( + ani_env *env, const std::shared_ptr &date, ani_object &outObj) +{ + ANS_LOGD("WarpNotificationDoNotDisturbDate call"); + if (env == nullptr || date == nullptr) { + ANS_LOGE("WarpNotificationDoNotDisturbDate failed, has nullptr"); + return false; + } + ani_class cls; + ani_enum_item stsEnumValue; + const char *className = "L@ohos/notificationManager/notificationManager/DoNotDisturbDateInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj) || outObj == nullptr) { + ANS_LOGE("WarpNotificationDoNotDisturbDate: create class faild"); + return false; + } + if (!EnumConvertNativeToAni( + env, "L@ohos/notificationManager/notificationManager/DoNotDisturbType;", + date->GetDoNotDisturbType(), stsEnumValue)) { + ANS_LOGE("EnumConvert_NativeToSts faild"); + return false; + } + if (!SetPropertyByRef(env, outObj, "type", stsEnumValue)) { + ANS_LOGE("set type faild."); + return false; + } + if (!SetDate(env, outObj, "begin", date->GetBeginDate())) { + ANS_LOGE("SetDate 'begin' faild."); + return false; + } + if (!SetDate(env, outObj, "end", date->GetEndDate())) { + ANS_LOGE("SetDate 'end' faild."); + return false; + } + ANS_LOGD("WarpNotificationDoNotDisturbDate end"); + return true; +} + +bool SetCheckInfoContentType(ani_env *env, ani_object &obj, const std::string &name, ContentType type) +{ + if (env == nullptr || obj == nullptr || name.empty()) { + ANS_LOGE("InvalidParam"); + return false; + } + STSContentType stsType = NOTIFICATION_CONTENT_BASIC_TEXT; + ani_enum_item item; + if (!StsContentTypeUtils::CToSts(type, stsType)) { + ANS_LOGE("CToSts 'contentType' faild."); + return false; + } + if (!EnumConvertNativeToAni(env, "L@ohos/notificationManager/notificationManager/ContentType;", stsType, item)) { + ANS_LOGE("EnumConvertNativeToAni 'contentType' faild."); + return false; + } + if (!SetPropertyByRef(env, obj, name.c_str(), static_cast(item))) { + ANS_LOGE("SetPropertyByRef 'contentType' faild."); + return false; + } + return true; +} + +bool SetCheckInfoSlotType(ani_env *env, ani_object &obj, const std::string &name, SlotType type) +{ + if (env == nullptr || obj == nullptr || name.empty()) { + ANS_LOGE("InvalidParam"); + return false; + } + STSSlotType stsType = UNKNOWN_TYPE; + ani_enum_item item; + if (!StsSlotTypeUtils::CToSts(type, stsType)) { + ANS_LOGE("CToSts 'slotType' faild."); + return false; + } + if (!EnumConvertNativeToAni(env, "L@ohos/notificationManager/notificationManager/SlotType;", stsType, item)) { + ANS_LOGE("EnumConvertNativeToAni 'slotType' faild."); + return false; + } + if (!SetPropertyByRef(env, obj, name.c_str(), static_cast(item))) { + ANS_LOGE("SetPropertyByRef 'slotType' faild."); + return false; + } + return true; +} + +bool SetNotificationCheckInfoNumber( + ani_env *env, const std::shared_ptr &data, ani_object &outObj) +{ + ani_status status = ANI_OK; + // notificationId: number; + if (ANI_OK != (status = env->Object_SetPropertyByName_Double( + outObj, "notificationId", static_cast(data->GetNotifyId())))) { + ANS_LOGE("WarpNotificationCheckInfo. set 'notificationId' faild. status %{public}d", status); + return false; + } + // creatorUserId: number; + if (ANI_OK != (status = env->Object_SetPropertyByName_Double( + outObj, "creatorUserId", static_cast(data->GetCreatorUserId())))) { + ANS_LOGE("WarpNotificationCheckInfo. set 'creatorUserId' faild. status %{public}d", status); + return false; + } + return true; +} + +bool SetNotificationCheckInfoString( + ani_env *env, const std::shared_ptr &data, ani_object &outObj) +{ + // bundleName: string; + if (!SetPropertyOptionalByString(env, outObj, "bundleName", data->GetPkgName())) { + ANS_LOGE("WarpNotificationCheckInfo set 'bundleName' faild"); + return false; + } + // label?: string; + if (!data->GetLabel().empty() && !SetPropertyOptionalByString(env, outObj, "label", data->GetLabel())) { + ANS_LOGE("WarpNotificationCheckInfo set 'label' faild"); + return false; + } + return true; +} + +bool SetNotificationCheckInfoEnum( + ani_env *env, const std::shared_ptr &data, ani_object &outObj) +{ + // contentType: ContentType; + if (!SetCheckInfoContentType(env, outObj, "contentType", static_cast(data->GetContentType()))) { + ANS_LOGE("WarpNotificationCheckInfo set 'contentType' faild"); + return false; + } + // slotType: SlotType; + if (!SetCheckInfoSlotType(env, outObj, "slotType", static_cast(data->GetSlotType()))) { + ANS_LOGE("WarpNotificationCheckInfo set 'slotType' faild"); + return false; + } + return true; +} + +bool SetNotificationCheckInfo( + ani_env *env, const std::shared_ptr &data, ani_object &outObj) +{ + if (!SetNotificationCheckInfoNumber(env, data, outObj)) { + ANS_LOGE("SetNotificationCheckInfoNumber faild"); + return false; + } + if (!SetNotificationCheckInfoString(env, data, outObj)) { + ANS_LOGE("SetNotificationCheckInfoString faild"); + return false; + } + if (!SetNotificationCheckInfoEnum(env, data, outObj)) { + ANS_LOGE("SetNotificationCheckInfoEnum faild"); + return false; + } + // extraInfos?: Record; + if (data->GetExtraInfo() != nullptr) { + ani_ref extraInfos = OHOS::AppExecFwk::WrapWantParams(env, *(data->GetExtraInfo())); + if (extraInfos == nullptr) { + ANS_LOGE("WrapWantParams 'extraInfos' faild"); + return false; + } + if (!SetPropertyByRef(env, outObj, "extraInfos", extraInfos)) { + ANS_LOGE("WarpNotificationCheckInfo set 'extraInfos' faild"); + return false; + } + } + return true; +} + +bool WarpNotificationCheckInfo( + ani_env *env, const std::shared_ptr &data, ani_object &outObj) +{ + ani_object obj; + ani_class cls; + if (env == nullptr || data == nullptr) { + ANS_LOGE("InvalidParam"); + return false; + } + if (!CreateClassObjByClassName( + env, "L@ohos/notificationManager/notificationManager/NotificationCheckInfoInner;", cls, obj)) { + ANS_LOGE("WarpNotificationCheckInfo create faild"); + return false; + } + if (!SetNotificationCheckInfo(env, data, obj)) { + ANS_LOGE("SetNotificationCheckInfo faild"); + return false; + } + outObj = obj; + return true; +} + +void GetDoNotDisturbDateByDoNotDisturbType(ani_env *env, ani_object obj, NotificationDoNotDisturbDate &doNotDisturbDate) +{ + ANS_LOGD("GetDoNotDisturbDateByDoNotDisturbType start"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("GetDoNotDisturbDateByDoNotDisturbType failed, has nullptr"); + return; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_OK; + ani_ref doNotDisturbTypeRef = {}; + if (ANI_OK != (status = GetPropertyRef(env, obj, "doNotDisturbType", isUndefined, doNotDisturbTypeRef)) + || isUndefined == ANI_TRUE || doNotDisturbTypeRef == nullptr) { + ANS_LOGE("GetDoNotDisturbDateByDoNotDisturbType: get Ref failed"); + return; + } + NotificationConstant::DoNotDisturbType type = NotificationConstant::DoNotDisturbType::NONE; + + if (!DoNotDisturbTypeEtsToC(env, static_cast(doNotDisturbTypeRef), type)) { + ANS_LOGE("GetDoNotDisturbDateByDoNotDisturbType: SlotTypeEtsToC failed"); + return; + } + doNotDisturbDate.SetDoNotDisturbType(type); + ANS_LOGD("GetDoNotDisturbDateByDoNotDisturbType end"); +} + +bool UnWarpNotificationDoNotDisturbDate( + ani_env* env, + const ani_object doNotDisturbDateObj, + NotificationDoNotDisturbDate& doNotDisturbDate) +{ + ani_boolean isUndefined = false; + ani_double mDouble = 0.0; + if (env == nullptr) { + ANS_LOGE("UnWarpNotificationDoNotDisturbDate: Invalid input parameters"); + return false; + } + GetDoNotDisturbDateByDoNotDisturbType(env, doNotDisturbDateObj, doNotDisturbDate); + + if (ANI_OK == GetPropertyDouble(env, doNotDisturbDateObj, "begin", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + doNotDisturbDate.SetBeginDate(static_cast(mDouble)); + } + if (ANI_OK == GetPropertyDouble(env, doNotDisturbDateObj, "end", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + doNotDisturbDate.SetEndDate(static_cast(mDouble)); + } + if (doNotDisturbDate.GetBeginDate() >= doNotDisturbDate.GetEndDate()) { + ANS_LOGE("Invalid time range"); + return false; + } + ANS_LOGD("Successfully parsed DoNotDisturbDate"); + return true; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed3de90e93ef280828b63b2f1f0a5e857a91ef28 --- /dev/null +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -0,0 +1,1322 @@ +/* + * Copyright (c) 2025 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 "sts_request.h" + +#include "sts_common.h" +#include "sts_convert_other.h" +#include "sts_notification_flag.h" +#include "sts_notification_manager.h" +#include "sts_notification_content.h" +#include "sts_action_button.h" +#include "sts_bundle_option.h" +#include "sts_template.h" +#include "ans_log_wrapper.h" +#include "want_params.h" +#include "ani_common_want.h" +#include "sts_bundle_option.h" +#include "sts_subscribe.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +constexpr int32_t STR_MAX_SIZE = 204; +void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions) +{ + ANS_LOGD("UnWarpDistributedOptions start"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpDistributedOptions failed, has nullptr"); + return; + } + // isDistributed?: boolean; + bool isDistributed = false; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyBool(env, obj, "isDistributed", isUndefined, isDistributed) + && isUndefined == ANI_FALSE) { + distributedOptions.isDistributed = isDistributed; + } else { + ANS_LOGD("UnWarpDistributedOptions: isDistributed get failed"); + } + // supportDisplayDevices?: Array; + std::vector supportDisplayDevices = {}; + isUndefined = ANI_TRUE; + if (GetPropertyStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK + && isUndefined == ANI_FALSE) { + distributedOptions.supportDisplayDevices = supportDisplayDevices; + } else { + ANS_LOGD("UnWarpDistributedOptions: supportDisplayDevices get failed"); + } + // supportOperateDevices?: Array; + std::vector supportOperateDevices = {}; + isUndefined = ANI_TRUE; + if (GetPropertyStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK + && isUndefined == ANI_FALSE) { + distributedOptions.supportOperateDevices = supportOperateDevices; + } else { + ANS_LOGD("UnWarpDistributedOptions: supportOperateDevices get failed"); + } + // readonly remindType?: number; + ani_double remindType = 0.0; + isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyDouble(env, obj, "remindType", isUndefined, remindType) + && isUndefined == ANI_FALSE) { + distributedOptions.remindType = static_cast(remindType); + } else { + ANS_LOGD("UnWarpDistributedOptions: remindType get failed"); + } + ANS_LOGD("UnWarpDistributedOptions end"); +} + +bool WarpNotificationUnifiedGroupInfo(ani_env* env, + const std::shared_ptr &groupInfo, ani_object &groupInfoObject) +{ + ANS_LOGD("WarpNotificationUnifiedGroupInfo start"); + if (env == nullptr || groupInfo == nullptr) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo failed, has nullptr"); + return false; + } + ani_class groupInfoCls = nullptr; + if ((!CreateClassObjByClassName(env, + "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)) + || groupInfoCls == nullptr || groupInfoObject == nullptr) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: create class failed"); + return false; + } + // key?: string; + if (!groupInfo->GetKey().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "key", groupInfo->GetKey())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set key failed"); + return false; + } + // title?: string; + if (!groupInfo->GetTitle().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "title", groupInfo->GetTitle())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set title failed"); + return false; + } + // content?: string; + if (!groupInfo->GetContent().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "content", groupInfo->GetContent())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set content failed"); + return false; + } + // sceneName?: string; + if (!groupInfo->GetSceneName().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "sceneName", groupInfo->GetSceneName())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set sceneName failed"); + return false; + } + // extraInfo?: Record; + std::shared_ptr extraInfo = groupInfo->GetExtraInfo(); + if (extraInfo) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *extraInfo); + if (valueRef == nullptr) { + ANS_LOGE("WrapWantParams faild. 'extraInfo'"); + return false; + } + if (!SetPropertyByRef(env, groupInfoObject, "extraInfo", valueRef)) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set extraInfo failed"); + return false; + } + } + ANS_LOGD("WarpNotificationUnifiedGroupInfo end"); + return true; +} + +void GetNotificationRequestByBooleanOne(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationRequestByBooleanOne start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationRequestByBooleanOne failed, has nullptr"); + return; + } + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyBool(env, obj, "isOngoing", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetInProgress(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "isUnremovable", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUnremovable(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "updateOnly", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUpdateOnly(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "tapDismissed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetTapDismissed(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "colorEnabled", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetColorEnabled(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "isAlertOnce", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetAlertOneTime(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "isStopwatch", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowStopwatch(mbool); + } + ANS_LOGD("GetNotificationRequestByBooleanOne end"); +} + +void GetNotificationRequestByBooleanTwo(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationRequestByBooleanTwo start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationRequestByBooleanTwo failed, has nullptr"); + return; + } + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetCountdownTimer(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "isFloatingIcon", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetFloatingIcon(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "showDeliveryTime", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowDeliveryTime(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "isRemoveAllowed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetRemoveAllowed(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "forceDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetForceDistributed(mbool); + } + if (ANI_OK == GetPropertyBool(env, obj, "notDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetNotDistributed(mbool); + } + ANS_LOGD("GetNotificationRequestByBooleanTwo end"); +} + +void GetNotificationRequestByBoolean(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + GetNotificationRequestByBooleanOne(env, obj, request); + GetNotificationRequestByBooleanTwo(env, obj, request); +} + +void GetNotificationRequestByString(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationRequestByString start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationRequestByString failed, has nullptr"); + return; + } + std::string mString = ""; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyString(env, obj, "classification", isUndefined, mString) && isUndefined == ANI_FALSE) { + if (mString.length() > STR_MAX_SIZE) { + mString.resize(STR_MAX_SIZE); + } + request->SetClassification(mString); + } + if (ANI_OK == GetPropertyString(env, obj, "appMessageId", isUndefined, mString) && isUndefined == ANI_FALSE) { + request->SetAppMessageId(mString); + } + if (ANI_OK == GetPropertyString(env, obj, "label", isUndefined, mString) && isUndefined == ANI_FALSE) { + if (mString.length() > STR_MAX_SIZE) { + mString.resize(STR_MAX_SIZE); + } + request->SetLabel(mString); + } + if (ANI_OK == GetPropertyString(env, obj, "groupName", isUndefined, mString) && isUndefined == ANI_FALSE) { + if (mString.length() > STR_MAX_SIZE) { + mString.resize(STR_MAX_SIZE); + } + request->SetGroupName(mString); + } + if (ANI_OK == GetPropertyString(env, obj, "sound", isUndefined, mString) && isUndefined == ANI_FALSE) { + request->SetSound(mString); + } + ANS_LOGD("GetNotificationRequestByString start"); +} + +void GetNotificationRequestByNumber(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationRequestByNumber start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGD("GetNotificationRequestByNumber failed, has nullptr"); + return; + } + ani_double mDouble = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK == GetPropertyDouble(env, obj, "id", isUndefined, mDouble) && isUndefined == ANI_FALSE) { + request->SetNotificationId(static_cast(mDouble)); + } else { + request->SetNotificationId(0); + } + if (ANI_OK == GetPropertyDouble(env, obj, "deliveryTime", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetDeliveryTime(static_cast(mDouble)); + } + if (ANI_OK == GetPropertyDouble(env, obj, "autoDeletedTime", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetAutoDeletedTime(static_cast(mDouble)); + } + if (ANI_OK == GetPropertyDouble(env, obj, "color", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetColor(static_cast(mDouble)); + } + if (ANI_OK == GetPropertyDouble(env, obj, "badgeIconStyle", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + int32_t style = static_cast(mDouble); + request->SetBadgeIconStyle(static_cast(style)); + } + if (ANI_OK == GetPropertyDouble(env, obj, "badgeNumber", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetBadgeNumber(static_cast(mDouble)); + } + if (ANI_OK == GetPropertyDouble(env, obj, "notificationControlFlags", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetNotificationControlFlags(static_cast(mDouble)); + } + ANS_LOGD("GetNotificationRequestByNumber end"); +} + +bool GetNotificationNormalContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationNormalContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationNormalContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "normal", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationNormalContent get ref failed"); + return false; + } + std::shared_ptr normalContent = std::make_shared(); + UnWarpNotificationNormalContent(env, static_cast(contentRef), normalContent); + request->SetContent(std::make_shared(normalContent)); + ANS_LOGD("GetNotificationNormalContent end"); + return true; +} + +bool GetNotificationLongTextContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationLongTextContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationLongTextContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "longText", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationLongTextContent get ref failed"); + return false; + } + std::shared_ptr longTextContent + = std::make_shared(); + UnWarpNotificationLongTextContent(env, static_cast(contentRef), longTextContent); + request->SetContent(std::make_shared(longTextContent)); + ANS_LOGD("GetNotificationLongTextContent end"); + return true; +} + +bool GetNotificationPictureContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationPictureContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationPictureContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "picture", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationPictureContent get ref failed"); + return false; + } + std::shared_ptr pictureContent + = std::make_shared(); + UnWarpNotificationPictureContent(env, static_cast(contentRef), pictureContent); + request->SetContent(std::make_shared(pictureContent)); + ANS_LOGD("GetNotificationPictureContent end"); + return true; +} + +bool GetNotificationMultiLineContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationMultiLineContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationMultiLineContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "multiLine", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationMultiLineContent get ref failed"); + return false; + } + std::shared_ptr multiLineContent + = std::make_shared(); + UnWarpNotificationMultiLineContent(env, static_cast(contentRef), multiLineContent); + request->SetContent(std::make_shared(multiLineContent)); + ANS_LOGD("GetNotificationMultiLineContent end"); + return true; +} + +bool GetNotificationLocalLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationLocalLiveViewContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationLocalLiveViewContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "systemLiveView", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationLocalLiveViewContent get ref failed"); + return false; + } + std::shared_ptr localLiveView + = std::make_shared(); + UnWarpNotificationLocalLiveViewContent(env, static_cast(contentRef), localLiveView); + request->SetContent(std::make_shared(localLiveView)); + ANS_LOGD("GetNotificationLocalLiveViewContent end"); + return true; +} + +bool GetNotificationLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationLiveViewContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationLiveViewContent failed, has nullptr"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + ani_ref contentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "liveView", isUndefined, contentRef) + || isUndefined == ANI_TRUE || contentRef == nullptr) { + ANS_LOGE("GetNotificationLiveViewContent get ref failed"); + return false; + } + std::shared_ptr liveViewContent + = std::make_shared(); + UnWarpNotificationLiveViewContent(env, static_cast(contentRef), liveViewContent); + request->SetContent(std::make_shared(liveViewContent)); + ANS_LOGD("GetNotificationLiveViewContent end"); + return true; +} + +bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationContentWithType start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationContent failed, has nullptr"); + return false; + } + ANS_LOGD("GetNotificationContent ContentType = %{public}d", static_cast(outType)); + switch (outType) { + case ContentType::BASIC_TEXT: + return GetNotificationNormalContent(env, obj, request); + case ContentType::LONG_TEXT: + return GetNotificationLongTextContent(env, obj, request); + case ContentType::PICTURE: + return GetNotificationPictureContent(env, obj, request); + case ContentType::MULTILINE: + return GetNotificationMultiLineContent(env, obj, request); + case ContentType::LOCAL_LIVE_VIEW: + return GetNotificationLocalLiveViewContent(env, obj, request); + case ContentType::LIVE_VIEW: + return GetNotificationLiveViewContent(env, obj, request); + case ContentType::CONVERSATION: + break; + default: + ANS_LOGD("ContentType not find. type %{public}d", static_cast(outType)); + break; + } + return true; +} + +ani_status GetNotificationContent(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationContent start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationContent failed, has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_OK; + ani_boolean isUndefined = ANI_TRUE; + ani_ref notificationContentRef = {}; + if (ANI_OK != (status = GetPropertyRef(env, obj, "content", isUndefined, notificationContentRef)) + || isUndefined == ANI_TRUE) { + ANS_LOGE("GetNotificationContent:get contentRef failed. status %{public}d", status); + return status; + } + ani_ref contentTypeRef; + if (ANI_OK != (status = GetPropertyRef(env, static_cast(notificationContentRef), + "notificationContentType", isUndefined, contentTypeRef)) + || isUndefined == ANI_TRUE || contentTypeRef == nullptr) { + ANS_LOGE("GetNotificationContent:get notificationContentType failed. status %{public}d", status); + return status; + } + ContentType type; + if (!ContentTypeEtsToC(env, static_cast(contentTypeRef), type)) { + ANS_LOGE("GetNotificationContent:ContentTypeEtsToC failed"); + return ANI_INVALID_ARGS; + } + if (!GetNotificationContent(env, static_cast(notificationContentRef), type, request)) { + ANS_LOGE("GetNotificationContent:GetNotificationContent failed"); + return ANI_INVALID_ARGS; + } + ANS_LOGD("GetNotificationContent end"); + return ANI_OK; +} + +void GetNotificationSlotType(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ANS_LOGD("GetNotificationSlotType start"); + if (env == nullptr || obj == nullptr || request == nullptr) { + ANS_LOGE("GetNotificationSlotType failed, has nullptr"); + return; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_OK; + ani_ref slotTypeRef = {}; + if (ANI_OK != (status = GetPropertyRef(env, obj, "notificationSlotType", isUndefined, slotTypeRef)) + || isUndefined == ANI_TRUE || slotTypeRef == nullptr) { + ANS_LOGE("GetNotificationSlotType: get Ref failed"); + return; + } + SlotType type = SlotType::OTHER; + if (!SlotTypeEtsToC(env, static_cast(slotTypeRef), type)) { + ANS_LOGE("GetNotificationSlotType: SlotTypeEtsToC failed"); + return; + } + request->SetSlotType(type); + ANS_LOGD("GetNotificationSlotType end"); +} + +void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref wantAgentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "wantAgent", isUndefined, wantAgentRef) + || isUndefined == ANI_TRUE || wantAgentRef == nullptr) { + ANS_LOGE("GetNotificationWantAgent: get ref failed"); + return; + } + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + if (wantAgent == nullptr) { + ANS_LOGD("wantAgent is null"); + return; + } + request->SetWantAgent(wantAgent); +} + +void GetNotificationExtraInfo(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref extraInfoRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef) + || isUndefined == ANI_TRUE || extraInfoRef == nullptr) { + ANS_LOGE("GetNotificationExtraInfo: get ref failed"); + return; + } + WantParams wantParams = {}; + UnwrapWantParams(env, extraInfoRef, wantParams); + std::shared_ptr extras = std::make_shared(wantParams); + request->SetAdditionalData(extras); +} + +void GetNotificationRemovalWantAgent(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref wantAgentRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "removalWantAgent", isUndefined, wantAgentRef) + || isUndefined == ANI_TRUE || wantAgentRef == nullptr) { + ANS_LOGE("GetNotificationRemovalWantAgent: get ref failed"); + return; + } + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + if (wantAgent == nullptr) { + ANS_LOGD("wantAgent is null"); + return; + } + request->SetRemovalWantAgent(wantAgent); +} + +void GetNotificationActionButtons(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + std::vector> buttons = {}; + ani_status status = GetNotificationActionButtonArray(env, obj, "actionButtons", buttons); + if (status == ANI_OK) { + for (auto button : buttons) { + request->AddActionButton(button); + } + } +} + +void GetNotificationSmallIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref smallIconRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "smallIcon", isUndefined, smallIconRef) + || isUndefined == ANI_TRUE || smallIconRef == nullptr) { + ANS_LOGE("GetNotificationSmallIcon: get ref failed"); + return; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(smallIconRef)); + if (pixelMap != nullptr) { + request->SetLittleIcon(pixelMap); + } +} + +void GetNotificationLargeIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref largeIconRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "largeIcon", isUndefined, largeIconRef) + || isUndefined == ANI_TRUE || largeIconRef == nullptr) { + ANS_LOGE("GetNotificationLargeIcon: get ref failed"); + return; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(largeIconRef)); + if (pixelMap != nullptr) { + request->SetBigIcon(pixelMap); + } +} + +void GetNotificationOverlayIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_ref overlayIconRef = {}; + if (ANI_OK != GetPropertyRef(env, obj, "overlayIcon", isUndefined, overlayIconRef) + || isUndefined == ANI_TRUE || overlayIconRef == nullptr) { + ANS_LOGE("GetNotificationOverlayIcon: get ref failed"); + return; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(overlayIconRef)); + if (pixelMap != nullptr) { + request->SetOverlayIcon(pixelMap); + } +} + +void GetNotificationRequestDistributedOptions(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref optionRef = {}; + ani_boolean isUndefind = ANI_TRUE; + status = GetPropertyRef(env, obj, "distributedOption", isUndefind, optionRef); + if (status == ANI_OK && isUndefind == ANI_FALSE) { + StsDistributedOptions options; + UnWarpDistributedOptions(env, static_cast(optionRef), options); + request->SetDistributed(options.isDistributed); + request->SetDevicesSupportDisplay(options.supportDisplayDevices); + request->SetDevicesSupportOperate(options.supportOperateDevices); + } +} + +void GetNotificationTemplate(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref templateRef = {}; + ani_boolean isUndefind = ANI_TRUE; + status = GetPropertyRef(env, obj, "template", isUndefind, templateRef); + if (status == ANI_OK && isUndefind == ANI_FALSE) { + OHOS::Notification::NotificationTemplate tmplate; + UnwrapNotificationTemplate(env, static_cast(templateRef), tmplate); + request->SetTemplate(std::make_shared(tmplate)); + } +} + +void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref infoRef = {}; + ani_boolean isUndefind = ANI_TRUE; + status = GetPropertyRef(env, obj, "unifiedGroupInfo", isUndefind, infoRef); + if (status != ANI_OK || isUndefind == ANI_TRUE) { + return; + } + std::shared_ptr unifiedGroupInfo = std::make_shared(); + std::string mString = ""; + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "key", isUndefind, mString) + && isUndefind == ANI_FALSE) { + unifiedGroupInfo->SetKey(mString); + } + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "title", isUndefind, mString) + && isUndefind == ANI_FALSE) { + unifiedGroupInfo->SetTitle(mString); + } + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "content", isUndefind, mString) + && isUndefind == ANI_FALSE) { + unifiedGroupInfo->SetContent(mString); + } + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "sceneName", isUndefind, mString) + && isUndefind == ANI_FALSE) { + unifiedGroupInfo->SetSceneName(mString); + } + ani_ref extraInfoRef = {}; + status = GetPropertyRef(env, static_cast(infoRef), "extraInfo", isUndefind, extraInfoRef); + if (status == ANI_OK && isUndefind == ANI_FALSE) { + WantParams wantParams = {}; + UnwrapWantParams(env, extraInfoRef, wantParams); + std::shared_ptr extras = std::make_shared(wantParams); + unifiedGroupInfo->SetExtraInfo(extras); + } + request->SetUnifiedGroupInfo(unifiedGroupInfo); +} + +void GetNotificationBundleOption(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref optionRef = {}; + ani_boolean isUndefind = ANI_TRUE; + status = GetPropertyRef(env, obj, "representativeBundle", isUndefind, optionRef); + if (status != ANI_OK || isUndefind == ANI_TRUE) { + ANS_LOGD("Cannot get the value of representativeBundle. status %{public}d isUndefind %{public}d", + status, isUndefind); + return; + } + OHOS::Notification::NotificationBundleOption option; + if (ANI_OK == UnwrapBundleOption(env, static_cast(optionRef), option)) { + request->SetBundleOption(std::make_shared(option)); + } +} + +ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest) +{ + ani_status status = GetNotificationContent(env, obj, notificationRequest); + if (status != ANI_OK) { + return ANI_INVALID_ARGS; + } + GetNotificationSlotType(env, obj, notificationRequest); + GetNotificationWantAgent(env, obj, notificationRequest); + GetNotificationExtraInfo(env, obj, notificationRequest); + GetNotificationRemovalWantAgent(env, obj, notificationRequest); + GetNotificationActionButtons(env, obj, notificationRequest); + GetNotificationSmallIcon(env, obj, notificationRequest); + GetNotificationLargeIcon(env, obj, notificationRequest); + GetNotificationOverlayIcon(env, obj, notificationRequest); + GetNotificationRequestDistributedOptions(env, obj, notificationRequest); + GetNotificationTemplate(env, obj, notificationRequest); + GetNotificationUnifiedGroupInfo(env, obj, notificationRequest); + GetNotificationBundleOption(env, obj, notificationRequest); + return status; +} + +ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest) +{ + ANS_LOGD("UnWarpNotificationRequest start"); + if (env == nullptr || obj == nullptr) { + ANS_LOGD("UnWarpNotificationRequest has nullptr"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + GetNotificationRequestByNumber(env, obj, notificationRequest); + GetNotificationRequestByString(env, obj, notificationRequest); + GetNotificationRequestByBoolean(env, obj, notificationRequest); + status = GetNotificationRequestByCustom(env, obj, notificationRequest); + ANS_LOGD("UnWarpNotificationRequest end"); + return status; +} + +bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, + ani_object &object) +{ + if (env == nullptr || cls == nullptr || object == nullptr || request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // isOngoing?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isOngoing", request->IsInProgress())) { + ANS_LOGD("SetNotificationRequest set 'isOngoing' faild"); + } + // isUnremovable?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isUnremovable", request->IsUnremovable())) { + ANS_LOGD("SetNotificationRequest set 'isUnremovable' faild"); + } + // tapDismissed?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "tapDismissed", request->IsTapDismissed())) { + ANS_LOGD("SetNotificationRequest set 'tapDismissed' faild"); + } + // colorEnabled?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "colorEnabled", request->IsColorEnabled())) { + ANS_LOGD("SetNotificationRequest set 'colorEnabled' faild"); + } + // isAlertOnce?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isAlertOnce", request->IsAlertOneTime())) { + ANS_LOGD("SetNotificationRequest set 'isAlertOnce' faild"); + } + // isStopwatch?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isStopwatch", request->IsShowStopwatch())) { + ANS_LOGD("SetNotificationRequest set 'isStopwatch' faild"); + } + // isCountDown?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isCountDown", request->IsCountdownTimer())) { + ANS_LOGD("SetNotificationRequest set 'isCountDown' faild"); + } + // isFloatingIcon?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "isFloatingIcon", request->IsFloatingIcon())) { + ANS_LOGD("SetNotificationRequest set 'isFloatingIcon' faild"); + } + // showDeliveryTime?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "showDeliveryTime", request->IsShowDeliveryTime())) { + ANS_LOGD("SetNotificationRequest set 'showDeliveryTime' faild"); + } + // updateOnly?: boolean + if (!SetPropertyOptionalByBoolean(env, object, "updateOnly", request->IsUpdateOnly())) { + ANS_LOGD("SetNotificationRequest set 'updateOnly' faild"); + } + return true; +} + +bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // classification?: string + std::string str = request->GetClassification(); + if (!SetPropertyOptionalByString(env, object, "classification", request->GetClassification())) { + ANS_LOGD("SetNotificationRequest set '' faild"); + } + // label?: string + if (!SetPropertyOptionalByString(env, object, "label", request->GetLabel())) { + ANS_LOGD("SetNotificationRequest set 'label' faild"); + } + // groupName?: string + if (!SetPropertyOptionalByString(env, object, "groupName", request->GetGroupName())) { + ANS_LOGD("SetNotificationRequest set 'groupName' faild"); + } + // readonly creatorBundleName?: string + if (!SetPropertyOptionalByString(env, object, "creatorBundleName", request->GetCreatorBundleName())) { + ANS_LOGD("SetNotificationRequest set 'creatorBundleName' faild"); + } + // readonly sound?: string + if (!SetPropertyOptionalByString(env, object, "sound", request->GetSound())) { + ANS_LOGD("SetNotificationRequest set 'sound' faild"); + } + // readonly appInstanceKey?: string + if (!SetPropertyOptionalByString(env, object, "appInstanceKey", request->GetAppInstanceKey())) { + ANS_LOGD("SetNotificationRequest set 'appInstanceKey' faild"); + } + return true; +} + +bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // id?: number + SetPropertyOptionalByDouble(env, object, "id", request->GetNotificationId()); + // slotType?: SlotType + ani_enum_item slotTypeItem {}; + if (SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { + CallSetter(env, cls, object, "notificationSlotType", slotTypeItem); + } + // deliveryTime?: number + SetPropertyOptionalByDouble(env, object, "deliveryTime", request->GetDeliveryTime()); + // autoDeletedTime?: number + SetPropertyOptionalByDouble(env, object, "autoDeletedTime", request->GetAutoDeletedTime()); + // color ?: number + SetPropertyOptionalByDouble(env, object, "color", request->GetColor()); + // badgeIconStyle ?: number + SetPropertyOptionalByDouble(env, object, "badgeIconStyle", + static_cast(request->GetBadgeIconStyle())); + // readonly creatorUid?: number + SetPropertyOptionalByDouble(env, object, "creatorUid", request->GetCreatorUid()); + // readonly creatorPid?: number + SetPropertyOptionalByDouble(env, object, "creatorPid", request->GetCreatorPid()); + // badgeNumber?: number + SetPropertyOptionalByDouble(env, object, "badgeNumber", request->GetBadgeNumber()); + // readonly creatorInstanceKey?: number + SetPropertyOptionalByDouble(env, object, "creatorInstanceKey", request->GetCreatorInstanceKey()); + return true; +} + +bool SetNotificationRequestByWantAgent(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // wantAgent?: WantAgent + std::shared_ptr agent = request->GetWantAgent(); + if (agent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + if (wantAgent == nullptr || !SetPropertyByRef(env, object, "wantAgent", wantAgent)) { + ANS_LOGD("SetNotificationRequest set 'wantAgent' faild"); + } + } + // removalWantAgent?: WantAgent + std::shared_ptr removalAgent = request->GetRemovalWantAgent(); + if (removalAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, removalAgent.get()); + if (wantAgent == nullptr || !SetPropertyByRef(env, object, "removalWantAgent", wantAgent)) { + ANS_LOGD("SetNotificationRequest set 'removalWantAgent' faild"); + } + } + // maxScreenWantAgent?: WantAgent + std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); + if (maxScreenAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, maxScreenAgent.get()); + if (wantAgent == nullptr || !SetPropertyByRef(env, object, "maxScreenWantAgent", wantAgent)) { + ANS_LOGD("SetNotificationRequest set 'maxScreenWantAgent' faild"); + } + } + return true; +} + +bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const NotificationRequest *request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // smallIcon?: image.PixelMap + std::shared_ptr littleIcon = request->GetLittleIcon(); + if (littleIcon) { + ani_object smallIconResult = CreateAniPixelMap(env, littleIcon); + if (smallIconResult == nullptr || !SetPropertyByRef(env, object, "smallIcon", smallIconResult)) { + ANS_LOGD("SetNotificationRequest set 'smallIcon' faild"); + } + } + // largeIcon?: image.PixelMap + std::shared_ptr largeIcon = request->GetBigIcon(); + if (largeIcon) { + ani_object largeIconResult = CreateAniPixelMap(env, largeIcon); + if (largeIconResult == nullptr || !SetPropertyByRef(env, object, "largeIcon", largeIconResult)) { + ANS_LOGD("SetNotificationRequest set 'largeIcon' faild"); + } + } + // overlayIcon?: image.PixelMap + std::shared_ptr overlayIcon = request->GetOverlayIcon(); + if (overlayIcon) { + ani_object overlayIconResult = CreateAniPixelMap(env, overlayIcon); + if (overlayIconResult == nullptr || !SetPropertyByRef(env, object, "overlayIcon", overlayIconResult)) { + ANS_LOGD("SetNotificationRequest set 'overlayIcon' faild"); + } + } + return true; +} + +bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + std::shared_ptr content = request->GetContent(); + ani_object contentObj; + if (!SetNotificationContent(env, content, contentObj)) { + ANS_LOGD("SetNotificationContent faild"); + return false; + } + if (contentObj == nullptr) { + ANS_LOGD("contentObj is nullptr"); + return false; + } + if (!SetPropertyByRef(env, object, "content", contentObj)) { + ANS_LOGD("SetNotificationRequestByNotificationContent. set content faild"); + return false; + } + return true; +} + +bool SetRequestExtraInfo(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::shared_ptr additionalData = request->GetAdditionalData(); + if (additionalData == nullptr) { + ANS_LOGD("extraInfo is Undefine"); + return true; + } + ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + if (extraInfo == nullptr || !SetPropertyByRef(env, object, "extraInfo", extraInfo)) { + ANS_LOGD("SetNotificationRequestByCustom: set extraInfo failed"); + } + return true; +} + +bool SetRequestActionButtons(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::vector> actionButtons = request->GetActionButtons(); + if (actionButtons.empty()) { + ANS_LOGD("actionButtons is Undefine"); + return true; + } + ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); + if (actionButtonsArrayObj == nullptr + || !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { + ANS_LOGD("SetNotificationRequest set 'actionButtons' faild"); + } + return true; +} + +bool SetRequestTemplate(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::shared_ptr templ = request->GetTemplate(); + if (templ == nullptr) { + ANS_LOGD("template is Undefine"); + return true; + } + ani_object templateObject = WrapNotificationTemplate(env, templ); + if (templateObject == nullptr || !SetPropertyByRef(env, object, "template", templateObject)) { + ANS_LOGD("SetNotificationRequest set 'template' faild"); + } + return true; +} + +bool SetRequestNotificationFlags( + ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::shared_ptr flags = request->GetFlags(); + if (flags == nullptr) { + ANS_LOGD("notificationFlags is Undefine"); + return true; + } + ani_object flagsObject = nullptr; + if (!WarpNotificationFlags(env, flags, flagsObject) || flagsObject == nullptr) { + ANS_LOGE("SetNotificationRequest Warp 'notificationFlags' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "notificationFlags", flagsObject)) { + ANS_LOGE("SetNotificationRequest set 'notificationFlags' faild"); + return false; + } + return true; +} + +bool SetRequestAgentBundle(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::shared_ptr agentBundle = request->GetAgentBundle(); + if (agentBundle == nullptr) { + ANS_LOGD("agentBundle is Undefine"); + return true; + } + ani_object agentBundleObject = nullptr; + if (!WrapBundleOption(env, agentBundle, agentBundleObject) || agentBundleObject == nullptr) { + ANS_LOGE("SetNotificationRequest Warp 'agentBundle' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "agentBundle", agentBundleObject)) { + ANS_LOGE("SetNotificationRequest set 'agentBundle' faild"); + return false; + } + return true; +} + +bool SetRequestUnifiedGroupInfo( + ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); + if (groupInfo == nullptr) { + ANS_LOGD("unifiedGroupInfo is Undefine"); + return true; + } + ani_object infoObject = nullptr; + if (!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { + ANS_LOGD("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); + } + if (!SetPropertyByRef(env, object, "unifiedGroupInfo", infoObject)) { + ANS_LOGD("SetNotificationRequest set 'unifiedGroupInfo' faild"); + } + return true; +} + +bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // content: NotificationContent + if (!SetNotificationRequestByNotificationContent(env, cls, request, object)) { + ANS_LOGE("SetNotificationRequestByCustom: set content failed"); + return false; + } + // extraInfo?: {[key:string] : any} + if (!SetRequestExtraInfo(env, request, object)) { + ANS_LOGE("set extraInfo faild"); + } + // actionButtons?: Array + if (!SetRequestActionButtons(env, request, object)) { + ANS_LOGD("set actionButtons faild"); + } + // template?: NotificationTemplate + if (!SetRequestTemplate(env, request, object)) { + ANS_LOGD("set template faild"); + } + // readonly notificationFlags?: NotificationFlags + if (!SetRequestNotificationFlags(env, request, object)) { + ANS_LOGD("set notificationFlags faild"); + } + // readonly agentBundle?: agentBundle + if (!SetRequestAgentBundle(env, request, object)) { + ANS_LOGD("set agentBundle faild"); + } + // unifiedGroupInfo?: unifiedGroupInfo + if (!SetRequestUnifiedGroupInfo(env, request, object)) { + ANS_LOGD("set unifiedGroupInfo faild"); + } + return true; +} + +bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::NotificationRequest *notificationRequest, + ani_class &cls, ani_object &outAniObj) +{ + ANS_LOGD("WarpNotificationRequest start"); + if (notificationRequest == nullptr) { + ANS_LOGE("notification is null"); + return false; + } + if (!CreateClassObjByClassName(env, + "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: create class failed"); + return false; + } + if (!SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set bools failed"); + return false; + } + if (!SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set strings failed"); + return false; + } + if (!SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set numbers failed"); + return false; + } + if (!SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set WantAgent failed"); + return false; + } + if (!SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set PixelMap failed"); + return false; + } + if (!SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("WarpNotificationRequest: set Customs failed"); + return false; + } + ANS_LOGD("WarpNotificationRequest end"); + return true; +} + +ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests) +{ + ani_object arrayObj = newArrayClass(env, requests.size()); + if (arrayObj == nullptr) { + ANS_LOGE("arrayObj is nullptr"); + return nullptr; + } + ani_size index = 0; + for (auto &request : requests) { + ani_class requestCls; + ani_object requestObj; + if (!WarpNotificationRequest(env, request.GetRefPtr(), requestCls, requestObj) || requestObj == nullptr) { + ANS_LOGE("WarpNotificationRequest faild. index %{public}d", index); + return nullptr; + } + if (ANI_OK != env->Object_CallMethodByName_Void( + arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)) { + ANS_LOGE("Object_CallMethodByName_Void faild. index %{public}d", index); + return nullptr; + } + index ++; + } + return arrayObj; +} + +ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vector> requests) +{ + ani_object arrayObj = newArrayClass(env, requests.size()); + if (arrayObj == nullptr) { + ANS_LOGE("arrayObj is nullptr"); + return nullptr; + } + ani_size index = 0; + for (auto &request : requests) { + ani_class requestCls; + ani_object requestObj; + if (!WarpNotificationRequest( + env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj) + || requestObj == nullptr) { + ANS_LOGE("WarpNotificationRequest faild. index %{public}d", index); + return nullptr; + } + if (ANI_OK + != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)) { + ANS_LOGE("Object_CallMethodByName_Void faild. index %{public}d", index); + return nullptr; + } + index ++; + } + return arrayObj; +} + +bool GetCheckRequestContent(ani_env *env, ani_object obj, NotificationContent::Type &outContentType) +{ + ani_status status = ANI_OK; + ani_ref contentAniType; + STSContentType contentType = NOTIFICATION_CONTENT_BASIC_TEXT; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(obj, "contentType", &contentAniType))) { + ANS_LOGE("GetCheckRequestContent get contentType faild. status %{public}d", status); + return false; + } + if (contentAniType == nullptr || + !EnumConvertAniToNative(env, static_cast(contentAniType), contentType)) { + ANS_LOGE("EnumConvertAniToNative contentType faild"); + return false; + } + if (!StsContentTypeUtils::StsToC(contentType, outContentType)) { + ANS_LOGE("StsToC contentType faild"); + return false; + } + return true; +} + +bool GetCheckRequestSlotType(ani_env *env, ani_object obj, NotificationConstant::SlotType &outSlotType) +{ + ani_status status = ANI_OK; + ani_ref slotAniType; + STSSlotType slotType = UNKNOWN_TYPE; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(obj, "slotType", &slotAniType))) { + ANS_LOGE("UnWarpNotificationCheckRequest get slotType faild. status %{public}d", status); + return false; + } + if (slotAniType == nullptr || !EnumConvertAniToNative(env, static_cast(slotAniType), slotType)) { + ANS_LOGE("EnumConvertAniToNative slotType faild"); + return false; + } + if (!StsSlotTypeUtils::StsToC(slotType, outSlotType)) { + ANS_LOGE("StsToC slotType faild"); + return false; + } + return true; +} + +bool UnWarpNotificationCheckRequest(ani_env *env, ani_object obj, sptr &checkRequest) +{ + if (env == nullptr || obj == nullptr || checkRequest == nullptr) { + ANS_LOGE("UnWarpNotificationCheckRequest invalid parameters"); + return false; + } + ani_status status = ANI_OK; + ani_ref extraInfoKeysObj; + NotificationContent::Type outContentType = NotificationContent::Type::NONE; + NotificationConstant::SlotType outSlotType = NotificationConstant::SlotType::OTHER; + std::vector extraInfoKeys; + // contentType: notificationManager.ContentType; + if (!GetCheckRequestContent(env, obj, outContentType)) { + ANS_LOGE("GetCheckRequestContent faild."); + return false; + } + checkRequest->SetContentType(outContentType); + // slotType: notificationManager.SlotType; + if (!GetCheckRequestSlotType(env, obj, outSlotType)) { + ANS_LOGE("GetCheckRequestSlotType faild."); + return false; + } + checkRequest->SetSlotType(outSlotType); + // extraInfoKeys: Array; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(obj, "extraInfoKeys", &extraInfoKeysObj))) { + ANS_LOGE("UnWarpNotificationCheckRequest get extraInfoKeys faild. status %{public}d", status); + return false; + } + if (!GetStringArrayByAniObj(env, static_cast(extraInfoKeysObj), extraInfoKeys)) { + ANS_LOGE("UnWarpNotificationCheckRequest. extraInfoKeys GetStringArrayByAniObj faild."); + return false; + } + checkRequest->SetExtraKeys(extraInfoKeys); + ANS_LOGD("contentType %{public}d slotType %{public}d", + checkRequest->GetContentType(), checkRequest->GetSlotType()); + for (auto &it : checkRequest->GetExtraKeys()) { + ANS_LOGD("extrakey %{public}s", it.c_str()); + } + return true; +} + +bool UnWarpNotificationFilter(ani_env *env, ani_object obj, LiveViewFilter& filter) +{ + ANS_LOGD("UnWarpNotificationFilter call"); + if (env == nullptr || obj == nullptr) { + ANS_LOGE("UnWarpNotificationFilter failed, has nullptr"); + return false; + } + + ani_status status = ANI_OK; + ani_boolean isUndefined = ANI_TRUE; + ani_ref bundleObj = {}; + if (ANI_OK != (status = GetPropertyRef(env, obj, "bundle", isUndefined, bundleObj)) + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationFilter:get bundle failed. status %{public}d", status); + return false; + } + if (!OHOS::NotificationSts::UnwrapBundleOption(env, static_cast(bundleObj), filter.bundle)) { + ANS_LOGE("UnWarpNotificationFilter:UnwrapBundleOption failed"); + return false; + } + + ani_ref notificationKeyObj = {}; + if (ANI_OK != (status = GetPropertyRef(env, obj, "notificationKey", isUndefined, notificationKeyObj)) + || isUndefined == ANI_TRUE) { + ANS_LOGE("UnWarpNotificationFilter:get notificationKey failed. status %{public}d", status); + return false; + } + + if (OHOS::NotificationSts::UnWarpNotificationKey(env, static_cast(notificationKeyObj), + filter.notificationKey)) { + ANS_LOGD("UnWarpNotificationFilter:UnWarpNotificationKey label is undefined"); + } + + if (ANI_OK != (status = GetPropertyStringArray(env, obj, "extraInfoKeys", isUndefined, filter.extraInfoKeys))) { + ANS_LOGD("UnWarpNotificationFilter:get extraInfoKeysObj failed. status %{public}d", status); + } + return true; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..844c3fc897cfb54454b656aef09ab893c8a509c7 --- /dev/null +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2025 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 "sts_slot.h" + +#include "ans_log_wrapper.h" +#include "sts_notification_manager.h" +#include "sts_common.h" + + +namespace OHOS { +namespace NotificationSts { +bool SetOptionalFieldSlotLevel( + ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotLevel value) +{ + ANS_LOGD("SetOptionalFieldSlotLevel call"); + if (env == nullptr || cls == nullptr || object == nullptr) { + ANS_LOGE("SetOptionalFieldSlotLevel failed, has nullptr"); + return false; + } + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_enum_item enumItem = nullptr; + NotificationSts::SlotLevelCToEts(env, value, enumItem); + if (enumItem == nullptr) { + ANS_LOGE("null enumItem"); + return false; + } + status = env->Object_SetField_Ref(object, field, enumItem); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +bool SetOptionalFieldSlotType( + ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotType value) +{ + ANS_LOGD("SetOptionalFieldSlotType call"); + if (env == nullptr || cls == nullptr || object == nullptr) { + ANS_LOGE("SetOptionalFieldSlotType failed, has nullptr"); + return false; + } + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_enum_item enumItem = nullptr; + NotificationSts::SlotTypeCToEts(env, value, enumItem); + if (enumItem == nullptr) { + ANS_LOGE("null enumItem"); + return false; + } + status = env->Object_SetField_Ref(object, field, enumItem); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +bool WrapNotificationSlotByBoolean(ani_env *env, sptr slot, ani_object &outAniObj) +{ + if (!SetPropertyOptionalByBoolean(env, outAniObj, "badgeFlag", slot->IsShowBadge())) { + ANS_LOGE("Set badgeFlag fail"); + return false; + } + if (!SetPropertyOptionalByBoolean(env, outAniObj, "bypassDnd", slot->IsEnableBypassDnd())) { + ANS_LOGE("Set bypassDnd fail"); + return false; + } + if (!SetPropertyOptionalByBoolean(env, outAniObj, "vibrationEnabled", slot->CanVibrate())) { + ANS_LOGE("Set vibrationEnabled fail"); + return false; + } + if (!SetPropertyOptionalByBoolean(env, outAniObj, "lightEnabled", slot->CanEnableLight())) { + ANS_LOGE("Set lightEnabled fail"); + return false; + } + if (!SetPropertyOptionalByBoolean(env, outAniObj, "enabled", slot->GetEnable())) { + ANS_LOGE("Set enabled fail"); + return false; + } + return true; +} + +bool WrapNotificationSlotByString(ani_env *env, sptr slot, ani_object &outAniObj) +{ + if (!SetPropertyOptionalByString(env, outAniObj, "desc", slot->GetDescription())) { + ANS_LOGE("Set desc fail"); + return false; + } + if (!SetPropertyOptionalByString(env, outAniObj, "sound", slot->GetSound().ToString().c_str())) { + ANS_LOGE("Set sound fail"); + return false; + } + return true; +} + +bool WrapNotificationSlotByDouble(ani_env *env, sptr slot, ani_object &outAniObj) +{ + if (!SetPropertyOptionalByDouble( + env, outAniObj, "lockscreenVisibility", static_cast(slot->GetLockScreenVisibleness()))) { + ANS_LOGE("Set lockscreenVisibility fail"); + return false; + } + if (!SetPropertyOptionalByDouble(env, outAniObj, "lightColor", static_cast(slot->GetLedLightColor()))) { + ANS_LOGE("Set lightColor fail"); + return false; + } + if (!SetPropertyOptionalByDouble(env, outAniObj, "reminderMode", static_cast(slot->GetReminderMode()))) { + ANS_LOGE("Set reminderMode fail"); + return false; + } + if (!SetPropertyOptionalByDouble( + env, outAniObj, "authorizedStatus", static_cast(slot->GetAuthorizedStatus()))) { + ANS_LOGE("Set authorizedStatus fail"); + return false; + } + return true; +} + +bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlot call"); + if (env == nullptr || slot == nullptr) { + ANS_LOGE("WrapNotificationSlot failed, has nullptr"); + return false; + } + ani_class cls; + if (!CreateClassObjByClassName(env, NOTIFICATION_SOLT_CLASSNAME, cls, outAniObj)) { + ANS_LOGE("CreateClassObjByClassName fail"); + return false; + } + if (cls == nullptr || outAniObj == nullptr) { + ANS_LOGE("Create class failed"); + return false; + } + + if (!SetOptionalFieldSlotType(env, cls, outAniObj, "notificationType", slot->GetType())) { + ANS_LOGE("Set notificationType fail"); + return false; + } + if (!SetOptionalFieldSlotLevel(env, cls, outAniObj, "notificationLevel", slot->GetLevel())) { + ANS_LOGE("Set notificationLevel fail"); + return false; + } + if (!WrapNotificationSlotByBoolean(env, slot, outAniObj)) { + ANS_LOGE("set Boolean params fail"); + return false; + } + if (!WrapNotificationSlotByString(env, slot, outAniObj)) { + ANS_LOGE("set String params fail"); + return false; + } + if (!WrapNotificationSlotByDouble(env, slot, outAniObj)) { + ANS_LOGE("set String params fail"); + return false; + } + if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { + ANS_LOGE("Set vibrationValues fail"); + return false; + } + ANS_LOGD("WrapNotificationSlot end"); + return true; +} + +bool WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, + ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlotArray call"); + outAniObj = newArrayClass(env, slots.size()); + if (outAniObj == nullptr) { + ANS_LOGE("outAniObj is null, newArrayClass Faild"); + return false; + } + int index = 0; + for (auto &it : slots) { + ani_object infoObj; + if (!WrapNotificationSlot(env, it, infoObj) || infoObj == nullptr) { + ANS_LOGE("WrapNotificationSlot Faild. index = %{public}d", index); + return false; + } + if (ANI_OK != env->Object_CallMethodByName_Void(outAniObj, "$_set", "ILstd/core/Object;:V", index, infoObj)) { + ANS_LOGE("set Faild. index = %{public}d", index); + return false; + } + index++; + } + ANS_LOGD("WrapNotificationSlotArray end"); + return true; +} + +bool ParseNotificationSlotByBasicType(ani_env *env, ani_object notificationSlotObj, NotificationSlot &slot) +{ + if (notificationSlotObj == nullptr) { + ANS_LOGE("notificationSlotObj is null"); + return false; + } + ani_boolean isUndefined = ANI_TRUE; + std::string desc = ""; + if (GetPropertyString(env, notificationSlotObj, "desc", isUndefined, desc) == ANI_OK && isUndefined == ANI_FALSE) { + slot.SetDescription(desc); + } + std::string sound = ""; + if (GetPropertyString(env, notificationSlotObj, "sound", isUndefined, sound) == ANI_OK && + isUndefined == ANI_FALSE) { + slot.SetSound(Uri(sound)); + } + ani_double doubleValue = 0.0; + if (GetPropertyDouble(env, notificationSlotObj, "lockscreenVisibility", isUndefined, doubleValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.SetLockscreenVisibleness( + Notification::NotificationConstant::VisiblenessType(static_cast(doubleValue))); + } + if (GetPropertyDouble(env, notificationSlotObj, "lightColor", isUndefined, doubleValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.SetLedLightColor(static_cast(doubleValue)); + } + bool boolValue = true; + if (GetPropertyBool(env, notificationSlotObj, "badgeFlag", isUndefined, boolValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.EnableBadge(boolValue); + } + if (GetPropertyBool(env, notificationSlotObj, "bypassDnd", isUndefined, boolValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.EnableBypassDnd(boolValue); + } + if (GetPropertyBool(env, notificationSlotObj, "lightEnabled", isUndefined, boolValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.SetEnableLight(boolValue); + } + if (GetPropertyBool(env, notificationSlotObj, "vibrationEnabled", isUndefined, boolValue) == ANI_OK + && isUndefined == ANI_FALSE) { + slot.SetEnableVibration(boolValue); + } + return true; +} + +bool UnwrapNotificationSlot(ani_env *env, ani_object notificationSlotObj, NotificationSlot &slot) +{ + ANS_LOGD("UnwrapNotificationSlot enter"); + if (notificationSlotObj == nullptr) { + ANS_LOGE("notificationSlotObj is null"); + return false; + } + ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; + ani_ref notificationTypeRef = {}; + status = GetPropertyRef(env, notificationSlotObj, "notificationType", isUndefined, notificationTypeRef); + if (status == ANI_OK && isUndefined == ANI_FALSE) { + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (SlotTypeEtsToC(env, static_cast(notificationTypeRef), slotType)) { + slot.SetType(slotType); + } + } + status = GetPropertyRef(env, notificationSlotObj, "notificationLevel", isUndefined, notificationTypeRef); + if (status == ANI_OK && isUndefined == ANI_FALSE) { + NotificationSlot::NotificationLevel outLevel {NotificationSlot::NotificationLevel::LEVEL_NONE}; + if (SlotLevelEtsToC(env, static_cast(notificationTypeRef), outLevel)) { + slot.SetLevel(outLevel); + } + } + if (!ParseNotificationSlotByBasicType(env, notificationSlotObj, slot)) { + ANS_LOGE("ParseNotificationSlotByBasicType failed"); + return false; + } + std::vector vibrationValues; + if (GetPropertyNumberArray(env, notificationSlotObj, "vibrationValues", isUndefined, vibrationValues) == ANI_OK && + isUndefined == ANI_FALSE) { + slot.SetVibrationStyle(vibrationValues); + } + ANS_LOGD("UnwrapNotificationSlot leave"); + return true; +} + +bool UnwrapNotificationSlotArrayByAniObj(ani_env *env, ani_object notificationSlotArrayObj, + std::vector &slots) +{ + ANS_LOGD("UnwrapNotificationSlotArrayByAniObj enter"); + if (notificationSlotArrayObj == nullptr) { + ANS_LOGE("notificationSlotArrayObj is null"); + return false; + } + ani_double length; + ani_status status = env->Object_GetPropertyByName_Double(notificationSlotArrayObj, "length", &length); + if (status != ANI_OK) { + ANS_LOGE("Object_GetPropertyByName_Double faild. status : %{public}d", status); + return false; + } + for (int i = 0; i < int(length); i++) { + ani_ref notificationSlotEntryRef; + status = env->Object_CallMethodByName_Ref(notificationSlotArrayObj, + "$_get", "I:Lstd/core/Object;", ¬ificationSlotEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Ref faild. status : %{public}d", status); + } + NotificationSlot slot; + if (!UnwrapNotificationSlot(env, static_cast(notificationSlotEntryRef), slot)) { + ANS_LOGE("UnwrapNotificationSlot faild"); + return false; + } + slots.emplace_back(slot); + } + ANS_LOGD("UnwrapNotificationSlotArrayByAniObj leave"); + return true; +} +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_sorting.cpp b/frameworks/ets/ani/src/sts_sorting.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d238ce92ed7662c566e4dd373696cb0eafc0b0b --- /dev/null +++ b/frameworks/ets/ani/src/sts_sorting.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 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 "sts_sorting.h" + +#include "ans_log_wrapper.h" +#include "sts_common.h" +#include "sts_slot.h" + +namespace OHOS { +namespace NotificationSts { +bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting &sorting, ani_object &outObj) +{ + ani_class cls; + ani_object obj; + ani_object slotObj; + ani_status status; + ani_string hashCodeObj; + std::string hashCode; + if (env == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + if (!CreateClassObjByClassName(env, "Lnotification/notificationSorting/NotificationSortingInner;", cls, obj)) { + ANS_LOGE("Create obj faild. NotificationSortingInner"); + return false; + } + // readonly slot: NotificationSlot + if (!WrapNotificationSlot(env, sorting.GetSlot(), slotObj)) { + ANS_LOGE("WrapNotificationSlot faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(obj, "slot", slotObj))) { + ANS_LOGE("set slot faild. status %{public}d", status); + return false; + } + hashCode = sorting.GetGroupKeyOverride(); + if (ANI_OK != GetAniStringByString(env, hashCode, hashCodeObj) || hashCodeObj == nullptr) { + ANS_LOGE("GetAniStringByString faild"); + return false; + } + // readonly hashCode: string; + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(obj, "hashCode", hashCodeObj))) { + ANS_LOGE("set hashCode faild. status %{public}d", status); + return false; + } + // readonly ranking: number; + if (ANI_OK != (status = env->Object_SetPropertyByName_Double( + obj, "ranking", static_cast(sorting.GetRanking())))) { + ANS_LOGE("set ranking faild. status %{public}d", status); + return false; + } + outObj = obj; + return true; +} +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67e99b3410ab48e87d9c289bfcf43872b69acef3 --- /dev/null +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 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 "sts_sorting_map.h" + +#include "sts_common.h" +#include "sts_sorting.h" + +namespace OHOS { +namespace NotificationSts { +bool GetKeySToRecode(ani_env *env, const std::shared_ptr &sortingMap, ani_object &recordObj) +{ + ani_status status = ANI_ERROR; + std::vector keys = sortingMap->GetKey(); + for (auto &it : keys) { + Notification::NotificationSorting sorting; + if (!sortingMap->GetNotificationSorting(it, sorting)) { + ANS_LOGE("GetNotificationSorting faild."); + return false; + } + ani_string keyString; + if (ANI_OK != GetAniStringByString(env, it, keyString)) { + ANS_LOGE("GetAniStringByString faild. key: %{public}s", it.c_str()); + return false; + } + ani_object sortingObj; + if (!WarpNotificationSorting(env, sorting, sortingObj)) { + ANS_LOGE("WarpNotificationSorting faild. key: %{public}s", it.c_str()); + return false; + } + if (keyString == nullptr) { + ANS_LOGE("GetAniString faild. key: %{public}s", it.c_str()); + return false; + } + if (ANI_OK != (status = env->Object_CallMethodByName_Void( + recordObj, "$_set", "Lstd/core/Object;Lstd/core/Object;:V", keyString, sortingObj))) { + ANS_LOGE("set key value faild. key: %{public}s status %{public}d", it.c_str(), status); + return false; + } + } + return true; +} + +bool WarpNotificationSortingMap(ani_env *env, + const std::shared_ptr &sortingMap, ani_object &outObj) +{ + ani_class cls; + ani_object recordObj; + ani_class recordCls; + ani_status status; + if (sortingMap == nullptr || env == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + + if (!CreateClassObjByClassName(env, + "Lnotification/notificationSortingMap/NotificationSortingMapInner;", cls, outObj)) { + ANS_LOGE("CreateClassObjByClassName faild."); + return false; + } + + if (!CreateClassObjByClassName(env, "Lescompat/Record;", recordCls, recordObj) || recordObj == nullptr) { + ANS_LOGE("Create recordObj faild."); + return false; + } + if (!GetKeySToRecode(env, sortingMap, recordObj)) { + ANS_LOGE("GetKeySToRecode failed."); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortings", recordObj))) { + ANS_LOGE("Object_SetPropertyByName_Ref sortings faild. status %{public}d", status); + return false; + } + std::vector keys = sortingMap->GetKey(); + if (!keys.empty()) { + ani_object arrayObj = GetAniStringArrayByVectorString(env, keys); + if (arrayObj == nullptr) { + ANS_LOGE("WarpVectorStringToSts sortedHashCode faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortedHashCode", arrayObj))) { + ANS_LOGE("Object_SetPropertyByName_Ref sortedHashCode faild. status %{public}d", status); + return false; + } + } + return true; +} +} // namespace NotificationSts +} // OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fd46299f415fa9d47cbbe4504b9ae65a93c4b15 --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -0,0 +1,813 @@ +/* + * Copyright (c) 2025 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 "sts_subscribe.h" + +#include "ans_log_wrapper.h" +#include "inner_errors.h" +#include "notification_helper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "sts_sorting_map.h" +#include "sts_subscribe_info.h" +#include "ani_common_util.h" + +namespace OHOS { +namespace NotificationSts { +StsDistributedOperationCallback::StsDistributedOperationCallback(ani_object promise, ani_resolver resolver) + : resolver_(resolver) +{ +} + +void StsDistributedOperationCallback::OnOperationCallback(const int32_t operationResult) +{ + std::lock_guard l(lock_); + if (isCall_) return; + if (etsVm_ == nullptr) { + ANS_LOGD("etsVm_ is null"); + return; + } + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = etsVm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("StsDistributedOperationCallback AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + OnStsOperationCallback(etsEnv, operationResult); + aniResult = etsVm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("StsDistributedOperationCallback DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + isCall_ = true; +} + +void StsDistributedOperationCallback::OnStsOperationCallback(ani_env *env, const int32_t operationResult) +{ + ANS_LOGD("ENTER"); + if (env == nullptr) { + ANS_LOGD("env is nullptr"); + return; + } + ani_status status = ANI_OK; + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(operationResult); + externalErrorCode = + (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? operationResult : externalErrorCode; + ANS_LOGD("operationResult %{public}d, externalCode %{public}d", operationResult, externalErrorCode); + + if (externalErrorCode == 0) { + ANS_LOGD("OnStsOperationCallback Resolve"); + ani_object ret = OHOS::AppExecFwk::createInt(env, externalErrorCode); + if (ANI_OK != (status = env->PromiseResolver_Resolve(resolver_, static_cast(ret)))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + return; + } + } else { + ANS_LOGD("OnStsOperationCallback reject"); + std::string errMsg = FindAnsErrMsg(externalErrorCode); + ani_error rejection = + static_cast(OHOS::AbilityRuntime::CreateStsError(env, externalErrorCode, errMsg)); + if (ANI_OK != (status = env->PromiseResolver_Reject(resolver_, rejection))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", status); + } + } +} + +void StsDistributedOperationCallback::SetVm(ani_vm *vm) +{ + etsVm_ = vm; +} + +StsSubscriberInstance::StsSubscriberInstance() +{} +StsSubscriberInstance::~StsSubscriberInstance() +{} +void StsSubscriberInstance::OnCanceled( + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int32_t deleteReason) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpSubscribeCallbackData(etsEnv, request, sortingMap, deleteReason, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onCancel", vec); + } else { + ANS_LOGD("WarpSubscribeCallbackData faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnConsumed( + const std::shared_ptr &request, + const std::shared_ptr &sortingMap) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpSubscribeCallbackData(etsEnv, request, sortingMap, -1, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onConsume", vec); + } else { + ANS_LOGD("WarpSubscribeCallbackData faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpNotificationSortingMap(etsEnv, sortingMap, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onUpdate", vec); + } else { + ANS_LOGD("WarpNotificationSortingMap faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnConnected() +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + CallFunction(etsEnv, "onConnect", vec); + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnDisconnected() +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + CallFunction(etsEnv, "onDisconnect", vec); + if (!SubscriberInstanceManager::GetInstance()->DelSubscriberInstancesInfo(etsEnv, obj_)) { + ANS_LOGD("DelSubscriberInstancesInfo faild"); + } else { + ANS_LOGD("DelSubscriberInstancesInfo suc.."); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnDied() +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + CallFunction(etsEnv, "onDestroy", vec); + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptr &date) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); +} +void StsSubscriberInstance::onDoNotDisturbChanged(const std::shared_ptr &date) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpNotificationDoNotDisturbDate(etsEnv, date, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onDoNotDisturbChanged", vec); + } else { + ANS_LOGD("WarpNotificationDoNotDisturbDate faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpEnabledNotificationCallbackData(etsEnv, callbackData, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onEnabledNotificationChanged", vec); + } else { + ANS_LOGD("WarpEnabledNotificationCallbackData faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnBadgeChanged(const std::shared_ptr &badgeData) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpBadgeNumberCallbackData(etsEnv, badgeData, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onBadgeChanged", vec); + } else { + ANS_LOGD("WarpBadgeNumberCallbackData faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnBadgeEnabledChanged(const sptr &callbackData) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + std::shared_ptr data = std::make_shared(); + data->SetBundle(callbackData->GetBundle()); + data->SetUid(callbackData->GetUid()); + data->SetEnable(callbackData->GetEnable()); + if (WarpEnabledNotificationCallbackData(etsEnv, data, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onBadgeEnabledChanged", vec); + } else { + ANS_LOGD("WarpEnabledNotificationCallbackData faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +void StsSubscriberInstance::OnBatchCanceled( + const std::vector> &requestList, + const std::shared_ptr &sortingMap, int32_t deleteReason) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return; + } + std::vector vec; + ani_object obj; + if (WarpSubscribeCallbackDataArray(etsEnv, requestList, sortingMap, deleteReason, obj)) { + vec.push_back(obj); + CallFunction(etsEnv, "onBatchCancel", vec); + } else { + ANS_LOGD("WarpSubscribeCallbackDataArray faild"); + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + ANS_LOGD("done"); +} +bool StsSubscriberInstance::HasOnBatchCancelCallback() +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + ani_env* etsEnv; + ani_status aniResult = ANI_ERROR; + ani_options aniArgs { 0, nullptr }; + aniResult = vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &etsEnv); + if (aniResult != ANI_OK) { + ANS_LOGD("AttachCurrentThread error. result: %{public}d.", aniResult); + return false; + } + + ani_ref fn_ref; + aniResult = etsEnv->Object_GetFieldByName_Ref(static_cast(ref_), "onBatchCancel", &fn_ref); + if (ANI_OK != aniResult) { + ANS_LOGD("Object_GetFieldByName_Ref 'onBatchCancel' error. result: %{public}d.", aniResult); + vm_->DetachCurrentThread(); + return false; + } + ani_boolean isUndefined = true; + if (ANI_OK != etsEnv->Reference_IsUndefined(fn_ref, &isUndefined)) { + ANS_LOGD("Reference_IsUndefined faild"); + vm_->DetachCurrentThread(); + return false; + } + aniResult = vm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("StsDistributedOperationCallback DetachCurrentThread error. result: %{public}d.", aniResult); + } + if (isUndefined == ANI_FALSE) { + return true; + } + return false; +} +bool StsSubscriberInstance::SetObject(ani_env *env, ani_object obj) +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + if (env == nullptr || obj == nullptr) return false; + if (ANI_OK != env->GetVM(&vm_)) { + ANS_LOGD("GetVM faild"); + return false; + } + if (ANI_OK != env->GlobalReference_Create(obj, &ref_)) { + ANS_LOGD("GlobalReference_Create faild"); + return false; + } + obj_ = obj; + return true; +} +bool StsSubscriberInstance::IsInit() +{ + ANS_LOGD("enter"); + std::lock_guard l(lock_); + return (ref_ != nullptr && vm_ != nullptr); +} +bool StsSubscriberInstance::Compare(ani_env *env, ani_object obj) +{ + ANS_LOGD("enter"); + if (!IsInit()) return false; + if (obj == nullptr || env == nullptr) return false; + ani_ref ref; + if (env->GlobalReference_Create(obj, &ref) != ANI_OK) return false; + ani_boolean result = ANI_FALSE; + env->Reference_StrictEquals(ref, ref_, &result); + env->GlobalReference_Delete(ref); + return (result == ANI_TRUE) ? true : false; +} +bool StsSubscriberInstance::Compare(std::shared_ptr instance) +{ + ANS_LOGD("enter"); + if (instance == nullptr) return false; + if (instance->obj_ == obj_) { + ANS_LOGD("Compare is ture"); + return true; + } + ANS_LOGD("Compare is false"); + return false; +} +bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::vector &parm) +{ + ANS_LOGD("enter"); + if (env == nullptr) return false; + ani_ref fn_ref; + ani_status aniResult = env->Object_GetPropertyByName_Ref(static_cast(ref_), func, &fn_ref); + if (ANI_OK != aniResult) { + ANS_LOGD("Object_GetPropertyByName_Ref '%{public}s' error. result: %{public}d.", func, aniResult); + return false; + } + ani_boolean IsUndefined = ANI_FALSE; + if (ANI_OK != env->Reference_IsUndefined(fn_ref, &IsUndefined) || IsUndefined == ANI_TRUE) { + ANS_LOGD("Reference_IsUndefined faild. or IsUndefined"); + return false; + } + ani_ref fnReturnVal; + aniResult = env->FunctionalObject_Call( + static_cast(fn_ref), parm.size(), parm.data(), &fnReturnVal); + if (ANI_OK != aniResult) { + ANS_LOGD("FunctionalObject_Call error. result: %{public}d.", aniResult); + return false; + } + ANS_LOGD("done"); + return true; +} + +bool SubscriberInstanceManager::HasNotificationSubscriber( + ani_env *env, ani_object value, std::shared_ptr &subscriberInfo) +{ + ANS_LOGD("enter"); + for (auto &iter : subscriberInstances_) { + if (iter->Compare(env, value)) { + subscriberInfo = iter; + return true; + } + } + return false; +} +bool SubscriberInstanceManager::AddSubscriberInstancesInfo( + ani_env *env, std::shared_ptr &subscriberInfo) +{ + ANS_LOGD("enter"); + if (!subscriberInfo->IsInit()) { + ANS_LOGE("subscriberInfo not init"); + return false; + } + std::lock_guard lock(mutex_); + subscriberInstances_.emplace_back(subscriberInfo); + return true; +} +bool SubscriberInstanceManager::DelSubscriberInstancesInfo( + ani_env *env, ani_object obj) +{ + ANS_LOGD("enter"); + if (obj == nullptr) { + ANS_LOGE("obj is null"); + return false; + } + std::lock_guard lock(mutex_); + for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { + if ((*it)->Compare(env, obj)) { + DelDeletingSubscriber((*it)); + subscriberInstances_.erase(it); + return true; + } + } + return false; +} +bool SubscriberInstanceManager::GetNotificationSubscriber( + ani_env *env, ani_object value, std::shared_ptr &subscriberInfo) +{ + ANS_LOGD("enter"); + subscriberInfo = std::make_shared(); + if (!subscriberInfo->SetObject(env, value)) { + ANS_LOGD("SetObject faild"); + return false; + } + return true; +} +bool SubscriberInstanceManager::AddDeletingSubscriber(std::shared_ptr subscriber) +{ + ANS_LOGD("enter"); + std::lock_guard lock(delMutex_); + if (subscriber == nullptr) return false; + auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); + if (iter != DeletingSubscriber.end()) { + return false; + } + DeletingSubscriber.push_back(subscriber); + return true; +} +void SubscriberInstanceManager::DelDeletingSubscriber(std::shared_ptr subscriber) +{ + ANS_LOGD("enter"); + std::lock_guard lock(delMutex_); + auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); + if (iter != DeletingSubscriber.end()) { + DeletingSubscriber.erase(iter); + } +} + +bool SubscriberInstanceManager::Subscribe(ani_env *env, ani_object subscriber, ani_object info) +{ + ANS_LOGD("enter"); + bool isSubscribeUndefine = IsUndefine(env, subscriber); + bool isInfoUndefine = IsUndefine(env, info); + if (isSubscribeUndefine) { + ANS_LOGD("subscriber is undefine"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, "subscriber is undefine"); + return false; + } + sptr SubscribeInfo = + new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); + if (!isInfoUndefine) { + if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { + ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, "UnwarpNotificationSubscribeInfo faild"); + return false; + } + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("GetNotificationSubscriber faild"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); + return false; + } + if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { + ANS_LOGD("AddSubscriberInstancesInfo faild"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); + return false; + } + } + ErrCode status = ERR_OK; + if (!isInfoUndefine) { + status = NotificationHelper::SubscribeNotification(stsSubscriber, SubscribeInfo); + } else { + status = NotificationHelper::SubscribeNotification(stsSubscriber); + } + if (status != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(status); + externalErrorCode = + (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? status : externalErrorCode; + ANS_LOGD("SubscribeNotification faild. status %{public}d ErrorToExternal %{public}d", + status, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + return false; + } + return true; +} + +bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) +{ + ANS_LOGD("enter"); + if (IsUndefine(env, subscriber)) { + ANS_LOGD("Subscriber is undefine"); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(ERR_ANS_INVALID_PARAM); + OHOS::AbilityRuntime::ThrowStsError(env, ERR_ANS_INVALID_PARAM, msg); + return false; + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("Subscriber not found"); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(ERR_ANS_INVALID_PARAM); + OHOS::AbilityRuntime::ThrowStsError(env, ERR_ANS_INVALID_PARAM, msg); + return false; + } + bool ret = AddDeletingSubscriber(stsSubscriber); + if (ret) { + int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); + if (status != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(status); + externalErrorCode = + (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? status : externalErrorCode; + ANS_LOGD("UnSubscribe faild. status %{public}d ErrorToExternal %{public}d", + status, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + DelDeletingSubscriber(stsSubscriber); + } + } else { + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(ERR_ANS_SUBSCRIBER_IS_DELETING); + OHOS::AbilityRuntime::ThrowStsError(env, ERR_ANS_SUBSCRIBER_IS_DELETING, msg); + return false; + } + return true; +} + +bool SubscriberInstanceManager::SubscribeSelf(ani_env *env, ani_object subscriber) +{ + ANS_LOGD("enter"); + bool isSubscribeUndefine = IsUndefine(env, subscriber); + if (isSubscribeUndefine) { + ANS_LOGD("subscriber is undefine"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, "subscriber is undefine"); + return false; + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("GetNotificationSubscriber faild"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); + return false; + } + if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { + ANS_LOGD("AddSubscriberInstancesInfo faild"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); + return false; + } + } + ErrCode status = ERR_OK; + status = NotificationHelper::SubscribeNotificationSelf(stsSubscriber); + if (status != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(status); + externalErrorCode = + (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? status : externalErrorCode; + ANS_LOGD("SubscribeNotificationSelf faild. status %{public}d ErrorToExternal %{public}d", + status, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + return false; + } + return true; +} + +bool GetDoubleValueByClassName( + ani_env *env, ani_object param, const char *className, const char *name, ani_double &value) +{ + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + ANS_LOGD("FindClass faild. %{public}s", className); + return false; + } + ani_method idGetter; + if (ANI_OK != env->Class_FindMethod(cls, name, nullptr, &idGetter)) { + ANS_LOGD("Class_FindMethod faild. %{public}s", className); + return false; + } + if (ANI_OK != env->Object_CallMethod_Double(param, idGetter, &value)) { + ANS_LOGD("Object_CallMethod_Double faild. %{public}s", className); + return false; + } + return true; +} + +bool UnWarpReasonEnum(ani_env *env, const ani_object enumItem, int32_t &outEnum) +{ + ani_status status = ANI_ERROR; + ani_int intValue{}; + status = env->EnumItem_GetValue_Int(static_cast(enumItem), &intValue); + if (ANI_OK != status) { + ANS_LOGD("EnumItem_GetValue_Int failed, status : %{public}d", status); + return false; + } + outEnum = static_cast(intValue); + return true; +} + +bool IsValidRemoveReason(int32_t reasonType) +{ + if (reasonType == OHOS::Notification::NotificationConstant::CLICK_REASON_DELETE || + reasonType == OHOS::Notification::NotificationConstant::CANCEL_REASON_DELETE) { + return true; + } + ANS_LOGD("Reason %{public}d is an invalid value", reasonType); + return false; +} + +bool UnWarpNotificationKey(ani_env *env, const ani_object obj, NotificationKey &OutObj) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_double idDouble = 0.0; + if (!GetDoubleValueByClassName(env, obj, + "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKeyInner;", "id", idDouble)) { + ANS_LOGD("GetDoubleValueByClassName id fail"); + return false; + } + OutObj.id = static_cast(idDouble); + std::string label; + if (GetPropertyString(env, obj, "label", isUndefined, label) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGD("UnWarpNotificationKey GetPropertyString label fail"); + return false; + } + OutObj.label = label; + ANS_LOGD("UnWarpNotificationKey id: %{public}d, label: %{public}s", OutObj.id, OutObj.label.c_str()); + return true; +} + +bool UnwarpOperationInfo(ani_env *env, const ani_object obj, StsNotificationOperationInfo &outObj) +{ + ani_boolean isUndefined = ANI_TRUE; + std::string actionName; + std::string userInput; + if (GetPropertyString(env, obj, "actionName", isUndefined, actionName) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGD("ConvertOperationInfoToNative GetStringOrUndefined actionName fail"); + return false; + } + outObj.SetActionName(actionName); + if (GetPropertyString(env, obj, "userInput", isUndefined, userInput) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGD("ConvertOperationInfoToNative GetStringOrUndefined userInput fail"); + return false; + } + outObj.SetUserInput(actionName); + ANS_LOGD("ConvertOperationInfoToNative actionName: %{public}s, userInput: %{public}s", + outObj.GetActionName().c_str(), outObj.GetUserInput().c_str()); + return true; +} + +sptr GetOperationInfoForDistributeOperation( + ani_env *env, ani_string hashcode, ani_object operationInfo, bool &noWithOperationInfo) +{ + std::string hashCodeStd; + sptr info = new (std::nothrow) StsNotificationOperationInfo(); + if (ANI_OK != GetStringByAniString(env, hashcode, hashCodeStd)) { + ANS_LOGD("hashCode is valid"); + return nullptr; + } + info->SetHashCode(hashCodeStd); + noWithOperationInfo = IsUndefine(env, operationInfo); + if (!noWithOperationInfo) { + if (!UnwarpOperationInfo(env, operationInfo, *info)) { + ANS_LOGD("operationInfo is valid"); + return nullptr; + } + ANS_LOGD("OperationInfo %{public}s %{public}s", + info->GetActionName().c_str(), info->GetUserInput().c_str()); + info->SetOperationType(OperationType::DISTRIBUTE_OPERATION_REPLY); + } else { + info->SetOperationType(OperationType::DISTRIBUTE_OPERATION_JUMP); + } + return info; +} +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_subscribe_info.cpp b/frameworks/ets/ani/src/sts_subscribe_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b5c4a891b9274af120fa3b13f583db05de47ebb --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscribe_info.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 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 "sts_subscribe_info.h" + +#include "sts_common.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace NotificationSts { +bool UnwarpNotificationSubscribeInfo(ani_env *env, ani_object value, NotificationSubscribeInfo &info) +{ + ANS_LOGD("enter"); + if (env == nullptr || value == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + std::vector res; + ani_double userId = 0.0; + ani_double filterLimit = 0.0; + std::string deviceType; + ani_boolean isUndefined = ANI_TRUE; + if (ANI_OK != GetPropertyStringArray(env, value, "bundleNames", isUndefined, res) + || isUndefined == ANI_TRUE + || res.empty()) { + ANS_LOGE("UnWarpStringArrayOrUndefinedByProperty faild"); + } + if (ANI_OK != GetPropertyDouble(env, value, "userId", isUndefined, userId) || isUndefined == ANI_TRUE) { + ANS_LOGE("GetDoubleOrUndefined faild"); + } + if (ANI_OK != GetPropertyString(env, value, "deviceType", isUndefined, deviceType) || isUndefined == ANI_TRUE) { + ANS_LOGE("GetStringOrUndefined faild"); + } + if (ANI_OK != GetPropertyDouble(env, value, "filterLimit", isUndefined, filterLimit) || isUndefined == ANI_TRUE) { + ANS_LOGE("GetDoubleOrUndefined faild"); + } + info.AddAppNames(res); + info.AddAppUserId(static_cast(userId)); + info.SetFilterType(static_cast(filterLimit)); + info.AddDeviceType(deviceType); + ANS_LOGD("userId %{public}d deviceType %{public}s filterLimit %{public}d", + info.GetAppUserId(), info.GetDeviceType().c_str(), info.GetFilterType()); + return true; +} + +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19c966c1548e0bbbf8a47d1130841e07ca7ca1b6 --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2025 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 "sts_subscriber.h" + +#include "ans_log_wrapper.h" +#include "sts_common.h" +#include "sts_request.h" +#include "sts_sorting_map.h" + +namespace OHOS { +namespace NotificationSts { +bool SetNotificationRequest(ani_env *env, const std::shared_ptr &request, ani_object &outObj) +{ + ani_status status = ANI_OK; + ani_object requestObj; + ani_class requestCls; + if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj) + || requestObj == nullptr) { + ANS_LOGE("WarpNotificationRequest faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "request", requestObj))) { + ANS_LOGE("set request faild. status %{public}d", status); + return false; + } + return true; +} + +bool SetNotificationSortingMap( + ani_env *env, const std::shared_ptr &sortingMap, ani_object &outObj) +{ + ani_status status = ANI_OK; + ani_object sortingMapObj; + if (!WarpNotificationSortingMap(env, sortingMap, sortingMapObj)) { + ANS_LOGE("WarpNotificationSortingMap faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortingMap", sortingMapObj))) { + ANS_LOGE("set sortingMap faild. status %{public}d", status); + return false; + } + return true; +} + +bool SetReason(ani_env *env, const int32_t deleteReason, ani_object &outObj) +{ + ani_status status = ANI_OK; + if (deleteReason != -1) { + ani_object reason = CreateDouble(env, static_cast(deleteReason)); + if (reason == nullptr) { + ANS_LOGE("reason Create faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "reason", reason))) { + ANS_LOGE("set reason faild. status %{public}d", status); + return false; + } + } + return true; +} + +bool SetSound(ani_env *env, const std::shared_ptr &request, ani_object &outObj) +{ + ani_status status = ANI_OK; + if (request->EnableSound()) { + std::string sound = request->GetSound().ToString(); + ani_string soundObj; + if (ANI_OK != GetAniStringByString(env, sound, soundObj) || soundObj == nullptr) { + ANS_LOGE("sound create faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sound", soundObj))) { + ANS_LOGE("set sound faild. status %{public}d", status); + } + } + return true; +} + +bool SetVibrationValues(ani_env *env, const std::shared_ptr &request, ani_object &outObj) +{ + ani_status status = ANI_OK; + if (request->EnableVibrate()) { + ani_object vibrationValuesObj; + const std::vector vibrationValues = request->GetVibrationStyle(); + vibrationValuesObj = newArrayClass(env, vibrationValues.size()); + if (vibrationValuesObj == nullptr) { + ANS_LOGE("CreateArray faild"); + return false; + } + for (size_t i = 0; i < vibrationValues.size(); i++) { + status = env->Object_CallMethodByName_Void( + vibrationValuesObj, "$_set", "ID:V", i, static_cast(vibrationValues[i])); + if (status != ANI_OK) { + ANS_LOGE("faild. status : %{public}d", status); + return false; + } + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "vibrationValues", vibrationValuesObj))) { + ANS_LOGE("set vibrationValuesObj faild. status %{public}d", status); + return false; + } + } + return true; +} + +bool WarpSubscribeCallbackData( + ani_env *env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int32_t deleteReason, + ani_object &outObj) +{ + ANS_LOGD("enter"); + ani_class cls; + if (env == nullptr || request == nullptr || sortingMap == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + if (!CreateClassObjByClassName( + env, "Lnotification/notificationSubscriber/SubscribeCallbackDataInner;", cls, outObj)) { + ANS_LOGE("CreateClassObjByClassName faild"); + return false; + } + // request: NotificationRequest + if (!SetNotificationRequest(env, request, outObj)) { + ANS_LOGE("SetNotificationRequest faild"); + return false; + } + // sortingMap?: NotificationSortingMap + if (!SetNotificationSortingMap(env, sortingMap, outObj)) { + ANS_LOGE("SetNotificationSortingMap faild"); + return false; + } + // reason?: number + if (!SetReason(env, deleteReason, outObj)) { + ANS_LOGE("SetReason faild"); + return false; + } + // sound?: string + if (!SetSound(env, request, outObj)) { + ANS_LOGE("SetSound faild"); + return false; + } + // vibrationValues?: Array + if (!SetVibrationValues(env, request, outObj)) { + ANS_LOGE("SetSound faild"); + return false; + } + return true; +} + +bool WarpSubscribeCallbackDataArray( + ani_env *env, + const std::vector> &requestList, + const std::shared_ptr &sortingMap, + int32_t deleteReason, + ani_object &outObj) +{ + ANS_LOGD("enter"); + if (env == nullptr || sortingMap == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + ani_status status; + if (env == nullptr) { + ANS_LOGE("env is nullptr"); + return false; + } + outObj = newArrayClass(env, requestList.size()); + if (outObj == nullptr) { + ANS_LOGE("CreateArray faild"); + return false; + } + for (size_t i = 0; i < requestList.size(); i++) { + ani_object obj; + if (!WarpSubscribeCallbackData(env, requestList[i], sortingMap, deleteReason, obj)) { + ANS_LOGE("WarpSubscribeCallbackData faild"); + return false; + } + if (ANI_OK != (status = env->Object_CallMethodByName_Void( + outObj, "$_set", "ILstd/core/Object;:V", i, obj))) { + ANS_LOGE("set object faild. status %{public}d", status); + return false; + } + } + return true; +} + +bool WarpEnabledNotificationCallbackData( + ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj) +{ + ANS_LOGD("enter"); + if (env == nullptr || callbackData == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + ani_class cls; + ani_status status; + const char *className = "Lnotification/notificationSubscriber/EnabledNotificationCallbackDataInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj)) { + ANS_LOGE("CreateClassObjByClassName faild"); + return false; + } + if (!SetFieldString(env, cls, outObj, "bundle", callbackData->GetBundle())) { + ANS_LOGE("SetFieldString bundle faild"); + return false; + } + if (!CallSetter(env, cls, outObj, "uid", static_cast(callbackData->GetUid()))) { + ANS_LOGE("uid set faild."); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Boolean( + outObj, "enable", BoolToAniBoolean(callbackData->GetEnable())))) { + ANS_LOGE("set enable faild. status %{public}d", status); + return false; + } + return true; +} + +bool WarpBadgeNumberCallbackData( + ani_env *env, const std::shared_ptr &badgeData, ani_object &outObj) +{ + ANS_LOGD("enter"); + if (env == nullptr || badgeData == nullptr) { + ANS_LOGE("invalid parameter value"); + return false; + } + ani_class cls; + ani_object instanceKeyObj; + const char *className = "Lnotification/notificationSubscriber/BadgeNumberCallbackDataInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj)) { + ANS_LOGE("CreateClassObjByClassName faild"); + return false; + } + if (!SetFieldString(env, cls, outObj, "bundle", badgeData->GetBundle())) { + ANS_LOGE("SetFieldString bundle faild"); + return false; + } + if (!CallSetter(env, cls, outObj, "uid", static_cast(badgeData->GetUid()))) { + ANS_LOGE("uid set faild."); + return false; + } + if (!CallSetter(env, cls, outObj, "badgeNumber", static_cast(badgeData->GetBadgeNumber()))) { + ANS_LOGE("badgeNumber set faild"); + return false; + } + instanceKeyObj = CreateDouble(env, static_cast(badgeData->GetInstanceKey())); + if (instanceKeyObj != nullptr) { + if (!CallSetter(env, cls, outObj, "instanceKey", instanceKeyObj)) { + ANS_LOGE("instanceKey set faild."); + return false; + } + } else { + ANS_LOGE("instanceKeyObj createDouble faild"); + } + if (!SetFieldString(env, cls, outObj, "appInstanceKey", badgeData->GetAppInstanceKey())) { + ANS_LOGD("SetFieldString appInstanceKey faild"); + return false; + } + return true; +} + +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_template.cpp b/frameworks/ets/ani/src/sts_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c4f5fc4f82603fe295482d3f16f9245913db28a --- /dev/null +++ b/frameworks/ets/ani/src/sts_template.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2025 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 "sts_template.h" + +#include "sts_common.h" +#include "want_params.h" +#include "ani_common_want.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, NotificationTemplate& tmplate) +{ + if (env == nullptr || aniObj == nullptr) { + ANS_LOGE("invalid parameter value"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + ani_ref nameRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(aniObj, "name", ":Lstd/core/String;", &nameRef))) { + ANS_LOGE("Object_CallMethodByName_Ref faild. status %{public}d", status); + return status; + } + std::string nameStr = ""; + if (ANI_OK != (status = GetStringByAniString(env, static_cast(nameRef), nameStr))) { + ANS_LOGE("GetStringByAniString faild. status %{public}d", status); + return status; + } + ani_ref dataRef; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(aniObj, "data", &dataRef))) { + ANS_LOGE("Object_GetPropertyByName_Ref 'data' faild. status %{public}d", status); + return status; + } + WantParams wantParams; + if (!UnwrapWantParams(env, dataRef, wantParams)) { + ANS_LOGE("UnwrapWantParams faild"); + return ANI_ERROR; + } + tmplate.SetTemplateName(nameStr); + tmplate.SetTemplateData(std::make_shared(wantParams)); + return status; +} + +ani_object WrapNotificationTemplate(ani_env* env, const std::shared_ptr &templ) +{ + if (templ == nullptr || env == nullptr) { + ANS_LOGE("invalid parameter value"); + return nullptr; + } + ani_object templateObject = nullptr; + ani_class templateCls = nullptr; + ani_status status = ANI_OK; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationTemplate/NotificationTemplateInner;", templateCls, templateObject)) { + ANS_LOGE("Create faild"); + return nullptr; + } + // name: string; + ani_string stringValue = nullptr; + if (ANI_OK != (status = GetAniStringByString(env, templ->GetTemplateName(), stringValue))) { + ANS_LOGE("GetAniStringByString faild. status %{public}d", status); + return nullptr; + } + if (!CallSetter(env, templateCls, templateObject, "name", stringValue)) { + ANS_LOGE("set 'name' faild."); + return nullptr; + } + // data: Record; + std::shared_ptr data = templ->GetTemplateData(); + if (data) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *data); + if (valueRef == nullptr) { + ANS_LOGE("WrapWantParams faild"); + return nullptr; + } + if (!CallSetter(env, templateCls, templateObject, "data", valueRef)) { + ANS_LOGE("set 'data' faild"); + return nullptr; + } + } + return templateObject; +} + +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_user_input.cpp b/frameworks/ets/ani/src/sts_user_input.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c56a0c669aadef44f1ae3488b6b6c9726e4ef38 --- /dev/null +++ b/frameworks/ets/ani/src/sts_user_input.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 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 "sts_user_input.h" + +#include "sts_common.h" + +namespace OHOS { +namespace NotificationSts { +ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, + std::shared_ptr &userInput) +{ + if (env == nullptr || param == nullptr) { + ANS_LOGE("invalid parameter value"); + return ANI_ERROR; + } + ani_status status = ANI_ERROR; + std::string inputKey; + ani_boolean isUndefined = ANI_TRUE; + if ((status = GetPropertyString(env, param, "inputKey", isUndefined, inputKey)) != ANI_OK + || isUndefined == ANI_TRUE) { + ANS_LOGE("GetPropertyString 'inputKey' faild"); + return ANI_INVALID_ARGS; + } + userInput = Notification::NotificationUserInput::Create(inputKey); + return status; +} + +ani_object WarpUserInput(ani_env *env, std::shared_ptr userInput) +{ + if (env == nullptr || userInput == nullptr) { + ANS_LOGE("invalid parameter value"); + return nullptr; + } + ani_class userInputCls = nullptr; + ani_object userInputObject = nullptr; + ani_status status = ANI_OK; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationUserInput/NotificationUserInputInner;", userInputCls, userInputObject)) { + ANS_LOGE("Create faild"); + return nullptr; + } + ani_string stringValue; + if (ANI_OK != (status = GetAniStringByString(env, userInput->GetInputKey(), stringValue))) { + ANS_LOGE("GetAniStringByString faild. status %{public}d", status); + return nullptr; + } + if (!CallSetter(env, userInputCls, userInputObject, "inputKey", stringValue)) { + ANS_LOGE("set inputKey"); + return nullptr; + } + return userInputObject; +} +} +} diff --git a/frameworks/ets/ani/src/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64e59665d76400e1b2e8a95d16d5f4fa6834a162 --- /dev/null +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2025 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 "ani_remove.h" + +#include "inner_errors.h" +#include "notification_helper.h" +#include "ans_log_wrapper.h" +#include "sts_throw_erro.h" +#include "sts_common.h" +#include "notification_request.h" +#include "sts_bundle_option.h" +#include "sts_subscribe.h" + +namespace OHOS { +namespace NotificationSubScribeSts { +using namespace OHOS::Notification; + +void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notificationKey, ani_object reasonEnum) +{ + ANS_LOGD("AniRemoveForBundle enter"); + BundleOption option; + NotificationKey key; + int32_t reasonType = 0; + if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { + ANS_LOGE("bundle is valid"); + std::string msg = "UnwrapBundleOption failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::UnWarpNotificationKey(env, notificationKey, key)) { + ANS_LOGE("notificationKey is valid"); + std::string msg = "UnWarpNotificationKey failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGE("enum convert failed"); + std::string msg = "UnWarpReasonEnum failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGE("reasonType is valid"); + std::string msg = "reasonType is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + int ret = NotificationHelper::RemoveNotification(option, key.id, key.label, reasonType); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEnum) +{ + ANS_LOGD("AniRemoveForHashCode enter"); + int32_t reasonType = -1; + std::string hashCodeStd; + if (ANI_OK != NotificationSts::GetStringByAniString(env, hashCode, hashCodeStd)) { + ANS_LOGE("hashCode is valid"); + std::string msg = "hashCode is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGE("enum convert failed"); + std::string msg = "UnWarpReasonEnum failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGE("reasonType is valid"); + std::string msg = "reasonType is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + ANS_LOGD("hashCode: %{public}s, reasonType: %{public}d", hashCodeStd.c_str(), reasonType); + int ret = NotificationHelper::RemoveNotification(hashCodeStd, reasonType); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForHashCode ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reasonEnum) +{ + ANS_LOGD("StsRemoveForHashCodes enter"); + std::vector hashCodesStd; + int32_t reasonType; + if (!NotificationSts::GetStringArrayByAniObj(env, hashCodes, hashCodesStd)) { + ANS_LOGE("hashCodes is valid"); + std::string msg = "hashCodes is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGE("enum convert failed"); + std::string msg = "UnWarpReasonEnum failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGE("reasonType is valid"); + std::string msg = "reasonType is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + int ret = NotificationHelper::RemoveNotifications(hashCodesStd, reasonType); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForHashCodes ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveAll(ani_env *env) +{ + ANS_LOGD("removeAll enter"); + int ret = NotificationHelper::RemoveNotifications(); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("AniRemoveAll ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveAllForBundle(ani_env *env, ani_object bundle) +{ + ANS_LOGD("AniRemoveAllForBundle enter"); + BundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { + ANS_LOGE("bundle is valid"); + std::string msg = "UnwrapBundleOption failed"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + int ret = NotificationHelper::RemoveAllNotifications(option); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveAllForUserId(ani_env *env, ani_double userId) +{ + ANS_LOGD("AniRemoveAllForUserId enter"); + int ret = NotificationHelper::RemoveNotifications(userId); + if (ret != ERR_OK) { + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} +} +} diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f73b6c60b49d95f64496b68dcfd8a872b2c52245 --- /dev/null +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2025 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 "ani_subscribe.h" + +#include +#include +#include "inner_errors.h" +#include "notification_helper.h" +#include "ani_remove.h" +#include "ans_log_wrapper.h" +#include "sts_subscribe.h" + +namespace OHOS { +namespace NotificationSubScribeSts { +static const char *REMOVE_FOR_BUNDLE_SIGNATURE = + "Lnotification/NotificationCommonDef/BundleOption;" + "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKey;" + "L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *REMOVE_FOR_HASHCODE_SIGNATURE = + "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *REMOVE_FOR_HASHCODES_SIGNATURE = + "Lescompat/Array;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *DISTRIBUTE_OPERATION_SIGNATURE = + "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/OperationInfo;:Lstd/core/Promise;"; +static const char *SUBSCRIBE_SIGNATURE = + "Lnotification/notificationSubscriber/NotificationSubscriber;" + "Lnotification/notificationSubscribeInfo/NotificationSubscribeInfo;:V"; +static const char *UNSUBSCRIBE_SIGNATURE = + "Lnotification/notificationSubscriber/NotificationSubscriber;:V"; +static const char *REMOVEALL_FOR_BUNDLEOPTION_SIGNATURE = + "Lnotification/NotificationCommonDef/BundleOption;:V"; +static const char *REMOVEALL_FOR_USERID_STGNATURE = "D:V"; +static const char *REMOVEALL_SIGNATURE = ":V"; + +ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo) +{ + ANS_LOGD("StsDistributeOperation enter"); + ani_object aniPromise {}; + ani_resolver aniResolver {}; + if (ANI_OK != env->Promise_New(&aniResolver, &aniPromise)) { + ANS_LOGE("Promise_New faild"); + return nullptr; + } + bool noWithOperationInfo = false; + auto info = NotificationSts::GetOperationInfoForDistributeOperation( + env, hashcode, operationInfo, noWithOperationInfo); + if (info == nullptr) { + ANS_LOGE("get distributeOperation object fail"); + return nullptr; + } + sptr callback + = new (std::nothrow) NotificationSts::StsDistributedOperationCallback(aniPromise, aniResolver); + if (callback == nullptr) { + ANS_LOGE("create callback object fail"); + return nullptr; + } + + ani_vm *vm = nullptr; + if (ANI_OK != env->GetVM(&vm)) { + ANS_LOGD("env GetVM faild"); + return nullptr; + } + callback->SetVm(vm); + int32_t result = Notification::NotificationHelper::DistributeOperation(info, callback); + ANS_LOGD("StsDistributeOperation ret %{public}d. ErrorToExternal %{public}d", + result, CJSystemapi::Notification::ErrorToExternal(result)); + if (result != ERR_OK || noWithOperationInfo) { + callback->OnStsOperationCallback(env, result); + } + return aniPromise; +} + +void AniSubscribe(ani_env *env, ani_object obj, ani_object info) +{ + ANS_LOGD("StsSubscribe enter"); + OHOS::NotificationSts::SubscriberInstanceManager::GetInstance()->Subscribe(env, obj, info); +} + +void AniUnSubscribe(ani_env *env, ani_object obj) +{ + ANS_LOGD("StsUnSubscribe enter"); + OHOS::NotificationSts::SubscriberInstanceManager::GetInstance()->UnSubscribe(env, obj); +} + +void AniSubscribeSelf(ani_env *env, ani_object obj) +{ + ANS_LOGD("StsSubscribeSelf enter"); + OHOS::NotificationSts::SubscriberInstanceManager::GetInstance()->SubscribeSelf(env, obj); +} + +void AniSubScribeRegistryInit(ani_env *env) +{ + ANS_LOGD("AniSubScribeRegistryInit call"); + static const char *npName = "L@ohos/notificationSubscribe/notificationSubscribe;"; + ani_namespace np; + if (ANI_OK != env->FindNamespace(npName, &np)) { + ANS_LOGD("Not found '%{public}s'", npName); + return; + } + + std::array methods = { + ani_native_function {"nativeRemove", + REMOVE_FOR_BUNDLE_SIGNATURE, reinterpret_cast(AniRemoveForBundle)}, + ani_native_function {"nativeRemove", + REMOVE_FOR_HASHCODE_SIGNATURE, reinterpret_cast(AniRemoveForHashCode)}, + ani_native_function {"nativeRemove", + REMOVE_FOR_HASHCODES_SIGNATURE, reinterpret_cast(AniRemoveForHashCodes)}, + ani_native_function {"nativeDistributeOperation", + DISTRIBUTE_OPERATION_SIGNATURE, reinterpret_cast(AniDistributeOperation)}, + ani_native_function {"nativeSubscribe", SUBSCRIBE_SIGNATURE, reinterpret_cast(AniSubscribe)}, + ani_native_function {"nativeUnSubscribe", UNSUBSCRIBE_SIGNATURE, reinterpret_cast(AniUnSubscribe)}, + ani_native_function {"nativeSubscribeSelf", UNSUBSCRIBE_SIGNATURE, reinterpret_cast(AniSubscribeSelf)}, + ani_native_function {"nativeRemoveAllForBundle", + REMOVEALL_FOR_BUNDLEOPTION_SIGNATURE, reinterpret_cast(AniRemoveAllForBundle)}, + ani_native_function {"nativeRemoveAllForUserId", + REMOVEALL_FOR_USERID_STGNATURE, reinterpret_cast(AniRemoveAllForUserId)}, + ani_native_function {"nativeRemoveAll", REMOVEALL_SIGNATURE, reinterpret_cast(AniRemoveAll)}, + }; + + ANS_LOGD("Start bind native methods to '%{public}s'", npName); + ani_status status = env->Namespace_BindNativeFunctions(np, methods.data(), methods.size()); + if (ANI_OK != status) { + ANS_LOGD("Cannot bind native methods to '%{public}s'. status %{public}d", npName, status); + return; + }; + ANS_LOGD("Finish bind native methods to '%{public}s'", npName); + + if (env->ResetError() != ANI_OK) { + ANS_LOGD("ResetError failed"); + } + ANS_LOGD("AniSubScribeRegistryInit end"); +} +} // namespace NotificationSubScribeSts +} // namespace OHOS + +extern "C" { +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + ANS_LOGD("ANI_Constructor enter"); + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + ANS_LOGD("Unsupported ANI_VERSION_1"); + return ANI_ERROR; + } + + OHOS::NotificationSubScribeSts::AniSubScribeRegistryInit(env); + ANS_LOGD("ANI_Constructor OK"); + *result = ANI_VERSION_1; + return ANI_OK; +} +} \ No newline at end of file diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets new file mode 100644 index 0000000000000000000000000000000000000000..1bd0e6d84443b487e9ee475f9ba542d95b7dc582 --- /dev/null +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -0,0 +1,2684 @@ +/* + * Copyright (c) 2025 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 { BundleOption } from 'notification.NotificationCommonDef'; +import { BusinessError, AsyncCallback } from '@ohos.base'; +import { NotificationSlot } from 'notification.notificationSlot'; +import { NotificationRequest, NotificationCheckRequest } from 'notification.notificationRequest'; +import UIAbilityContext from 'application.UIAbilityContext'; +import { NotificationBasicContent } from 'notification.notificationContent'; +import { NotificationLongTextContent } from 'notification.notificationContent'; +import { NotificationMultiLineContent } from 'notification.notificationContent'; +import { NotificationPictureContent } from 'notification.notificationContent'; +import { NotificationSystemLiveViewContent } from 'notification.notificationContent'; +import { NotificationTemplate } from 'notification.notificationTemplate'; +import { DistributedOptions } from 'notification.notificationRequest'; +import { NotificationLiveViewContent } from 'notification.notificationContent'; +import { UnifiedGroupInfo } from 'notification.notificationRequest'; +import { NotificationFilter } from 'notification.notificationRequest'; +import image from '@ohos.multimedia.image'; + +type ResolveCallback = (data: T) => void; +type RejectCallback = (err: Error) => void; +type CallbackForCheckInfo = + (checkInfo: notificationManager.NotificationCheckInfo)=> notificationManager.NotificationCheckResult; + +const ERROR_OK = 0; +const ERROR_PARAM_INVALID = 401; +const ERROR_INTERNAL_ERROR = 160001; + +const rejectInternalError: BusinessError = {code: ERROR_INTERNAL_ERROR, data: "Internal error."}; +const callbackInternalError: BusinessError = {code: ERROR_INTERNAL_ERROR, data: undefined}; +const successCallbackError: BusinessError = {code: ERROR_OK, data: undefined}; + +const errorParamInvalid: BusinessError = {code: ERROR_PARAM_INVALID, message: "Invalid parameter"}; + +export default namespace notificationManager { + loadLibrary("notification_manager_ani.z") + export enum SlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + LIVE_VIEW = 4, + CUSTOMER_SERVICE = 5, + EMERGENCY_INFORMATION = 10, + OTHER_TYPES = 0xFFFF, + } + + export enum ContentType { + NOTIFICATION_CONTENT_BASIC_TEXT, + NOTIFICATION_CONTENT_LONG_TEXT, + NOTIFICATION_CONTENT_PICTURE, + NOTIFICATION_CONTENT_CONVERSATION, + NOTIFICATION_CONTENT_MULTILINE, + NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW, + NOTIFICATION_CONTENT_LIVE_VIEW, + } + + export enum SlotLevel { + LEVEL_NONE = 0, + LEVEL_MIN = 1, + LEVEL_LOW = 2, + LEVEL_DEFAULT = 3, + LEVEL_HIGH = 4, + } + + export enum DoNotDisturbType { + TYPE_NONE = 0, + TYPE_ONCE = 1, + TYPE_DAILY = 2, + TYPE_CLEARLY = 3, + } + + export interface DoNotDisturbDate { + type: DoNotDisturbType; + begin: Date; + end: Date; + } + + class DoNotDisturbDateInner implements DoNotDisturbDate { + type: DoNotDisturbType; + begin: Date; + end: Date; + } + + export interface DoNotDisturbProfile { + id: number; + name: string; + trustlist?: Array; + } + + class DoNotDisturbProfileInner implements DoNotDisturbProfile { + id: number = -1; + name: string = ""; + trustlist?: Array = new Array(); + } + + export interface ButtonOptions { + buttonName: string; + } + + class ButtonOptionsInner implements ButtonOptions { + buttonName: string = ""; + } + + export interface SystemLiveViewSubscriber { + onResponse?: (notificationId: number, buttonOptions: ButtonOptions) => void; + } + + class SystemLiveViewSubscriberInner implements SystemLiveViewSubscriber { + onResponse?: (notificationId: number, buttonOptions: ButtonOptions) => void; + } + + export enum DeviceRemindType { + IDLE_DONOT_REMIND = 0, + IDLE_REMIND = 1, + ACTIVE_DONOT_REMIND = 2, + ACTIVE_REMIND = 3, + } + + export native function nativeCancelAll(): void; + export native function nativeCancelWithId(id: number): void; + export native function nativeCancelWithIdLabel(id: number, label: string): void; + export native function nativeCancelWithIdOptionalLabel(id: number, label?: string): void; + export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; + + export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; + export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; + export native function nativeSetBadgeNumber(badgeNumber: number): void; + export native function nativeSetBadgeNumberByBundle(bundle: BundleOption, badgeNumber: number): void; + + export native function nativeGetActiveNotificationCount(): number; + export native function nativeGetActiveNotifications():Array; + export native function nativeGetAllActiveNotifications():Array; + export native function nativeGetActiveNotificationByFilter(filter: NotificationFilter): NotificationRequest; + + export native function nativeAddDoNotDisturbProfile(templates: Array): void; + export native function nativeRemoveDoNotDisturbProfile(templates: Array): void; + + export native function nativeSubscribeSystemLiveView(subscriber: SystemLiveViewSubscriber): void; + export native function nativeTriggerSystemLiveView( + bundle: BundleOption, notificationId: number, buttonOptions: ButtonOptions): void; + + export native function nativePublishWithUserId(request: NotificationRequest, userId: number):void; + export native function nativePublish(request: NotificationRequest):void; + + export native function nativeGetSlotFlagsByBundle(bundle: BundleOption): int; + export native function nativeSetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; + export native function nativeGetSlotsByBundle(bundle: BundleOption): Array; + + export native function nativeIsNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; + export native function nativeSetNotificationEnableSlot( + bundle: BundleOption, type: SlotType, enable: boolean): void; + export native function nativeSetNotificationEnableSlotWithForce( + bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean): void; + + export native function nativeIsNotificationEnabled(): boolean; + export native function nativeIsNotificationEnabledWithId(userId : number): boolean; + export native function nativeIsNotificationEnabledWithBundleOption(bundleOption: BundleOption): boolean; + export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; + export native function nativeRequestEnableNotification(content: UIAbilityContext): Promise; + export native function nativeGetAllNotificationEnabledBundles(): Array; + export native function nativeIsNotificationEnabledSync(): boolean; + + export native function nativeRemoveGroupByBundle(bundle: BundleOption, groupName: string): void; + + export native function nativeAddSlotByNotificationSlot(slot: NotificationSlot): void; + export native function nativeAddSlotBySlotType(type: SlotType): void; + export native function nativeAddSlots(slots: Array): void; + export native function nativeGetSlot(slotType: SlotType): NotificationSlot; + export native function nativeGetSlots(): Array; + export native function nativeRemoveSlot(slotType: SlotType): void; + export native function nativeRemoveAllSlots(): void; + export native function nativeSetSlotByBundle(bundle: BundleOption, slot: NotificationSlot): void; + export native function nativeGetSlotNumByBundle(bundle: BundleOption): number; + export native function nativeIsSupportTemplate(templateName: string): boolean; + export native function nativeSetDistributedEnable(enable: boolean): void; + export native function nativeIsDistributedEnabled(): boolean; + export native function nativeIsDistributedEnabledByBundle(bundle: BundleOption): boolean; + export native function nativeIsDistributedEnabledByBundleType(bundle: BundleOption, deviceType: string): boolean; + export native function nativeGetDeviceRemindType(): DeviceRemindType; + export native function nativeSetSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): void; + export native function nativeGetSyncNotificationEnabledWithoutApp(userId: number): boolean; + + export native function nativePublishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): void; + export native function nativePublishAsBundleWithBundleOption(representativeBundle: BundleOption, request: NotificationRequest): void; + export native function nativeCancelAsBundle(id: number, representativeBundle: string, userId: number): void; + export native function nativeCancelAsBundleWithBundleOption(representativeBundle: BundleOption, id: number): void; + export native function nativeCancelGroup(groupName: string): void; + export native function nativeSetDoNotDisturbDate(date: DoNotDisturbDate): void; + export native function nativeSetDoNotDisturbDateWithId(date: DoNotDisturbDate, userId: number): void; + export native function nativeGetDoNotDisturbDate(): DoNotDisturbDate; + export native function nativeGetDoNotDisturbDateWithId(userId: number): DoNotDisturbDate; + export native function nativeIsSupportDoNotDisturbMode(): boolean; + export native function nativeGetDoNotDisturbProfile(id: number): DoNotDisturbProfile; + + export native function nativeOpenNotificationSettings(content: UIAbilityContext): Promise; + + export native function nativesetTargetDeviceStatus(deviceType: string, status: number): void; + export native function nativesetDistributedEnabledByBundle(bundle: BundleOption, deviceType: string, enable: boolean): void; + export native function nativesetSmartReminderEnabled(deviceType: string, enable: boolean): void; + export native function nativeisSmartReminderEnabled(deviceType: string): boolean; + export native function nativesetDistributedEnabledBySlot(slot: SlotType, deviceType: string, enabled: boolean): void; + export native function nativeisDistributedEnabledBySlot(slot: SlotType, deviceType: string): boolean; + export native function nativesetAdditionalConfig(key: string, value: string): int; + export native function nativesetDistributedEnableByBundle(bundle: BundleOption, enable: boolean):void; + export native function nativedisableNotificationFeature(disabled:boolean, bundleList: Array):void; + + function isInvalidParameter(doNotDisturbDate: DoNotDisturbDate): BusinessError + { + let error: BusinessError = successCallbackError + if (doNotDisturbDate == null) { + error = errorParamInvalid + return error; + } + return error; + } + + function isInvalidParameter(slot: NotificationSlot): BusinessError + { + if (slot == null) { + return errorParamInvalid; + } + if (slot.lockscreenVisibility !== undefined && typeof slot.lockscreenVisibility === 'number') { + const num = slot.lockscreenVisibility ?? -1; + if (num < 0) { + return errorParamInvalid; + } + } + if (slot.lightColor !== undefined && typeof slot.lightColor === 'number') { + const num = slot.lightColor ?? -1; + if (num < 0) { + return errorParamInvalid; + } + } + if (slot.desc !== undefined && slot.desc?.trim() === '') { + return errorParamInvalid; + } + if (slot.sound !== undefined && slot.sound?.trim() === '') { + return errorParamInvalid; + } + if (slot.vibrationValues !== undefined && slot.vibrationValues?.length === 0) { + return errorParamInvalid; + } + return successCallbackError; + } + + export native function nativeOn( + type: 'checkNotification', callback: CallbackForCheckInfo, checkRequest?: NotificationCheckRequest): int; + export native function nativeOff( + type: 'checkNotification', callback?: CallbackForCheckInfo): int; + + function isInvalidParameter(bundle: BundleOption): BusinessError + { + let error: BusinessError = successCallbackError + if (bundle == null) { + error = errorParamInvalid + return error; + } + if (bundle.bundle == null || bundle.bundle?.length === 0) { + error = errorParamInvalid + return error; + } + return error; + } + + function isInvalidParameter(option: ButtonOptions): BusinessError + { + let error: BusinessError = successCallbackError + if (option == null) { + error = errorParamInvalid + return error; + } + if (option.buttonName == null || option.buttonName?.length === 0) { + error = errorParamInvalid + return error; + } + return error; + } + function isInvalidParameter(filter: NotificationFilter): BusinessError + { + let error: BusinessError = successCallbackError; + if (filter == null) { + return errorParamInvalid; + } + error = isInvalidParameter(filter.bundle); + if (error.code != 0) { + return error; + } + if (filter.notificationKey?.label !== undefined && filter.notificationKey?.label?.trim() === '') { + return errorParamInvalid; + } + if (filter?.extraInfoKeys !== undefined && filter?.extraInfoKeys?.length === 0) { + return errorParamInvalid; + } + return error; + } + function isInvalidContent(normal?: NotificationBasicContent): boolean + { + if (normal === null) { + return false; + } + if (!normal?.title || normal?.title?.trim() === '') { + return false; + } + if (!normal?.text || normal?.text?.trim() === '') { + return false; + } + if (normal?.additionalText !== undefined && normal?.additionalText?.trim() === '') { + return false; + } + if (normal?.lockscreenPicture != undefined && !(normal?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + return true; + } + function isInvalidLongText(longText?: NotificationLongTextContent): boolean + { + if (longText === null) { + return false; + } + if (!longText?.title || longText?.title?.trim() === '') { + return false; + } + if (!longText?.text || longText?.text?.trim() === '') { + return false; + } + if (longText?.additionalText !== undefined && longText?.additionalText?.trim() === '') { + return false; + } + if (longText?.lockscreenPicture != undefined && !(longText?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + if (!longText?.longText || longText?.longText?.trim() === '') { + return false; + } + if (!longText?.briefText || longText?.briefText?.trim() === '') { + return false; + } + if (!longText?.expandedTitle || longText?.expandedTitle?.trim() === '') { + return false; + } + return true; + } + function isInvalidMultiLine(multiLine?: NotificationMultiLineContent): boolean + { + if (multiLine === null) { + return false + } + if (!multiLine?.title || multiLine?.title?.trim() === '') { + return false; + } + if (!multiLine?.text || multiLine?.text?.trim() === '') { + return false; + } + if (multiLine?.additionalText !== undefined && multiLine?.additionalText?.trim() === '') { + return false; + } + if (multiLine?.lockscreenPicture != undefined && !(multiLine?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + if (!multiLine?.briefText || multiLine?.briefText.trim() === '') { + return false; + } + if (!multiLine?.longTitle || multiLine?.longTitle.trim() === '') { + return false; + } + if (multiLine?.lines?.length === 0) { + return false; + } + return true; + } + function isInvalidPicture(picture?: NotificationPictureContent): boolean + { + if (picture === null) { + return false; + } + if (!picture?.title || picture?.title?.trim() === '') { + return false; + } + if (!picture?.text || picture?.text?.trim() === '') { + return false; + } + if (picture?.additionalText !== undefined && picture?.additionalText?.trim() === '') { + return false; + } + if (picture?.lockscreenPicture != undefined && !(picture?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + if (!picture?.briefText || picture?.briefText?.trim() === '') { + return false; + } + if (!picture?.expandedTitle || picture?.expandedTitle?.trim() === '') { + return false; + } + if (!(picture?.picture instanceof image.PixelMap)) { + return false; + } + return true; + } + function isInvalidSystemLiveView(systemLiveView?: NotificationSystemLiveViewContent): boolean + { + if (systemLiveView === null) { + return false + } + if (!systemLiveView?.title || systemLiveView?.title?.trim() === '') { + return false; + } + if (!systemLiveView?.text || systemLiveView?.text?.trim() === '') { + return false; + } + if (systemLiveView?.additionalText !== undefined && systemLiveView?.additionalText?.trim() === '') { + return false; + } + if (systemLiveView?.lockscreenPicture != undefined && !(systemLiveView?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + if (systemLiveView?.capsule !== undefined && systemLiveView?.capsule === null) { + return false + } + if (systemLiveView?.capsule?.title !== undefined && systemLiveView?.capsule?.title?.trim() === '') { + return false; + } + if (systemLiveView?.capsule?.icon != undefined && !(systemLiveView?.capsule?.icon instanceof image.PixelMap)) { + return false; + } + if (systemLiveView?.capsule?.backgroundColor != undefined && systemLiveView?.capsule?.backgroundColor?.trim() === '') { + return false; + } + if (systemLiveView?.capsule?.content != undefined && systemLiveView?.capsule?.content?.trim() === '') { + return false; + } + if (systemLiveView?.capsule?.capsuleButtons != undefined && systemLiveView?.capsule?.capsuleButtons?.length === 0) { + return false; + } + if (systemLiveView?.button !== undefined && systemLiveView?.button === null) { + return false; + } + if (systemLiveView?.button?.names != undefined && systemLiveView?.button?.names?.length === 0) { + return false; + } + if (systemLiveView?.button?.icons != undefined && systemLiveView?.button?.icons?.length === 0) { + return false; + } + if (systemLiveView?.button?.iconsResource != undefined && systemLiveView?.button?.iconsResource?.length === 0) { + return false; + } + + if (systemLiveView?.cardButtons !== undefined && systemLiveView?.cardButtons?.length === 0) { + return false; + } + return true; + } + function isInvalidLiveView(liveView?: NotificationLiveViewContent): boolean + { + if (liveView === null) { + return false; + } + if (!liveView?.title || liveView?.title?.trim() === '') { + return false; + } + if (!liveView?.text || liveView?.text?.trim() === '') { + return false; + } + if (liveView?.additionalText !== undefined && liveView?.additionalText?.trim() === '') { + return false; + } + if (liveView?.lockscreenPicture != undefined && !(liveView?.lockscreenPicture instanceof image.PixelMap)) { + return false; + } + if (liveView?.extraInfo !== undefined && liveView?.extraInfo === null) { + return false; + } + if (liveView?.pictureInfo !== undefined && liveView?.pictureInfo === null) { + return false; + } + return true; + } + function isInvalidTemplate(template?: NotificationTemplate): boolean + { + if (template === null) { + return false; + } + if (template?.name != undefined && template?.name?.trim() === '') { + return false; + } + if (template?.data != undefined && template?.data === null) { + return false; + } + return true; + } + function isInvalidDistributedOption(distributedOption?: DistributedOptions): boolean + { + if (distributedOption === null) { + return false + } + if (distributedOption?.supportDisplayDevices != undefined && distributedOption?.supportDisplayDevices?.length === 0) { + return false; + } + if (distributedOption?.supportOperateDevices != undefined && distributedOption?.supportOperateDevices?.length === 0) { + return false; + } + return true; + } + function isInvalidUnifiedGroupInfo(unifiedGroupInfo?: UnifiedGroupInfo): boolean + { + if (unifiedGroupInfo === null) { + return false; + } + if (unifiedGroupInfo?.key != undefined && unifiedGroupInfo?.key?.trim() === '') { + return false; + } + if (unifiedGroupInfo?.title != undefined && unifiedGroupInfo?.title?.trim() === '') { + return false; + } + if (unifiedGroupInfo?.content != undefined && unifiedGroupInfo?.content?.trim() === '') { + return false; + } + if (unifiedGroupInfo?.sceneName != undefined && unifiedGroupInfo?.sceneName?.trim() === '') { + return false; + } + if (unifiedGroupInfo?.extraInfo != undefined && unifiedGroupInfo?.extraInfo == null) { + return false; + } + return true; + } + function isInvalidBundleOption(bundleOption?: BundleOption): boolean + { + if (bundleOption === null) { + return false; + } + if (bundleOption?.bundle != undefined && bundleOption?.bundle?.trim() === '') { + return false; + } + return true; + } + function isInvalidParameter(request: NotificationRequest): BusinessError + { + let error: BusinessError = successCallbackError + if (request == null) { + error = errorParamInvalid + return error; + } + if (request.content == null || request.content == undefined) { + error = errorParamInvalid + return error; + } + if (request.content?.normal !== undefined && !isInvalidContent(request.content.normal)) { + return errorParamInvalid; + } + if (request.content?.longText !== undefined && !isInvalidLongText(request.content.longText)) { + return errorParamInvalid; + } + if (request.content?.multiLine !== undefined && !isInvalidMultiLine(request.content.multiLine)) { + return errorParamInvalid; + } + if (request.content?.picture !== undefined && !isInvalidPicture(request.content.picture)) { + return errorParamInvalid; + } + if (request.content?.systemLiveView !== undefined && !isInvalidSystemLiveView(request.content.systemLiveView)) { + return errorParamInvalid; + } + if (request.content?.liveView !== undefined && !isInvalidLiveView(request.content.liveView)) { + return errorParamInvalid; + } + if (request?.appMessageId !== undefined && request?.appMessageId?.trim() === '') { + return errorParamInvalid; + } + if (request?.wantAgent !== undefined && request.wantAgent == null) { + return errorParamInvalid; + } + if(request?.extraInfo !== undefined && request?.extraInfo == null) { + return errorParamInvalid; + } + if (request?.actionButtons !== undefined && request?.actionButtons?.length === 0) { + return errorParamInvalid; + } + if (request.smallIcon !== undefined && request.smallIcon == null) { + return errorParamInvalid; + } + if (request?.largeIcon !== undefined && request.largeIcon == null) { + return errorParamInvalid; + } + if (request?.overlayIcon !== undefined && request.overlayIcon == null) { + return errorParamInvalid; + } + if (request?.groupName !== undefined && request?.groupName?.trim() === '') { + return errorParamInvalid; + } + if (request?.creatorBundleName !== undefined && request?.creatorBundleName?.trim() === '') { + return errorParamInvalid; + } + if (request?.sound !== undefined && request?.sound?.trim() === '') { + return errorParamInvalid; + } + if (request?.classification !== undefined && request?.classification?.trim() === '') { + return errorParamInvalid; + } + if (request?.hashCode !== undefined && request?.hashCode?.trim() === '') { + return errorParamInvalid; + } + if (request?.template !== undefined && !isInvalidTemplate(request.template)) { + return errorParamInvalid; + } + if (request?.distributedOption !== undefined && !isInvalidDistributedOption(request.distributedOption)) { + return errorParamInvalid; + } + if (request?.deviceId !== undefined && request?.deviceId?.trim() === '') { + return errorParamInvalid; + } + if (request?.removalWantAgent !== undefined && request.removalWantAgent == null) { + return errorParamInvalid; + } + if (request?.representativeBundle !== undefined && !isInvalidBundleOption(request.representativeBundle)) { + return errorParamInvalid; + } + if (request?.agentBundle !== undefined && !isInvalidBundleOption(request.agentBundle)) { + return errorParamInvalid; + } + if (request?.unifiedGroupInfo !== undefined && !isInvalidUnifiedGroupInfo(request.unifiedGroupInfo)) { + return errorParamInvalid; + } + if (request?.appInstanceKey !== undefined && request?.appInstanceKey?.trim() === '') { + return errorParamInvalid; + } + if (request?.color !== undefined && typeof request.color === 'number') { + const num = request.color ?? -1; + if (num < 0) { + return errorParamInvalid; + } + } + if (request?.badgeNumber !== undefined && typeof request.badgeNumber === 'number') { + const num = request.badgeNumber ?? -1; + if (num < 0) { + return errorParamInvalid; + } + } + return error; + } + + export function getSlotNumByBundle(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): number => { return nativeGetSlotNumByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : number = data as number; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): number => { return nativeGetSlotNumByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : number = data as number; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret: number = -1; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }); + } + + export function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== ERROR_OK) { + throw slotError; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeSetSlotByBundle(bundle, slot); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== ERROR_OK) { + throw slotError; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetSlotByBundle(bundle, slot); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeAllSlots(callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeRemoveAllSlots(); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function removeAllSlots(): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeRemoveAllSlots(); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeSlot(slotType: SlotType, callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeRemoveSlot(slotType); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function removeSlot(slotType: SlotType): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeRemoveSlot(slotType); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlots(): Promise> { + let pPromise = new Promise>((resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetSlots(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlots(callback: AsyncCallback>): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): Array => { return nativeGetSlots(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }); + } + + export function getSlot(slotType: SlotType): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): NotificationSlot => { return nativeGetSlot(slotType); }); + p.then((data: NullishType): void => { + let ret : NotificationSlot = data as NotificationSlot; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlot(slotType: SlotType, callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): NotificationSlot => { return nativeGetSlot(slotType); }); + p.then((data: NullishType): void => { + let ret : NotificationSlot = data as NotificationSlot; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : NotificationSlot = { enabled: false, reminderMode: 0, authorizedStatus: 0 } as NotificationSlot; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }); + } + + export function addSlots(slots: Array): Promise { + if (!slots || slots.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeAddSlots(slots); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addSlots(slots: Array, callback: AsyncCallback): void { + if (!slots || slots.length === 0) { + throw errorParamInvalid; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeAddSlots(slots); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function addSlot(slot: NotificationSlot): Promise { + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== ERROR_OK) { + throw slotError; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeAddSlotByNotificationSlot(slot); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addSlot(slot: NotificationSlot, callback: AsyncCallback): void { + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== ERROR_OK) { + throw slotError; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeAddSlotByNotificationSlot(slot); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function addSlot(type: SlotType, callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeAddSlotBySlotType(type); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function addSlot(type: SlotType): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeAddSlotBySlotType(type); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundleOption); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isNotificationEnabled(bundleOption: BundleOption): Promise + { + let error: BusinessError = isInvalidParameter(bundleOption); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute( + (): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); + }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(userId: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithId(userId); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isNotificationEnabled(userId: number): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithId(userId); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isNotificationEnabled(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnableSlot( + bundle: BundleOption, + type: SlotType, + enable: boolean, + isForceControl: boolean, + callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute( + (): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); + }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setNotificationEnableSlot( + bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let forceControl: boolean = false; + if (isForceControl != undefined) { + forceControl = isForceControl; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute( + (): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, forceControl); + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnableSlot( + bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); + p.then((data: NullishType): void => { + let slots : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, slots); + }, (error: Error): void => { + let slots : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, slots); + }) + } + + export function getSlotsByBundle(bundle: BundleOption): Promise> + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise>( + (resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); + p.then((data: NullishType): void => { + let slots : Array = data as Array; + resolve(slots); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetSlotFlagsByBundle(bundle, slotFlags); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlotFlagsByBundle(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): number => { return nativeGetSlotFlagsByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : Double = data as Double; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function publish(request: NotificationRequest, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativePublish(request); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function publish(request: NotificationRequest): Promise { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativePublish(request); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function publish(request: NotificationRequest, userId: number): Promise { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function triggerSystemLiveView( + bundle: BundleOption, notificationId: number, buttonOptions: ButtonOptions): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + error = isInvalidParameter(buttonOptions); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { + return nativeTriggerSystemLiveView(bundle, notificationId, buttonOptions); + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function subscribeSystemLiveView(subscriber: SystemLiveViewSubscriber): Promise + { + if(subscriber === null) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSubscribeSystemLiveView(subscriber); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeDoNotDisturbProfile(templates: Array): Promise { + if (!templates || templates.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addDoNotDisturbProfile(templates: Array): Promise { + if (!templates || templates.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getAllActiveNotifications(callback: AsyncCallback>): void { + if (!callback) { + throw errorParamInvalid; + } + let p = taskpool.execute((): Array => { return nativeGetAllActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let retData : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, retData); + }) + } + + export function getAllActiveNotifications(): Promise> { + let pPromise + = new Promise>( + (resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetAllActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getActiveNotifications(): Promise> { + let pPromise = new Promise>((resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getActiveNotifications(callback: AsyncCallback>): void { + if (!callback) { + throw errorParamInvalid; + } + let p = taskpool.execute((): Array => { return nativeGetActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let retData : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, retData); + }) + } + + export function getActiveNotificationCount(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): number => { return nativeGetActiveNotificationCount(); }); + p.then((data: NullishType): void => { + let ret : number = data as number; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, -1); + }) + } + + export function getActiveNotificationCount(): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback):void => { + let p = taskpool.execute((): number => { return nativeGetActiveNotificationCount(); }); + p.then((data :NullishType): void => { + let ret : number = data as number; + resolve(ret); + }, (err:Error): void => { + reject(err); + }); + }); + return pPromise; + } + + export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); + p.then((e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function displayBadge(bundle: BundleOption, enable: boolean): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isBadgeDisplayed(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(bundle: BundleOption, id: number): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithBundle(bundle, id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label?: string): Promise { + if (label == null || label?.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithIdOptionalLabel(id, label); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label: string, callback: AsyncCallback): void { + if (label == null || label?.length === 0) { + throw errorParamInvalid; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function cancel(id: number, callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function cancelAll(): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAll(callback: AsyncCallback): void { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function requestEnableNotification(context: UIAbilityContext): Promise + { + if (context == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): Promise => { return nativeRequestEnableNotification(context); }); + p.then( + (data: NullishType): void => { + if (data == undefined) { + reject(rejectInternalError); + } else { + let result: int = data as int; + if (result == 0) { + resolve(undefined); + } else { + reject(rejectInternalError); + } + } + }, + (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function requestEnableNotification(context: UIAbilityContext, callback: AsyncCallback): void + { + if (context == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): Promise => { return nativeRequestEnableNotification(context); }); + p.then( + (data: NullishType): void => { + if (data == undefined) { + callback(callbackInternalError, undefined); + } else { + let result: int = data as int; + if (result == 0) { + callback(successCallbackError, undefined); + } else { + callback(callbackInternalError, undefined); + } + } + }, + (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export interface NotificationCheckResult { + code: number; + message: string; + } + + class NotificationCheckResultInner implements NotificationCheckResult { + public code: number = -1; + public message: string = ''; + } + + export function on( + type: 'checkNotification', callback: (checkInfo: NotificationCheckInfo) => NotificationCheckResult): void + { + let errCode = nativeOn(type, callback); + if (errCode != 0) { + const error: BusinessError = {code: errCode, message: "unknown error"}; + throw error; + } + } + + export function on(type: 'checkNotification', checkRequest: NotificationCheckRequest, + callback: (checkInfo: NotificationCheckInfo) => Promise): void + { + let onFuncCallback: CallbackForCheckInfo = + (checkInfo: notificationManager.NotificationCheckInfo): notificationManager.NotificationCheckResult => { + let result: notificationManager.NotificationCheckResult = { + code: -1, + message: 'unknown error' + }; + let p = callback(checkInfo); + await p.then( + (e: NullishType): void => { + result = e as notificationManager.NotificationCheckResult; + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + result = { + code: err.code, + message: err.message + }; + } + ); + return result; + }; + let errCode = nativeOn(type, onFuncCallback, checkRequest); + if (errCode != 0) { + const error: BusinessError = {code: errCode, message: "unknown error"}; + throw error; + } + } + + export function off( + type: 'checkNotification', + callback?: (checkInfo: NotificationCheckInfo) => NotificationCheckResult + ): void + { + let errCode = -1; + if (callback === undefined) { + errCode = nativeOff(type); + } else { + errCode = nativeOff(type, callback); + } + if (errCode != 0) { + const error: BusinessError = {code: errCode, message: "unknown error"}; + throw error; + } + } + + export interface NotificationCheckInfo { + bundleName: string; + notificationId: number; + label?: string; + contentType: ContentType; + creatorUserId: number; + slotType: SlotType; + extraInfos?: Record; + } + + class NotificationCheckInfoInner implements NotificationCheckInfo { + public bundleName: string = ''; + public notificationId: number = -1; + public label?: string; + public contentType: ContentType = ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + public creatorUserId: number = -1; + public slotType: SlotType = SlotType.UNKNOWN_TYPE; + public extraInfos?: Record; + } + + export function getAllNotificationEnabledBundles(): Promise> + { + let pPromise = new Promise>( + (resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetAllNotificationEnabledBundles(); }); + p.then((data: NullishType): void => { + let options : Array = data as Array; + resolve(options); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabledSync(): boolean + { + return nativeIsNotificationEnabledSync(); + } + + export function setBadgeNumber(badgeNumber: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeSetBadgeNumber(badgeNumber); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function setBadgeNumber(badgeNumber: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetBadgeNumber(badgeNumber); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setBadgeNumberByBundle(bundle: BundleOption, badgeNumber: number): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetBadgeNumberByBundle(bundle, badgeNumber); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getActiveNotificationByFilter(filter: NotificationFilter, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(filter); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback === null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): NotificationRequest => { return nativeGetActiveNotificationByFilter(filter); }); + p.then((data: NullishType): void => { + let ret : NotificationRequest = data as NotificationRequest; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + let retData: NotificationRequest = { + content:{}, + creatorBundleName: undefined, + creatorUid:undefined, + creatorPid:undefined, + creatorUserId:undefined, + hashCode:undefined, + notificationFlags:undefined, + source : undefined, + deviceId : undefined, + agentBundle : undefined, + appInstanceKey : undefined, + badgeNumber : undefined + }; + let err: BusinessError = error as BusinessError; + callback(err, retData); + }) + } + + export function getActiveNotificationByFilter(filter: NotificationFilter): Promise + { + let error: BusinessError = isInvalidParameter(filter); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): NotificationRequest => { return nativeGetActiveNotificationByFilter(filter); }); + p.then((data: NullishType): void => { + let ret : NotificationRequest = data as NotificationRequest; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isSupportTemplate(templateName: string): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsSupportTemplate(templateName); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (groupName === '') { + throw errorParamInvalid; + } + if (!callback) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeRemoveGroupByBundle(bundle, groupName); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function removeGroupByBundle(bundle: BundleOption, groupName: string): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (groupName === '') { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeRemoveGroupByBundle(bundle, groupName); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + + if (callback == null) { + throw errorParamInvalid; + } + if (representativeBundle == null || representativeBundle?.length === 0) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativePublishAsBundle(request, representativeBundle, userId); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise + { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + if (representativeBundle == null || representativeBundle?.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativePublishAsBundle(request, representativeBundle, userId); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function publishAsBundle(representativeBundle: BundleOption, request: NotificationRequest): Promise + { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== ERROR_OK) { + throw error; + } + let err: BusinessError = isInvalidParameter(representativeBundle); + if (err.code !== ERROR_OK) { + throw err; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativePublishAsBundleWithBundleOption(representativeBundle, request); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + if (representativeBundle == null || representativeBundle?.length === 0) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeCancelAsBundle(id, representativeBundle, userId); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise + { + if (representativeBundle == null || representativeBundle?.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelAsBundle(id, representativeBundle, userId); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAsBundle(representativeBundle: BundleOption, id: number): Promise + { + let error: BusinessError = isInvalidParameter(representativeBundle); + if (error.code !== ERROR_OK) { + throw error; + } + + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelAsBundleWithBundleOption(representativeBundle, id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelGroup(groupName: string, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + if (groupName == null || groupName?.length === 0) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeCancelGroup(groupName); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function cancelGroup(groupName: string): Promise + { + if (groupName == null || groupName?.length === 0) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelGroup(groupName); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let error: BusinessError = isInvalidParameter(date); + if (error.code !== ERROR_OK) { + throw error; + } + let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDate(date); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setDoNotDisturbDate(date: DoNotDisturbDate): Promise + { + let error: BusinessError = isInvalidParameter(date); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDate(date); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let error: BusinessError = isInvalidParameter(date); + if (error.code !== ERROR_OK) { + throw error; + } + let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDateWithId(date, userId); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise + { + let error: BusinessError = isInvalidParameter(date); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDateWithId(date, userId); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getDoNotDisturbDate(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): DoNotDisturbDate => { return nativeGetDoNotDisturbDate(); }); + p.then((data: NullishType): void => { + let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, doNotDisturbDate); + }, (error: Object): void => { + let doNotDisturbDate : DoNotDisturbDate = {}; + let err: BusinessError = error as BusinessError; + callback(err, doNotDisturbDate); + }) + } + + export function getDoNotDisturbDate(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): DoNotDisturbDate => { return nativeGetDoNotDisturbDate(); }); + p.then((data: NullishType): void => { + let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; + resolve(doNotDisturbDate); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getDoNotDisturbDate(userId: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): DoNotDisturbDate => { return nativeGetDoNotDisturbDateWithId(userId); }); + p.then((data: NullishType): void => { + let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, doNotDisturbDate); + }, (error: Object): void => { + let doNotDisturbDate : DoNotDisturbDate = {}; + let err: BusinessError = error as BusinessError; + callback(err, doNotDisturbDate); + }); + } + + export function getDoNotDisturbDate(userId: number): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): DoNotDisturbDate => { return nativeGetDoNotDisturbDateWithId(userId); }); + p.then((data: NullishType): void => { + let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; + resolve(doNotDisturbDate); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isSupportDoNotDisturbMode(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsSupportDoNotDisturbMode(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isSupportTemplate(templateName: string, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsSupportTemplate(templateName); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isSupportDoNotDisturbMode(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsSupportDoNotDisturbMode(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getDoNotDisturbProfile(id: number): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): DoNotDisturbProfile => { return nativeGetDoNotDisturbProfile(id); }); + p.then((data: NullishType): void => { + let ret : DoNotDisturbProfile = data as DoNotDisturbProfile; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function openNotificationSettings(context: UIAbilityContext): Promise + { + if (context == undefined || context === null) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): Promise => { return nativeOpenNotificationSettings(context); }); + p.then( + (data: NullishType): void => { + if (data == undefined) { + reject(rejectInternalError); + } else { + let result: int = data as int; + if (result == 0) { + resolve(undefined); + } else { + reject(rejectInternalError); + } + } + }, + (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function setTargetDeviceStatus(deviceType: string, status: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativesetTargetDeviceStatus(deviceType,status); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setDistributedEnabledByBundle(bundle: BundleOption, deviceType: string, enable: boolean): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativesetDistributedEnabledByBundle(bundle, deviceType, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + + export function setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativesetDistributedEnableByBundle(bundle, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setSmartReminderEnabled(deviceType: string, enable: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativesetSmartReminderEnabled(deviceType, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isSmartReminderEnabled(deviceType: string): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeisSmartReminderEnabled(deviceType); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setDistributedEnabledBySlot(slot: SlotType, deviceType: string, enabled: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { + return nativesetDistributedEnabledBySlot(slot, deviceType, enabled); + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isDistributedEnabledBySlot(slot: SlotType, deviceType: string): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeisDistributedEnabledBySlot(slot, deviceType); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setAdditionalConfig(key: string, value: string): Promise{ + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): number => { return nativesetAdditionalConfig(key,value); }); + p.then((data: NullishType): void => { + let ret : Double = data as Double; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function disableNotificationFeature(disabled:boolean, bundleList: Array): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { + return nativedisableNotificationFeature(disabled,bundleList); + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativesetDistributedEnableByBundle(bundle, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setDistributedEnable(enable: boolean, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeSetDistributedEnable(enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function setDistributedEnable(enable: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetDistributedEnable(enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isDistributedEnabled(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsDistributedEnabled(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isDistributedEnabled(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsDistributedEnabled(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isDistributedEnabledByBundle(bundle: BundleOption): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsDistributedEnabledByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback): void + { + + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeIsDistributedEnabledByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isDistributedEnabledByBundle(bundle: BundleOption, deviceType: string): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsDistributedEnabledByBundleType(bundle, deviceType); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getDeviceRemindType(): Promise + { + let pPromise = new Promise( + (resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): DeviceRemindType => { return nativeGetDeviceRemindType(); }); + p.then((data: NullishType): void => { + let ret : DeviceRemindType = data as DeviceRemindType; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getDeviceRemindType(callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): DeviceRemindType => { return nativeGetDeviceRemindType(); }); + p.then((data: NullishType): void => { + let ret : DeviceRemindType = data as DeviceRemindType; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + const defaultRemindType: DeviceRemindType = DeviceRemindType.IDLE_DONOT_REMIND; + let err: BusinessError = error as BusinessError; + callback(err, defaultRemindType); + }) + } + + export function setSyncNotificationEnabledWithoutApp + (userId: number, enable: boolean, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => + { return nativeSetSyncNotificationEnabledWithoutApp(userId, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => + { return nativeSetSyncNotificationEnabledWithoutApp(userId, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSyncNotificationEnabledWithoutApp(userId: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => + { return nativeGetSyncNotificationEnabledWithoutApp(userId); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback): void + { + if (callback == null) { + throw errorParamInvalid; + } + let p = taskpool.execute((): boolean => { return nativeGetSyncNotificationEnabledWithoutApp(userId); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); + }, (error: Error): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } +} diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets new file mode 100644 index 0000000000000000000000000000000000000000..d3ad2cbc96bf0e727df414f55ba7a1632a3ac3df --- /dev/null +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -0,0 +1,437 @@ +/* + * Copyright (c) 2025 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 { AsyncCallback, BusinessError } from '@ohos.base'; +import { BundleOption } from 'notification.NotificationCommonDef'; +import { NotificationSubscribeInfo } from 'notification.notificationSubscribeInfo'; +import { NotificationSubscriber } from 'notification.notificationSubscriber'; + +type ResolveCallback = (data: T) => void; +type RejectCallback = (err: Error) => void; + +const ERROR_OK = 0; +const ERROR_PARAM_INVALID = 401; +const ERROR_INTERNAL_ERROR = 160001; + +const rejectInternalError: BusinessError = {code: ERROR_INTERNAL_ERROR, data: "Internal error."}; +const callbackInternalError: BusinessError = {code: ERROR_INTERNAL_ERROR, data: undefined}; +const successCallbackError: BusinessError = {code: ERROR_OK, data: undefined}; + +const errorParamInvalid: BusinessError = {code: ERROR_PARAM_INVALID, data: "Invalid parameter"}; + +function isInvalidParameter(bundle: BundleOption): BusinessError +{ + let error: BusinessError = { + code: ERROR_OK, + message: "" + } + + let errorCode: BusinessError = { + code: ERROR_PARAM_INVALID, + message: "Invalid parameter" + } + + if (bundle == null) { + return errorCode; + } + if (bundle.bundle == null || bundle.bundle?.length === 0) { + return errorCode; + } + return error; +} + +export default namespace notificationSubscribe { + loadLibrary("notification_subscribe_ani.z") + export interface NotificationKey { + id: number; + label?: string; + } + + class NotificationKeyInner implements NotificationKey { + id: number = -1; + label?: string; + } + + export enum RemoveReason { + CLICK_REASON_REMOVE = 1, + CANCEL_REASON_REMOVE = 2 + } + + export native function nativeRemove( + bundle: BundleOption, + notificationKey: NotificationKey, + reason: RemoveReason): void; + export native function nativeRemove(hashCode: string, reason: RemoveReason): void; + export native function nativeRemove(hashCodes: Array, reason: RemoveReason): void; + export native function nativeDistributeOperation(hashcode: string, operationInfo?: OperationInfo): Promise; + export native function nativeSleep(seconds: int): void; + export native function nativeSubscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): void; + export native function nativeUnSubscribe(subscriber: NotificationSubscriber): void + export native function nativeSubscribeSelf(subscriber: NotificationSubscriber): void + export native function nativeRemoveAllForBundle(bundle?: BundleOption): void; + export native function nativeRemoveAllForUserId(userId: number): void; + export native function nativeRemoveAll(): void; + + export function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void { + if (subscriber == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { notificationSubscribe.nativeSubscribe(subscriber) }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + export function subscribe( + subscriber: NotificationSubscriber, + info: NotificationSubscribeInfo, + callback: AsyncCallback + ): void { + if (subscriber == undefined || info == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { notificationSubscribe.nativeSubscribe(subscriber, info) }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + export function subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise { + if (subscriber == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { notificationSubscribe.nativeSubscribe(subscriber, info)}); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void { + if (subscriber == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { notificationSubscribe.nativeUnSubscribe(subscriber) }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function unsubscribe(subscriber: NotificationSubscriber): Promise { + if (subscriber == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { notificationSubscribe.nativeUnSubscribe(subscriber) }); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove( + bundle: BundleOption, + notificationKey: NotificationKey, + reason: RemoveReason, + callback: AsyncCallback + ): void { + if (bundle == undefined || notificationKey == undefined || reason == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + notificationSubscribe.nativeRemove(bundle, notificationKey, reason); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function remove( + bundle: BundleOption, + notificationKey: NotificationKey, + reason: RemoveReason + ): Promise { + if (bundle == undefined || notificationKey == undefined || reason == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { + notificationSubscribe.nativeRemove(bundle, notificationKey, reason); + }); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback): void { + if (hashCode == undefined || reason == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemove(hashCode, reason); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function remove(hashCode: string, reason: RemoveReason): Promise { + if (hashCode == undefined || reason == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemove(hashCode, reason); + }); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove(hashCodes: Array, reason: RemoveReason, callback: AsyncCallback): void { + if (hashCodes == undefined || reason == undefined || callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + notificationSubscribe.nativeRemove(hashCodes, reason); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Error): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function remove(hashCodes: Array, reason: RemoveReason): Promise { + if (hashCodes == undefined || reason == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { + notificationSubscribe.nativeRemove(hashCodes, reason); + }); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function distributeOperation(hashcode: string, operationInfo?: OperationInfo): Promise { + if (hashcode == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): Promise => { + if (operationInfo == undefined) { + return notificationSubscribe.nativeDistributeOperation(hashcode); + } else { + return notificationSubscribe.nativeDistributeOperation(hashcode, operationInfo); + } + }); + p.then( + (e: NullishType): void => { + if (e == undefined) { + reject(rejectInternalError); + } + let result: int = e as int; + if (result != 0) { + reject(rejectInternalError); + } else { + resolve(undefined); + } + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export interface OperationInfo { + actionName?: string; + userInput?: string; + } + + class OperationInfoInner implements OperationInfo { + public actionName?: string; + public userInput?: string; + } + + export function subscribeSelf(subscriber: NotificationSubscriber): Promise { + if (subscriber == undefined) { + throw errorParamInvalid; + } + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void =>{ + let p = taskpool.execute((): void => { notificationSubscribe.nativeSubscribeSelf(subscriber)}); + p.then( + (e: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function removeAll(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemoveAllForBundle(bundle); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function removeAll(bundle?: BundleOption): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { + if (bundle == undefined) { + return notificationSubscribe.nativeRemoveAll(); + } else { + return notificationSubscribe.nativeRemoveAllForBundle(bundle); + } + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeAll(callback: AsyncCallback): void { + if (callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemoveAll(); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function removeAll(userId: number, callback: AsyncCallback): void { + if (callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemoveAllForUserId(userId); + }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } + + export function removeAll(userId: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return notificationSubscribe.nativeRemoveAllForUserId(userId); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Error): void => { + reject(error); + }); + }); + return pPromise; + } +} diff --git a/frameworks/ets/ets/BUILD.gn b/frameworks/ets/ets/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d58786dc68a9c58654ecdd8bdff02c628d6767b5 --- /dev/null +++ b/frameworks/ets/ets/BUILD.gn @@ -0,0 +1,374 @@ +# Copyright (c) 2025 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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//base/notification/distributed_notification_service/notification.gni") + +# start : notification/notificationUserInput.ets +generate_static_abc("notification_user_input_abc") { + base_url = "./" + files = [ + "./notification/notificationUserInput.ets", + ] + + dst_file = "$target_out_dir/notification_user_input.abc" + out_puts = [ "$target_out_dir/notification_user_input.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_user_input.abc" +} + +ohos_prebuilt_etc("notification_user_input_etc") { + source = "$target_out_dir/notification_user_input.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_user_input_abc" ] +} +# end : notification/notificationUserInput.ets + +# start : notification/notificationTemplate.ets +generate_static_abc("notification_template_abc") { + base_url = "./" + files = [ + "./notification/notificationTemplate.ets", + ] + + dst_file = "$target_out_dir/notification_template.abc" + out_puts = [ "$target_out_dir/notification_template.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_template.abc" +} + +ohos_prebuilt_etc("notification_template_etc") { + source = "$target_out_dir/notification_template.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_template_abc" ] +} +# end : notification/notificationTemplate.ets + + + +# start : notification/notificationSubscriber.ets +generate_static_abc("notification_subscriber_abc") { + base_url = "./" + files = [ + "./notification/notificationSubscriber.ets", + ] + + dst_file = "$target_out_dir/notification_subscriber.abc" + out_puts = [ "$target_out_dir/notification_subscriber.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_subscriber.abc" +} + +ohos_prebuilt_etc("notification_subscriber_etc") { + source = "$target_out_dir/notification_subscriber.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_subscriber_abc" ] +} +# end : notification/notificationSubscriber.ets + +# start : notification/notificationSubscribeInfo.ets +generate_static_abc("notification_subscribe_info_abc") { + base_url = "./" + files = [ + "./notification/notificationSubscribeInfo.ets", + ] + + dst_file = "$target_out_dir/notification_subscribe_info.abc" + out_puts = [ "$target_out_dir/notification_subscribe_info.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_subscribe_info.abc" +} + +ohos_prebuilt_etc("notification_subscribe_info_etc") { + source = "$target_out_dir/notification_subscribe_info.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_subscribe_info_abc" ] +} +# end : notification/notificationSubscribeInfo.ets + +# start : notification/notificationSortingMap.ets +generate_static_abc("notification_sorting_map_abc") { + base_url = "./" + files = [ + "./notification/notificationSortingMap.ets", + ] + + dst_file = "$target_out_dir/notification_sorting_map.abc" + out_puts = [ "$target_out_dir/notification_sorting_map.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_sorting_map.abc" +} + +ohos_prebuilt_etc("notification_sorting_map_etc") { + source = "$target_out_dir/notification_sorting_map.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_sorting_map_abc" ] +} +# end : notification/notificationSortingMap.ets + +# start : notification/notificationSorting.ets +generate_static_abc("notification_sorting_abc") { + base_url = "./" + files = [ + "./notification/notificationSorting.ets", + ] + + dst_file = "$target_out_dir/notification_sorting.abc" + out_puts = [ "$target_out_dir/notification_sorting.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_sorting.abc" +} + +ohos_prebuilt_etc("notification_sorting_etc") { + source = "$target_out_dir/notification_sorting.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_sorting_abc" ] +} +# end : notification/notificationSorting.ets + +# start : notification/notificationSlot.ets +generate_static_abc("notification_slot_abc") { + base_url = "./" + files = [ + "./notification/notificationSlot.ets", + ] + + dst_file = "$target_out_dir/notification_slot.abc" + out_puts = [ "$target_out_dir/notification_slot.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_slot.abc" +} + +ohos_prebuilt_etc("notification_slot_etc") { + source = "$target_out_dir/notification_slot.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_slot_abc" ] +} +# end : notification/notificationSlot.ets + +# start : notification/notificationRequest.ets +generate_static_abc("notification_request_abc") { + base_url = "./" + files = [ + "./notification/notificationRequest.ets", + ] + + dst_file = "$target_out_dir/notification_request.abc" + out_puts = [ "$target_out_dir/notification_request.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_request.abc" +} + +ohos_prebuilt_etc("notification_request_etc") { + source = "$target_out_dir/notification_request.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_request_abc" ] +} +# end : notification/notificationRequest.ets + +# start : notification/notificationFlags.ets +generate_static_abc("notification_flags_abc") { + base_url = "./" + files = [ + "./notification/notificationFlags.ets", + ] + + dst_file = "$target_out_dir/notification_flags.abc" + out_puts = [ "$target_out_dir/notification_flags.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_flags.abc" +} + +ohos_prebuilt_etc("notification_flags_etc") { + source = "$target_out_dir/notification_flags.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_flags_abc" ] +} +# end : notification/notificationFlags.ets + +# start : notification/notificationContent.ets +generate_static_abc("notification_content_abc") { + base_url = "./" + files = [ + "./notification/notificationContent.ets", + ] + + dst_file = "$target_out_dir/notification_content.abc" + out_puts = [ "$target_out_dir/notification_content.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_content.abc" +} + +ohos_prebuilt_etc("notification_content_etc") { + source = "$target_out_dir/notification_content.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_content_abc" ] +} +# end : notification/notificationContent.ets + +# start : notification/NotificationCommonDef.ets +generate_static_abc("notification_common_def_abc") { + base_url = "./" + files = [ + "./notification/NotificationCommonDef.ets", + ] + + dst_file = "$target_out_dir/notification_common_def.abc" + out_puts = [ "$target_out_dir/notification_common_def.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_common_def.abc" +} + +ohos_prebuilt_etc("notification_common_def_etc") { + source = "$target_out_dir/notification_common_def.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_common_def_abc" ] +} +# end : notification/NotificationCommonDef.ets + + +# start : notification/notificationActionButton.ets +generate_static_abc("notification_action_button_abc") { + base_url = "./" + files = [ + "./notification/notificationActionButton.ets", + ] + + dst_file = "$target_out_dir/notification_action_button.abc" + out_puts = [ "$target_out_dir/notification_action_button.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_action_button.abc" +} + +ohos_prebuilt_etc("notification_action_button_etc") { + source = "$target_out_dir/notification_action_button.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_action_button_abc" ] +} +# end : notification/notificationActionButton.ets + +# start : @ohos.notificationManager.ets +generate_static_abc("notification_manager_abc") { + base_url = "./" + files = [ + "./@ohos.notificationManager.ets", + ] + + dst_file = "$target_out_dir/notification_manager.abc" + out_puts = [ "$target_out_dir/notification_manager.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_manager.abc" +} + +ohos_prebuilt_etc("notification_manager_etc") { + source = "$target_out_dir/notification_manager.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_manager_abc" ] +} +# end : @ohos.notificationManager.ets + +# start : @ohos.notificationSubscribe.ets +generate_static_abc("notification_subscribe_abc") { + base_url = "./" + files = [ + "./@ohos.notificationSubscribe.ets", + ] + + dst_file = "$target_out_dir/notification_subscribe.abc" + out_puts = [ "$target_out_dir/notification_subscribe.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_subscribe.abc" +} + +ohos_prebuilt_etc("notification_subscribe_etc") { + source = "$target_out_dir/notification_subscribe.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_subscribe_abc" ] +} +# end : @ohos.notificationSubscribe.ets + +group("ets_files") { + deps = [ + ":notification_user_input_abc", + ":notification_user_input_etc", + ":notification_template_abc", + ":notification_template_etc", + ":notification_subscriber_abc", + ":notification_subscriber_etc", + ":notification_subscribe_info_abc", + ":notification_subscribe_info_etc", + ":notification_sorting_map_abc", + ":notification_sorting_map_etc", + ":notification_sorting_abc", + ":notification_sorting_etc", + ":notification_slot_abc", + ":notification_slot_etc", + ":notification_request_abc", + ":notification_request_etc", + ":notification_flags_abc", + ":notification_flags_etc", + ":notification_content_abc", + ":notification_content_etc", + ":notification_common_def_abc", + ":notification_common_def_etc", + ":notification_action_button_abc", + ":notification_action_button_etc", + ":notification_manager_abc", + ":notification_manager_etc", + ":notification_subscribe_abc", + ":notification_subscribe_etc", + ] +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/NotificationCommonDef.ets b/frameworks/ets/ets/notification/NotificationCommonDef.ets new file mode 100644 index 0000000000000000000000000000000000000000..df9b9489224cfbc550bd7dc4af83ef9dcb55d24b --- /dev/null +++ b/frameworks/ets/ets/notification/NotificationCommonDef.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 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. + */ + +export interface BundleOption { + bundle: string; + uid?: number; +} + +class BundleOptionInner implements BundleOption { + public bundle: string = ''; + public uid?: number | undefined; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationActionButton.ets b/frameworks/ets/ets/notification/notificationActionButton.ets new file mode 100644 index 0000000000000000000000000000000000000000..6ae8430600483f8cf203b54d5a744748553f6370 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationActionButton.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 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 { NotificationUserInput } from './notificationUserInput'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; + +export interface NotificationActionButton { + + title: string; + + wantAgent: WantAgent; + + extras?: Record; + + userInput?: NotificationUserInput; +} + +class NotificationActionButtonInner implements NotificationActionButton { + + public title: string = ''; + + public wantAgent: WantAgent = {}; + + public extras?: Record | undefined; + + public userInput?: NotificationUserInput | undefined; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationContent.ets b/frameworks/ets/ets/notification/notificationContent.ets new file mode 100644 index 0000000000000000000000000000000000000000..edd60593c42864b9b77e491451468757c0ddf321 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationContent.ets @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2025 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 image from '@ohos.multimedia.image'; +import { Resource } from 'global.resource'; +import type notificationManager from '@ohos.notificationManager'; + +type IconType = Resource | image.PixelMap; + +class RecordTools { + public static GetKeys(record: Record): Array { + try { + let keys: Array = Object.keys(record); + return keys; + } catch (err) { + return {}; + } + } +} + +export interface NotificationBasicContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; +} + +class NotificationBasicContentInner implements NotificationBasicContent { + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string | undefined; + + public lockscreenPicture?: image.PixelMap | undefined; +} + +export interface NotificationLongTextContent extends NotificationBasicContent { + + longText: string; + + briefText: string; + + expandedTitle: string; +} + +class NotificationLongTextContentInner implements NotificationLongTextContent { + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string; + + public lockscreenPicture?: image.PixelMap | undefined; + + public longText: string = ''; + + public briefText: string = ''; + + public expandedTitle: string = ''; +} + +export enum LiveViewStatus { + + LIVE_VIEW_CREATE = 0, + + LIVE_VIEW_INCREMENTAL_UPDATE = 1, + + LIVE_VIEW_END = 2, + + LIVE_VIEW_FULL_UPDATE = 3 +} + +export enum LiveViewTypes { + + LIVE_VIEW_ACTIVITY = 0, + + LIVE_VIEW_INSTANT = 1, + + LIVE_VIEW_LONG_TERM = 2 +} + +export interface NotificationLiveViewContent extends NotificationBasicContent { + + status: LiveViewStatus; + + version?: number; + + extraInfo?: Record; + + pictureInfo?: Record>; + + isLocalUpdateOnly?: boolean; +} + +class NotificationLiveViewContentInner implements NotificationLiveViewContent { + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string | undefined; + + public lockscreenPicture?: image.PixelMap | undefined; + + public status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; + + public version?: number | undefined; + + public extraInfo?: Record | undefined; + + public pictureInfo?: Record> | undefined; + + public isLocalUpdateOnly?: boolean | undefined; +} + +export interface NotificationMultiLineContent extends NotificationBasicContent { + + briefText: string; + + longTitle: string; + + lines: Array; +} + +class NotificationMultiLineContentInner implements NotificationMultiLineContent { + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string | undefined; + + public lockscreenPicture?: image.PixelMap | undefined; + + public briefText: string = ''; + + public longTitle: string = ''; + + public lines: Array = {}; +} + +export interface NotificationPictureContent extends NotificationBasicContent { + + briefText: string; + + expandedTitle: string; + + picture: image.PixelMap; +} + +class NotificationPictureContentInner implements NotificationPictureContent { + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string | undefined; + + public lockscreenPicture?: image.PixelMap | undefined; + + public briefText: string = ''; + + public expandedTitle: string = ''; + + public picture: image.PixelMap = this.CreatePixelMap(); +} + +export interface NotificationSystemLiveViewContent extends NotificationBasicContent { + + typeCode: number; + + capsule?: NotificationCapsule; + + button?: NotificationButton; + + cardButtons?: Array; + + time?: NotificationTime; + + progress?: NotificationProgress; + + liveViewType?: LiveViewTypes; +} + +class NotificationSystemLiveViewContentInner implements NotificationSystemLiveViewContent { + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } + + public title: string = ''; + + public text: string = ''; + + public additionalText?: string | undefined; + + public lockscreenPicture?: image.PixelMap | undefined; + + public briefText: string = ''; + + public expandedTitle: string = ''; + + public picture: image.PixelMap = this.CreatePixelMap(); + + public typeCode: number = 0; + + public capsule?: NotificationCapsule | undefined; + + public button?: NotificationButton | undefined; + + public cardButtons?: Array | undefined; + + public time?: NotificationTime | undefined; + + public progress?: NotificationProgress | undefined; + + public liveViewType?: LiveViewTypes | undefined; +} + +export interface NotificationCapsule { + + title?: string; + + icon?: image.PixelMap; + + backgroundColor?: string; + + content?: string; + + time?: number; + + capsuleButtons?: Array; +} + +class NotificationCapsuleInner implements NotificationCapsule { + + public title?: string | undefined; + + public icon?: image.PixelMap | undefined; + + public backgroundColor?: string | undefined; + + public content?: string | undefined; + + public time?: number | undefined; + + public capsuleButtons?: Array | undefined; +} + +export interface NotificationIconButton { + + name: string; + + iconResource: IconType; + + text?: string; + + hidePanel?: boolean; +} + +class NotificationIconButtonInner implements NotificationIconButton { + + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } + return image.createPixelMapSync(opts); + } + + public name: string = ''; + + public iconResource: IconType = this.CreatePixelMap(); + + public text?: string | undefined; + + public hidePanel?: boolean | undefined; +} + +export interface NotificationButton { + + names?: Array; + + icons?: Array; + + iconsResource?: Array; +} + +class NotificationButtonInner implements NotificationButton { + + public names?: Array | undefined; + + public icons?: Array | undefined; + + public iconsResource?: Array | undefined; +} + +export interface NotificationTime { + + initialTime?: number; + + isCountDown?: boolean; + + isPaused?: boolean; + + isInTitle?: boolean; +} + +class NotificationTimeInner implements NotificationTime { + + public initialTime?: number | undefined; + + public isCountDown?: boolean | undefined; + + public isPaused?: boolean | undefined; + + public isInTitle?: boolean | undefined; +} + +export interface NotificationProgress { + + maxValue?: number; + + currentValue?: number; + + isPercentage?: boolean; +} + +class NotificationProgressInner implements NotificationProgress { + + public maxValue?: number | undefined; + + public currentValue?: number | undefined; + + public isPercentage?: boolean | undefined; +} + +export interface NotificationContent { + + notificationContentType?: notificationManager.ContentType; + + normal?: NotificationBasicContent; + + longText?: NotificationLongTextContent; + + multiLine?: NotificationMultiLineContent; + + picture?: NotificationPictureContent; + + systemLiveView?: NotificationSystemLiveViewContent; + + liveView?: NotificationLiveViewContent; +} + +class NotificationContentInner implements NotificationContent { + + public notificationContentType?: notificationManager.ContentType | undefined; + + public normal?: NotificationBasicContent | undefined; + + public longText?: NotificationLongTextContent | undefined; + + public multiLine?: NotificationMultiLineContent | undefined; + + public picture?: NotificationPictureContent | undefined; + + public systemLiveView?: NotificationSystemLiveViewContent | undefined; + + public liveView?: NotificationLiveViewContent | undefined; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationFlags.ets b/frameworks/ets/ets/notification/notificationFlags.ets new file mode 100644 index 0000000000000000000000000000000000000000..7c98b19f50bca91d04f264823e7c50fa61837c5c --- /dev/null +++ b/frameworks/ets/ets/notification/notificationFlags.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 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. + */ + +export enum NotificationFlagStatus { + + TYPE_NONE = 0, + + TYPE_OPEN = 1, + + TYPE_CLOSE = 2 +} + +export interface NotificationFlags { + + readonly soundEnabled?: NotificationFlagStatus; + + readonly vibrationEnabled?: NotificationFlagStatus; + + readonly reminderFlags?: number; +} + +class NotificationFlagsInner implements NotificationFlags { + + public soundEnabled?: NotificationFlagStatus | undefined; + + public vibrationEnabled?: NotificationFlagStatus | undefined; + + public reminderFlags?: number | undefined; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationRequest.ets b/frameworks/ets/ets/notification/notificationRequest.ets new file mode 100644 index 0000000000000000000000000000000000000000..b990da8d56f06a96bf3348824e1385cc17b9a942 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationRequest.ets @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2025 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 image from '@ohos.multimedia.image'; +import type notificationManager from '@ohos.notificationManager'; +import type notificationSubscribe from '@ohos.notificationSubscribe'; +import { NotificationContent } from 'notification.notificationContent'; +import { NotificationActionButton } from 'notification.notificationActionButton'; +import { NotificationTemplate } from 'notification.notificationTemplate'; +import { NotificationFlags } from 'notification.notificationFlags'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BundleOption } from 'notification.NotificationCommonDef'; + +export interface DistributedOptions { + isDistributed?: boolean; + supportDisplayDevices?: Array; + supportOperateDevices?: Array; + readonly remindType?: number; +} + +class DistributedOptionsInner implements DistributedOptions { + public isDistributed?: boolean | undefined; + public supportDisplayDevices?: Array | undefined; + public supportOperateDevices?: Array | undefined; + public readonly remindType?: number | undefined; +} + +export interface NotificationFilter { + bundle: BundleOption; + notificationKey: notificationSubscribe.NotificationKey; + extraInfoKeys?: Array; +} + +class NotificationFilterInner implements NotificationFilter { + public bundle: BundleOption = {}; + public notificationKey: notificationSubscribe.NotificationKey = {}; + public extraInfoKeys?: Array | undefined; +} + +export interface NotificationCheckRequest { + contentType: notificationManager.ContentType; + slotType: notificationManager.SlotType; + extraInfoKeys: Array; +} + +class NotificationCheckRequestInner implements NotificationCheckRequest { + public contentType: notificationManager.ContentType = + notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + public slotType: notificationManager.SlotType = notificationManager.SlotType.OTHER_TYPES; + public extraInfoKeys: Array = {}; +} + +export interface UnifiedGroupInfo { + key?: string; + title?: string; + content?: string; + sceneName?: string; + extraInfo?: Record; +} + +class UnifiedGroupInfoInner implements UnifiedGroupInfo { + public key?: string | undefined; + public title?: string | undefined; + public content?: string | undefined; + public sceneName?: string | undefined; + public extraInfo?: Record | undefined; +} + +export interface NotificationRequest { + content: NotificationContent; + id?: number; + appMessageId?: string; + notificationSlotType?: notificationManager.SlotType; + isOngoing?: boolean; + isUnremovable?: boolean; + updateOnly?: boolean; + deliveryTime?: number; + tapDismissed?: boolean; + autoDeletedTime?: number; + wantAgent?: WantAgent; + extraInfo?: Record; + color?: number; + colorEnabled?: boolean; + isAlertOnce?: boolean; + isStopwatch?: boolean; + isCountDown?: boolean; + isFloatingIcon?: boolean; + label?: string; + badgeIconStyle?: number; + showDeliveryTime?: boolean; + actionButtons?: Array; + smallIcon?: image.PixelMap; + largeIcon?: image.PixelMap; + overlayIcon?: image.PixelMap; + groupName?: string; + readonly creatorBundleName?: string; + readonly creatorUid?: number; + readonly creatorPid?: number; + readonly creatorUserId?: number; + sound?: string; + classification?: string; + readonly hashCode?: string; + isRemoveAllowed?: boolean; + readonly source?: number; + template?: NotificationTemplate; + distributedOption?: DistributedOptions; + readonly deviceId?: string; + readonly notificationFlags?: NotificationFlags; + removalWantAgent?: WantAgent; + badgeNumber?: number; + representativeBundle?: BundleOption; + readonly agentBundle?: BundleOption; + unifiedGroupInfo?: UnifiedGroupInfo; + notificationControlFlags?: number; + readonly appInstanceKey?: string; + forceDistributed?: boolean; + notDistributed?: boolean; +} + +class NotificationRequestInner implements NotificationRequest { + public content: NotificationContent = {}; + public id?: number | undefined; + public appMessageId?: string | undefined; + public notificationSlotType?: notificationManager.SlotType | undefined; + public isOngoing?: boolean | undefined; + public isUnremovable?: boolean | undefined; + public updateOnly?: boolean | undefined; + public deliveryTime?: number | undefined; + public tapDismissed?: boolean | undefined; + public autoDeletedTime?: number | undefined; + public wantAgent?: WantAgent | undefined; + public extraInfo?: Record | undefined; + public color?: number | undefined; + public colorEnabled?: boolean | undefined; + public isAlertOnce?: boolean | undefined; + public isStopwatch?: boolean | undefined; + public isCountDown?: boolean | undefined; + public isFloatingIcon?: boolean | undefined; + public label?: string | undefined; + public badgeIconStyle?: number | undefined; + public showDeliveryTime?: boolean | undefined; + public actionButtons?: Array | undefined; + public smallIcon?: image.PixelMap | undefined; + public largeIcon?: image.PixelMap | undefined; + public overlayIcon?: image.PixelMap | undefined; + public groupName?: string | undefined; + public readonly creatorBundleName?: string | undefined; + public readonly creatorUid?: number | undefined; + public readonly creatorPid?: number | undefined; + public readonly creatorUserId?: number | undefined; + public sound?: string | undefined; + public classification?: string | undefined; + public readonly hashCode?: string | undefined; + public isRemoveAllowed?: boolean | undefined; + public readonly source?: number | undefined; + public template?: NotificationTemplate | undefined; + public distributedOption?: DistributedOptions | undefined; + public readonly deviceId?: string | undefined; + public readonly notificationFlags?: NotificationFlags | undefined; + public removalWantAgent?: WantAgent | undefined; + public badgeNumber?: number | undefined; + public representativeBundle?: BundleOption | undefined; + public readonly agentBundle?: BundleOption | undefined; + public unifiedGroupInfo?: UnifiedGroupInfo | undefined; + public notificationControlFlags?: number | undefined; + public readonly appInstanceKey?: string | undefined; + public forceDistributed?: boolean | undefined; + public notDistributed?: boolean | undefined; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSlot.ets b/frameworks/ets/ets/notification/notificationSlot.ets new file mode 100644 index 0000000000000000000000000000000000000000..6cca29daff3b33113f0268f20fd9aa279e89c330 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSlot.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 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 type notificationManager from '@ohos.notificationManager'; + +export interface NotificationSlot { + notificationType?: notificationManager.SlotType; + notificationLevel?: notificationManager.SlotLevel; + desc?: string; + badgeFlag?: boolean; + bypassDnd?: boolean; + lockscreenVisibility?: number; + vibrationEnabled?: boolean; + sound?: string; + lightEnabled?: boolean; + lightColor?: number; + vibrationValues?: Array; + readonly enabled?: boolean; + readonly reminderMode?: number; + readonly authorizedStatus?: number; +} + +class NotificationSlotInner implements NotificationSlot { + public notificationType?: notificationManager.SlotType; + public notificationLevel?: notificationManager.SlotLevel; + public desc?: string; + public badgeFlag?: boolean; + public bypassDnd?: boolean; + public lockscreenVisibility?: number; + public vibrationEnabled?: boolean; + public sound?: string; + public lightEnabled?: boolean; + public lightColor?: number; + public vibrationValues?: Array; + public readonly enabled?: boolean; + public readonly reminderMode?: number; + public readonly authorizedStatus?: number; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSorting.ets b/frameworks/ets/ets/notification/notificationSorting.ets new file mode 100644 index 0000000000000000000000000000000000000000..c3c2d28c06e85c71d3aae9167519a085125444fe --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSorting.ets @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 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 { NotificationSlot } from 'notification.notificationSlot'; + +export interface NotificationSorting { + readonly slot: NotificationSlot; + readonly hashCode: string; + readonly ranking: number; +} + +class NotificationSortingInner implements NotificationSorting { + public readonly slot: NotificationSlot = { + notificationType: undefined, + //level?: notification.SlotLevel; + desc: undefined, + badgeFlag: undefined, + bypassDnd: undefined, + lockscreenVisibility: undefined, + vibrationEnabled: undefined, + sound: undefined, + lightEnabled: undefined, + lightColor: undefined, + vibrationValues: undefined, + enabled: undefined, + reminderMode: undefined, + authorizedStatus: undefined + }; + public readonly hashCode: string = ''; + public readonly ranking: number = -1; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSortingMap.ets b/frameworks/ets/ets/notification/notificationSortingMap.ets new file mode 100644 index 0000000000000000000000000000000000000000..de4511790a87a8046a3265aa696d450ef04e8c15 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSortingMap.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 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 { NotificationSorting } from 'notification.notificationSorting'; + +export interface NotificationSortingMap { + readonly sortings: Record; + readonly sortedHashCode: Array; +} + +class NotificationSortingMapInner implements NotificationSortingMap { + public readonly sortings: Record = {}; + public readonly sortedHashCode: Array = {}; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSubscribeInfo.ets b/frameworks/ets/ets/notification/notificationSubscribeInfo.ets new file mode 100644 index 0000000000000000000000000000000000000000..aba794d1688849e30e4b39833ec2451a2b146c8b --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSubscribeInfo.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 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. + */ + +export interface NotificationSubscribeInfo { + bundleNames?: Array; + userId?: number; + deviceType?: string; + filterLimit?: number; +} + +class NotificationSubscribeInfoInner implements NotificationSubscribeInfo { + public bundleNames?: Array; + public userId?: number; + public deviceType?: string; + public filterLimit?: number; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSubscriber.ets b/frameworks/ets/ets/notification/notificationSubscriber.ets new file mode 100644 index 0000000000000000000000000000000000000000..62aef5c5d43b280f0a680416f7c1ec45d2d92ef8 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSubscriber.ets @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2025 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 { NotificationRequest, DistributedOptions, UnifiedGroupInfo } from 'notification.notificationRequest'; +import { NotificationSortingMap } from 'notification.notificationSortingMap'; +import notificationManager from '@ohos.notificationManager'; +import { NotificationContent } from 'notification.notificationContent'; + +import image from '@ohos.multimedia.image'; +// import type notificationManager from '@ohos.notificationManager'; +// import type notificationSubscribe from '@ohos.notificationSubscribe'; +// import { NotificationContent } from 'notification.notificationContent'; +import { NotificationActionButton } from 'notification.notificationActionButton'; +import { NotificationTemplate } from 'notification.notificationTemplate'; +import { NotificationFlags } from 'notification.notificationFlags'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BundleOption } from 'notification.NotificationCommonDef'; + + +export interface NotificationSubscriber { + onConsume?: (data: SubscribeCallbackData) => void; + + onCancel?: (data: SubscribeCallbackData) => void; + + onUpdate?: (data: NotificationSortingMap) => void; + + onConnect?: () => void; + + onDisconnect?: () => void; + + onDestroy?: () => void; + + onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; + + onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; + + onBadgeChanged?: (data: BadgeNumberCallbackData) => void; + + onBadgeEnabledChanged?: BadgeEnabledChangedCallback; + + onBatchCancel?: (data: Array) => void; +} + +export class NotificationSubscriberInner implements NotificationSubscriber { + public onConsume?: (data: SubscribeCallbackData) => void; + + public onCancel?: (data: SubscribeCallbackData) => void; + + public onUpdate?: (data: NotificationSortingMap) => void; + + public onConnect?: () => void; + + public onDisconnect?: () => void; + + public onDestroy?: () => void; + + public onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; + + public onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; + + public onBadgeChanged?: (data: BadgeNumberCallbackData) => void; + + public onBadgeEnabledChanged?: BadgeEnabledChangedCallback; + + public onBatchCancel?: (data: Array) => void; +} + +export interface SubscribeCallbackData { + readonly request: NotificationRequest; + readonly sortingMap?: NotificationSortingMap; + readonly reason?: number; + readonly sound?: string; + readonly vibrationValues?: Array; +} + +class SubscribeCallbackDataInner implements SubscribeCallbackData { + public readonly request: NotificationRequest = { + content: {}, + id: undefined, + appMessageId: undefined, + notificationSlotType: undefined, + isOngoing: undefined, + isUnremovable: undefined, + updateOnly: undefined, + deliveryTime: undefined, + tapDismissed: undefined, + autoDeletedTime: undefined, + wantAgent: undefined, + extraInfo: undefined, + color: undefined, + colorEnabled: undefined, + isAlertOnce: undefined, + isStopwatch: undefined, + isCountDown: undefined, + isFloatingIcon: undefined, + label: undefined, + badgeIconStyle: undefined, + showDeliveryTime: undefined, + actionButtons: undefined, + smallIcon: undefined, + largeIcon: undefined, + overlayIcon: undefined, + groupName: undefined, + creatorBundleName: undefined, + creatorUid: undefined, + creatorPid: undefined, + creatorUserId: undefined, + // creatorInstanceKey: undefined, + sound: undefined, + classification: undefined, + hashCode: undefined, + isRemoveAllowed: undefined, + source: undefined, + template: undefined, + distributedOption: undefined, + deviceId: undefined, + notificationFlags: undefined, + removalWantAgent: undefined, + badgeNumber: undefined, + representativeBundle: undefined, + agentBundle: undefined, + unifiedGroupInfo: undefined, + notificationControlFlags: undefined, + appInstanceKey: undefined, + forceDistributed: undefined, + notDistributed: undefined + }; + public readonly sortingMap?: NotificationSortingMap; + public readonly reason?: number; + public readonly sound?: string; + public readonly vibrationValues?: Array; +} + +export interface EnabledNotificationCallbackData { + readonly bundle: string; + readonly uid: number; + readonly enable: boolean; +} + +class EnabledNotificationCallbackDataInner implements EnabledNotificationCallbackData { + public readonly bundle: string = ''; + public readonly uid: number = -1; + public readonly enable: boolean = false; +} + +export interface BadgeNumberCallbackData { + readonly bundle: string; + readonly uid: number; + readonly badgeNumber: number; + readonly instanceKey?: number; + readonly appInstanceKey?: string; +} + +class BadgeNumberCallbackDataInner implements BadgeNumberCallbackData { + public readonly bundle: string = ''; + public readonly uid: number = -1; + public readonly badgeNumber: number = -1; + public readonly instanceKey?: number; + public readonly appInstanceKey?: string; +} + +export type BadgeEnabledChangedCallback = (data: EnabledNotificationCallbackData) => void; \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationTemplate.ets b/frameworks/ets/ets/notification/notificationTemplate.ets new file mode 100644 index 0000000000000000000000000000000000000000..1adf3a2969525bbf89bfd32f7d6fd550be8990bf --- /dev/null +++ b/frameworks/ets/ets/notification/notificationTemplate.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 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. + */ + + export interface NotificationTemplate { + name: string; + data: Record; +} + +class NotificationTemplateInner implements NotificationTemplate { + public name: string = ''; + public data: Record = {}; +} \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationUserInput.ets b/frameworks/ets/ets/notification/notificationUserInput.ets new file mode 100644 index 0000000000000000000000000000000000000000..0b220dc0139f68a0b4616e3ee7bafba27f974dbe --- /dev/null +++ b/frameworks/ets/ets/notification/notificationUserInput.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 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. + */ + +export interface NotificationUserInput { + inputKey: string; +} + +class NotificationUserInputInner implements NotificationUserInput { + public inputKey: string = ''; +} \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 19aad802afe6e395c6d164b5b74e5584d14bf45f..098cd250c06e11b81d937919453971987adc0c61 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -1341,6 +1341,52 @@ ohos_unittest("advanced_datashare_observer_unit_test") { part_name = "${component_name}" } +ohos_unittest("notification_extension_wrapper_unit_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + defines = [] + + sources = [ "notification_extension_wrapper_test.cpp" ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + ] + + external_deps = [ + "ability_runtime:dataobs_manager", + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + ] + + if (distributed_notification_service_feature_summary || + distributed_notification_service_feature_additional_control || + distributed_notification_service_feature_privileged_message) { + defines += [ "ENABLE_ANS_EXT_WRAPPER" ] + } + + if (distributed_notification_service_feature_privileged_message) { + defines += [ "ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER" ] + } + + if (distributed_notification_service_feature_additional_control) { + defines += [ "ENABLE_ANS_ADDITIONAL_CONTROL" ] + } + + if (distributed_notification_service_feature_summary) { + defines += [ "ENABLE_ANS_AGGREGATION" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + ohos_unittest("advanced_notification_service_unit_test") { sanitize = { integer_overflow = true @@ -1407,6 +1453,7 @@ group("unittest") { ":disturb_manager_unit_test", ":notification_config_parse_test", ":notification_dialog_test", + ":notification_extension_wrapper_unit_test", ":notification_preferences_database_branch_test", ":notification_preferences_database_test", ":notification_preferences_test", diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index e1ac5d5cda715defaca83d400364b8818c0b1d09..6379db5e5be5ec060760d78dfe05386d58551a33 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -2202,7 +2202,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22100, HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22500, Function | SmallTest | Level1) { GTEST_LOG_(INFO) << "PushCheck_0100 test start"; - + MockIsVerfyPermisson(false); sptr req = new (std::nothrow) NotificationRequest(); ASSERT_EQ(advancedNotificationService_->PushCheck(req), ERR_ANS_PUSH_CHECK_UNREGISTERED); diff --git a/services/ans/test/unittest/notification_extension_wrapper_test.cpp b/services/ans/test/unittest/notification_extension_wrapper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c6fe14e5ba646fdbc2b830cd40f1cbc24c4f9f4 --- /dev/null +++ b/services/ans/test/unittest/notification_extension_wrapper_test.cpp @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2025 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 "gtest/gtest.h" +#define private public +#include "notification_extension_wrapper.h" +#undef private + +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace Notification { +const int32_t ACTIVE_DELETE = 0; +const int32_t PASSITIVE_DELETE = 1; + +static bool g_mockCalled = false; +static bool g_mockLocalSwitch = false; +static int g_mockUpdateByCancelReason = 0; + +static void MockSetLocalSwitch(bool status) +{ + g_mockCalled = true; + g_mockLocalSwitch = status; +} + +static void MockUpdateByCancel(const std::vector>& notifications, int deleteType) +{ + g_mockCalled = true; + g_mockUpdateByCancelReason = deleteType; +} + +class NotificationExtensionWrapperTest : public ::testing::Test { +protected: + void SetUp() override {} + void TearDown() override {} + static void SetUpTestCas() + { + g_mockCalled = false; + g_mockLocalSwitch = false; + g_mockUpdateByCancelReason = 0; + } + static void TearDownTestCase() {}; +}; + +HWTEST_F(NotificationExtensionWrapperTest, InitExtentionWrapper_Test, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + extensionWrapper.InitExtentionWrapper(); +#ifdef ENABLE_ANS_EXT_WRAPPER + // 验证extensionWrapperHandle_是否被正确初始化 + EXPECT_NE(extensionWrapper.extensionWrapperHandle_, nullptr); + + // 验证syncAdditionConfig_是否被正确初始化 + EXPECT_NE(extensionWrapper.syncAdditionConfig_, nullptr); +#else + EXPECT_EQ(extensionWrapper.extensionWrapperHandle_, nullptr); + EXPECT_EQ(extensionWrapper.syncAdditionConfig_, nullptr); +#endif + + // 验证localControl_、reminderControl_、bannerControl_是否被正确初始化 +#ifdef ENABLE_ANS_ADDITIONAL_CONTROL + EXPECT_NE(extensionWrapper.localControl_, nullptr); + EXPECT_NE(extensionWrapper.reminderControl_, nullptr); + EXPECT_NE(extensionWrapper.bannerControl_, nullptr); +#endif + + // 验证modifyReminderFlags_是否被正确初始化 +#ifdef ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER + EXPECT_NE(extensionWrapper.modifyReminderFlags_, nullptr); +#endif + + // 验证initSummary_是否被正确初始化 +#ifdef ENABLE_ANS_AGGREGATION + EXPECT_NE(extensionWrapper.initSummary_, nullptr); +#endif +} + + +HWTEST_F(NotificationExtensionWrapperTest, CheckIfSetlocalSwitch_001, TestSize.Level0) +{ + // 创建ExtensionWrapper对象 + ExtensionWrapper extensionWrapper; + // 设置extensionWrapperHandle_为nullptr + extensionWrapper.extensionWrapperHandle_ = nullptr; + // 调用待测函数 + extensionWrapper.CheckIfSetlocalSwitch(); + // 验证extensionWrapperHandle_仍然为nullptr + EXPECT_EQ(extensionWrapper.extensionWrapperHandle_, nullptr); +} + +HWTEST_F(NotificationExtensionWrapperTest, CheckIfSetlocalSwitch_002, TestSize.Level0) +{ + // 创建ExtensionWrapper对象 + ExtensionWrapper extensionWrapper; + // 设置extensionWrapperHandle_不为nullptr + extensionWrapper.extensionWrapperHandle_ = new int; + // 设置isRegisterDataSettingObserver为false + extensionWrapper.isRegisterDataSettingObserver = false; + // 调用待测函数 + extensionWrapper.CheckIfSetlocalSwitch(); + // 验证isRegisterDataSettingObserver为true + EXPECT_EQ(extensionWrapper.isRegisterDataSettingObserver, true); +} + +HWTEST_F(NotificationExtensionWrapperTest, CheckIfSetlocalSwitch_003, TestSize.Level0) +{ + // 创建ExtensionWrapper对象 + ExtensionWrapper extensionWrapper; + // 设置extensionWrapperHandle_不为nullptr + extensionWrapper.extensionWrapperHandle_ = new int; + // 设置isRegisterDataSettingObserver为true + extensionWrapper.isRegisterDataSettingObserver = true; + // 调用待测函数 + extensionWrapper.CheckIfSetlocalSwitch(); + // 验证isRegisterDataSettingObserver仍然为true + EXPECT_EQ(extensionWrapper.isRegisterDataSettingObserver, true); +} + +HWTEST_F(NotificationExtensionWrapperTest, SetlocalSwitch_False_Test, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + std::string enable = "false"; + extensionWrapper.setLocalSwitch_ = reinterpret_cast(&MockSetLocalSwitch); + + extensionWrapper.SetlocalSwitch(enable); + + EXPECT_TRUE(g_mockCalled); + EXPECT_FALSE(g_mockLocalSwitch); +} + +HWTEST_F(NotificationExtensionWrapperTest, SetlocalSwitch_True_Test, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + std::string enable = "true"; + extensionWrapper.setLocalSwitch_ = reinterpret_cast(&MockSetLocalSwitch); + + extensionWrapper.SetlocalSwitch(enable); + + EXPECT_TRUE(g_mockCalled); + EXPECT_TRUE(g_mockLocalSwitch); +} + +HWTEST_F(NotificationExtensionWrapperTest, SyncAdditionConfig_NullSyncAdditionConfig, TestSize.Level0) +{ + ExtensionWrapper extensionWrapper; + ErrCode result = extensionWrapper.SyncAdditionConfig("key", "value"); + EXPECT_EQ(result, 0); +} + +HWTEST_F(NotificationExtensionWrapperTest, SyncAdditionConfig_ValidSyncAdditionConfig, TestSize.Level0) +{ + ExtensionWrapper extensionWrapper; + extensionWrapper.syncAdditionConfig_ = [](const std::string& key, const std::string& value) { + return 1; + }; + ErrCode result = extensionWrapper.SyncAdditionConfig("key", "value"); + EXPECT_EQ(result, 1); +} + +HWTEST_F(NotificationExtensionWrapperTest, UpdateByCancel_NullUpdateByCancel, TestSize.Level0) +{ + // Arrange + ExtensionWrapper wrapper; + std::vector> notifications; + int deleteReason = 1; + int expectedReason = 0; + + wrapper.UpdateByCancel(notifications, deleteReason); + + EXPECT_NE(expectedReason, deleteReason); +} + +HWTEST_F(NotificationExtensionWrapperTest, UpdateByCancel_Normal_Test, TestSize.Level0) { + ExtensionWrapper wrapper; + wrapper.updateByCancel_ = reinterpret_cast(&MockUpdateByCancel); + + std::vector> notifications; + int deleteReason = 5; + + wrapper.UpdateByCancel(notifications, deleteReason); + + EXPECT_TRUE(g_mockCalled); + EXPECT_EQ(g_mockUpdateByCancelReason, 1); +} + +HWTEST_F(NotificationExtensionWrapperTest, GetUnifiedGroupInfo_NullFunction, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + OHOS::sptr request = nullptr; + EXPECT_EQ(extensionWrapper.GetUnifiedGroupInfo(request), 0); +} + +HWTEST_F(NotificationExtensionWrapperTest, GetUnifiedGroupInfo_ValidFunction, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + OHOS::sptr request = new OHOS::Notification::NotificationRequest(); + extensionWrapper.getUnifiedGroupInfo_ = [](const OHOS::sptr &request) { + return 1; + }; + EXPECT_EQ(extensionWrapper.GetUnifiedGroupInfo(request), 1); +} + + +HWTEST_F(NotificationExtensionWrapperTest, ReminderControl_NullReminderControl, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + std::string bundleName = "testBundle"; + int32_t result = extensionWrapper.ReminderControl(bundleName); + EXPECT_EQ(result, 0); +} + +HWTEST_F(NotificationExtensionWrapperTest, ReminderControl_ValidReminderControl, TestSize.Level0) +{ + OHOS::Notification::ExtensionWrapper extensionWrapper; + std::string bundleName = "testBundle"; + extensionWrapper.reminderControl_ = [](const std::string &bundleName) { return 1; }; + int32_t result = extensionWrapper.ReminderControl(bundleName); + EXPECT_EQ(result, 1); +} + +HWTEST_F(NotificationExtensionWrapperTest, BannerControl_NullBannerControl, TestSize.Level0) +{ + // Arrange + ExtensionWrapper wrapper; + std::string bundleName = "testBundle"; + + // Act + int32_t result = wrapper.BannerControl(bundleName); + + // Assert + EXPECT_EQ(-1, result); +} + +HWTEST_F(NotificationExtensionWrapperTest, BannerControl_ValidBannerControl, TestSize.Level0) +{ + // Arrange + ExtensionWrapper wrapper; + std::string bundleName = "testBundle"; + auto mockBannerControl = [](const std::string &bundleName) { return 0; }; + wrapper.bannerControl_ = mockBannerControl; + + // Act + int32_t result = wrapper.BannerControl(bundleName); + + // Assert + EXPECT_EQ(0, result); +} + +#ifdef ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER +HWTEST_F(NotificationExtensionWrapperTest, ModifyReminderFlags_NullCase, TestSize.Level0) { + // Arrange + OHOS::Notification::ExtensionWrapper wrapper; + wrapper.modifyReminderFlags_ = nullptr; + auto request = new NotificationRequest(); + + // Act + bool result = wrapper.ModifyReminderFlags(request); + + // Assert + ASSERT_FALSE(result); +} + +HWTEST_F(NotificationExtensionWrapperTest, ModifyReminderFlags_SuccessCase, TestSize.Level0) { + // Arrange + OHOS::Notification::ExtensionWrapper wrapper; + bool (*mockFunc)(const sptr &) = [](const sptr &req) { + return true; + }; + wrapper.modifyReminderFlags_ = mockFunc; + auto request = new NotificationRequest(); + + // Act + bool result = wrapper.ModifyReminderFlags(request); + + // Assert + ASSERT_TRUE(result); +} +#endif +HWTEST_F(NotificationExtensionWrapperTest, LocalControl_NullCase, TestSize.Level0) { + // Arrange + OHOS::Notification::ExtensionWrapper wrapper; + wrapper.localControl_ = nullptr; + auto request = new NotificationRequest(); + + // Act + int32_t result = wrapper.LocalControl(request); + + // Assert + ASSERT_EQ(0, result); // 预期返回 0 +} + +HWTEST_F(NotificationExtensionWrapperTest, LocalControl_SuccessCase, TestSize.Level0) { + // Arrange + OHOS::Notification::ExtensionWrapper wrapper; + int32_t (*mockFunc)(const sptr &) = [](const sptr &req) { + return 1; + }; + wrapper.localControl_ = mockFunc; + auto request = new NotificationRequest(); + + // Act + int32_t result = wrapper.LocalControl(request); + + // Assert + ASSERT_EQ(1, result); +} + +HWTEST_F(NotificationExtensionWrapperTest, convertToDelType_ActiveDelete, TestSize.Level0) +{ + // Arrange + int32_t deleteReason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE + 1; + int32_t expectedDelType = ACTIVE_DELETE; + + // Act + int32_t actualDelType = OHOS::Notification::ExtensionWrapper::convertToDelType(deleteReason); + + // Assert + ASSERT_EQ(expectedDelType, actualDelType); +} + +HWTEST_F(NotificationExtensionWrapperTest, convertToDelType_PassiveDelete, TestSize.Level0) +{ + // Arrange + int32_t deleteReason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE; + int32_t expectedDelType = PASSITIVE_DELETE; + + // Act + int32_t actualDelType = OHOS::Notification::ExtensionWrapper::convertToDelType(deleteReason); + + // Assert + ASSERT_EQ(expectedDelType, actualDelType); +} + +HWTEST_F(NotificationExtensionWrapperTest, convertToDelType_UserRemovedReasonDelete, TestSize.Level0) +{ + // Arrange + int32_t deleteReason = NotificationConstant::USER_REMOVED_REASON_DELETE; + int32_t expectedDelType = PASSITIVE_DELETE; + + // Act + int32_t actualDelType = OHOS::Notification::ExtensionWrapper::convertToDelType(deleteReason); + + // Assert + ASSERT_EQ(expectedDelType, actualDelType); +} + +HWTEST_F(NotificationExtensionWrapperTest, convertToDelType_DisableSlotReasonDelete, TestSize.Level0) +{ + // Arrange + int32_t deleteReason = NotificationConstant::DISABLE_SLOT_REASON_DELETE; + int32_t expectedDelType = PASSITIVE_DELETE; + + // Act + int32_t actualDelType = OHOS::Notification::ExtensionWrapper::convertToDelType(deleteReason); + + // Assert + ASSERT_EQ(expectedDelType, actualDelType); +} + +HWTEST_F(NotificationExtensionWrapperTest, convertToDelType_DisableNotificationReasonDelete, TestSize.Level0) +{ + // Arrange + int32_t deleteReason = NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE; + int32_t expectedDelType = PASSITIVE_DELETE; + + // Act + int32_t actualDelType = OHOS::Notification::ExtensionWrapper::convertToDelType(deleteReason); + + // Assert + ASSERT_EQ(expectedDelType, actualDelType); +} +} //namespace Notification +} //namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index a4ffc4433a7c725daa91569a3c09e1c4f00f2138..67944f396461338de14d97588e3ac004b8517017 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1398,7 +1398,7 @@ HWTEST_F(NotificationPreferencesTest, AddDoNotDisturbProfiles_0100, TestSize.Lev profile->SetProfileId(0); profiles.emplace_back(profile); auto res = NotificationPreferences::GetInstance()->AddDoNotDisturbProfiles(userId, profiles); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); + ASSERT_EQ(res, ERR_OK); } /** @@ -1444,7 +1444,7 @@ HWTEST_F(NotificationPreferencesTest, RemoveDoNotDisturbProfiles_0100, TestSize. profile->SetProfileId(0); profiles.emplace_back(profile); auto res = NotificationPreferences::GetInstance()->RemoveDoNotDisturbProfiles(userId, profiles); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); + ASSERT_EQ(res, ERR_OK); } /** @@ -1478,20 +1478,6 @@ HWTEST_F(NotificationPreferencesTest, RemoveDoNotDisturbProfiles_0300, TestSize. ASSERT_EQ(res, ERR_OK); } -/** - * @tc.name: GetDoNotDisturbProfile_0100 - * @tc.desc: test GetDoNotDisturbProfile when profileId Not within the correct range. - * @tc.type: FUNC - */ -HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbProfile_0100, TestSize.Level1) -{ - int32_t profileId = 0; - int32_t userId = 1; - sptr profile; - auto res = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(profileId, userId, profile); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); -} - /** * @tc.name: GetDoNotDisturbProfile_0200 * @tc.desc: test GetDoNotDisturbProfile when GetDoNotDisturbProfiles of preferncesDB_ return false. @@ -1747,7 +1733,7 @@ HWTEST_F(NotificationPreferencesTest, UpdateDoNotDisturbProfiles_00200, Function auto res = NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles( userId, profileId, name, bundleList); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); + ASSERT_EQ(res, ERR_OK); } /**