From 34616e9ceabbf783c311a67bbd3ece261068c805 Mon Sep 17 00:00:00 2001 From: songbao1 Date: Thu, 24 Apr 2025 17:05:15 +0800 Subject: [PATCH 01/52] =?UTF-8?q?tdd=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 --- ...tification_do_not_disturb_profile_test.cpp | 22 ------------------- .../ans/test/unittest/notification_test.cpp | 3 +-- .../advanced_notification_service_test.cpp | 2 +- .../notification_preferences_test.cpp | 20 +++-------------- 4 files changed, 5 insertions(+), 42 deletions(-) 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 0212181c0..27a748516 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 17937fcd6..7346ad239 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/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index e1ac5d5cd..6379db5e5 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_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index a4ffc4433..67944f396 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); } /** -- Gitee From 65dccc164bc7a859ab2ff113940a158200cd1d0d Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 13 May 2025 10:44:53 +0800 Subject: [PATCH 02/52] =?UTF-8?q?ans=E6=A8=A1=E5=9D=97=E9=9D=99=E6=80=81an?= =?UTF-8?q?i=E5=8C=96=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: heguokai --- bundle.json | 4 +- frameworks/ets/BUILD.gn | 22 + frameworks/ets/ani/BUILD.gn | 88 ++ .../ets/ani/include/manager/ani_cance.h | 29 + .../ani/include/manager/ani_display_badge.h | 27 + .../manager/ani_do_not_disturb_profile.h | 27 + .../ets/ani/include/manager/ani_get_active.h | 26 + .../ani/include/manager/ani_local_live_view.h | 27 + .../ets/ani/include/manager/ani_manager.h | 24 + .../include/manager/ani_notification_enable.h | 29 + .../ets/ani/include/manager/ani_publish.h | 27 + frameworks/ets/ani/include/manager/ani_slot.h | 32 + .../ets/ani/include/sts_action_button.h | 60 + .../ets/ani/include/sts_bundle_option.h | 33 + frameworks/ets/ani/include/sts_common.h | 279 +++++ .../ets/ani/include/sts_convert_other.h | 57 + frameworks/ets/ani/include/sts_disturb_mode.h | 31 + .../ani/include/sts_notification_content.h | 100 ++ .../ets/ani/include/sts_notification_flag.h | 27 + .../ani/include/sts_notification_manager.h | 140 +++ frameworks/ets/ani/include/sts_request.h | 43 + frameworks/ets/ani/include/sts_slot.h | 39 + frameworks/ets/ani/include/sts_template.h | 28 + frameworks/ets/ani/include/sts_throw_erro.h | 77 ++ frameworks/ets/ani/include/sts_user_input.h | 30 + frameworks/ets/ani/src/manager/ani_cance.cpp | 89 ++ .../ets/ani/src/manager/ani_display_badge.cpp | 85 ++ .../manager/ani_do_not_disturb_profile.cpp | 72 ++ .../ets/ani/src/manager/ani_get_active.cpp | 40 + .../ani/src/manager/ani_local_live_view.cpp | 71 ++ .../ets/ani/src/manager/ani_manager.cpp | 111 ++ .../src/manager/ani_notification_enable.cpp | 96 ++ .../ets/ani/src/manager/ani_publish.cpp | 67 ++ frameworks/ets/ani/src/manager/ani_slot.cpp | 176 +++ frameworks/ets/ani/src/sts_action_button.cpp | 181 +++ frameworks/ets/ani/src/sts_bundle_option.cpp | 96 ++ frameworks/ets/ani/src/sts_common.cpp | 444 +++++++ frameworks/ets/ani/src/sts_convert_other.cpp | 401 +++++++ frameworks/ets/ani/src/sts_disturb_mode.cpp | 88 ++ .../ets/ani/src/sts_notification_content.cpp | 1020 +++++++++++++++++ .../ets/ani/src/sts_notification_flag.cpp | 50 + .../ets/ani/src/sts_notification_manager.cpp | 371 ++++++ frameworks/ets/ani/src/sts_request.cpp | 947 +++++++++++++++ frameworks/ets/ani/src/sts_slot.cpp | 180 +++ frameworks/ets/ani/src/sts_template.cpp | 74 ++ frameworks/ets/ani/src/sts_user_input.cpp | 47 + .../ets/ets/@ohos.notificationManager.ets | 473 ++++++++ frameworks/ets/ets/BUILD.gn | 247 ++++ .../notification/NotificationCommonDef.ets | 24 + .../notification/notificationActionButton.ets | 39 + .../ets/notification/notificationContent.ets | 390 +++++++ .../ets/notification/notificationFlags.ets | 41 + .../ets/notification/notificationRequest.ets | 181 +++ .../ets/ets/notification/notificationSlot.ets | 35 + .../ets/notification/notificationTemplate.ets | 19 + .../notification/notificationUserInput.ets | 18 + 56 files changed, 7478 insertions(+), 1 deletion(-) create mode 100644 frameworks/ets/BUILD.gn create mode 100644 frameworks/ets/ani/BUILD.gn create mode 100644 frameworks/ets/ani/include/manager/ani_cance.h create mode 100644 frameworks/ets/ani/include/manager/ani_display_badge.h create mode 100644 frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h create mode 100644 frameworks/ets/ani/include/manager/ani_get_active.h create mode 100644 frameworks/ets/ani/include/manager/ani_local_live_view.h create mode 100644 frameworks/ets/ani/include/manager/ani_manager.h create mode 100644 frameworks/ets/ani/include/manager/ani_notification_enable.h create mode 100644 frameworks/ets/ani/include/manager/ani_publish.h create mode 100644 frameworks/ets/ani/include/manager/ani_slot.h create mode 100644 frameworks/ets/ani/include/sts_action_button.h create mode 100644 frameworks/ets/ani/include/sts_bundle_option.h create mode 100644 frameworks/ets/ani/include/sts_common.h create mode 100644 frameworks/ets/ani/include/sts_convert_other.h create mode 100644 frameworks/ets/ani/include/sts_disturb_mode.h create mode 100644 frameworks/ets/ani/include/sts_notification_content.h create mode 100644 frameworks/ets/ani/include/sts_notification_flag.h create mode 100644 frameworks/ets/ani/include/sts_notification_manager.h create mode 100644 frameworks/ets/ani/include/sts_request.h create mode 100644 frameworks/ets/ani/include/sts_slot.h create mode 100644 frameworks/ets/ani/include/sts_template.h create mode 100644 frameworks/ets/ani/include/sts_throw_erro.h create mode 100644 frameworks/ets/ani/include/sts_user_input.h create mode 100644 frameworks/ets/ani/src/manager/ani_cance.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_display_badge.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_get_active.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_local_live_view.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_manager.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_notification_enable.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_publish.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_slot.cpp create mode 100644 frameworks/ets/ani/src/sts_action_button.cpp create mode 100644 frameworks/ets/ani/src/sts_bundle_option.cpp create mode 100644 frameworks/ets/ani/src/sts_common.cpp create mode 100644 frameworks/ets/ani/src/sts_convert_other.cpp create mode 100644 frameworks/ets/ani/src/sts_disturb_mode.cpp create mode 100644 frameworks/ets/ani/src/sts_notification_content.cpp create mode 100644 frameworks/ets/ani/src/sts_notification_flag.cpp create mode 100644 frameworks/ets/ani/src/sts_notification_manager.cpp create mode 100644 frameworks/ets/ani/src/sts_request.cpp create mode 100644 frameworks/ets/ani/src/sts_slot.cpp create mode 100644 frameworks/ets/ani/src/sts_template.cpp create mode 100644 frameworks/ets/ani/src/sts_user_input.cpp create mode 100644 frameworks/ets/ets/@ohos.notificationManager.ets create mode 100644 frameworks/ets/ets/BUILD.gn create mode 100644 frameworks/ets/ets/notification/NotificationCommonDef.ets create mode 100644 frameworks/ets/ets/notification/notificationActionButton.ets create mode 100644 frameworks/ets/ets/notification/notificationContent.ets create mode 100644 frameworks/ets/ets/notification/notificationFlags.ets create mode 100644 frameworks/ets/ets/notification/notificationRequest.ets create mode 100644 frameworks/ets/ets/notification/notificationSlot.ets create mode 100644 frameworks/ets/ets/notification/notificationTemplate.ets create mode 100644 frameworks/ets/ets/notification/notificationUserInput.ets diff --git a/bundle.json b/bundle.json index de58f375c..4beffc327 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/ets/BUILD.gn b/frameworks/ets/BUILD.gn new file mode 100644 index 000000000..ce8395589 --- /dev/null +++ b/frameworks/ets/BUILD.gn @@ -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. + +import("//base/notification/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +group("ani_packages") { + deps = [ +# "./ets:ets_files", + "./ani:notification_manager_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 000000000..2751913fe --- /dev/null +++ b/frameworks/ets/ani/BUILD.gn @@ -0,0 +1,88 @@ +# 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/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_get_active.cpp", + "./src/manager/ani_manager.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_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", + ] + + 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_cance.h b/frameworks/ets/ani/include/manager/ani_cance.h new file mode 100644 index 000000000..d1f71d4cc --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_cance.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_CANCE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_CANCE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniCancelAll(ani_env* env); +void AniCancelWithId(ani_env* env, ani_int id); +void AniCancelWithIdLabel(ani_env* env, ani_int id, ani_string label); +void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id); +} // 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 000000000..32c00b23e --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_display_badge.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DISPLAY_BADGE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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); +} +} +#endif + 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 000000000..7da166437 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DO_NOT_DISTURB_PROFILE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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); +} +} +#endif + 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 000000000..2299c4c91 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_get_active.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_GET_ACTIVE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_GET_ACTIVE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_double AniGetActiveNotificationCount(ani_env *env); +} // 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 000000000..d4fb91a7c --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_LOCAL_LIVE_VIEW_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..faab4a7fe --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_manager.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_MANAGER_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..c24accc63 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_ENABLE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_ENABLE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_boolean AniIsNotificationEnabled(ani_env *env); +ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_int userId); +ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bundleOption); +void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean enable); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + 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 000000000..134d900a2 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_publish.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_PUBLISH_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_PUBLISH_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj); +void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj, + ani_double userId); +} // 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 000000000..d72fcae1e --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -0,0 +1,32 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SLOT_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SLOT_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption); +void AniSetNotificationEnableSlotSync(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_object isForceControl); +ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type); +ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj); +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj); +} // namespace NotificationManagerSts +} // namespace OHOS +#endif + 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 000000000..047a3259c --- /dev/null +++ b/frameworks/ets/ani/include/sts_action_button.h @@ -0,0 +1,60 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ACTION_BUTTON_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..c149dc228 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_BUNDLE_OPTION_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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); +} +} + +#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 000000000..6a0c0c472 --- /dev/null +++ b/frameworks/ets/ani/include/sts_common.h @@ -0,0 +1,279 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_H + +#include "ani.h" +#include +#include +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace NotificationSts { +ani_object CreateBoolean(ani_env *env, bool value); +ani_object CreateDouble(ani_env *env, ani_double value); +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); +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 GetStringArray(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); + +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) { + 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; +} + +template +static bool CallSetterOptional( + ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) +{ + if(env == nullptr || cls == nullptr || object == nullptr) { + return false; + } + if constexpr (std::is_pointer_v && std::is_base_of_v<__ani_ref, std::remove_pointer_t>) { + return CallSetter(env, cls, object, propertyName, value); + } + const char* valueClassName = nullptr; + const char* ctorSig = nullptr; + if constexpr (std::is_same_v) { + valueClassName = "Lstd/core/Boolean;"; + ctorSig = "Z:V"; + } else if constexpr (std::is_same_v) { + valueClassName = "Lstd/core/Char;"; + ctorSig = "C:V"; + } else 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) { + valueClassName = "Lstd/core/Double;"; + ctorSig = "D:V"; + } else { + ANS_LOGE("Classname %{public}s Unsupported", propertyName); + return false; + } + ani_class valueClass = nullptr; + ani_status status = env->FindClass(valueClassName, &valueClass); + if (status != ANI_OK) { + ANS_LOGE("FindClass %{public}s %{public}s failed %{public}d", propertyName, valueClassName, status); + return false; + } + ani_method ctor = nullptr; + status = env->Class_FindMethod(valueClass, "", ctorSig, &ctor); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod %{public}s failed %{public}d", propertyName, status); + return false; + } + ani_object valueObj = nullptr; + 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) { + status = env->Object_New(valueClass, ctor, &valueObj, static_cast(value)); + } else { + ANS_LOGE("Classname %{public}s Unsupported", propertyName); + return false; + } + if (status != ANI_OK) { + ANS_LOGE("Object_New %{public}s failed %{public}d", propertyName, status); + return false; + } + return CallSetter(env, cls, object, propertyName, valueObj); +} + +[[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 +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; +} + +#define ANI_FAILED_AND_RETURN(status) \ +do \ +{ \ + ani_status const local_status = (status); \ + if (ani_status::ANI_OK != local_status) \ + { \ + ANS_LOGE("check status error: %{public}d", (int)local_status); \ + return false; \ + } \ +} while (0) + +#define RETURN_NULL_IF_NULL(ptr) \ + do { \ + if ((ptr) == nullptr) { \ + ANS_LOGE("ptr is null"); \ + return nullptr; \ + } \ + } while (0) +#define RETURN_FALSE_IF_NULL(ptr) \ + do { \ + if ((ptr) == nullptr) { \ + ANS_LOGE("ptr is null"); \ + return false; \ + } \ + } while (0) +#define RETURN_NULL_IF_FALSE(condition) \ + do { \ + if (!(condition)) { \ + ANS_LOGE("condition is false"); \ + return nullptr; \ + } \ + } while (0) +#define RETURN_FALSE_IF_FALSE(condition) \ + do { \ + if (!(condition)) { \ + return false; \ + } \ + } while (0) +#define RETURN_ANI_STATUS_IF_NOT_OK(res, err) \ + do { \ + if ((res) != ANI_OK) { \ + ANS_LOGE(err); \ + return res; \ + } \ + } while (0) + +} // 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 000000000..d89acd5e6 --- /dev/null +++ b/frameworks/ets/ani/include/sts_convert_other.h @@ -0,0 +1,57 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_OTHER_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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; + +void UnwrapWantAgent(ani_env *env, ani_object agent, void** result); +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 000000000..b01efa564 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DISTURB_MODE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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); +} // 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 000000000..645619473 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_NOTIFICATION_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..1f850fff5 --- /dev/null +++ b/frameworks/ets/ani/include/sts_notification_flag.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_FLAG_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_FLAG_H +#include "ani.h" +#include "notification_flags.h" + +namespace OHOS { +namespace NotificationSts { +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 000000000..974da4522 --- /dev/null +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -0,0 +1,140 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_MANAGER_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_MANAGER_H +#include "ani.h" +#include "notification_constant.h" +#include "notification_content.h" +#include "notification_slot.h" +#include "notification_button_option.h" +#include "notification_local_live_view_subscriber.h" +#include "sts_runtime.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; +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, +}; + +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 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); + + +ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonOptionObj, + ButtonOption &buttonOption); +ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption); +} // 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 000000000..aa4e5b5f2 --- /dev/null +++ b/frameworks/ets/ani/include/sts_request.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_REQUEST_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_REQUEST_H +#include "ani.h" +#include "notification_request.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::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); +} // 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 000000000..934519c34 --- /dev/null +++ b/frameworks/ets/ani/include/sts_slot.h @@ -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. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SLOT_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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); + +} // 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 000000000..4427c6b37 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_TEMPLATE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..d4335acd9 --- /dev/null +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -0,0 +1,77 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONTENT_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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()) { + ANSR_LOGI("FindAnsErrMsg Inner error."); + return "Inner error."; + } + return findMsg->second; +} + +inline void ThrowStsErroWithLog(ani_env *env, std::string logMsg) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("%{public}s", logMsg.c_str()); +} +} // 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 000000000..d94a7e887 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_USER_INPUT_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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/src/manager/ani_cance.cpp b/frameworks/ets/ani/src/manager/ani_cance.cpp new file mode 100644 index 000000000..6f6e6c549 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_cance.cpp @@ -0,0 +1,89 @@ +/* + * 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_int id) +{ + ANS_LOGD("AniCancelWithId call,id : %{public}d", id); + int returncode = Notification::NotificationHelper::CancelNotification(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_int id, ani_string label) +{ + ANS_LOGD("AniCancelWithIdLabel call"); + std::string labelStr; + if (ANI_OK != NotificationSts::GetStringByAniString(env, label, labelStr)) { + NotificationSts::ThrowStsErroWithLog(env, "Label parse failed!"); + return; + } + + ANS_LOGD("Cancel by label id:%{public}d label:%{public}s", id, labelStr.c_str()); + int returncode = Notification::NotificationHelper::CancelNotification(labelStr, 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_int id) +{ + ANS_LOGD("AniCancelWithBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleObj, option)) { + NotificationSts::ThrowStsErroWithLog(env, "BundleOption parse failed!"); + return; + } + + ANS_LOGD("Cancel by bundle:%{public}s id:%{public}d", + option.GetBundleName().c_str(), id); + int returncode = Notification::NotificationHelper::CancelAsBundle(option, 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"); +} +} // 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 000000000..16ec7f616 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_display_badge.cpp @@ -0,0 +1,85 @@ +/* + * 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); +} +} +} + 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 000000000..ab0842aef --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.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_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" + +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"); +} +} +} + + 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 000000000..ad3c0efdd --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -0,0 +1,40 @@ +/* + * 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" + +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 -1; + } + return retNum; +} +} // 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 000000000..3e8c0fbff --- /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)) { + 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 000000000..8ab7355a5 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -0,0 +1,111 @@ +/* + * 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_profile.h" +#include "ani_get_active.h" +#include "ani_publish.h" +#include "ani_local_live_view.h" + +namespace OHOS { +namespace NotificationManagerSts { + +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_LOGD("FindNamespace notificationManager failed status : %{public}d", status); + return; + } + + std::array kitFunctions = { + 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 {"nativeIsNotificationEnabled", nullptr, + reinterpret_cast(AniIsNotificationEnabled)}, + ani_native_function {"nativeIsNotificationEnabledWithId", nullptr, + reinterpret_cast(AniIsNotificationEnabledWithId)}, + ani_native_function {"nativeIsNotificationEnabledWithBundleOption", nullptr, + reinterpret_cast(AniIsNotificationEnabledWithBundleOption)}, + ani_native_function {"nativeGetSlotFlagsByBundle", nullptr, reinterpret_cast(AniGetSlotFlagsByBundle)}, + ani_native_function {"nativeSetSlotFlagsByBundle", nullptr, reinterpret_cast(AniSetSlotFlagsByBundle)}, + ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(AniSetNotificationEnable)}, + ani_native_function {"nativeisNotificationSlotEnabled", nullptr, + reinterpret_cast(AniIsNotificationSlotEnabled)}, + 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 {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, + ani_native_function {"nativeGetSlotsByBundle", nullptr, reinterpret_cast(AniGetSlotsByBundle)}, + ani_native_function {"nativeaddDoNotDisturbProfile", nullptr, reinterpret_cast(AniAddDoNotDisturbProfile)}, + ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, reinterpret_cast(AniRemoveDoNotDisturbProfile)}, + ani_native_function {"nativeSetNotificationEnableSlotWithForce", nullptr, + reinterpret_cast(AniSetNotificationEnableSlotWithForce)}, + ani_native_function {"nativeSetNotificationEnableSlotSync", nullptr, + reinterpret_cast(AniSetNotificationEnableSlotSync)}, + ani_native_function {"nativePublishWithUserId", nullptr, reinterpret_cast(AniPublishWithId)}, + ani_native_function {"nativePublish", nullptr, reinterpret_cast(AniPublish)}, + ani_native_function {"nativeSubscribeSystemLiveView", nullptr, + reinterpret_cast(AniSubscribeSystemLiveView)}, + ani_native_function {"nativeAniTriggerSystemLiveView", nullptr, + reinterpret_cast(AniTriggerSystemLiveView)}, + }; + + status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.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_LOGD("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 000000000..672df8ba7 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -0,0 +1,96 @@ +/* + * 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::IsAllowedNotify(allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + 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_int userId) +{ + ANS_LOGD("AniIsNotificationEnabledWithId call"); + bool allowed = false; + int returncode = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + 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 = 0; + bool allowed = false; + BundleOption option; + if(NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + returncode = Notification::NotificationHelper::IsAllowedNotify(option, allowed); + } else { + NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return ANI_FALSE; + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + 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::ThrowStsErroWithLog(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 != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetNotificationEnable -> error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniSetNotificationEnable end"); +} +} // namespace NotificationManagerSts +} // namespace OHOS \ 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 000000000..944077959 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -0,0 +1,67 @@ +/* + * 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_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, [[maybe_unused]]ani_class aniClass, 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::ThrowStsErroWithLog(env, "AniPublish ERROR_INTERNAL_ERROR"); + return; + } + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniPublish error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniPublish end"); +} + +void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj, + ani_double userId) +{ + //NotificationRequest request; + std::shared_ptr notificationRequest = std::make_shared(); + if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { + ANS_LOGE("UnWarpNotificationRequest failed"); + NotificationSts::ThrowStsErroWithLog(env, "AniPublishWithId ERROR_INTERNAL_ERROR"); + return; + } + notificationRequest->SetOwnerUserId(static_cast(userId)); + int returncode = NotificationHelper::PublishNotification(*notificationRequest); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniPublishWithId error, errorCode: %{public}d", externalCode); + } + ANS_LOGD("AniPublishWithId leave"); +} +} // namespace NotificationManagerSts +} // namespace OHOS \ 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 000000000..bdb58cb0c --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -0,0 +1,176 @@ +/* + * 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 { + +ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) +{ + ANS_LOGD("sts GetSlotsByBundle enter"); + int returncode = 0; + std::vector> slots; + BundleOption option; + if(NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + returncode = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); + } else { + NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return nullptr; + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("sts GetSlotsByBundle error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_object outAniObj; + if (!NotificationSts::WrapNotificationSlotArray(env, slots, outAniObj)) { + NotificationSts::ThrowStsErroWithLog(env, "GetSlotsByBundle:failed to WrapNotificationSlotArray"); + return nullptr; + } + ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", externalCode); + return outAniObj; +} + +void AniSetNotificationEnableSlotSync(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) +{ + ANS_LOGD("SetNotificationEnableSlotByOld enter "); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + NotificationSts::ThrowStsErroWithLog(env, "sts AniSetNotificationEnableSlotSync ERROR_INTERNAL_ERROR"); + return; + } + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!NotificationSts::SlotTypeEtsToC(env, type, slotType)) { + NotificationSts::ThrowStsErroWithLog(env, "sts AniSetNotificationEnableSlotSync 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 != 0) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts AniSetNotificationEnableSlotSync end"); +} + +void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, + ani_object isForceControl) +{ + ANS_LOGD("AniSetNotificationEnableSlotWithForce enter "); + ani_boolean isUndefined = false; + ani_boolean res = 0.0; + Notification::NotificationBundleOption option; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + if (!(NotificationSts::SlotTypeEtsToC(env, type, slotType)) + || !(NotificationSts::UnwrapBundleOption(env, bundleOption, option))) { + NotificationSts::ThrowStsErroWithLog(env, "SetNotificationEnableSlotWithForce ERROR_INTERNAL_ERROR"); + return; + } + int returncode = 0; + env->Reference_IsUndefined(isForceControl, &isUndefined); + if(isUndefined) { + bool forceControl = false; + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, + NotificationSts::AniBooleanToBool(enable), forceControl); + } else { + if (ANI_OK !=env->Object_CallMethodByName_Boolean(isForceControl, "booleanValue", nullptr, &res)){ + NotificationSts::ThrowStsErroWithLog(env, "SetNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); + return; + } + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, + NotificationSts::AniBooleanToBool(enable), NotificationSts::AniBooleanToBool(res)); + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", 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::ThrowStsErroWithLog(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 != 0) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("IsNotificationSlotEnabled -> error, errorCode: %{public}d", 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::ThrowStsErroWithLog(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 != 0) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniGetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + } + return slotFlags; +} + +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts setSlotFlagsByBundle call"); + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { + NotificationSts::ThrowStsErroWithLog(env, "AniSetSlotFlagsByBundle : erro arguments."); + return; + } + uint32_t slotFlags = 0; + int returncode = Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + } +} +} +} \ 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 000000000..f7fc64c01 --- /dev/null +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -0,0 +1,181 @@ +/* + * 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 "sts_user_input.h" + + +namespace OHOS { +namespace NotificationSts { +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + 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) { + return ANI_INVALID_ARGS; + } + ani_ref wantAgentRef; + WantAgent* pWantAgent = nullptr; + if(ANI_OK == GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) && isUndefind == ANI_FALSE) { + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + } else { + return ANI_INVALID_ARGS; + } + if (pWantAgent == nullptr) { + return ANI_INVALID_ARGS; + } + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + + 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 { + return ANI_INVALID_ARGS; + } + std::shared_ptr extras = std::make_shared(wantParams); + + 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); + } + if (userInput == nullptr) { + userInput = {}; + } + actionButton.icon = nullptr; + actionButton.title = title; + actionButton.wantAgent = wantAgent; + actionButton.extras = extras; + actionButton.semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + actionButton.autoCreatedReplies = true; + actionButton.mimeTypeOnlyInputs = {}; + actionButton.userInput = userInput; + actionButton.isContextual = false; + return status; +} + +ani_object WrapNotificationActionButton(ani_env* env, + const std::shared_ptr &actionButton) +{ + if (actionButton == nullptr) { + ANS_LOGE("actionButton is null"); + return nullptr; + } + ani_object iconButtonObject = nullptr; + ani_class iconButtonCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)); + // title: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, actionButton->GetTitle(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "title", stringValue)); + // wantAgent: WantAgent; + //napi处理过程 + std::shared_ptr agent = actionButton->GetWantAgent(); + if (agent == nullptr) { + ANS_LOGI("agent is null"); + return nullptr; + } else { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); + } + + // need to do + // extras?: Record; napi中没有处理它的过程? + //napi位置:notification_distributed_notification_service-OpenHarmony_feature_20250328\frameworks\js\napi\src\common_convert_request.cpp 419行 + // // icon?: image.PixelMap 未找到ETS属性 + + // userInput?: NotificationUserInput -> inputKey: string; + ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)); + + return iconButtonObject; +} + +ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, + const char *name, std::vector> &res) +{ + 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_LOGI("status : %{public}d , %{public}s : may be undefined", status, name); + return ANI_INVALID_ARGS; + } + status = GetPropertyDouble(env, static_cast(arrayObj), "length", isUndefined, 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; + } + status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton); + if (status != ANI_OK) { + ANS_LOGI("ActionButton failed, index: %{public}d", 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); + } + return status; +} + +ani_object GetAniArrayNotificationActionButton(ani_env* env, + const std::vector> &actionButtons) +{ + if (actionButtons.empty()) { + ANS_LOGE("actionButtons is empty"); + return nullptr; + } + ani_object arrayObj = newArrayClass(env, actionButtons.size()); + if (arrayObj == nullptr) { + ANS_LOGE("arrayObj is empty"); + return nullptr; + } + ani_size index = 0; + for (auto &button : actionButtons) { + ani_object item = WrapNotificationActionButton(env, button); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + 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 000000000..c55396dbb --- /dev/null +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -0,0 +1,96 @@ +/* + * 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"); + std::string bundleName; + ani_boolean isUndefined = ANI_ERROR; + if(GetPropertyString(env, obj, "bundle", isUndefined, bundleName) !=ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("get bundle failed, bundle must be string."); + return false; + } + option.SetBundleName(bundleName); + ANS_LOGD("WrapBundleOption bundleName: %{public}s", bundleName.c_str()); + + ani_double result = 0.0; + if(GetPropertyDouble(env, obj, "uid", isUndefined, result) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGE("Wrong argument type or uid is Undefined."); + return false; + } + int32_t uid = static_cast(result); + ANS_LOGD("WrapBundleOption bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), uid); + option.SetUid(uid); + return true; +} + +bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector& options) +{ + ani_status status; + ani_double length; + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + + Notification::NotificationBundleOption option; + for (int i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + return false; + } + + if (!UnwrapBundleOption(env, static_cast(optionRef), option)) { + ANS_LOGD("Get BundleOption failed, index: %{public}d", i); + return false; + } + options.push_back(option); + ANS_LOGD("GetOptions index: %{public}d", i); + } + return true; +} + +bool WrapBundleOption(ani_env* env, + const std::shared_ptr &bundleOption, ani_object &bundleObject) +{ + if (bundleOption == nullptr) { + ANS_LOGE("agentBundle is null"); + return false; + } + ani_class bundleCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject)); + RETURN_FALSE_IF_FALSE(bundleCls != nullptr && bundleObject != nullptr); + // bundle: string; + ani_string stringValue = nullptr; + RETURN_FALSE_IF_FALSE(GetAniStringByString(env, bundleOption->GetBundleName(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)); + // uid?: number; + uint32_t uid = bundleOption->GetUid(); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, bundleCls, bundleObject, "uid", uid)); + 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 000000000..95c439dc2 --- /dev/null +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -0,0 +1,444 @@ +/* + * 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" + +namespace OHOS { +namespace NotificationSts { +constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; +constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; + +ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& aniStr) +{ + 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) +{ + ani_size sz {}; + ani_status status = ANI_ERROR; + if ((status = env->String_GetUTF8Size(str, &sz)) != ANI_OK) { + ANS_LOGD("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_LOGD("status : %{public}d", status); + return status; + } + res.resize(sz); + return status; +} + +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, std::string &outStr) +{ + ani_status status = ANI_ERROR; + ani_ref strRef; + if ((status =env->Object_GetPropertyByName_Ref(obj, name, &strRef)) != ANI_OK) { + ANS_LOGD("Object_GetField_Ref bundle fail, status: %{public}d", status); + return status; + } + status = env->Reference_IsUndefined(strRef, &isUndefined); + if (status != ANI_OK) { + ANS_LOGD("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + return status; + } + if(isUndefined == ANI_TRUE) { + ANS_LOGI("%{public}s is undefined", name); + return status; + } + if ((status = GetStringByAniString(env, reinterpret_cast(strRef), outStr)) != ANI_OK) { + ANS_LOGD("GetStdString failed"); + return status; + } + return status; +} + +ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, + ani_boolean isUndefined, bool outvalue) +{ + ani_ref refObj = nullptr; + ani_status status = ANI_ERROR; + ani_ref uidRef; + status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef); + if (ANI_OK != status) { + ANS_LOGD("Object_GetPropertyByName_Ref fail, status: %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { + ANS_LOGD("Reference_IsUndefined failed, status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{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_LOGD("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) +{ + ani_status status = ANI_ERROR; + ani_ref uidRef; + if ((status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef)) != ANI_OK) { + ANS_LOGI("Object_GetPropertyByName_Ref fail, status: %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) == ANI_OK) { + ANS_LOGI("Reference_IsUndefined failed, status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s is undefined", name); + return ANI_INVALID_ARGS; + } + status = env->Object_CallMethodByName_Double(static_cast(uidRef), "doubleValue", nullptr, &outvalue); + if (ANI_OK != status) { + ANS_LOGI("Object_CallMethodByName_Double uid fail, status: %{public}d", status); + return status; + } + return status; +} + +ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_boolean &isUndefined, ani_ref &outRef) +{ + ani_status status = env->Object_GetPropertyByName_Ref(obj, name, &outRef); + if (status != ANI_OK) { + ANS_LOGI("Failed to get property '%{public}s', status: %{public}d", name, status); + return status; + } + status = env->Reference_IsUndefined(outRef, &isUndefined); + if (status != ANI_OK) { + ANS_LOGI("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + } + return status; +} + +ani_status GetStringArray(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res) +{ + ani_ref arrayObj = nullptr; + ani_status status; + ani_double length; + std::string str; + 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 stringEntryRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + str = ""; + status = GetStringByAniString(env, static_cast(stringEntryRef), str); + if (status != ANI_OK) { + ANS_LOGI("GetStdString failed, index: %{public}d", i); + return status; + } + + res.push_back(str); + ANS_LOGI("GetStdString index: %{public}d %{public}s", i, str.c_str()); + } + return status; +} + +ani_object GetAniStringArrayByVectorString(ani_env *env, std::vector &strs) +{ + if (strs.empty()) { + return nullptr; + } + int length = strs.size(); + ani_object arrayObj = newArrayClass(env, length); + ani_size i = 0; + for (auto &str : strs) { + ani_string aniStr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, str, aniStr) != ANI_OK); + if (aniStr == nullptr) { + 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) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + 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) { + 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) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + 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)); + RETURN_FALSE_IF_NULL(boolObj); + 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) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + 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); + RETURN_FALSE_IF_NULL(doubleObj); + 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 boolCls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_BOOLEAN, &boolCls)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_method boolCtor; + if ((status = env->Class_FindMethod(boolCls, "", "Z:V", &boolCtor)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_object boolObj; + if ((status = env->Object_New(boolCls, boolCtor, &boolObj, value ? ANI_TRUE : ANI_FALSE)) + != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + return boolObj; +} + +ani_object CreateDouble(ani_env *env, double value) +{ + 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"); + 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 arrayObj; + } + ANS_LOGD("newArrayClass end"); + return arrayObj; +} + +ani_object newRecordClass(ani_env *env) +{ + ANS_LOGD("newRecordClass call"); + ani_class recordCls; + ani_method ctor; + if (ANI_OK != env->FindClass("Lescompat/Record;", &recordCls)) { + return nullptr; + } + + if (ANI_OK != env->Class_FindMethod(recordCls, "", nullptr, &ctor)) { + return nullptr; + } + ani_object recordObj = {}; + if (ANI_OK != env->Object_New(recordCls, ctor, &recordObj)) { + return nullptr; + } + ANS_LOGD("newRecordClass end"); + return recordObj; +} + +ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values) +{ + if (values.empty()) { + 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 (values.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) +{ + ANI_FAILED_AND_RETURN(env->FindClass(className, &cls)); + ani_method ctor; + ANI_FAILED_AND_RETURN(env->Class_FindMethod(cls, "", nullptr, &ctor)); + outAniObj = {}; + ANI_FAILED_AND_RETURN(env->Object_New(cls, ctor, &outAniObj)); + 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 000000000..734d039d1 --- /dev/null +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -0,0 +1,401 @@ +/* + * 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 { +void UnwrapWantAgent(ani_env *env, ani_object agent, void** result) +{ + ANS_LOGI("called"); + if (agent == nullptr) { + ANS_LOGI("agent null"); + return; + } + ani_long param_value; + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + ani_method method {}; + if ((status = env->FindClass("Lstd/core/Long;", &cls)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + if ((status = env->Class_FindMethod(cls, "unboxed", nullptr, &method)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + if ((status = env->Object_CallMethod_Long(agent, method, ¶m_value)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + *result = reinterpret_cast(param_value); +} + +ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource) +{ + 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); + return status; +} + +ani_object CreateAniPixelMap(ani_env* env, std::shared_ptr pixelMap) +{ + if (pixelMap == nullptr) { + return nullptr; + } + return PixelMapAni::CreatePixelMap(env, pixelMap); +} + +std::shared_ptr GetPixelMapFromEnvSp(ani_env* env, ani_object obj) +{ + ani_status ret; + ani_long nativeObj {}; + if ((ret = env->Object_GetFieldByName_Long(obj, "nativeObj", &nativeObj)) != ANI_OK) { + ANS_LOGI("[GetPixelMapFromEnv] Object_GetField_Long fetch failed"); + return nullptr; + } + PixelMapAni* pixelmapAni = reinterpret_cast(nativeObj); + if (!pixelmapAni) { + ANS_LOGI("[GetPixelMapFromEnv] pixelmapAni nullptr"); + return nullptr; + } + return pixelmapAni->nativePixelMap_; +} + +ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector> &pixelMaps) +{ + ani_status status = ANI_ERROR; + ani_double length; + status = env->Object_GetPropertyByName_Double(static_cast(param), "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 pixelMapRef; + status = env->Object_CallMethodByName_Ref(static_cast(param), + "$_get", "I:Lstd/core/Object;", &pixelMapRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pixelMapRef)); + if (pixelMap == nullptr) { + return ANI_INVALID_ARGS; + } + pixelMaps.push_back(pixelMap); + } + return status; +} + +ani_status GetPixelMapArray(ani_env *env, + ani_object param, const char *name, std::vector> &pixelMaps) +{ + 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) { + return status; + } + return status; +} + +ani_status GetResourceArray(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + 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) { + 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 iconRef; + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &iconRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + ResourceManager::Resource resource; + if(ANI_OK != UnwrapResource(env, static_cast(iconRef), resource)) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + res.push_back(resource); + } + return status; +} + +ani_status GetKeyString(ani_env *env, ani_object obj, int index, ani_string &str) +{ + 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_LOGI("status : %{public}d, index: %{public}d", status, index); + return status; + } + str = static_cast(stringEntryRef); + return status; +} + +ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vector keys, + std::map>> &pictureMap) +{ + 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))) { + return status; + } + std::vector> pixelMaps = {}; + if((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { + return status; + } + std::string str = ""; + if((status = GetStringByAniString(env, anikey, str)) != ANI_OK) { + return status; + } + pictureMap[str] = pixelMaps; + } + return status; +} + +ani_status GetMapOfPictureInfo(ani_env *env, ani_object obj, + std::map>> pictureMap) +{ + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + RETURN_ANI_STATUS_IF_NOT_OK(status = env->FindClass("Lnotification/notificationContent/RecordTools;", &cls), + "failed to find class -> Lnotification/notificationContent/RecordTools;"); + if (cls == nullptr) { + return ANI_INVALID_TYPE; + } + ani_static_method keysMethod = nullptr; + RETURN_ANI_STATUS_IF_NOT_OK(status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod), + "find Method GetKeys failed."); + ani_ref keysStrArrayRef = nullptr; + RETURN_ANI_STATUS_IF_NOT_OK(status = env->Class_CallStaticMethod_Ref(cls, keysMethod, &keysStrArrayRef, obj), + "failed to call method GetKeys"); + ani_boolean isUndefined = ANI_TRUE; + if ((status = env->Reference_IsUndefined(keysStrArrayRef, &isUndefined)) != ANI_OK) { + return status; + } + if (isUndefined) { + return ANI_INVALID_ARGS; + } + ani_double length; + RETURN_ANI_STATUS_IF_NOT_OK( + status = env->Object_GetPropertyByName_Double(static_cast(keysStrArrayRef), "length", &length), + "get length ok keys failed."); + 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) { + return status; + } + keys.push_back(strAni); + } + status = GetPixelMapByKeys(env, obj, keys, pictureMap); + return status; +} + +ani_object GetAniResource(ani_env *env, const std::shared_ptr &resource) +{ + ani_class resourceCls = nullptr; + ani_object resourceObject = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lglobal/resource/ResourceInner;", resourceCls, resourceObject)); + // bundleName: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, resource->bundleName, stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "bundleName", stringValue)); + // moduleName: string; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, resource->moduleName, stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "moduleName", stringValue)); + // id: number; + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "id", resource->id)); + return resourceObject; +} + +ani_object GetAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps) +{ + RETURN_NULL_IF_NULL(env); + if (pixelMaps.empty()) { + return nullptr; + } + + ani_size length = pixelMaps.size(); + ani_object arrayObj = newArrayClass(env, length); + if (arrayObj == nullptr) { + return nullptr; + } + ani_size i = 0; + for (auto &pixelMap : pixelMaps) { + ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, pixelMap); + if (pixelMapObject == nullptr) { + ANS_LOGE("CreatePixelMap failed, 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("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + return arrayObj; +} + +ani_object GetAniArrayResource(ani_env *env, + const std::vector> &resources) +{ + RETURN_NULL_IF_NULL(env); + if (resources.empty()) { + ANS_LOGE("resources is empty"); + return nullptr; + } + + ani_size length = resources.size(); + ani_object arrayObj = newArrayClass(env, length); + if (arrayObj == nullptr) { + return nullptr; + } + ani_size i = 0; + for (auto &resource : resources) { + ani_object resourceObject = GetAniResource(env, resource); + if (resourceObject == nullptr) { + ANS_LOGE("GetAniResource failed, 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("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + return arrayObj; +} + +bool GetAniPictrueInfo(ani_env *env, std::map>> pictureMap, + ani_object &pictureInfoObj) +{ + if (pictureMap.empty()) { + return false; + } + pictureInfoObj = newRecordClass(env); + for (const auto& [key, value] : pictureMap) { + ani_string aniKey; + if(GetAniStringByString(env, key, aniKey) != ANI_OK || aniKey == nullptr) { + return false; + } + ani_object aniPictrueArray = GetAniArrayPixelMap(env, value); + if (aniPictrueArray == nullptr) { + return false; + } + if (ANI_OK != env->Object_CallMethodByName_Void(pictureInfoObj, + "$_set", "Lstd/core/Object;Lstd/core/Object;:V", aniKey, aniPictrueArray)) { + return false; + } + } + return true; +} + +ani_object WarpWantAgent(ani_env *env, std::shared_ptr wantAgent) +{ + if (wantAgent == nullptr) { + return nullptr; + } + return AppExecFwk::WrapWantAgent(env, wantAgent.get()); +} + +ani_object GetAniWantAgentArray(ani_env *env, std::vector> wantAgents) +{ + ani_status status = ANI_ERROR; + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, wantAgents.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_size index = 0; + for (auto &wantAgent : wantAgents) { + ani_object item = AppExecFwk::WrapWantAgent(env, wantAgent.get()); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + 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 000000000..3dfe020da --- /dev/null +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -0,0 +1,88 @@ +/* + * 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"); + ani_boolean isUndefined = ANI_TRUE; + + ani_double idAni = 0.0; + if (ANI_OK != GetPropertyDouble(env, param, "id", isUndefined, idAni) || isUndefined == ANI_TRUE) { + ANS_LOGE("GetPropertyDouble id : failed"); + return false; + } + std::string nameStr = ""; + if (ANI_OK != GetPropertyString(env, param, "name", isUndefined, nameStr) || isUndefined == ANI_TRUE) { + ANS_LOGE("GetPropertyString name : failed"); + return false; + } + profile->SetProfileId(static_cast(idAni)); + profile->SetProfileName(nameStr); + + ani_ref trustlistRef; + if (ANI_OK != GetPropertyRef(env, param, "trustlist", isUndefined, trustlistRef) || isUndefined == ANI_TRUE) { + ANS_LOGD("GetPropertyRef trustlist failed, maybe is isUndefined"); + } 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) +{ + ani_status status; + ani_double length; + + status = env->Object_GetPropertyByName_Double(arrayObj, "length", &length); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + + sptr profile; + for (int i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", + "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + return false; + } + + if (!UnwrapDoNotDisturbProfile(env, static_cast(optionRef), profile)) { + ANS_LOGD("Get profile failed, index: %{public}d", i); + return false; + } + profiles.push_back(profile); + ANS_LOGD("GetProfiles index: %{public}d", i); + } + 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 000000000..bec99944e --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -0,0 +1,1020 @@ +/* + * 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) +{ + 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) +{ + 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) +{ + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + if(EnumConvertAniToNative(env, enumItem, stsLiveViewStatus)) { + StsLiveViewStatusUtils::StsToC(stsLiveViewStatus, liveViewStatus); + return true; + } + return false; +} + +bool LiveViewStatusCToEts(ani_env *env, LiveViewStatus liveViewStatus, ani_enum_item &enumItem) +{ + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + StsLiveViewStatusUtils::CToSts(liveViewStatus, stsLiveViewStatus); + if(EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewStatus", stsLiveViewStatus, enumItem)) { + return true; + } + return false; +} + +bool LiveViewTypesEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewTypes &liveViewTypes) +{ + return EnumConvertAniToNative(env, enumItem, liveViewTypes); +} + +bool LiveViewTypesCToEts(ani_env *env, LiveViewTypes liveViewTypes, ani_enum_item &enumItem) +{ + return EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewTypes", liveViewTypes, enumItem); +} + +void UnWarpNotificationProgress(ani_env *env, ani_object obj, + NotificationProgress ¬ificationProgress) +{ + 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)); + } + ani_double currentValueAni = 0.0; + if(GetPropertyDouble(env, obj, "currentValue", isUndefined, currentValueAni) == ANI_OK + && isUndefined == ANI_FALSE) { + notificationProgress.SetCurrentValue(static_cast(currentValueAni)); + } + + bool isPercentage = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isPercentage", isUndefined, isPercentage) + && isUndefined == ANI_FALSE) { + notificationProgress.SetIsPercentage(isPercentage); + } +} + +bool WarpNotificationProgress(ani_env *env, const NotificationProgress &progress, ani_object &progressObject) +{ + ani_class progressClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationProgressInner;", progressClass, progressObject)); + // maxValue?: number; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "maxValue", + progress.GetMaxValue())); + // currentValue?: number; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "currentValue", + progress.GetCurrentValue())); + // isPercentage?: boolean; + RETURN_FALSE_IF_FALSE(CallSetter(env, progressClass, progressObject, "isPercentage", + BoolToAniBoolean(progress.GetIsPercentage()))); + return true; +} + +void UnWarpNotificationTime(ani_env *env, ani_object obj, + NotificationTime ¬ificationTime) +{ + 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)); + } + + bool isCountDown = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, isCountDown) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsCountDown(isCountDown); + } + + bool isPaused = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isPaused", isUndefined, isPaused) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsPaused(isPaused); + } + + bool isInTitle = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isInTitle", isUndefined, isInTitle) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsInTitle(isInTitle); + } +} + +bool WarpNotificationTime(ani_env *env, const NotificationTime &time, bool isInitialTimeExist, ani_object &timeObject) +{ + ani_class timeClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationTimeInner;", timeClass, timeObject)); + // initialTime?: number; + if (isInitialTimeExist) { + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "initialTime", + time.GetInitialTime())); + } + // isCountDown?: boolean; + RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isCountDown", + BoolToAniBoolean(time.GetIsCountDown()))); + // isPaused?: boolean; + RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isPaused", + BoolToAniBoolean(time.GetIsPaused()))); + // isInTitle?: boolean; + RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isInTitle", + BoolToAniBoolean(time.GetIsInTitle()))); + return true; +} + +ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, + NotificationIconButton &iconButton) +{ + 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) { + return ANI_INVALID_ARGS; + } + iconButton.SetName(name); + + ani_ref iconRef = {}; + if ((status = env->Object_GetPropertyByName_Ref(obj, "iconResource", &iconRef)) != ANI_OK) { + return status; + } + 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) { + return ANI_INVALID_ARGS; + } + iconButton.SetIconImage(pixelMap); + } + + std::string text = ""; + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "text", isUndefined, text) == ANI_OK && isUndefined == ANI_FALSE) { + iconButton.SetName(text); + } + + bool hidePanel = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "hidePanel", isUndefined, hidePanel) + && isUndefined == ANI_FALSE) { + iconButton.SetHidePanel(hidePanel); + } + return status; +} + +ani_status GetIconButtonArray(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + 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); + } + } + return status; +} + +void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, + NotificationLocalLiveViewButton &button) +{ + std::vector names = {}; + ani_boolean isUndefined = ANI_TRUE; + if(GetStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { + for(auto name: names) { + button.addSingleButtonName(name); + } + } + + std::vector> icons = {}; + if(ANI_OK == GetPixelMapArray(env, obj, "icons", icons)) { + for(auto icon: icons) { + button.addSingleButtonIcon(icon); + } + } + 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); + } + } +} + +bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLiveViewButton &button, ani_object &buttonObject) +{ + ani_class buttonClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationButtonInner;", buttonClass, buttonObject)); + // names?: Array; + std::vector names = button.GetAllButtonNames(); + ani_object namesObjectArray = GetAniStringArrayByVectorString(env, names); + if (namesObjectArray == nullptr) { + ANS_LOGE("namesObjectArray is nullptr"); + return false; + } + RETURN_FALSE_IF_FALSE(CallSetter(env, buttonClass, buttonObject, "names", namesObjectArray)); + // icons?: Array; + std::vector> icons = button.GetAllButtonIcons(); + ani_object iconsObjectArray = GetAniArrayPixelMap(env, icons); + if (iconsObjectArray == nullptr) { + ANS_LOGE("iconsObjectArray is nullptr"); + return false; + } + RETURN_FALSE_IF_FALSE(CallSetter(env, buttonClass, buttonObject, "icons", iconsObjectArray)); + // iconsResource?: Array; + std::vector> iconsResource = button.GetAllButtonIconResource(); + ani_object resourceObjectArray = GetAniArrayResource(env, iconsResource); + if (resourceObjectArray == nullptr) { + ANS_LOGE("resourceObjectArray is nullptr"); + return false; + } + return CallSetter(env, buttonClass, buttonObject, "iconsResource", resourceObjectArray); +} + +void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule &capsule) +{ + ani_boolean isUndefined = ANI_TRUE; + std::string title = ""; + if(GetPropertyString(env, obj, "title", isUndefined, title) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetTitle(title); + } + + std::string backgroundColor = ""; + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "backgroundColor", isUndefined, backgroundColor) == ANI_OK + && isUndefined == ANI_FALSE) { + capsule.SetBackgroundColor(backgroundColor); + } + + std::string content = ""; + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "content", isUndefined, content) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetContent(content); + } + + ani_double time = 0.0; + if(GetPropertyDouble(env, obj, "time", isUndefined, time) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetTime(static_cast(time)); + } + + ani_ref iconRef = {}; + if(GetPropertyRef(env, obj, "time", isUndefined, iconRef) == ANI_OK && isUndefined == ANI_FALSE) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap != nullptr) { + capsule.SetIcon(pixelMap); + } + } + + std::vector iconButtons = {}; + if (GetIconButtonArray(env, obj, "capsuleButtons", iconButtons) == ANI_OK && !(iconButtons.empty())) { + capsule.SetCapsuleButton(iconButtons); + } +} + +ani_object WarpNotificationIconButton(ani_env *env, const NotificationIconButton &button) +{ + ani_class iconButtonCls = nullptr; + ani_object iconButtonObject = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationIconButtonInner;", iconButtonCls, iconButtonObject)); + // name: string + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, button.GetName(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "name", stringValue)); + // text?: string; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, button.GetText(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "text", stringValue)); + // hidePanel?: boolean; + RETURN_NULL_IF_FALSE(CallSetter( + env, iconButtonCls, iconButtonObject, "hidePanel", BoolToAniBoolean(button.GetHidePanel()))); + // 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("CreatePixelMap failed, pixelMapObject is nullptr"); + return nullptr; + } + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", pixelMapObject)); + } else { + ani_object resourceObject = GetAniResource(env, button.GetIconResource()); + if (resourceObject == nullptr) { + ANS_LOGE("SetResourceObject failed, resourceObject is nullptr"); + return nullptr; + } + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", resourceObject)); + } + return iconButtonObject; +} + +ani_object GetAniIconButtonArray(ani_env *env, const std::vector buttons) +{ + if (buttons.empty()) { + return nullptr; + } + ani_object arrayObj = newArrayClass(env,buttons.size()); + ani_size index = 0; + for (auto &button : buttons) { + ani_object item = WarpNotificationIconButton(env, button); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; +} + +bool WarpNotificationCapsule(ani_env *env, const NotificationCapsule &capsule, ani_object &capsuleObject) +{ + ani_class capsuleClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationCapsuleInner;", capsuleClass, capsuleObject)); + // title?: string; + ani_string stringValue = nullptr; + if(GetAniStringByString(env, capsule.GetTitle(), stringValue)) { + CallSetter(env, capsuleClass, capsuleObject, "title", stringValue); + } + // 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 { + CallSetter(env, capsuleClass, capsuleObject, "icon", pixelMapObject); + } + } + // backgroundColor?: string; + if(GetAniStringByString(env, capsule.GetBackgroundColor(), stringValue)) { + CallSetter(env, capsuleClass, capsuleObject, "backgroundColor", stringValue); + } + //content?: string; + if(GetAniStringByString(env, capsule.GetContent(), stringValue)) { + CallSetter(env, capsuleClass, capsuleObject, "content", stringValue); + } + // time?: number; + CallSetterOptional(env, capsuleClass, capsuleObject, "time", capsule.GetTime()); + // capsuleButtons?: Array; + std::vector buttons = capsule.GetCapsuleButton(); + ani_object buttonsObjectArray = GetAniIconButtonArray(env, buttons); + if (buttonsObjectArray != nullptr) { + CallSetter(env, capsuleClass, capsuleObject, "capsuleButtons", buttonsObjectArray); + } + return true; +} + +ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, + std::shared_ptr basicContent) +{ + ANS_LOGI("UnWarpNotificationBasicContent call"); + 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) { + return ANI_INVALID_ARGS; + } + basicContent->SetTitle(title); + + std::string text; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "text", isUndefined, text)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + basicContent->SetText(text); + + std::string additionalText; + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "additionalText", isUndefined, additionalText) == ANI_OK + && isUndefined == ANI_FALSE) { + basicContent->SetAdditionalText(additionalText); + } + + ani_ref lockscreenPictureRef = {}; + if (env->Object_GetPropertyByName_Ref(obj, "lockscreenPicture", &lockscreenPictureRef)) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(lockscreenPictureRef)); + if (pixelMap != nullptr) { + basicContent->SetLockScreenPicture(pixelMap); + } + } + return status; +} + +ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, + std::shared_ptr &normalContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, normalContent)) != ANI_OK) { + return status; + } + return status; +} + +ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, + std::shared_ptr &longTextContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, longTextContent)) != ANI_OK) { + return status; + } + + ani_boolean isUndefined = ANI_TRUE; + std::string longText; + if((status = GetPropertyString(env, obj, "longText", isUndefined, longText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + longTextContent->SetLongText(longText); + + std::string briefText; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + longTextContent->SetBriefText(briefText); + + std::string expandedTitle; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + longTextContent->SetExpandedTitle(expandedTitle); + + return status; +} + +ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, + std::shared_ptr &multiLineContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, multiLineContent)) != ANI_OK) { + return status; + } + + ani_boolean isUndefined = ANI_TRUE; + std::string longTitle; + if((status = GetPropertyString(env, obj, "longTitle", isUndefined, longTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + 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) { + return ANI_INVALID_ARGS; + } + multiLineContent->SetBriefText(briefText); + + std::vector lines = {}; + isUndefined = ANI_TRUE; + if((status = GetStringArray(env, obj, "lines", isUndefined, lines)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + for(auto line : lines) { + multiLineContent->AddSingleLine(line); + } + return status; +} + +ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, + std::shared_ptr &pictureContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, pictureContent)) != ANI_OK) { + return status; + } + + std::string expandedTitle; + ani_boolean isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + pictureContent->SetExpandedTitle(expandedTitle); + + std::string briefText; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; + } + pictureContent->SetBriefText(briefText); + + ani_ref pictureRef = {}; + if ((status = env->Object_GetPropertyByName_Ref(obj, "picture", &pictureRef)) != ANI_OK) { + return status; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pictureRef)); + if (pixelMap == nullptr) { + return ANI_INVALID_ARGS; + } + pictureContent->SetBigPicture(pixelMap); + + return status; +} + +ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { + return status; + } + + ani_ref statusRef; + if((status = env->Object_GetPropertyByName_Ref(obj, "status", &statusRef)) != ANI_OK) { + return status; + } + LiveViewStatus liveViewStatus = LiveViewStatus::LIVE_VIEW_CREATE; + if(!LiveViewStatusEtsToC(env, static_cast(statusRef), liveViewStatus)) { + return ANI_INVALID_ARGS; + } + liveViewContent->SetLiveViewStatus(liveViewStatus); + + ani_double versionAni = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if (GetPropertyDouble(env, obj, "version", isUndefined, versionAni) == ANI_OK + && isUndefined == ANI_FALSE) { + liveViewContent->SetVersion(static_cast(versionAni)); + } + + ani_ref extraInfoRef; + isUndefined = ANI_TRUE; + if (ANI_OK == (status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef)) + && env->Reference_IsUndefined(extraInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + AAFwk::WantParams wantParams = {}; + if(UnwrapWantParams(env, extraInfoRef, wantParams)) { + std::shared_ptr extraInfo = std::make_shared(wantParams); + liveViewContent->SetExtraInfo(extraInfo); + } + } + + ani_ref pictureInfoRef; + isUndefined = ANI_TRUE; + if (ANI_OK == env->Object_GetPropertyByName_Ref(obj, "pictureInfo", &pictureInfoRef) + && env->Reference_IsUndefined(pictureInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + std::map>> pictureMap; + if(GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { + liveViewContent->SetPicture(pictureMap); + } + } + + bool isLocalUpdateOnly = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) + && isUndefined == ANI_FALSE) { + liveViewContent->SetIsOnlyLocalUpdate(isLocalUpdateOnly); + } + return status; +} + +ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, localLiveViewContent)) != ANI_OK) { + 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) { + return ANI_INVALID_ARGS; + } + localLiveViewContent->SetType(static_cast(typeCode)); + + ani_ref capsuleRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "capsule", &capsuleRef) == ANI_OK) { + NotificationCapsule capsule; + UnWarpNotificationCapsule(env, static_cast(capsuleRef), capsule); + localLiveViewContent->SetCapsule(capsule); + } + + ani_ref buttonRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "button", &buttonRef) == ANI_OK) { + NotificationLocalLiveViewButton button; + UnWarpNotificationLocalLiveViewButton(env, static_cast(buttonRef), button); + localLiveViewContent->SetButton(button); + } + + std::vector buttons = {}; + if(GetIconButtonArray(env, obj, "cardButtons", buttons) == ANI_OK) { + localLiveViewContent->SetCardButton(buttons); + } + + ani_ref timeRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "time", &timeRef) == ANI_OK) { + NotificationTime notificationTime; + UnWarpNotificationTime(env, static_cast(timeRef), notificationTime); + localLiveViewContent->SetTime(notificationTime); + } + + ani_ref progressRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "progress", &progressRef) == ANI_OK) { + NotificationProgress notificationProgress; + UnWarpNotificationProgress(env, static_cast(progressRef), notificationProgress); + localLiveViewContent->SetProgress(notificationProgress); + } + + ani_ref liveViewTypeRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "liveViewType", &liveViewTypeRef) == ANI_OK) { + LiveViewTypes liveViewTypes = LiveViewTypes::LIVE_VIEW_ACTIVITY; + if(LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { + localLiveViewContent->SetLiveViewType(liveViewTypes); + } + } + + return status; +} + +bool SetNotificationBasicContent( + ani_env* env, ani_class contentCls, const NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + ani_string aniStr; + if(GetAniStringByString(env, basicContent->GetTitle(), aniStr)) { + CallSetter(env, contentCls, object, "title", aniStr); + } + if(GetAniStringByString(env, basicContent->GetText(), aniStr)) { + CallSetter(env, contentCls, object, "text", aniStr); + } + if(GetAniStringByString(env, basicContent->GetAdditionalText(), aniStr)) { + CallSetter(env, contentCls, object, "additionalText", aniStr); + } + ani_object lockScreenPicObj = CreateAniPixelMap(env, basicContent->GetLockScreenPicture()); + if (lockScreenPicObj != nullptr) { + CallSetter(env, contentCls, object, "lockScreenPicture", lockScreenPicObj); + } + return true; +} + +bool SetNotificationNormalContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationBasicContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, basicContent.get(), contentObj)); + return CallSetter(env, ncCls, ncObj, "normal", contentObj); +} + +bool SetNotificationLongTextContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("enter SetNotificationLongTextContent"); + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationLongTextContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + NotificationLongTextContent *content = static_cast(basicContent.get()); + if (content == nullptr) { + ANS_LOGE("TextContent is null"); + return false; + } + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + + ani_string aniStr; + if(GetAniStringByString(env, content->GetLongText(), aniStr)) { + CallSetter(env, contentCls, contentObj, "longText", aniStr); + } + if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { + CallSetter(env, contentCls, contentObj, "briefText", aniStr); + } + if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { + CallSetter(env, contentCls, contentObj, "expandedTitle", aniStr); + } + return CallSetter(env, ncCls, ncObj, "longText", contentObj); +} + +bool SetNotificationPictureContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("enter SetNotificationPictureContent"); + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationPictureContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + NotificationPictureContent *content = static_cast(basicContent.get()); + if (content == nullptr) { + ANS_LOGE("TextContent is null"); + return false; + } + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + + ani_string aniStr; + if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { + CallSetter(env, contentCls, contentObj, "briefText", aniStr); + } + if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { + CallSetter(env, contentCls, contentObj, "expandedTitle", aniStr); + } + ani_object pictureObj = CreateAniPixelMap(env, content->GetBigPicture()); + if (pictureObj != nullptr) { + CallSetter(env, contentCls, contentObj, "picture", pictureObj); + } + return CallSetter(env, ncCls, ncObj, "picture", contentObj); +} + +bool SetNotificationMultiLineContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("enter SetNotificationMultiLineContent"); + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationMultiLineContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + NotificationMultiLineContent *content = static_cast(basicContent.get()); + if (content == nullptr) { + ANS_LOGE("Content is null"); + return false; + } + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + + ani_string aniStr; + if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { + CallSetter(env, contentCls, contentObj, "briefText", aniStr); + } + if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { + CallSetter(env, contentCls, contentObj, "longTitle", aniStr); + } + std::vector allLines = content->GetAllLines(); + ani_object allLinesObject = GetAniStringArrayByVectorString(env, allLines); + if(allLinesObject != nullptr) { + CallSetter(env, contentCls, contentObj, "lines", allLinesObject); + } + ani_object lineWantAgentsObject = GetAniWantAgentArray(env, content->GetLineWantAgents()); + if(lineWantAgentsObject != nullptr) { + CallSetter(env, contentCls, contentObj, "lineWantAgents", lineWantAgentsObject); + } + return CallSetter(env, ncCls, ncObj, "multiLine", contentObj); +} + +bool SetNotificationLocalLiveViewContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + NotificationLocalLiveViewContent *content = static_cast(basicContent.get()); + if (content == nullptr) { + ANS_LOGE("Content is null"); + return false; + } + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + + CallSetterOptional(env, contentCls, contentObj, "typeCode", content->GetType()); + + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { + ani_object capsuleObject = nullptr; + if(WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) && capsuleObject != nullptr) { + CallSetter(env, contentCls, contentObj, "capsule", capsuleObject); + } + } + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::BUTTON)) { + ani_object buttonObject = nullptr; + if(WarpNotificationLocalLiveViewButton(env, content->GetButton(), buttonObject) && buttonObject != nullptr) { + CallSetter(env, contentCls, contentObj, "button", buttonObject); + } + } + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CARD_BUTTON)) { + std::vector buttons = content->GetCardButton(); + ani_object buttonsObjectArray = GetAniIconButtonArray(env, buttons); + if (buttonsObjectArray != nullptr) { + CallSetter(env, contentCls, contentObj, "cardButtons", buttonsObjectArray); + } + } + + ani_enum_item enumItem = nullptr; + if (LiveViewTypesCToEts(env, content->GetLiveViewType(), enumItem) && enumItem != nullptr) { + CallSetter(env, contentCls, contentObj, "liveViewType", enumItem); + } + + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::PROGRESS)) { + ani_object progressObject = nullptr; + if (WarpNotificationProgress(env, content->GetProgress(), progressObject) && progressObject != nullptr) { + CallSetter(env, contentCls, contentObj, "progress", progressObject); + } + } + + 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) { + CallSetter(env, contentCls, contentObj, "time", timeObject); + } + } + return CallSetter(env, ncCls, ncObj, "systemLiveView", contentObj); +} + +bool SetNotificationLiveViewContent( + ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) +{ + ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + ani_class contentCls; + ani_object contentObj; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationLiveViewContentInner;", contentCls, contentObj)); + RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + std::shared_ptr basicContent = nContent->GetNotificationContent(); + RETURN_FALSE_IF_NULL(basicContent); + NotificationLiveViewContent *content = static_cast(basicContent.get()); + if (content == nullptr) { + ANS_LOGE("Content is null"); + return false; + } + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + + ani_object lockScreenPicObj = CreateAniPixelMap(env, content->GetLockScreenPicture()); + if (lockScreenPicObj != nullptr) { + CallSetter(env, contentCls, contentObj, "lockScreenPicture", lockScreenPicObj); + } + ani_enum_item enumItem = nullptr; + if(LiveViewStatusCToEts(env, content->GetLiveViewStatus(), enumItem) && enumItem != nullptr) { + CallSetter(env, contentCls, contentObj, "status", enumItem); + } + CallSetterOptional(env, contentCls, contentObj, "version", static_cast(content->GetVersion())); + std::shared_ptr extraInfoData = content->GetExtraInfo(); + if (extraInfoData != nullptr) { + ani_ref extraInfoObj = WrapWantParams(env, *extraInfoData); + if (extraInfoObj != nullptr) { + CallSetter(env, contentCls, contentObj, "extraInfo", extraInfoObj); + } + } + ani_object pictureInfoObj = nullptr; + if (GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) && pictureInfoObj != nullptr) { + CallSetter(env, contentCls, contentObj, "pictureInfo", pictureInfoObj); + } + return CallSetter(env, ncCls, ncObj, "liveView", contentObj); +} + +bool SetNotificationContent(ani_env* env, std::shared_ptr ncContent, ani_object &ncObj) +{ + ani_class ncCls; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationContentInner;", ncCls, ncObj)); + // notificationContentType?: notificationManager.ContentType; + ContentType contentType = ncContent->GetContentType(); + ani_enum_item contentTypeItem {}; + RETURN_FALSE_IF_FALSE(ContentTypeCToEts(env, contentType, contentTypeItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, ncCls, ncObj, "notificationContentType", contentTypeItem)); + switch (contentType) { + case ContentType::BASIC_TEXT: // normal?: NotificationBasicContent + return SetNotificationNormalContent(env, ncCls, ncContent, ncObj); + case ContentType::LONG_TEXT: // longText?: NotificationLongTextContent + return SetNotificationLongTextContent(env, ncCls, ncContent, ncObj); + case ContentType::PICTURE: // picture?: NotificationPictureContent + return SetNotificationPictureContent(env, ncCls, ncContent, ncObj); + // need to do + //case ContentType::CONVERSATION: // conversation?: NotificationConversationalContent + //ret = SetNotificationConversationalContent(env, basicContent.get(), contentResult); + // break; + case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent + return SetNotificationMultiLineContent(env, ncCls, ncContent, ncObj); + case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent + return SetNotificationLocalLiveViewContent(env, ncCls, ncContent, ncObj); + break; + case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent +// RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, +// "Lnotification/notificationContent/NotificationLiveViewContentInner;", clsContent, aniContext)); +// RETURN_FALSE_IF_NULL(clsContent); +// RETURN_FALSE_IF_NULL(aniContext); +// RETURN_FALSE_IF_FALSE(SetNotificationLiveViewContent(env, clsContent, basicContent.get(), aniContext)); +// RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "liveView", aniContext)); + break; + default: + ANS_LOGE("ContentType is does not exist"); + return false; + } + return true; +} + +} // 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 000000000..7a3791b16 --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -0,0 +1,50 @@ +/* + * 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) +{ + if (flags == nullptr) { + ANS_LOGE("flags is null"); + return false; + } + + ani_class flagsCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationFlags/NotificationFlagsInner;", flagsCls, flagsObject)); + // readonly soundEnabled?: NotificationFlagStatus; + int32_t soundEnabled = static_cast(flags->IsSoundEnabled()); + ani_enum_item enumItem = nullptr; + RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + soundEnabled, enumItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "soundEnabled", enumItem)); + // readonly vibrationEnabled?: NotificationFlagStatus; + int32_t vibrationEnabled = static_cast(flags->IsVibrationEnabled()); + RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + vibrationEnabled, enumItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "vibrationEnabled", enumItem)); + // readonly reminderFlags?: number; + uint32_t reminderFlags = flags->GetReminderFlags(); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, flagsCls, flagsObject, "reminderFlags", reminderFlags)); + 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 000000000..a5e915ff1 --- /dev/null +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -0,0 +1,371 @@ +/* + * 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" + +namespace OHOS { +namespace NotificationSts { +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; +} + +StsNotificationLocalLiveViewSubscriber::StsNotificationLocalLiveViewSubscriber() +{} + +StsNotificationLocalLiveViewSubscriber::~StsNotificationLocalLiveViewSubscriber() +{} + +void StsNotificationLocalLiveViewSubscriber::OnConnected() +{} + +void StsNotificationLocalLiveViewSubscriber::OnDisconnected() +{} + +void StsNotificationLocalLiveViewSubscriber::OnDied() +{} + +void StsNotificationLocalLiveViewSubscriber::OnResponse(int32_t notificationId, sptr buttonOption) +{ + 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; + status = env->Object_GetPropertyByName_Ref(stsSubscriberObj, functionName.c_str(), &funRef); + if (status != ANI_OK) { + 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_LOGD("FunctionalObject_Call failed, status: %{public}d", status); + return; + } +} + +void StsNotificationLocalLiveViewSubscriber::SetStsNotificationLocalLiveViewSubscriber( + ani_env *env, ani_object &localLiveViewSubscriberObj) +{ + if (env == nullptr) { + return; + } + stsSubscriber_ = std::make_unique(); + ani_ref objRef = nullptr; + if (env->GlobalReference_Create(localLiveViewSubscriberObj, &objRef) != ANI_OK) { + return; + } + + ani_vm *aniVM = nullptr; + if (env->GetVM(&aniVM) != ANI_OK) { + return; + } + vm_ = aniVM; + if (stsSubscriber_ == nullptr) { + return; + } + stsSubscriber_->aniObj = localLiveViewSubscriberObj; + stsSubscriber_->aniRef = objRef; +} + +ani_env* StsNotificationLocalLiveViewSubscriber::GetAniEnv() +{ + if (vm_ == nullptr) { + return nullptr; + } + ani_env* aniEnv = nullptr; + if (vm_->GetEnv(ANI_VERSION_1, &aniEnv) != ANI_OK) { + return nullptr; + } + return aniEnv; +} + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType) +{ + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + EnumConvertAniToNative(env, enumItem, stsSlotType); + StsSlotTypeUtils::StsToC(stsSlotType, slotType); + return true; +} + +bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem) +{ + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + StsSlotTypeUtils::CToSts(slotType, stsSlotType); + EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/#SlotType;", stsSlotType, enumItem); + return true; +} + +bool SlotLevelEtsToC(ani_env *env, ani_enum_item enumItem, SlotLevel &slotLevel) +{ + STSSlotLevel stsSlotLevel = STSSlotLevel::LEVEL_NONE; + EnumConvertAniToNative(env, enumItem, stsSlotLevel); + StsSlotLevelUtils::StsToC(stsSlotLevel, slotLevel); + return true; +} +bool SlotLevelCToEts(ani_env *env, SlotLevel slotLevel, ani_enum_item &enumItem) +{ + STSSlotLevel stsSlotLevel = STSSlotLevel::LEVEL_NONE; + StsSlotLevelUtils::CToSts(slotLevel, stsSlotLevel); + EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/#SlotLevel;", stsSlotLevel, enumItem); + return true; +} + +bool ContentTypeEtsToC(ani_env *env, ani_enum_item enumItem, ContentType &contentType) +{ + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + if(EnumConvertAniToNative(env, enumItem, stsContentType)) { + StsContentTypeUtils::StsToC(stsContentType, contentType); + return true; + } + return false; +} + +bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enumItem) +{ + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + StsContentTypeUtils::CToSts(contentType, stsContentType); + if(EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/#ContentType", stsContentType, enumItem)) { + return true; + } + return false; +} + +ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonOptionObj, + ButtonOption &buttonOption) +{ + 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) { + return ANI_INVALID_ARGS; + } + buttonOption.SetButtonName(buttonName); + return status; +} + +ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption) +{ + if (buttonOption == nullptr) { + ANS_LOGE("buttonOption is null"); + return nullptr; + } + ani_object optObj = nullptr; + ani_class optCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "L@ohos/notificationManager/notificationManager/ButtonOptionsInner;", optCls, optObj)); + // title: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, buttonOption->GetButtonName(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, optCls, optObj, "buttonName", stringValue)); + return optObj; +} +} // namespace NotificationSts +} // OHOS diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp new file mode 100644 index 000000000..3ba390d32 --- /dev/null +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -0,0 +1,947 @@ +/* + * 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 "want_params.h" +#include "ani_common_want.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions) +{ + bool isDistributed = false; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isDistributed", isUndefined, isDistributed) + && isUndefined == ANI_FALSE) { + distributedOptions.isDistributed = isDistributed; + } + + std::vector supportDisplayDevices = {}; + isUndefined = ANI_TRUE; + if(GetStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK + && isUndefined == ANI_FALSE) { + distributedOptions.supportDisplayDevices = supportDisplayDevices; + } + + std::vector supportOperateDevices = {}; + isUndefined = ANI_TRUE; + if(GetStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK + && isUndefined == ANI_FALSE) { + distributedOptions.supportOperateDevices = supportOperateDevices; + } + + 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); + } +} + +bool WarpNotificationUnifiedGroupInfo(ani_env* env, + const std::shared_ptr &groupInfo, ani_object &groupInfoObject) +{ + if (groupInfo == nullptr) { + ANS_LOGE("groupInfo is null"); + return false; + } + ani_class groupInfoCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)); + // key?: string; + ani_string stringValue = nullptr; + if (GetAniStringByString(env, groupInfo->GetKey(), stringValue)) { + CallSetter(env, groupInfoCls, groupInfoObject, "key", stringValue); + } + // title?: string; + if (GetAniStringByString(env, groupInfo->GetTitle(), stringValue)) { + CallSetter(env, groupInfoCls, groupInfoObject, "title", stringValue); + } + // content?: string; + if (GetAniStringByString(env, groupInfo->GetContent(), stringValue)) { + CallSetter(env, groupInfoCls, groupInfoObject, "content", stringValue); + } + // sceneName?: string; + if (GetAniStringByString(env, groupInfo->GetSceneName(), stringValue)) { + CallSetter(env, groupInfoCls, groupInfoObject, "sceneName", stringValue); + } + // extraInfo?: Record; + std::shared_ptr extraInfo = groupInfo->GetExtraInfo(); + if (extraInfo) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *extraInfo); + CallSetter(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef); + } + return true; +} + +void GetNotificationRequestByBooleanOne(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + + if(ANI_OK == GetPropertyBool(env, obj, "isOngoing", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetInProgress(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isUnremovable", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUnremovable(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "updateOnly", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUpdateOnly(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "tapDismissed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetTapDismissed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "colorEnabled", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetColorEnabled(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isAlertOnce", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetAlertOneTime(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isStopwatch", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowStopwatch(mbool); + } +} + +void GetNotificationRequestByBooleanTwo(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetCountdownTimer(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isFloatingIcon", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetFloatingIcon(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "showDeliveryTime", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowDeliveryTime(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "isRemoveAllowed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetRemoveAllowed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "forceDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetForceDistributed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBool(env, obj, "notDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetNotDistributed(mbool); + } +} + +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) { + std::string mString = ""; + ani_boolean isUndefined = ANI_TRUE; + + if (ANI_OK == GetPropertyString(env, obj, "classification", isUndefined, mString) && isUndefined == ANI_FALSE) { + 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) { + request->SetLabel(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "groupName", isUndefined, mString) && isUndefined == ANI_FALSE) { + request->SetGroupName(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "sound", isUndefined, mString) && isUndefined == ANI_FALSE) { + request->SetSound(mString); + } +} + +void GetNotificationRequestByNumber(ani_env *env, ani_object obj, + std::shared_ptr &request) { + 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)); + } +} + +bool GetNotificationNormalContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "normal", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr normalContent = std::make_shared(); + UnWarpNotificationNormalContent(env, static_cast(contentRef), normalContent); + request->SetContent(std::make_shared(normalContent)); + return true; +} + +bool GetNotificationLongTextContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "longText", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr longTextContent + = std::make_shared(); + UnWarpNotificationLongTextContent(env, static_cast(contentRef), longTextContent); + request->SetContent(std::make_shared(longTextContent)); + return true; +} + +bool GetNotificationPictureContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "picture", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr pictureContent + = std::make_shared(); + UnWarpNotificationPictureContent(env, static_cast(contentRef), pictureContent); + request->SetContent(std::make_shared(pictureContent)); + return true; +} + +bool GetNotificationMultiLineContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "multiLine", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr multiLineContent + = std::make_shared(); + UnWarpNotificationMultiLineContent(env, static_cast(contentRef), multiLineContent); + request->SetContent(std::make_shared(multiLineContent)); + return true; +} + +bool GetNotificationLocalLiveViewContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "systemLiveView", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr localLiveView + = std::make_shared(); + UnWarpNotificationLocalLiveViewContent(env, static_cast(contentRef), localLiveView); + request->SetContent(std::make_shared(localLiveView)); + return true; +} + +bool GetNotificationLiveViewContent(ani_env *env, ani_object obj, ani_ref contentRef, + std::shared_ptr &request) +{ + if(env->Object_GetPropertyByName_Ref(obj, "liveView", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr liveViewContent + = std::make_shared(); + UnWarpNotificationLiveViewContent(env, static_cast(contentRef), liveViewContent); + request->SetContent(std::make_shared(liveViewContent)); + return true; +} + +bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, + std::shared_ptr &request) +{ + ani_ref contentRef = {}; + switch (outType) { + case ContentType::BASIC_TEXT: + return GetNotificationNormalContent(env, obj, contentRef, request); + case ContentType::LONG_TEXT: + return GetNotificationLongTextContent(env, obj, contentRef, request); + case ContentType::PICTURE: + return GetNotificationPictureContent(env, obj, contentRef, request); + case ContentType::MULTILINE: + return GetNotificationMultiLineContent(env, obj, contentRef, request); + case ContentType::LOCAL_LIVE_VIEW: + return GetNotificationLocalLiveViewContent(env, obj, contentRef, request); + case ContentType::LIVE_VIEW: + return GetNotificationLiveViewContent(env, obj, contentRef, request); + case ContentType::CONVERSATION: + // need to add + break; + default: + break; + } + return true; +} + +ani_status GetNotificationContent(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref notificationContentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "content", ¬ificationContentRef))!= ANI_OK) { + return status; + } + ani_ref contentTypeRef; + if((status = env->Object_GetPropertyByName_Ref(static_cast(notificationContentRef), + "notificationContentType", &contentTypeRef)) != ANI_OK) { + return status; + } + ani_boolean isUndefined = ANI_TRUE; + if ((status = env->Reference_IsUndefined(contentTypeRef, &isUndefined)) != ANI_OK) { + return status; + } + if (isUndefined == ANI_TRUE) { + return ANI_INCORRECT_REF; + } + ContentType type; + if(!ContentTypeEtsToC(env, static_cast(contentTypeRef), type)) { + return ANI_INVALID_ARGS; + } + + if(!GetNotificationContent(env, static_cast(notificationContentRef), type, request)) { + return ANI_INVALID_ARGS; + } + return status; +} + +void GetNotificationSlotType(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref slotTypeRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "notificationSlotType", &slotTypeRef))!= ANI_OK) { + return; + } + SlotType type = SlotType::OTHER; + if(!SlotTypeEtsToC(env, static_cast(slotTypeRef), type)) { + return; + } + request->SetSlotType(type); +} + +void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref wantAgentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "wantAgent", &wantAgentRef))!= ANI_OK) { + return; + } + WantAgent* pWantAgent = nullptr; + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + if (pWantAgent == nullptr) { + return; + } + + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + request->SetWantAgent(wantAgent); +} + +void GetNotificationExtraInfo(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref extraInfoRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + WantParams wantParams = {}; + if ((status = env->Reference_IsUndefined(extraInfoRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + 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_status status = ANI_ERROR; + ani_ref wantAgentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "removalWantAgent", &wantAgentRef))!= ANI_OK) { + return; + } + WantAgent* pWantAgent = nullptr; + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + if (pWantAgent == nullptr) { + return; + } + + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + 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_status status = ANI_ERROR; + ani_ref smallIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "smallIcon", &smallIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(smallIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + 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_status status = ANI_ERROR; + ani_ref largeIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "largeIcon", &largeIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(largeIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + 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_status status = ANI_ERROR; + ani_ref overlayIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "overlayIcon", &overlayIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(overlayIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + 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, "distributedOptionRef", 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, "template", 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) { + 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); +// // need to do GetNotificationMaxScreenWantAgent 没看明白 +// /* +// // maxScreenWantAgent?: WantAgent +// if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { +// return nullptr; +// } +// */ + + return status; +} + +ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest) +{ + ani_status status = ANI_ERROR; + GetNotificationRequestByNumber(env, obj, notificationRequest); + GetNotificationRequestByString(env, obj, notificationRequest); + GetNotificationRequestByBoolean(env, obj, notificationRequest); + status = GetNotificationRequestByCustom(env, obj, notificationRequest); + return status; +} + +bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // isOngoing?: boolean + CallSetter(env, cls, object, "isOngoing", BoolToAniBoolean(request->IsInProgress())); + // isUnremovable?: boolean + CallSetter(env, cls, object, "isUnremovable", BoolToAniBoolean(request->IsUnremovable())); + // tapDismissed?: boolean + CallSetter(env, cls, object, "tapDismissed", BoolToAniBoolean(request->IsTapDismissed())); + // colorEnabled?: boolean + CallSetter(env, cls, object, "colorEnabled", BoolToAniBoolean(request->IsColorEnabled())); + // isAlertOnce?: boolean + CallSetter(env, cls, object, "isAlertOnce", BoolToAniBoolean(request->IsAlertOneTime())); + // isStopwatch?: boolean + CallSetter(env, cls, object, "isStopwatch", BoolToAniBoolean(request->IsShowStopwatch())); + // isCountDown?: boolean + CallSetter(env, cls, object, "isCountDown", BoolToAniBoolean(request->IsCountdownTimer())); + // isFloatingIcon?: boolean + CallSetter(env, cls, object, "isFloatingIcon", BoolToAniBoolean(request->IsFloatingIcon())); + // showDeliveryTime?: boolean + CallSetter(env, cls, object, "showDeliveryTime", BoolToAniBoolean(request->IsShowDeliveryTime())); + // updateOnly?: boolean + CallSetter(env, cls, object, "updateOnly", BoolToAniBoolean(request->IsUpdateOnly())); + 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; + } + ani_string stringValue = nullptr; + // classification?: string + if (GetAniStringByString(env, request->GetClassification(), stringValue)) { + CallSetter(env, cls, object, "classification", stringValue); + } + // need to do ets中没有找到statusBarText属性 + // statusBarText?: string + // if (StringToAniStr(env, request->GetStatusBarText(), stringValue)) { + // RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, STATUS_BAR_TEXT, stringValue)); + // } + // label?: string + if (GetAniStringByString(env, request->GetLabel(), stringValue)) { + CallSetter(env, cls, object, "label", stringValue); + } + // groupName?: string + if (GetAniStringByString(env, request->GetGroupName(), stringValue)) { + CallSetter(env, cls, object, "groupName", stringValue); + } + // readonly creatorBundleName?: string + if (GetAniStringByString(env, request->GetCreatorBundleName(), stringValue)) { + CallSetter(env, cls, object, "creatorBundleName", stringValue); + } + // readonly sound?: string + if (GetAniStringByString(env, request->GetSound(), stringValue)) { + CallSetter(env, cls, object, "sound", stringValue); + } + // readonly appInstanceKey?: string + if (GetAniStringByString(env, request->GetAppInstanceKey(), stringValue)) { + CallSetter(env, cls, object, "appInstanceKey", stringValue); + } + 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 + CallSetterOptional(env, cls, object, "id", request->GetNotificationId()); + // slotType?: SlotType + ani_enum_item slotTypeItem {}; + if(SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { + CallSetter(env, cls, object, "slotType", slotTypeItem); + } + + // deliveryTime?: number + CallSetterOptional(env, cls, object, "deliveryTime", request->GetDeliveryTime()); + // autoDeletedTime?: number + CallSetterOptional(env, cls, object, "autoDeletedTime", request->GetAutoDeletedTime()); + // color ?: number + CallSetterOptional(env, cls, object, "color", request->GetColor()); + // badgeIconStyle ?: number + CallSetterOptional(env, cls, object, "badgeIconStyle", + static_cast(request->GetBadgeIconStyle())); + // readonly creatorUid?: number + CallSetterOptional(env, cls, object, "creatorUid", request->GetCreatorUid()); + // readonly creatorPid?: number + CallSetterOptional(env, cls, object, "creatorPid", request->GetCreatorPid()); + // badgeNumber?: number + CallSetterOptional(env, cls, object, "badgeNumber", request->GetBadgeNumber()); + // readonly creatorInstanceKey?: number + CallSetterOptional(env, cls, 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()); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "wantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "wantAgent")); + } + // removalWantAgent?: WantAgent + std::shared_ptr removalAgent = request->GetRemovalWantAgent(); + if (removalAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, removalAgent.get()); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "removalWantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "removalWantAgent")); + } + // maxScreenWantAgent?: WantAgent + std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); + if (maxScreenAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, maxScreenAgent.get()); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "maxScreenWantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "maxScreenWantAgent")); + } + 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) { + ANS_LOGE("CreatePixelMap failed,, smallIconResult is nullptr "); + return false; + } + CallSetter(env, cls, object, "smallIcon", smallIconResult); + } + // largeIcon?: image.PixelMap + std::shared_ptr largeIcon = request->GetBigIcon(); + if (largeIcon) { + ani_object largeIconResult = CreateAniPixelMap(env, largeIcon); + if (largeIconResult == nullptr) { + ANS_LOGE("CreatePixelMap failed, largeIconResult is nullptr"); + return false; + } + CallSetter(env, cls, object, "largeIcon", largeIconResult); + } + // overlayIcon?: image.PixelMap + std::shared_ptr overlayIcon = request->GetOverlayIcon(); + if (overlayIcon) { + ani_object overlayIconResult = CreateAniPixelMap(env, overlayIcon); + if (overlayIconResult == nullptr) { + ANS_LOGE("CreatePixelMap failed, overlayIconResult is nullptr"); + return false; + } + CallSetter(env, cls, object, "overlayIcon", overlayIconResult); + } + 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; + RETURN_FALSE_IF_FALSE(SetNotificationContent(env, content, contentObj)); + RETURN_FALSE_IF_FALSE(contentObj == nullptr); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "content", contentObj)); + 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 + RETURN_FALSE_IF_FALSE(SetNotificationRequestByNotificationContent(env, cls, request, object)); + // extraInfo?: {[key:string] : any} + std::shared_ptr additionalData = request->GetAdditionalData(); + if (additionalData) { + ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "extraInfo", extraInfo)); + } + + // actionButtons?: Array + std::vector> actionButtons = request->GetActionButtons(); + ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); + if (actionButtonsArrayObj != nullptr) { + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "actionButtons", actionButtonsArrayObj)); + } + // template?: NotificationTemplate + std::shared_ptr templ = request->GetTemplate(); + if (templ) { + ani_object templateObject = WrapNotificationTemplate(env, templ); + if (templateObject != nullptr) { + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "template", templateObject)); + } + } + // readonly notificationFlags?: NotificationFlags + std::shared_ptr flags = request->GetFlags(); + if (flags) { + ani_object flagsObject = nullptr; + if (WarpNotificationFlags(env, flags, flagsObject) && flagsObject != nullptr) { + CallSetter(env, cls, object, "notificationFlags", flagsObject); + } + } + // readonly agentBundle?: agentBundle + std::shared_ptr agentBundle = request->GetAgentBundle(); + if (agentBundle) { + ani_object agentBundleObject = nullptr; + if (WrapBundleOption(env, agentBundle, agentBundleObject) && agentBundleObject != nullptr) { + CallSetter(env, cls, object, "agentBundle", agentBundleObject); + } + } + // unifiedGroupInfo?: unifiedGroupInfo + std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); + if (groupInfo) { + ani_object infoObject = nullptr; + if(WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) && infoObject != nullptr) { + CallSetter(env, cls, object, "unifiedGroupInfo", infoObject); + } + } + return true; +} + +bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::NotificationRequest *notificationRequest, + ani_class &cls, ani_object &outAniObj) +{ + if (notificationRequest == nullptr) { + ANS_LOGE("notification is null"); + return false; + } + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)); + RETURN_FALSE_IF_FALSE(SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)); + return true; +} + +ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests) +{ + if (requests.empty()) { + ANS_LOGE("actionButtons is empty"); + return nullptr; + } + 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; + RETURN_NULL_IF_FALSE(WarpNotificationRequest(env, request.GetRefPtr(), requestCls, requestObj)); + RETURN_NULL_IF_NULL(requestObj); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; +} +} // 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 000000000..9db1901bf --- /dev/null +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -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. + */ +#include "sts_slot.h" + +#include "sts_notification_manager.h" +#include "sts_common.h" + +namespace OHOS { +namespace NotificationSts { +bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, + const SlotType value) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + 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 WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlot call"); + if (slot == nullptr) { + ANS_LOGE("slot is null"); + return false; + } + ani_class cls; + if (!CreateClassObjByClassName(env, NOTIFICATION_SOLT_CLASSNAME, cls, outAniObj)) { + ANS_LOGE("CreateClassObjByClassName fail"); + return false; + } + if (!SetOptionalFieldSlotType(env, cls, outAniObj, "notificationType", slot->GetType())) { + ANS_LOGE("Set notificationType fail"); + return false; + } + if (!SetFieldString(env, cls, outAniObj, "desc", slot->GetDescription())) { + ANS_LOGE("Set desc fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "badgeFlag", slot->IsShowBadge())) { + ANS_LOGE("Set badgeFlag fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "bypassDnd", slot->IsEnableBypassDnd())) { + ANS_LOGE("Set bypassDnd fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "lockscreenVisibility", + static_cast(slot->GetLockScreenVisibleness()))) { + ANS_LOGE("Set lockscreenVisibility fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "vibrationEnabled", slot->CanVibrate())) { + ANS_LOGE("Set vibrationEnabled fail"); + return false; + } + if (!SetFieldString(env, cls, outAniObj, "sound", slot->GetSound().ToString().c_str())) { + ANS_LOGE("Set sound fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "lightEnabled", slot->CanEnableLight())) { + ANS_LOGE("Set lightEnabled fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "lightColor", static_cast(slot->GetLedLightColor()))) { + ANS_LOGE("Set lightColor fail"); + return false; + } + if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) + { + ANS_LOGE("Set vibrationValues fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "enabled", slot->GetEnable())) { + ANS_LOGE("Set enabled fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "reminderMode", static_cast(slot->GetReminderMode()))) { + ANS_LOGE("Set reminderMode fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "authorizedStatus", + static_cast(slot->GetAuthorizedStatus()))) { + ANS_LOGE("Set authorizedStatus fail"); + return false; + } + ANS_LOGD("WrapNotificationSlot end"); + return true; +} + +bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, + const SlotLevel value) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + 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 WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, + ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlotArray call"); + if (slots.empty()) { + ANS_LOGD("slots is empty"); + return false; + } + 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)) { + ANS_LOGE("WrapNotificationSlot Faild. index = %{public}d", index); + return false; + } + ANI_FAILED_AND_RETURN(env->Object_CallMethodByName_Void(outAniObj, + "$_set", "ILstd/core/Object;:V", index, infoObj)); + index++; + } + + ANS_LOGD("WrapNotificationSlotArray end"); + 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 000000000..33092a9de --- /dev/null +++ b/frameworks/ets/ani/src/sts_template.cpp @@ -0,0 +1,74 @@ +/* + * 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) +{ + ani_status status = ANI_ERROR; + ani_ref nameRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(aniObj, "name",":Lstd/core/String;", &nameRef))) { + return status; + } + std::string nameStr = ""; + if (ANI_OK != (status = GetStringByAniString(env, static_cast(nameRef), nameStr))) { + return status; + } + ani_ref dataRef; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(aniObj, "data", &dataRef))) { + return status; + } + WantParams wantParams; + if(!UnwrapWantParams(env, dataRef, wantParams)) { + 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) { + ANS_LOGE("templ is null"); + return nullptr; + } + ani_object templateObject = nullptr; + ani_class templateCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationTemplate/NotificationTemplateInner;", templateCls, templateObject)); + // name: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, templ->GetTemplateName(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, templateCls, templateObject, "name", stringValue)); + // data: Record; + std::shared_ptr data = templ->GetTemplateData(); + if (data) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *data); + RETURN_NULL_IF_FALSE(CallSetter(env, templateCls, templateObject, "data", valueRef)); + } + 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 000000000..beeddbab0 --- /dev/null +++ b/frameworks/ets/ani/src/sts_user_input.cpp @@ -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. + */ +#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) +{ + 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) { + return ANI_INVALID_ARGS; + } + userInput = Notification::NotificationUserInput::Create(inputKey); + return status; +} + +ani_object WarpUserInput(ani_env *env, std::shared_ptr userInput) +{ + ani_class userInputCls = nullptr; + ani_object userInputObject = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationUserInput/NotificationUserInputInner;", userInputCls, userInputObject)); + ani_string stringValue; + RETURN_NULL_IF_FALSE(GetAniStringByString(env, userInput->GetInputKey(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, userInputCls, userInputObject, "inputKey", stringValue)); + return userInputObject; +} +} +} diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets new file mode 100644 index 000000000..e2b40bf45 --- /dev/null +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -0,0 +1,473 @@ +/* + * 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'; + +type ResolveCallback = (data: T) => void; +type RejectCallback = (err: Object) => void; + +export default namespace notificationManager { + loadLibrary("notification_manager_ani_kit.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 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 native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; + export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; + export native function nativeGetActiveNotificationCount(): number; + export native function nativeIsNotificationEnabled(userId?: number, bundleOption?: BundleOption): boolean; + export native function nativegetSlotFlagsByBundle(bundle: BundleOption): int; + export native function nativesetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; + export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; + export native function nativeisNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; + export native function nativeCancelWithId(id: number): void; + export native function nativeCancelWithIdLabel(id: number, label: string): void; + export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; + export native function nativeCancelAll(): void; + export native function nativeGetSlotsByBundle(bundle: BundleOption): Array; + export native function nativeaddDoNotDisturbProfile(templates: Array): void; + export native function nativeremoveDoNotDisturbProfile(templates: Array): void; + export native function nativeSetNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): void; + export native function nativeSetNotificationEnableSlotByOld(bundle: BundleOption, type: SlotType, enable: boolean): void; + + export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + 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: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + export function displayBadge(bundle: BundleOption, enable: boolean): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { + 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: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } + + export function isBadgeDisplayed(bundle: BundleOption): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + 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:Object): void => { + reject(err); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(userId: number, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + 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 isNotificationEnabled(userId: number): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + 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 isNotificationEnabled(bundleOption: BundleOption): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + 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 isNotificationEnabled(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlotFlagsByBundle(bundle: BundleOption): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise + { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function cancel(id: number, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function cancel(id: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label: string): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label: string, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function cancel(bundle: BundleOption, id: number): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAll(callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { + 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: Object): void => { + let slots : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, slots); + }) + } + + export function getSlotsByBundle(bundle: BundleOption): Promise> { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addDoNotDisturbProfile(templates: Array): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeDoNotDisturbProfile(templates: Array): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void + { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotByOld(bundle, type, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void + { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } +} diff --git a/frameworks/ets/ets/BUILD.gn b/frameworks/ets/ets/BUILD.gn new file mode 100644 index 000000000..85071d4b2 --- /dev/null +++ b/frameworks/ets/ets/BUILD.gn @@ -0,0 +1,247 @@ +# 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/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 + +group("ets_files") { + deps = [ + ":notification_user_input_abc", + ":notification_user_input_etc", + ":notification_template_abc", + ":notification_template_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", + ] +} \ 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 000000000..df9b94892 --- /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 000000000..509e4a494 --- /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 { + + title: string = ""; + + wantAgent: WantAgent = {}; + + extras?: Record | undefined; + + 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 000000000..78d12b8b3 --- /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 { + + title: string = ""; + + text: string = ""; + + additionalText?: string | undefined; + + lockscreenPicture?: image.PixelMap | undefined; +} + +export interface NotificationLongTextContent extends NotificationBasicContent { + + longText: string; + + briefText: string; + + expandedTitle: string; +} + +class NotificationLongTextContentInner implements NotificationLongTextContent { + + title: string = ""; + + text: string = ""; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap | undefined; + + longText: string = ""; + + briefText: string = ""; + + 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 { + + title: string = ""; + + text: string = ""; + + additionalText?: string | undefined; + + lockscreenPicture?: image.PixelMap | undefined; + + status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; + + version?: number | undefined; + + extraInfo?: Record | undefined; + + pictureInfo?: Record> | undefined; + + isLocalUpdateOnly?: boolean | undefined; +} + +export interface NotificationMultiLineContent extends NotificationBasicContent { + + briefText: string; + + longTitle: string; + + lines: Array; +} + +class NotificationMultiLineContentInner implements NotificationMultiLineContent { + + title: string = ""; + + text: string = ""; + + additionalText?: string | undefined; + + lockscreenPicture?: image.PixelMap | undefined; + + briefText: string = ""; + + longTitle: string = ""; + + 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); + } + + title: string = ""; + + text: string = ""; + + additionalText?: string | undefined; + + lockscreenPicture?: image.PixelMap | undefined; + + briefText: string = ""; + + expandedTitle: string = ""; + + 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); + } + + title: string = ""; + + text: string = ""; + + additionalText?: string | undefined; + + lockscreenPicture?: image.PixelMap | undefined; + + briefText: string = ""; + + expandedTitle: string = ""; + + picture: image.PixelMap = this.CreatePixelMap(); + + typeCode: number = 0; + + capsule?: NotificationCapsule | undefined; + + button?: NotificationButton | undefined; + + cardButtons?: Array | undefined; + + time?: NotificationTime | undefined; + + progress?: NotificationProgress | undefined; + + liveViewType?: LiveViewTypes | undefined; +} + +export interface NotificationCapsule { + + title?: string; + + icon?: image.PixelMap; + + backgroundColor?: string; + + content?: string; + + time?: number; + + capsuleButtons?: Array; +} + +class NotificationCapsuleInner implements NotificationCapsule { + + title?: string | undefined; + + icon?: image.PixelMap | undefined; + + backgroundColor?: string | undefined; + + content?: string | undefined; + + time?: number | undefined; + + 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); + } + + name: string = ""; + + iconResource: IconType = this.CreatePixelMap(); + + text?: string | undefined; + + hidePanel?: boolean | undefined; +} + +export interface NotificationButton { + + names?: Array; + + icons?: Array; + + iconsResource?: Array; +} + +class NotificationButtonInner implements NotificationButton { + + names?: Array | undefined; + + icons?: Array | undefined; + + iconsResource?: Array | undefined; +} + +export interface NotificationTime { + + initialTime?: number; + + isCountDown?: boolean; + + isPaused?: boolean; + + isInTitle?: boolean; +} + +class NotificationTimeInner implements NotificationTime { + + initialTime?: number; + + isCountDown?: boolean; + + isPaused?: boolean; + + isInTitle?: boolean; +} + +export interface NotificationProgress { + + maxValue?: number; + + currentValue?: number; + + isPercentage?: boolean; +} + +class NotificationProgressInner implements NotificationProgress { + + maxValue?: number | undefined; + + currentValue?: number | undefined; + + 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 { + + notificationContentType?: notificationManager.ContentType | undefined; + + normal?: NotificationBasicContent | undefined; + + longText?: NotificationLongTextContent | undefined; + + multiLine?: NotificationMultiLineContent | undefined; + + picture?: NotificationPictureContent | undefined; + + systemLiveView?: NotificationSystemLiveViewContent | undefined; + + 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 000000000..e5480471a --- /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 { + + soundEnabled?: NotificationFlagStatus | undefined; + + vibrationEnabled?: NotificationFlagStatus| undefined; + + 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 000000000..493450a41 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationRequest.ets @@ -0,0 +1,181 @@ +/* + * 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 { + isDistributed?: boolean | undefined; + supportDisplayDevices?: Array | undefined; + supportOperateDevices?: Array | undefined; + readonly remindType?: number | undefined; +} + +export interface NotificationFilter { + bundle: BundleOption; + notificationKey: notificationSubscribe.NotificationKey; + extraInfoKeys?: Array; +} + +class NotificationFilterInner implements NotificationFilter { + bundle: BundleOption = {}; + notificationKey: notificationSubscribe.NotificationKey = {}; + extraInfoKeys?: Array | undefined; +} + +export interface NotificationCheckRequest { + contentType: notificationManager.ContentType; + slotType: notificationManager.SlotType; + extraInfoKeys: Array; +} + +class NotificationCheckRequestInner implements NotificationCheckRequest { + contentType: notificationManager.ContentType = notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + slotType: notificationManager.SlotType = notificationManager.SlotType.OTHER_TYPES; + extraInfoKeys: Array = {}; +} + +export interface UnifiedGroupInfo { + key?: string; + title?: string; + content?: string; + sceneName?: string; + extraInfo?: Record; +} + +class UnifiedGroupInfoInner implements UnifiedGroupInfo { + key?: string | undefined; + title?: string | undefined; + content?: string | undefined; + sceneName?: string | undefined; + 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; + readonly creatorInstanceKey?: 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 { + content: NotificationContent = {}; + id?: number | undefined; + appMessageId?: string | undefined; + notificationSlotType?: notificationManager.SlotType | undefined; + isOngoing?: boolean | undefined; + isUnremovable?: boolean | undefined; + updateOnly?: boolean | undefined; + deliveryTime?: number | undefined; + tapDismissed?: boolean | undefined; + autoDeletedTime?: number | undefined; + wantAgent?: WantAgent | undefined; + extraInfo?: Record | undefined; + color?: number | undefined; + colorEnabled?: boolean | undefined; + isAlertOnce?: boolean | undefined; + isStopwatch?: boolean | undefined; + isCountDown?: boolean | undefined; + isFloatingIcon?: boolean | undefined; + label?: string | undefined; + badgeIconStyle?: number | undefined; + showDeliveryTime?: boolean | undefined; + actionButtons?: Array | undefined; + smallIcon?: image.PixelMap | undefined; + largeIcon?: image.PixelMap | undefined; + overlayIcon?: image.PixelMap | undefined; + groupName?: string | undefined; + readonly creatorBundleName?: string | undefined; + readonly creatorUid?: number | undefined; + readonly creatorPid?: number | undefined; + readonly creatorUserId?: number | undefined; + readonly creatorInstanceKey?: number | undefined; + sound?: string | undefined; + classification?: string | undefined; + readonly hashCode?: string | undefined; + isRemoveAllowed?: boolean | undefined; + readonly source?: number | undefined; + template?: NotificationTemplate | undefined; + distributedOption?: DistributedOptions | undefined; + readonly deviceId?: string | undefined; + readonly notificationFlags?: NotificationFlags | undefined; + removalWantAgent?: WantAgent | undefined; + badgeNumber?: number | undefined; + representativeBundle?: BundleOption | undefined; + readonly agentBundle?: BundleOption | undefined; + unifiedGroupInfo?: UnifiedGroupInfo | undefined; + notificationControlFlags?: number | undefined; + readonly appInstanceKey?: string | undefined; + forceDistributed?: boolean | undefined; + 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 000000000..f2cb24694 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSlot.ets @@ -0,0 +1,35 @@ +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 { + 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; +} \ 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 000000000..1c0a07e43 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationTemplate.ets @@ -0,0 +1,19 @@ +/* + * 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; +} \ 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 000000000..eef5e12cc --- /dev/null +++ b/frameworks/ets/ets/notification/notificationUserInput.ets @@ -0,0 +1,18 @@ +/* + * 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; +} \ No newline at end of file -- Gitee From 488d76a88d5f041cf14793faa48e6fa24d16c8cc Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 13 May 2025 14:49:49 +0800 Subject: [PATCH 03/52] modify Signed-off-by: heguokai --- .../ets/ani/include/manager/ani_get_active.h | 2 + frameworks/ets/ani/include/manager/ani_slot.h | 7 +-- .../ets/ani/include/sts_notification_flag.h | 3 +- frameworks/ets/ani/include/sts_request.h | 3 ++ .../ets/ani/src/manager/ani_get_active.cpp | 44 ++++++++++++++++ .../ets/ani/src/manager/ani_manager.cpp | 51 +++++++++++-------- .../ets/ani/src/sts_notification_flag.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 27 ++++++++++ 8 files changed, 113 insertions(+), 26 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_get_active.h b/frameworks/ets/ani/include/manager/ani_get_active.h index 2299c4c91..67c375b5f 100644 --- a/frameworks/ets/ani/include/manager/ani_get_active.h +++ b/frameworks/ets/ani/include/manager/ani_get_active.h @@ -20,6 +20,8 @@ namespace OHOS { namespace NotificationManagerSts { ani_double AniGetActiveNotificationCount(ani_env *env); +ani_object AniGetAllActiveNotifications(ani_env *env); +ani_object AniGetActiveNotifications(ani_env *env); } // namespace NotificationManagerSts } // namespace OHOS #endif diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h index d72fcae1e..27de0996e 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -19,13 +19,14 @@ namespace OHOS { namespace NotificationManagerSts { +ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj); +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj); + ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption); +ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type); void AniSetNotificationEnableSlotSync(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_object isForceControl); -ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type); -ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj); -void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj); } // namespace NotificationManagerSts } // namespace OHOS #endif diff --git a/frameworks/ets/ani/include/sts_notification_flag.h b/frameworks/ets/ani/include/sts_notification_flag.h index 1f850fff5..a85baa69f 100644 --- a/frameworks/ets/ani/include/sts_notification_flag.h +++ b/frameworks/ets/ani/include/sts_notification_flag.h @@ -20,7 +20,8 @@ namespace OHOS { namespace NotificationSts { -bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, +using NotificationFlags = OHOS::Notification::NotificationFlags; +bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, ani_object &flagsObject); } // namespace NotificationSts } // OHOS diff --git a/frameworks/ets/ani/include/sts_request.h b/frameworks/ets/ani/include/sts_request.h index aa4e5b5f2..e6449af4f 100644 --- a/frameworks/ets/ani/include/sts_request.h +++ b/frameworks/ets/ani/include/sts_request.h @@ -16,11 +16,13 @@ #ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_REQUEST_H #define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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; @@ -38,6 +40,7 @@ ani_status UnWarpNotificationRequest( 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); } // namespace NotificationSts } // OHOS #endif \ 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 index ad3c0efdd..0bd09a533 100644 --- a/frameworks/ets/ani/src/manager/ani_get_active.cpp +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -18,6 +18,7 @@ #include "notification_helper.h" #include "ans_log_wrapper.h" #include "sts_throw_erro.h" +#include "sts_request.h" namespace OHOS { namespace NotificationManagerSts { @@ -36,5 +37,48 @@ ani_double AniGetActiveNotificationCount(ani_env *env) } 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("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_object 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("AniTriggerSystemLiveView buttonOption ERROR_INTERNAL_ERROR"); + } + ANS_LOGD("sts AniGetAllActiveNotifications end"); + return arrayRequestObj; +} + +ani_object AniGetActiveNotifications(ani_env *env) +{ + ANS_LOGD("sts AniGetAllActiveNotifications 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("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + return nullptr; + } + ani_object 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("AniTriggerSystemLiveView buttonOption ERROR_INTERNAL_ERROR"); + } + ANS_LOGD("sts AniGetAllActiveNotifications end"); + return arrayRequestObj; +} + } // 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 index 8ab7355a5..257606366 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -34,58 +34,67 @@ void AniNotificationManagerRegistryInit(ani_env *env) 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_LOGD("FindNamespace notificationManager failed status : %{public}d", status); return; } - std::array kitFunctions = { + ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, + 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 {"nativeAniTriggerSystemLiveView", nullptr, + reinterpret_cast(AniTriggerSystemLiveView)}, + 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 {"nativeGetSlotFlagsByBundle", nullptr, reinterpret_cast(AniGetSlotFlagsByBundle)}, - ani_native_function {"nativeSetSlotFlagsByBundle", nullptr, reinterpret_cast(AniSetSlotFlagsByBundle)}, - ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(AniSetNotificationEnable)}, ani_native_function {"nativeisNotificationSlotEnabled", nullptr, reinterpret_cast(AniIsNotificationSlotEnabled)}, - 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 {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, + + 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 {"nativeaddDoNotDisturbProfile", nullptr, reinterpret_cast(AniAddDoNotDisturbProfile)}, - ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, reinterpret_cast(AniRemoveDoNotDisturbProfile)}, - ani_native_function {"nativeSetNotificationEnableSlotWithForce", nullptr, - reinterpret_cast(AniSetNotificationEnableSlotWithForce)}, + ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(AniSetNotificationEnable)}, ani_native_function {"nativeSetNotificationEnableSlotSync", nullptr, reinterpret_cast(AniSetNotificationEnableSlotSync)}, - ani_native_function {"nativePublishWithUserId", nullptr, reinterpret_cast(AniPublishWithId)}, - ani_native_function {"nativePublish", nullptr, reinterpret_cast(AniPublish)}, - ani_native_function {"nativeSubscribeSystemLiveView", nullptr, - reinterpret_cast(AniSubscribeSystemLiveView)}, - ani_native_function {"nativeAniTriggerSystemLiveView", nullptr, - reinterpret_cast(AniTriggerSystemLiveView)}, + ani_native_function {"nativeSetNotificationEnableSlotWithForce", nullptr, + reinterpret_cast(AniSetNotificationEnableSlotWithForce)}, }; status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.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 diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp index 7a3791b16..cdbc798f2 100644 --- a/frameworks/ets/ani/src/sts_notification_flag.cpp +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -18,7 +18,7 @@ namespace OHOS { namespace NotificationSts { -bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, +bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &flags, ani_object &flagsObject) { if (flags == nullptr) { diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 3ba390d32..907568262 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -943,5 +943,32 @@ ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests) +{ + if (requests.empty()) { + ANS_LOGE("actionButtons is empty"); + return nullptr; + } + 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; + RETURN_NULL_IF_FALSE(WarpNotificationRequest( + env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)); + RETURN_NULL_IF_NULL(requestObj); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; +} } // namespace NotificationSts } // OHOS \ No newline at end of file -- Gitee From fdc7838c54931edd320eb7a0a2b77869ed86bdc5 Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 14 May 2025 21:27:10 +0800 Subject: [PATCH 04/52] add subscribe Signed-off-by: heguokai --- frameworks/ets/BUILD.gn | 3 +- frameworks/ets/ani/BUILD.gn | 77 ++ frameworks/ets/ani/include/manager/ani_slot.h | 2 +- frameworks/ets/ani/include/sts_common.h | 6 +- .../ani/include/sts_notification_manager.h | 3 + frameworks/ets/ani/include/sts_sorting.h | 26 + frameworks/ets/ani/include/sts_sorting_map.h | 28 + frameworks/ets/ani/include/sts_subscribe.h | 136 +++ .../ets/ani/include/sts_subscribe_info.h | 28 + frameworks/ets/ani/include/sts_subscriber.h | 47 ++ frameworks/ets/ani/include/sts_throw_erro.h | 2 +- .../ets/ani/include/subscribe/ani_remove.h | 26 + .../ets/ani/include/subscribe/ani_subscribe.h | 27 + .../ets/ani/src/manager/ani_manager.cpp | 31 +- frameworks/ets/ani/src/manager/ani_slot.cpp | 12 +- frameworks/ets/ani/src/sts_common.cpp | 37 +- frameworks/ets/ani/src/sts_convert_other.cpp | 2 +- .../ets/ani/src/sts_notification_content.cpp | 4 +- .../ets/ani/src/sts_notification_manager.cpp | 35 +- frameworks/ets/ani/src/sts_request.cpp | 4 +- frameworks/ets/ani/src/sts_slot.cpp | 2 + frameworks/ets/ani/src/sts_sorting.cpp | 70 ++ frameworks/ets/ani/src/sts_sorting_map.cpp | 87 ++ frameworks/ets/ani/src/sts_subscribe.cpp | 789 ++++++++++++++++++ frameworks/ets/ani/src/sts_subscribe_info.cpp | 53 ++ frameworks/ets/ani/src/sts_subscriber.cpp | 227 +++++ .../ets/ani/src/subscribe/ani_remove.cpp | 100 +++ .../ets/ani/src/subscribe/ani_subscribe.cpp | 136 +++ .../ets/ets/@ohos.notificationManager.ets | 566 ++++++++----- .../ets/ets/@ohos.notificationSubscribe.ets | 487 +++++++++++ frameworks/ets/ets/BUILD.gn | 127 +++ .../ets/notification/notificationContent.ets | 8 +- .../ets/ets/notification/notificationSlot.ets | 14 + .../ets/notification/notificationSorting.ets | 43 + .../notification/notificationSortingMap.ets | 26 + .../notificationSubscribeInfo.ets | 28 + .../notification/notificationSubscriber.ets | 179 ++++ .../ets/notification/notificationTemplate.ets | 5 + .../notification/notificationUserInput.ets | 4 + 39 files changed, 3251 insertions(+), 236 deletions(-) create mode 100644 frameworks/ets/ani/include/sts_sorting.h create mode 100644 frameworks/ets/ani/include/sts_sorting_map.h create mode 100644 frameworks/ets/ani/include/sts_subscribe.h create mode 100644 frameworks/ets/ani/include/sts_subscribe_info.h create mode 100644 frameworks/ets/ani/include/sts_subscriber.h create mode 100644 frameworks/ets/ani/include/subscribe/ani_remove.h create mode 100644 frameworks/ets/ani/include/subscribe/ani_subscribe.h create mode 100644 frameworks/ets/ani/src/sts_sorting.cpp create mode 100644 frameworks/ets/ani/src/sts_sorting_map.cpp create mode 100644 frameworks/ets/ani/src/sts_subscribe.cpp create mode 100644 frameworks/ets/ani/src/sts_subscribe_info.cpp create mode 100644 frameworks/ets/ani/src/sts_subscriber.cpp create mode 100644 frameworks/ets/ani/src/subscribe/ani_remove.cpp create mode 100644 frameworks/ets/ani/src/subscribe/ani_subscribe.cpp create mode 100644 frameworks/ets/ets/@ohos.notificationSubscribe.ets create mode 100644 frameworks/ets/ets/notification/notificationSorting.ets create mode 100644 frameworks/ets/ets/notification/notificationSortingMap.ets create mode 100644 frameworks/ets/ets/notification/notificationSubscribeInfo.ets create mode 100644 frameworks/ets/ets/notification/notificationSubscriber.ets diff --git a/frameworks/ets/BUILD.gn b/frameworks/ets/BUILD.gn index ce8395589..37059d00d 100644 --- a/frameworks/ets/BUILD.gn +++ b/frameworks/ets/BUILD.gn @@ -16,7 +16,8 @@ import("//build/ohos.gni") group("ani_packages") { deps = [ -# "./ets:ets_files", + "./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 index 2751913fe..358cf28eb 100644 --- a/frameworks/ets/ani/BUILD.gn +++ b/frameworks/ets/ani/BUILD.gn @@ -82,6 +82,83 @@ ohos_shared_library("notification_manager_ani") { "resource_management:global_resmgr", ] + 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}" diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h index 27de0996e..7e419a6af 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -24,7 +24,7 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj); ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption); ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type); -void AniSetNotificationEnableSlotSync(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable); +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_object isForceControl); } // namespace NotificationManagerSts diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 6a0c0c472..16987dd35 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -23,10 +23,12 @@ 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_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); @@ -40,7 +42,7 @@ 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 GetStringArray(ani_env *env, ani_object param, const char *name, +ani_status GetPropertyStringArray(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, @@ -80,7 +82,7 @@ static bool CallSetter(ani_env* env, ani_class cls, ani_object object, const cha } 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 || std::is_same_v) { status = env->Object_CallMethod_Void(object, setter, static_cast(value)); } else { diff --git a/frameworks/ets/ani/include/sts_notification_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h index 974da4522..363f6c21f 100644 --- a/frameworks/ets/ani/include/sts_notification_manager.h +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -30,6 +30,7 @@ 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; enum STSSlotType { UNKNOWN_TYPE = 0, SOCIAL_COMMUNICATION = 1, @@ -135,6 +136,8 @@ bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enu ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonOptionObj, ButtonOption &buttonOption); ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption); +bool WarpNotificationDoNotDisturbDate( + ani_env *env, const std::shared_ptr &date, ani_object &outObj); } // 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 000000000..029e017c5 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..3c51d775d --- /dev/null +++ b/frameworks/ets/ani/include/sts_sorting_map.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_MAP_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..ec780e460 --- /dev/null +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -0,0 +1,136 @@ +/* + * 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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 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 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 000000000..d77c54b4f --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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 000000000..d2b375f9b --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBER_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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_throw_erro.h b/frameworks/ets/ani/include/sts_throw_erro.h index d4335acd9..de62ad197 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -68,7 +68,7 @@ inline std::string FindAnsErrMsg(const int32_t errCode) inline void ThrowStsErroWithLog(ani_env *env, std::string logMsg) { OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, - NotificationSts::FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); ANS_LOGE("%{public}s", logMsg.c_str()); } } // namespace NotificationSts 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 000000000..830000329 --- /dev/null +++ b/frameworks/ets/ani/include/subscribe/ani_remove.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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SUBSCRIBE_REMOVE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SUBSCRIBE_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); +} +} +#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 000000000..212697561 --- /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 OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_SUBSCRIBE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_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_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 257606366..a597b22af 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -56,36 +56,37 @@ void AniNotificationManagerRegistryInit(ani_env *env) ani_native_function {"nativeGetAllActiveNotifications", nullptr, reinterpret_cast(AniGetAllActiveNotifications)}, - ani_native_function {"nativeaddDoNotDisturbProfile", nullptr, + ani_native_function {"nativeAddDoNotDisturbProfile", nullptr, reinterpret_cast(AniAddDoNotDisturbProfile)}, - ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, + ani_native_function {"nativeRemoveDoNotDisturbProfile", nullptr, reinterpret_cast(AniRemoveDoNotDisturbProfile)}, ani_native_function {"nativeSubscribeSystemLiveView", nullptr, reinterpret_cast(AniSubscribeSystemLiveView)}, - ani_native_function {"nativeAniTriggerSystemLiveView", nullptr, + ani_native_function {"nativeTriggerSystemLiveView", nullptr, reinterpret_cast(AniTriggerSystemLiveView)}, - 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 {"nativeisNotificationSlotEnabled", nullptr, - reinterpret_cast(AniIsNotificationSlotEnabled)}, - 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 {"nativeSetNotificationEnable", nullptr, reinterpret_cast(AniSetNotificationEnable)}, - ani_native_function {"nativeSetNotificationEnableSlotSync", nullptr, - reinterpret_cast(AniSetNotificationEnableSlotSync)}, + + 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)}, }; status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index bdb58cb0c..c03126d5b 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -56,17 +56,17 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) return outAniObj; } -void AniSetNotificationEnableSlotSync(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) +void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) { - ANS_LOGD("SetNotificationEnableSlotByOld enter "); + ANS_LOGD("AniSetNotificationEnableSlot enter "); Notification::NotificationBundleOption option; if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { - NotificationSts::ThrowStsErroWithLog(env, "sts AniSetNotificationEnableSlotSync ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithLog(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); return; } Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; if (!NotificationSts::SlotTypeEtsToC(env, type, slotType)) { - NotificationSts::ThrowStsErroWithLog(env, "sts AniSetNotificationEnableSlotSync ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithLog(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); return; } int returncode = 0; @@ -77,10 +77,10 @@ void AniSetNotificationEnableSlotSync(ani_env *env, ani_object bundleOption, ani int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); - ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + ANS_LOGE("AniSetNotificationEnableSlot error, errorCode: %{public}d", externalCode); return; } - ANS_LOGD("sts AniSetNotificationEnableSlotSync end"); + ANS_LOGD("AniSetNotificationEnableSlot end"); } void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 95c439dc2..44d44c24a 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -21,6 +21,16 @@ namespace NotificationSts { constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; +bool IsUndefine(ani_env *env, const ani_object &obj) +{ + ani_boolean isUndefined; + if (ANI_OK != env->Reference_IsUndefined(obj,&isUndefined)) { + ANS_LOGD("Reference_IsUndefined faild"); + return true; + } + return (isUndefined == ANI_TRUE) ? true : false; +} + ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& aniStr) { ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); @@ -48,6 +58,31 @@ ani_status GetStringByAniString(ani_env *env, ani_string str, std::string &res) return status; } +bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector &stdVString) +{ + ani_double length; + ani_status status = env->Object_GetPropertyByName_Double(ani_obj, "length", &length); + if (status != ANI_OK) { + ANS_LOGD("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_LOGD("status : %{public}d", status); + } + std::string std_string; + if (!GetStringByAniString(env, static_cast(stringEntryRef), std_string)) { + ANS_LOGD("GetStdString faild"); + 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) { @@ -141,7 +176,7 @@ ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_bo return status; } -ani_status GetStringArray(ani_env *env, ani_object param, const char *name, +ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *name, ani_boolean &isUndefined, std::vector &res) { ani_ref arrayObj = nullptr; diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index 734d039d1..3010668ad 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -257,7 +257,7 @@ ani_object GetAniResource(ani_env *env, const std::shared_ptrbundleName, stringValue)); diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index bec99944e..1cdaae424 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -278,7 +278,7 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, { std::vector names = {}; ani_boolean isUndefined = ANI_TRUE; - if(GetStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { + if(GetPropertyStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { for(auto name: names) { button.addSingleButtonName(name); } @@ -571,7 +571,7 @@ ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, std::vector lines = {}; isUndefined = ANI_TRUE; - if((status = GetStringArray(env, obj, "lines", isUndefined, lines)) != ANI_OK + if((status = GetPropertyStringArray(env, obj, "lines", isUndefined, lines)) != ANI_OK || isUndefined == ANI_TRUE) { return ANI_INVALID_ARGS; } diff --git a/frameworks/ets/ani/src/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index a5e915ff1..bfdce45b4 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -367,5 +367,38 @@ ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonO RETURN_NULL_IF_FALSE(CallSetter(env, optCls, optObj, "buttonName", stringValue)); return optObj; } + +bool WarpNotificationDoNotDisturbDate( + ani_env *env, const std::shared_ptr &date, ani_object &outObj) +{ + ani_class cls; + ani_object obj; + ani_enum_item stsEnumValue; + const char *className = "L@ohos/notificationManager/notificationManager/DoNotDisturbDateInner;"; + if (!CreateClassObjByClassName(env, className, cls, obj)) { + ANS_LOGD("CreateClassObjByClassName faild"); + return false; + } + if (!EnumConvertNativeToAni( + env, "L@ohos/notificationManager/notificationManager/DoNotDisturbType;", + date->GetDoNotDisturbType(), stsEnumValue)) { + ANS_LOGD("EnumConvert_NativeToSts faild"); + return false; + } + if (!CallSetter(env, cls, obj, "type", stsEnumValue)) { + ANS_LOGD("set type faild."); + return false; + } + if (!CallSetter(env, cls, obj, "begin", date->GetBeginDate())) { + ANS_LOGD("SetDate 'begin' faild."); + return false; + } + if (!CallSetter(env, cls, obj, "end", date->GetBeginDate())) { + ANS_LOGD("SetDate 'begin' faild."); + return false; + } + outObj = obj; + return true; +} } // namespace NotificationSts -} // OHOS +} // 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 index 907568262..0de7edf9f 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -41,14 +41,14 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption std::vector supportDisplayDevices = {}; isUndefined = ANI_TRUE; - if(GetStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK + if(GetPropertyStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK && isUndefined == ANI_FALSE) { distributedOptions.supportDisplayDevices = supportDisplayDevices; } std::vector supportOperateDevices = {}; isUndefined = ANI_TRUE; - if(GetStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK + if(GetPropertyStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK && isUndefined == ANI_FALSE) { distributedOptions.supportOperateDevices = supportOperateDevices; } diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 9db1901bf..5df8a44d2 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -14,9 +14,11 @@ */ #include "sts_slot.h" +#include "ans_log_wrapper.h" #include "sts_notification_manager.h" #include "sts_common.h" + namespace OHOS { namespace NotificationSts { bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, diff --git a/frameworks/ets/ani/src/sts_sorting.cpp b/frameworks/ets/ani/src/sts_sorting.cpp new file mode 100644 index 000000000..12f1026a1 --- /dev/null +++ b/frameworks/ets/ani/src/sts_sorting.cpp @@ -0,0 +1,70 @@ +/* + * 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_LOGD("faild. env is nullptr"); + return false; + } + if (!CreateClassObjByClassName(env, "Lnotification/notificationSorting/NotificationSortingInner;", cls, obj)) { + ANS_LOGD("Create obj faild. NotificationSortingInner"); + return false; + } + + // TODO + // readonly slot: NotificationSlot + // sptr slot = new NotificationSlot(*sorting.GetSlot()); + if (!WrapNotificationSlot(env, sorting.GetSlot(), slotObj)) { + ANS_LOGD("WrapNotificationSlot faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(obj, "slot", slotObj))) { + ANS_LOGD("set slot faild. status %{public}d", status); + return false; + } + + hashCode = sorting.GetGroupKeyOverride(); + if (ANI_OK != GetAniStringByString(env, hashCode, hashCodeObj) || hashCodeObj == nullptr) { + return false; + } + // readonly hashCode: string; + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(obj, "hashCode", hashCodeObj))) { + ANS_LOGD("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_LOGD("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 000000000..23136d821 --- /dev/null +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -0,0 +1,87 @@ +/* + * 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 WarpNotificationSortingMap(ani_env *env, const std::shared_ptr &sortingMap, ani_object &outObj) +{ + ani_class cls; + ani_object recordObj; + ani_class recordCls; + ani_object arrayObj; + ani_status status; + if (sortingMap == nullptr) { + ANS_LOGD("sortingMap is nullptr"); + return false; + } + + if (!CreateClassObjByClassName(env, "Lnotification/notificationSortingMap/NotificationSortingMapInner;", cls, outObj)) { + ANS_LOGD("CreateClassObjByClassName faild."); + return false; + } + + if (!CreateClassObjByClassName(env, "Lescompat/Record;", recordCls, recordObj)) { + ANS_LOGD("Create recordObj faild."); + return false; + } + + std::vector keys = sortingMap->GetKey(); + for (auto &it : keys) { + Notification::NotificationSorting sorting; + if (sortingMap->GetNotificationSorting(it, sorting)) { + ani_string keyString; + if (ANI_OK != GetAniStringByString(env, it, keyString)) { + ANS_LOGD("GetAniStringByString faild. key: %{public}s", it.c_str()); + continue; + } + ani_object sortingObj; + if (!WarpNotificationSorting(env, sorting, sortingObj)) { + ANS_LOGD("WarpNotificationSorting faild. key: %{public}s", it.c_str()); + continue; + } + + if (keyString == nullptr) { + ANS_LOGD("GetAniString faild. key: %{public}s", it.c_str()); + continue; + } + + if (ANI_OK != (status = env->Object_CallMethodByName_Void( + recordObj, "$_set", "Lstd/core/Object;Lstd/core/Object;:V", keyString, sortingObj))) { + ANS_LOGD("set key value faild. key: %{public}s status %{public}d", it.c_str(), status); + continue; + } + } + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortings", recordObj))) { + ANS_LOGD("Object_SetPropertyByName_Ref sortings faild. status %{public}d", status); + return false; + } + arrayObj = GetAniStringArrayByVectorString(env, keys); + if (arrayObj == nullptr) { + ANS_LOGD("WarpVectorStringToSts sortedHashCode faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortedHashCode", arrayObj))) { + ANS_LOGD("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 000000000..c21bbecc7 --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -0,0 +1,789 @@ +/* + * 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" + +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; + ANS_LOGD("OnOperationCallback ENTER"); + int32_t externalCode = OHOS::CJSystemapi::Notification::ErrorToExternal(operationResult); + ANS_LOGD("operationResult %{public}d, externalCode %{public}d", operationResult, externalCode); + 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; + } + + if (operationResult == 0) { + ANS_LOGD("OnOperationCallback Resolve"); + ani_ref ref {}; + if (ANI_OK != (aniResult = etsEnv->PromiseResolver_Resolve(resolver_, ref))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", aniResult); + } + } else { + ANS_LOGD("OnOperationCallback reject"); + std::string errMsg = FindAnsErrMsg(externalCode); + ani_error rejection = static_cast(OHOS::AbilityRuntime::CreateStsError(etsEnv, externalCode, errMsg)); + if (ANI_OK != (aniResult = etsEnv->PromiseResolver_Reject(resolver_, rejection))) { + ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", aniResult); + } + } + aniResult = etsVm_->DetachCurrentThread(); + if (aniResult != ANI_OK) { + ANS_LOGD("StsDistributedOperationCallback DetachCurrentThread error. result: %{public}d.", aniResult); + return; + } + isCall_ = true; +} + +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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; + } +} +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_GetFieldByName_Ref(static_cast(ref_), func, &fn_ref); + if (ANI_OK != aniResult) { + ANS_LOGD("Object_GetFieldByName_Ref '%{public}s' error. result: %{public}d.", func, aniResult); + return false; + } + ani_boolean flag = false; + if (ANI_OK != env->Reference_IsUndefined(fn_ref, &flag)) { + ANS_LOGD("Reference_IsUndefined faild"); + } + ANS_LOGD("[%{public}s] %{public}d. %{public}d", __func__, __LINE__, (int32_t)flag); + 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("[%{public}s] %{public}d", __func__, __LINE__); + 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"); + return false; + } + sptr SubscribeInfo = + new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); + if (!isInfoUndefine) { + if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { + ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); + return false; + } + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("GetNotificationSubscriber faild"); + return false; + } + if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { + ANS_LOGD("AddSubscriberInstancesInfo faild"); + return false; + } + } + ErrCode status = 0; + if (!isInfoUndefine) { + status = NotificationHelper::SubscribeNotification(stsSubscriber, SubscribeInfo); + } else { + status = NotificationHelper::SubscribeNotification(stsSubscriber); + } + if (status != 0) { + ANS_LOGD("SubscribeNotification faild. status %{public}d ErrorToExternal %{public}d", + status, OHOS::CJSystemapi::Notification::ErrorToExternal(status)); + return false; + } +// testThread = std::thread([stsSubscriber](){ +// std::shared_ptr data = std::make_shared(); +// std::shared_ptr callbackData = std::make_shared(); +// std::shared_ptr badgeData = std::make_shared(); +// sptr callbackDataSptr = new EnabledNotificationCallbackData(); +// +// std::string groupKeyOverride = "GroupKeyOverride"; +// int32_t importance = 10; +// uint64_t ranking = 20; +// int32_t visibleness =30; +// bool isDisplayBadge = false; +// bool isHiddenNotification = true; +// NotificationSorting sorting; +// sorting.SetGroupKeyOverride(groupKeyOverride); +// sorting.SetImportance(importance); +// sorting.SetRanking(ranking); +// sorting.SetVisiblenessOverride(visibleness); +// sorting.SetDisplayBadge(isDisplayBadge); +// sorting.SetHiddenNotification(isHiddenNotification); +// std::vector VSorting; +// for (int i = 0; i < 5; i++) { +// sorting.SetKey(std::to_string(i)); +// VSorting.emplace_back(sorting); +// } +// std::shared_ptr sortingMap = std::make_shared(VSorting); +// data->SetBeginDate(1746588038); +// data->SetEndDate(1746588038); +// data->SetDoNotDisturbType(NotificationConstant::DoNotDisturbType::DAILY); +// ANS_LOGD("%{public}d", __LINE__); +// stsSubscriber->onDoNotDisturbChanged(data); +// ANS_LOGD("%{public}d", __LINE__); +// +// callbackData->SetBundle("hello world"); +// callbackData->SetUid(10010); +// callbackData->SetEnable(true); +// ANS_LOGD("%{public}d", __LINE__); +// stsSubscriber->OnEnabledNotificationChanged(callbackData); +// ANS_LOGD("%{public}d", __LINE__); +// +// badgeData->SetAppInstanceKey("SetAppInstanceKey"); +// badgeData->SetBadgeNumber(10086); +// badgeData->SetBundle("hello world"); +// badgeData->SetUid(100100); +// badgeData->SetInstanceKey(111000); +// ANS_LOGD("%{public}d", __LINE__); +// stsSubscriber->OnBadgeChanged(badgeData); +// ANS_LOGD("%{public}d", __LINE__); +// +// callbackDataSptr->SetBundle("hello world"); +// callbackDataSptr->SetUid(10010); +// callbackDataSptr->SetEnable(true); +// ANS_LOGD("%{public}d", __LINE__); +// stsSubscriber->OnBadgeEnabledChanged(callbackDataSptr); +// ANS_LOGD("%{public}d", __LINE__); +// +// stsSubscriber->OnUpdate(sortingMap); +// ANS_LOGD("%{public}d", __LINE__); +// +// std::shared_ptr request = std::make_shared(new NotificationRequest()); +// request->SetRemindType(NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); +// stsSubscriber->OnCanceled(request, sortingMap, 123); +// ANS_LOGD("%{public}d", __LINE__); +// stsSubscriber->OnConsumed(request, sortingMap); +// +// ANS_LOGD("%{public}d", __LINE__); +// std::vector> requestLists; +// requestLists.emplace_back(request); +// stsSubscriber->OnBatchCanceled(requestLists, sortingMap, 10086); +// ANS_LOGD("%{public}d", __LINE__); +// }); +// testThread.detach(); + return true; + } + + bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) + { + ANS_LOGD("enter"); + if (IsUndefine(env, subscriber)) { + return false; + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("Subscriber not found"); + // ERR_ANS_INVALID_PARAM + return false; + } + bool ret = AddDeletingSubscriber(stsSubscriber); + if (ret) { + int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); + if (status != 0) { + ANS_LOGD("errorCode is not ERR_OK. %{public}d ErrorToExternal %{public}d", + status, OHOS::CJSystemapi::Notification::ErrorToExternal(status)); + DelDeletingSubscriber(stsSubscriber); + } + } else { + // ERR_ANS_SUBSCRIBER_IS_DELETING + 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 (GetPropertyDouble(env, obj, "id", isUndefined, idDouble) != ANI_OK || isUndefined == ANI_TRUE) { + ANS_LOGD("UnWarpNotificationKey GetPropertyDouble 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 000000000..53cffd756 --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscribe_info.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 "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) +{ + 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_LOGD("UnWarpStringArrayOrUndefinedByProperty faild"); + } + if (ANI_OK != GetPropertyDouble(env, value, "userId", isUndefined, userId) || isUndefined == ANI_TRUE) { + ANS_LOGD("GetDoubleOrUndefined faild"); + } + if (ANI_OK != GetPropertyString(env, value, "deviceType", isUndefined, deviceType) || isUndefined == ANI_TRUE) { + ANS_LOGD("GetStringOrUndefined faild"); + } + if (ANI_OK != GetPropertyDouble(env, value, "filterLimit", isUndefined, filterLimit) || isUndefined == ANI_TRUE) { + ANS_LOGD("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 000000000..a78c3301b --- /dev/null +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -0,0 +1,227 @@ +/* + * 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 WarpSubscribeCallbackData( + ani_env *env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, + int32_t deleteReason, + ani_object &outObj) +{ + ANS_LOGD("enter"); + ani_object sortingMapObj; + ani_status status; + ani_class cls; + if (env == nullptr) { + ANS_LOGD("env is nullptr"); + return false; + } + + if (!CreateClassObjByClassName( + env, "Lnotification/notificationSubscriber/SubscribeCallbackDataInner;", cls, outObj)) { + ANS_LOGD("CreateClassObjByClassName faild"); + return false; + } + + // request: NotificationRequest + // TODO + // Warp NotificationRequest + ani_object requestObj; + ani_class requestCls; + if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)) { + return false; + } + if (requestObj == nullptr) { + ANS_LOGD("WarpNotificationRequest faild"); + return false; + } + + // for test + // if (!CreateClassObjByClassName( + // env, "Lnotification/notificationRequest/NotificationRequestInner;", requestCls, requestObj)) { + // ANS_LOGD("create NotificationRequest faild."); + // return false; + // } + + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "request", requestObj))) { + ANS_LOGD("set request faild. status %{public}d", status); + return false; + } + + // sortingMap?: NotificationSortingMap + if (!WarpNotificationSortingMap(env, sortingMap, sortingMapObj)) { + ANS_LOGD("WarpNotificationSortingMap faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortingMap", sortingMapObj))) { + ANS_LOGD("set sortingMap faild. status %{public}d", status); + return false; + } + + // reason?: number + if (deleteReason != -1) { + ani_object reason = CreateDouble(env, static_cast(deleteReason)); + if (reason == nullptr) { + ANS_LOGD("reason Create faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "reason", reason))) { + ANS_LOGD("set reason faild. status %{public}d", status); + return false; + } + } + + // sound?: string + if (request->EnableSound()) { + std::string sound = request->GetSound().ToString(); + ani_string soundObj; + if (ANI_OK != GetAniStringByString(env, sound, soundObj) || soundObj == nullptr) { + ANS_LOGD("sound create faild"); + return false; + } + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sound", soundObj))) { + ANS_LOGD("set sound faild. status %{public}d", status); + } + } + + // vibrationValues?: Array + if (request->EnableVibrate()) { + ani_object vibrationValuesObj; + const std::vector vibrationValues = request->GetVibrationStyle(); + vibrationValuesObj = newArrayClass(env, vibrationValues.size()); + if (vibrationValuesObj == nullptr) { + ANS_LOGD("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_LOGD("faild. status : %{public}d", status); + return false; + } + } + + if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "vibrationValues", vibrationValuesObj))) { + ANS_LOGD("set vibrationValuesObj faild. status %{public}d", status); + 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"); + ani_status status; + + if (env == nullptr) { + ANS_LOGD("env is nullptr"); + return false; + } + outObj = newArrayClass(env, requestList.size()); + if (outObj == nullptr) { + ANS_LOGD("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_LOGD("WarpSubscribeCallbackData faild"); + return false; + } + if (ANI_OK != (status = env->Object_CallMethodByName_Void( + outObj, "$_set", "ILstd/core/Object;:V", i, obj))) { + ANS_LOGD("set object faild. index %{public}d status %{public}d", i, status); + return false; + } + } + return true; +} + +bool WarpEnabledNotificationCallbackData(ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj) +{ + ani_class cls; + const char *className = "Lnotification/notificationSubscriber/EnabledNotificationCallbackDataInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj)) { + ANS_LOGD("CreateClassObjByClassName faild"); + return false; + } + if (!SetFieldString(env, cls, outObj, "bundle", callbackData->GetBundle())) { + ANS_LOGD("SetFieldString bundle faild"); + return false; + } + if (!CallSetter(env, cls, outObj, "uid", static_cast(callbackData->GetUid()))) { + ANS_LOGD("uid set faild."); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outObj, "enable", callbackData->GetEnable())) { + ANS_LOGD("Set enable faild."); + return false; + } + return true; +} + +bool WarpBadgeNumberCallbackData(ani_env *env, const std::shared_ptr &badgeData, ani_object &outObj) +{ + ani_class cls; + ani_object instanceKeyObj; + const char *className = "Lnotification/notificationSubscriber/BadgeNumberCallbackDataInner;"; + if (!CreateClassObjByClassName(env, className, cls, outObj)) { + ANS_LOGD("CreateClassObjByClassName faild"); + return false; + } + if (!SetFieldString(env, cls, outObj, "bundle", badgeData->GetBundle())) { + ANS_LOGD("SetFieldString bundle faild"); + return false; + } + if (!CallSetter(env, cls, outObj, "uid", static_cast(badgeData->GetUid()))) { + ANS_LOGD("uid set faild."); + return false; + } + if (!CallSetter(env, cls, outObj, "badgeNumber", static_cast(badgeData->GetBadgeNumber()))) { + ANS_LOGD("badgeNumber set faild"); + return false; + } + instanceKeyObj = CreateDouble(env, static_cast(badgeData->GetInstanceKey())); + if (instanceKeyObj != nullptr) { + if (!CallSetter(env, cls, outObj, "instanceKey", instanceKeyObj)) { + ANS_LOGD("instanceKey set faild."); + return false; + } + } else { + ANS_LOGD("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/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp new file mode 100644 index 000000000..dfb53a80f --- /dev/null +++ b/frameworks/ets/ani/src/subscribe/ani_remove.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 "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 { +void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notificationKey, ani_object reasonEnum) +{ + ANS_LOGD("AniRemoveForBundle enter"); + BundleOption option; + Notification::NotificationKey key; + int32_t reasonType = -1; + if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { + ANS_LOGD("bundle is valid"); + return; + } + if (!NotificationSts::UnWarpNotificationKey(env, notificationKey, key)) { + ANS_LOGD("notificationKey is valid"); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGD("enum convert failed"); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGD("reasonType is valid"); + return; + } + int ret = Notification::NotificationHelper::RemoveNotification(option, key.id, key.label, reasonType); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", + ret, CJSystemapi::Notification::ErrorToExternal(ret)); +} + +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_LOGD("hashCode is valid"); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGD("enum convert failed"); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGD("reasonType is valid"); + return; + } + ANS_LOGD("hashCode: %{public}s, reasonType: %{public}d", hashCodeStd.c_str(), reasonType); + int ret = Notification::NotificationHelper::RemoveNotification(hashCodeStd, reasonType); + ANS_LOGD("StsRemoveForHashCode ret %{public}d. ErrorToExternal %{public}d", + ret, CJSystemapi::Notification::ErrorToExternal(ret)); +} + +void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reasonEnum) +{ + ANS_LOGD("StsRemoveForHashCodes enter"); + std::vector hashCodesStd; + int32_t reasonType; + if (ANI_OK != NotificationSts::GetStringArrayByAniObj(env, hashCodes, hashCodesStd)) { + ANS_LOGD("hashCodes is valid"); + return; + } + if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { + ANS_LOGD("enum convert failed"); + return; + } + if (!NotificationSts::IsValidRemoveReason(reasonType)) { + ANS_LOGD("reasonType is valid"); + return; + } + int ret = Notification::NotificationHelper::RemoveNotifications(hashCodesStd, reasonType); + ANS_LOGD("StsRemoveForHashCodes ret %{public}d. ErrorToExternal %{public}d", + ret, CJSystemapi::Notification::ErrorToExternal(ret)); +} +} +} 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 000000000..302f5fb30 --- /dev/null +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -0,0 +1,136 @@ +/* + * 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 *cRemoveForBundleSignature = + "Lnotification/NotificationCommonDef/BundleOption;" + "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKey;" + "L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *cRemoveForHashCodeSignature = + "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *cRemoveForHashCodesSignature = + "Lescompat/Array;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; +static const char *cDistributeOperationSignature = + "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/OperationInfo;:Lstd/core/Promise;"; +//static const char *cSubscribeSignature = +// "Lnotification/notificationSubscriber/NotificationSubscriber;" +// "Lnotification/notificationSubscribeInfo/NotificationSubscribeInfo;:V"; +//static const char *cUnSubscribeSignature = +// "Lnotification/notificationSubscriber/NotificationSubscriber;: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_LOGD("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); + std::thread t = std::thread([noWithOperationInfo, callback, info]() { + sptr callback_ = callback; + sptr info_ = info; + 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->OnOperationCallback(result); + } + }); + t.detach(); + return aniPromise; +} + +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", cRemoveForBundleSignature, reinterpret_cast(AniRemoveForBundle)}, + ani_native_function {"nativeRemove", cRemoveForHashCodeSignature, reinterpret_cast(AniRemoveForHashCode)}, + ani_native_function {"nativeRemove", cRemoveForHashCodesSignature, reinterpret_cast(AniRemoveForHashCodes)}, + ani_native_function {"nativeDistributeOperation", cDistributeOperationSignature, reinterpret_cast(AniDistributeOperation)}, +// ani_native_function {"nativeSubscribe", cSubscribeSignature, reinterpret_cast(StsSubscribe)}, +// ani_native_function {"nativeUnSubscribe", cUnSubscribeSignature, reinterpret_cast(StsUnSubscribe)}, + }; + + 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 index e2b40bf45..7dc07c424 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -16,12 +16,13 @@ import { BundleOption } from 'notification.NotificationCommonDef'; import { BusinessError, AsyncCallback } from '@ohos.base'; import { NotificationSlot } from 'notification.notificationSlot'; +import { NotificationRequest } from 'notification.notificationRequest'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; export default namespace notificationManager { - loadLibrary("notification_manager_ani_kit.z") + loadLibrary("notification_manager_ani.z") export enum SlotType { UNKNOWN_TYPE = 0, SOCIAL_COMMUNICATION = 1, @@ -58,6 +59,18 @@ export default namespace notificationManager { 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; @@ -78,49 +91,76 @@ export default namespace notificationManager { buttonName: string = ""; } - export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; - export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; - export native function nativeGetActiveNotificationCount(): number; - export native function nativeIsNotificationEnabled(userId?: number, bundleOption?: BundleOption): boolean; - export native function nativegetSlotFlagsByBundle(bundle: BundleOption): int; - export native function nativesetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; - export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; - export native function nativeisNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; + export interface SystemLiveViewSubscriber { + onResponse?: (notificationId: number, buttonOptions: ButtonOptions) => void; + } + + class SystemLiveViewSubscriberInner implements SystemLiveViewSubscriber { + onResponse?: (notificationId: number, buttonOptions: ButtonOptions) => void; + } + + export native function nativeCancelAll(): void; export native function nativeCancelWithId(id: number): void; export native function nativeCancelWithIdLabel(id: number, label: string): void; export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; - export native function nativeCancelAll(): void; + + export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; + export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; + + export native function nativeGetActiveNotificationCount(): number; + export native function nativeGetActiveNotifications():Array; + export native function nativeGetAllActiveNotifications():Array; + + 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 nativeaddDoNotDisturbProfile(templates: Array): void; - export native function nativeremoveDoNotDisturbProfile(templates: Array): void; - export native function nativeSetNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): void; - export native function nativeSetNotificationEnableSlotByOld(bundle: BundleOption, type: SlotType, enable: boolean): void; - export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { - 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: Object): void => { - let err: BusinessError = error as BusinessError; - callback(err, undefined); - }) + 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( + userId?: number, bundleOption?: BundleOption): boolean; + export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; + + export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; } - export function displayBadge(bundle: BundleOption, enable: boolean): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { - resolve(undefined); + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); }, (error: Object): void => { - reject(error); - }); - }); - return pPromise; + }) } - export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { - let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); + export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void + { + 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}; @@ -131,28 +171,16 @@ export default namespace notificationManager { callback(err, ret); }) } - - export function isBadgeDisplayed(bundle: BundleOption): Promise { - 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: Object): void => { - reject(error); - }); - }); - return pPromise; - } - 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; + export function isNotificationEnabled(bundleOption: BundleOption): Promise + { + 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); - }, (err:Object): void => { - reject(err); + }, (error: Object): void => { + reject(error); }); }); return pPromise; @@ -160,7 +188,7 @@ export default namespace notificationManager { export function isNotificationEnabled(userId: number, callback: AsyncCallback): void { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + 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}; @@ -175,20 +203,20 @@ export default namespace notificationManager { export function isNotificationEnabled(userId: number): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); - p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - resolve(ret); - }, (error: Object): void => { - reject(error); - }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithId(userId); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } - export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void + export function isNotificationEnabled(callback: AsyncCallback): void { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + 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}; @@ -200,131 +228,207 @@ export default namespace notificationManager { }) } - export function isNotificationEnabled(bundleOption: BundleOption): Promise + export function isNotificationEnabled(): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void + { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); }); p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - resolve(ret); + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); }, (error: Object): void => { - reject(error); }); + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } - export function isNotificationEnabled(callback: AsyncCallback): void + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable); }); p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - let err: BusinessError = {code: 0, data: undefined}; - callback(err, ret); + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); }, (error: Object): void => { - let ret : boolean = false; - let err: BusinessError = error as BusinessError; - callback(err, ret); }) } - export function isNotificationEnabled(): Promise + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - resolve(ret); + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); }, (error: Object): void => { - reject(error); - }); - }); - return pPromise; + }) } - export function getSlotFlagsByBundle(bundle: BundleOption): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): number => { return nativegetSlotFlagsByBundle(bundle); }); + export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { + let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); p.then((data: NullishType): void => { - let ret : Double = data as Double; - resolve(ret); + let slots : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, slots); }, (error: Object): void => { - reject(error); - }); + let slots : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, slots); + }) + } + + export function getSlotsByBundle(bundle: BundleOption): Promise> { + 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: Object): void => { + reject(error); + }); }); return pPromise; } export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { 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: Object): void => { - reject(error); + let p = taskpool.execute((): void => { return nativeSetSlotFlagsByBundle(bundle, slotFlags); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); + return pPromise; + } + + export function getSlotFlagsByBundle(bundle: BundleOption): Promise { + 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: Object): void => { + reject(error); + }); }); return pPromise; } - export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + export function publish(request: NotificationRequest, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativePublish(request); }); p.then((data: NullishType): void => { - resolve(undefined); + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); }, (error: Object): void => { - reject(error); + let err: BusinessError = error as BusinessError; + callback(err, undefined); }); + } + + export function publish(request: NotificationRequest): Promise { + 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: Object): void => { + reject(error); + }); }); return pPromise; } - - export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { - let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + + export function publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - - export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise - { - 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: Object): void => { - reject(error); - }); + + export function publish(request: NotificationRequest, userId: number): Promise { + 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: Object): void => { + reject(error); + }); }); return pPromise; } - export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + export function triggerSystemLiveView( + bundle: BundleOption, notificationId: number, buttonOptions: ButtonOptions): Promise { - let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); - p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; - callback(err, ret); - }, (error: Object): void => { - }) + 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: Object): void => { + reject(error); + }); + }); + return pPromise; } - export function cancel(id: number, callback: AsyncCallback): void { - let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); - p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; - callback(err, undefined); - }, (error: Object): void => { - }) + export function subscribeSystemLiveView(subscriber: SystemLiveViewSubscriber): Promise + { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; } - export function cancel(id: number): Promise { + export function removeDoNotDisturbProfile(templates: Array): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -334,9 +438,9 @@ export default namespace notificationManager { return pPromise; } - export function cancel(id: number, label: string): Promise { + export function addDoNotDisturbProfile(templates: Array): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -346,101 +450,146 @@ export default namespace notificationManager { return pPromise; } - export function cancel(id: number, label: string, callback: AsyncCallback): void { - let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + export function getAllActiveNotifications(callback: AsyncCallback>): void { + let p = taskpool.execute((): Array => { return nativeGetAllActiveNotifications(); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; - callback(err, undefined); + let ret : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function cancel(bundle: BundleOption, id: number): Promise { - 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: Object): void => { - reject(error); + 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: Object): 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: Object): void => { + reject(error); + }); }); return pPromise; } - export function cancelAll(): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelAll(); }); + export function getActiveNotifications(callback: AsyncCallback>): void { + let p = taskpool.execute((): Array => { return nativeGetActiveNotifications(); }); p.then((data: NullishType): void => { - resolve(undefined); + let ret : Array = data as Array; + let err: BusinessError = {code: 0, data: undefined}; + callback(err, ret); }, (error: Object): void => { - reject(error); - }); + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }) + } + + 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:Object): void => { + reject(err); + }); }); return pPromise; } - export function cancelAll(callback: AsyncCallback): void { - let p = taskpool.execute((): void => { return nativeCancelAll(); }); - p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + 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: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } + + export function displayBadge(bundle: BundleOption, enable: boolean): Promise { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } - export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { - let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); + export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { + let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); p.then((data: NullishType): void => { - let slots : Array = data as Array; + let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; - callback(err, slots); + callback(err, ret); }, (error: Object): void => { - let slots : Array = []; + let ret : boolean = false; let err: BusinessError = error as BusinessError; - callback(err, slots); - }) + callback(err, ret); + }) } - export function getSlotsByBundle(bundle: BundleOption): Promise> { - 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: Object): void => { - reject(error); - }); + export function isBadgeDisplayed(bundle: BundleOption): Promise { + 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: Object): void => { + reject(error); + }); }); return pPromise; } - export function addDoNotDisturbProfile(templates: Array): Promise { + export function cancel(bundle: BundleOption, id: number): Promise { 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: Object): void => { - reject(error); - }); + let p = taskpool.execute((): void => { return nativeCancelWithBundle(bundle, id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } - export function removeDoNotDisturbProfile(templates: Array): Promise { + export function cancel(id: number, label: string): Promise { 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: Object): void => { - reject(error); - }); + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void - { - let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotByOld(bundle, type, enable); }); + export function cancel(id: number, label: string, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 1, data: undefined}; callback(err, undefined); @@ -448,9 +597,8 @@ export default namespace notificationManager { }) } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void - { - let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); + export function cancel(id: number, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 1, data: undefined}; callback(err, undefined); @@ -458,16 +606,36 @@ export default namespace notificationManager { }) } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise - { + export function cancel(id: number): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); - p.then((data: NullishType): void => { - resolve(undefined); - }, (error: Object): void => { - reject(error); + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); + return pPromise; + } + + 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: Object): void => { + reject(error); + }); }); return pPromise; } -} + + export function cancelAll(callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } +} \ No newline at end of file diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets new file mode 100644 index 000000000..7fa6fd4d2 --- /dev/null +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -0,0 +1,487 @@ +/* + * 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: Object) => void; + +export default namespace notificationSubscribe { + 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 function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { notificationSubscribe.nativeSubscribe(subscriber) }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + } + ) + } + export function subscribe( + subscriber: NotificationSubscriber, + info: NotificationSubscribeInfo, + callback: AsyncCallback + ): void { + 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: Object): void => { + } + ) + } + export function subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise { + 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { notificationSubscribe.nativeUnSubscribe(subscriber) }); + p.then( + (e: NullishType): void => { + let err: BusinessError = {code: 0, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + } + ) + } + + export function unsubscribe(subscriber: NotificationSubscriber): Promise { + 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove( + bundle: BundleOption, + notificationKey: NotificationKey, + reason: RemoveReason, + callback: AsyncCallback + ): void { + 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: Object): void => { + } + ) + } + + export function remove( + bundle: BundleOption, + notificationKey: NotificationKey, + reason: RemoveReason + ): Promise { + 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback): void { + 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: Object): void => { + } + ) + } + + export function remove(hashCode: string, reason: RemoveReason): Promise { + 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function remove(hashCodes: Array, reason: RemoveReason, callback: AsyncCallback): void { + 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: Object): void => { + } + ) + } + + export function remove(hashCodes: Array, reason: RemoveReason): Promise { + 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function distributeOperation(hashcode: string, operationInfo?: OperationInfo): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + console.log("===============================1111"); + let p = taskpool.execute((): Object => { + if (operationInfo == undefined) { + return notificationSubscribe.nativeDistributeOperation(hashcode); + } else { + return notificationSubscribe.nativeDistributeOperation(hashcode, operationInfo); + } + }); + console.log("===============================2222"); + p.then( + (e: NullishType): void => { + try { + console.log("===============================3333"); + let stsPromise = e as String; + console.log("==================================================================== data", stsPromise); + resolve(undefined); + } catch(error) { + console.log("===============================6666. error", JSON.stringify(error)); + } + }, (error: Object): void => { + console.log("===============================4444"); + reject(error); + } + ) + console.log("===============================5555"); + }); + return pPromise; + } + + export interface OperationInfo { + actionName?: string; + userInput?: string; + } + + class OperationInfoInner implements OperationInfo { + public actionName?: string; + public userInput?: string; + } +} +/* +loadLibrary("notification_subscribe_ani_kit.z"); +let TAG = 'SUB_NOTIFICATION_ANS_SYSTEM_API_TEST ===>' +function StsRemoveForHashCodeAsyncCallback() +{ + console.log("StsRemoveForHashCodeAsyncCallback START"); + try { + notificationSubscribe.remove("device_0_1", notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { + if (err) { + console.info(`${TAG} StsRemoveForHashCode AsyncCallback errCode: ${err.code}`) + } else { + console.info(`${TAG} StsRemoveForHashCode AsyncCallback success`) + } + }); + } catch(error) { + console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForHashCodeAsyncCallback END`); +} + +function StsRemoveForHashCodePromise() +{ + console.log("StsRemoveForHashCodeAsyncCallback START"); + try { + let p = notificationSubscribe.remove("device_0_1", notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); + p.then( + (data: NullishType): void => { + console.info(`${TAG} StsRemoveForHashCodePromise suc..`); + }, (error: Object): void => { + console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); + } + ) + } catch(error) { + console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForHashCodeAsyncCallback END`); +} + +function StsRemoveForBundleAsyncCallback() +{ + console.log("StsRemoveForBundleAsyncCallback START"); + let option: BundleOption = { bundle: 'device_0_1', uid: 10001 }; + let key: notificationSubscribe.NotificationKey = { id: 2001, label: 'label' }; + try { + notificationSubscribe.remove(option, key, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { + if (err) { + console.info(`${TAG} StsRemoveForBundleAsyncCallback errCode: ${err.code}`) + } else { + console.info(`${TAG} StsRemoveForBundleAsyncCallback success`) + } + }); + } catch(error) { + console.info("StsRemoveForBundleAsyncCallback error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForBundleAsyncCallback END`); +} + +function StsRemoveForBundlePromise() +{ + console.log("StsRemoveForBundlePromise START"); + let option: BundleOption = { bundle: 'device_0_1', uid: 10001 }; + let key: notificationSubscribe.NotificationKey = { id: 2001, label: 'label' }; + try { + let p = notificationSubscribe.remove(option, key, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); + p.then( + (data: NullishType): void => { + console.info(`${TAG} StsRemoveForBundlePromise suc..`); + }, (error: Object): void => { + console.info("StsRemoveForBundlePromise error ", JSON.stringify(error)); + } + ) + } catch(error) { + console.info("StsRemoveForBundlePromise error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForBundlePromise END`); +} + +function StsRemoveForHashCodesAsyncCallback() +{ + console.log("StsRemoveForHashCodesAsyncCallback START"); + let hasCodes = ['str1', 'str2', 'str3']; + try { + notificationSubscribe.remove(hasCodes, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { + if (err) { + console.info(`${TAG} StsRemoveForHashCodesAsyncCallback errCode: ${err.code}`) + } else { + console.info(`${TAG} StsRemoveForHashCodesAsyncCallback success`) + } + }); + } catch(error) { + console.info("StsRemoveForHashCodesAsyncCallback error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForHashCodesAsyncCallback END`); +} + +function StsRemoveForHashCodesPromise() +{ + console.log("StsRemoveForHashCodesPromise START"); + let hasCodes = ['str1', 'str2', 'str3']; + try { + let p = notificationSubscribe.remove(hasCodes, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); + p.then( + (data: NullishType): void => { + console.info(`${TAG} StsRemoveForHashCodesPromise suc..`); + }, (error: Object): void => { + console.info("StsRemoveForHashCodesPromise error ", JSON.stringify(error)); + } + ) + } catch(error) { + console.info("StsRemoveForHashCodesPromise error ", JSON.stringify(error)); + } + console.info(`${TAG} StsRemoveForHashCodesPromise END`); +} + +function StsDistributeOperationPromise() +{ + console.log("StsDistributeOperationPromise START"); + let hasCode = "hasCode"; + let info: notificationSubscribe.OperationInfo = { + actionName: "actionName", + userInput: "userInput" + } + try { + console.info(`${TAG} StsDistributeOperationPromise THEN Before `); + let p = notificationSubscribe.distributeOperation(hasCode, info); + console.info(`${TAG} StsDistributeOperationPromise THEN After`); + p.then( + (data: NullishType): void => { + console.info(`${TAG} StsDistributeOperationPromise suc..`); + }, (error: Object): void => { + console.info("StsDistributeOperationPromise error ", JSON.stringify(error)); + } + ) + } catch(error) { + console.info("StsDistributeOperationPromise error ", JSON.stringify(error)); + } + console.info(`${TAG} StsDistributeOperationPromise END`); +} + +function StsSubscribeAsyncCallback() +{ + try { + let sub: NotificationSubscriber = { + + } + console.info("StsSubscribeAsyncCallback Before"); + notificationSubscribe.subscribe(sub, (err: BusinessError, data: NullishType): void => { + console.log('StsSubscribeAsyncCallback suc...'); + }); + console.info("StsSubscribeAsyncCallback After"); + } catch(error) { + console.info("StsSubscribeAsyncCallback error ", JSON.stringify(error)); + } +} + +// type FnOnDisconnect = onDisconnect: () => void; + +class TestNotificationSubscriber implements NotificationSubscriber { + onDisconnect?: () => void = () => { + console.log('====================== onDisconnect'); + } + + onConnect?: () => void = () => { + console.log('====================== onConnect'); + } + + onDestroy?: () => void = () => { + console.log('====================== onDestroy'); + } +} + +function StsSubscribeForInfoAsynCallback() +{ + try { + let sub: NotificationSubscriber = new TestNotificationSubscriber; + + let info: NotificationSubscribeInfo = { + bundleNames: ['zxh', 'xhz', 'hzx'], + userId: 1000, + deviceType: 'deviceType test', + filterLimit: 1001 + } + console.info("StsSubscribeForInfoAsynCallback Before"); + notificationSubscribe.subscribe(sub, info, (err: BusinessError, data: NullishType): void => { + console.log('StsSubscribeForInfoAsynCallback suc...'); + }); + console.info("StsSubscribeForInfoAsynCallback After"); + } catch(error) { + console.info("StsSubscribeForInfoAsynCallback error ", JSON.stringify(error)); + } +} + +function StsSubscribePromise() +{ + try { + let sub: NotificationSubscriber = { + + } + + let info: NotificationSubscribeInfo = { + bundleNames: ['zxh', 'xhz', 'hzx'], + userId: 1000, + deviceType: 'deviceType test', + filterLimit: 1001 + } + console.log(JSON.stringify(info)); + console.info("StsSubscribePromise Before"); + let p = notificationSubscribe.subscribe(sub, info); + p.then( + (e: NullishType): void => { + console.info("StsSubscribePromise suc.."); + }, (error: Object): void => { + console.info("StsSubscribePromise error ", JSON.stringify(error)); + } + ) + + let p1 = notificationSubscribe.unsubscribe(sub); + p1.then( + (e: NullishType): void => { + console.info("un StsSubscribePromise suc.. "); + }, (error: Object): void => { + console.info("un StsSubscribePromise error ", JSON.stringify(error)); + } + ) + } catch(error) { + console.info("StsSubscribePromise error ", JSON.stringify(error)); + } +} + +function main() +{ + StsDistributeOperationPromise(); + StsSubscribeAsyncCallback(); + StsSubscribeForInfoAsynCallback(); + StsSubscribePromise(); +} +*/ \ No newline at end of file diff --git a/frameworks/ets/ets/BUILD.gn b/frameworks/ets/ets/BUILD.gn index 85071d4b2..d58786dc6 100644 --- a/frameworks/ets/ets/BUILD.gn +++ b/frameworks/ets/ets/BUILD.gn @@ -61,6 +61,100 @@ ohos_prebuilt_etc("notification_template_etc") { } # 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 = "./" @@ -223,12 +317,43 @@ ohos_prebuilt_etc("notification_manager_etc") { } # 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", @@ -243,5 +368,7 @@ group("ets_files") { ":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/notificationContent.ets b/frameworks/ets/ets/notification/notificationContent.ets index 78d12b8b3..17286ab57 100644 --- a/frameworks/ets/ets/notification/notificationContent.ets +++ b/frameworks/ets/ets/notification/notificationContent.ets @@ -328,13 +328,13 @@ export interface NotificationTime { class NotificationTimeInner implements NotificationTime { - initialTime?: number; + initialTime?: number | undefined; - isCountDown?: boolean; + isCountDown?: boolean | undefined; - isPaused?: boolean; + isPaused?: boolean | undefined; - isInTitle?: boolean; + isInTitle?: boolean | undefined; } export interface NotificationProgress { diff --git a/frameworks/ets/ets/notification/notificationSlot.ets b/frameworks/ets/ets/notification/notificationSlot.ets index f2cb24694..4b3c3c769 100644 --- a/frameworks/ets/ets/notification/notificationSlot.ets +++ b/frameworks/ets/ets/notification/notificationSlot.ets @@ -1,3 +1,17 @@ +/* + * 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 { diff --git a/frameworks/ets/ets/notification/notificationSorting.ets b/frameworks/ets/ets/notification/notificationSorting.ets new file mode 100644 index 000000000..c3c2d28c0 --- /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 000000000..de4511790 --- /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 000000000..aba794d16 --- /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 000000000..3dc212b86 --- /dev/null +++ b/frameworks/ets/ets/notification/notificationSubscriber.ets @@ -0,0 +1,179 @@ +/* + * 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; + + // // onDoNotDisturbDateChange?: (mode: notification.DoNotDisturbDate) => 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 { + onConsume?: (data: SubscribeCallbackData) => void; + + onCancel?: (data: SubscribeCallbackData) => void; + + onUpdate?: (data: NotificationSortingMap) => void; + + onConnect?: () => void; + + onDisconnect?: () => void = ()=>{ + + }; + + onDestroy?: () => void; + + // // onDoNotDisturbDateChange?: (mode: notification.DoNotDisturbDate) => void; + + onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; + + onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; + + onBadgeChanged?: (data: BadgeNumberCallbackData) => void; + + onBadgeEnabledChanged?: BadgeEnabledChangedCallback; + + 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 index 1c0a07e43..8033b7723 100644 --- a/frameworks/ets/ets/notification/notificationTemplate.ets +++ b/frameworks/ets/ets/notification/notificationTemplate.ets @@ -16,4 +16,9 @@ export interface NotificationTemplate { name: string; data: Record; +} + +class NotificationTemplateInner implements NotificationTemplate { + name: string = ""; + data: Record = {}; } \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationUserInput.ets b/frameworks/ets/ets/notification/notificationUserInput.ets index eef5e12cc..6ac04f685 100644 --- a/frameworks/ets/ets/notification/notificationUserInput.ets +++ b/frameworks/ets/ets/notification/notificationUserInput.ets @@ -15,4 +15,8 @@ export interface NotificationUserInput { inputKey: string; +} + +class NotificationUserInputInner implements NotificationUserInput { + inputKey: string = ""; } \ No newline at end of file -- Gitee From a1dc3d157d206f8ecc07b8411fd0d754ffbfaf16 Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 14 May 2025 21:44:55 +0800 Subject: [PATCH 05/52] ets erro Signed-off-by: heguokai --- .../ets/ets/@ohos.notificationManager.ets | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 7dc07c424..91a4694de 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -133,8 +133,7 @@ export default namespace notificationManager { export native function nativeIsNotificationEnabled(): boolean; export native function nativeIsNotificationEnabledWithId(userId : number): boolean; - export native function nativeIsNotificationEnabledWithBundleOption( - userId?: number, bundleOption?: BundleOption): boolean; + export native function nativeIsNotificationEnabledWithBundleOption(bundleOption: BundleOption): boolean; export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { @@ -428,24 +427,24 @@ export default namespace notificationManager { export function removeDoNotDisturbProfile(templates: Array): Promise { 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: Object): void => { - reject(error); - }); + let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } export function addDoNotDisturbProfile(templates: Array): Promise { 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: Object): void => { - reject(error); - }); + let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } @@ -457,8 +456,6 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { - let err: BusinessError = error as BusinessError; - callback(err, undefined); }) } @@ -497,8 +494,7 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { - let err: BusinessError = error as BusinessError; - callback(err, undefined); + }) } -- Gitee From 35d1cd4e8763778ced8f958e42080354f6c28f70 Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 15 May 2025 11:24:00 +0800 Subject: [PATCH 06/52] git modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_action_button.cpp | 4 ++-- frameworks/ets/ani/src/sts_common.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 4 ++-- frameworks/ets/ani/src/sts_user_input.cpp | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index f7fc64c01..9dc131976 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -87,7 +87,7 @@ ani_object WrapNotificationActionButton(ani_env* env, // title: string; ani_string stringValue = nullptr; RETURN_NULL_IF_FALSE(GetAniStringByString(env, actionButton->GetTitle(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "title", stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)); // wantAgent: WantAgent; //napi处理过程 std::shared_ptr agent = actionButton->GetWantAgent(); @@ -96,7 +96,7 @@ ani_object WrapNotificationActionButton(ani_env* env, return nullptr; } else { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); - RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); } // need to do diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 44d44c24a..bda214501 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -146,7 +146,7 @@ ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, ANS_LOGI("Object_GetPropertyByName_Ref fail, status: %{public}d", status); return status; } - if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) == ANI_OK) { + if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { ANS_LOGI("Reference_IsUndefined failed, status : %{public}d", status); return status; } diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 0de7edf9f..8f2bb71fe 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -856,14 +856,14 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not std::shared_ptr additionalData = request->GetAdditionalData(); if (additionalData) { ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "extraInfo", extraInfo)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "extraInfo", extraInfo)); } // actionButtons?: Array std::vector> actionButtons = request->GetActionButtons(); ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); if (actionButtonsArrayObj != nullptr) { - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "actionButtons", actionButtonsArrayObj)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "actionButtons", actionButtonsArrayObj)); } // template?: NotificationTemplate std::shared_ptr templ = request->GetTemplate(); diff --git a/frameworks/ets/ani/src/sts_user_input.cpp b/frameworks/ets/ani/src/sts_user_input.cpp index beeddbab0..30f97fc89 100644 --- a/frameworks/ets/ani/src/sts_user_input.cpp +++ b/frameworks/ets/ani/src/sts_user_input.cpp @@ -40,7 +40,7 @@ ani_object WarpUserInput(ani_env *env, std::shared_ptrGetInputKey(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetterOptional(env, userInputCls, userInputObject, "inputKey", stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, userInputCls, userInputObject, "inputKey", stringValue)); return userInputObject; } } -- Gitee From 22fc4b6aeb3c21a8a42e4ba585434be4851ecb5a Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 15 May 2025 18:05:28 +0800 Subject: [PATCH 07/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/include/manager/ani_cance.h | 4 ++-- frameworks/ets/ani/include/manager/ani_display_badge.h | 4 ++-- .../ets/ani/include/manager/ani_do_not_disturb_profile.h | 4 ++-- frameworks/ets/ani/include/manager/ani_get_active.h | 4 ++-- frameworks/ets/ani/include/manager/ani_local_live_view.h | 4 ++-- frameworks/ets/ani/include/manager/ani_manager.h | 5 +++-- .../ets/ani/include/manager/ani_notification_enable.h | 4 ++-- frameworks/ets/ani/include/manager/ani_publish.h | 4 ++-- frameworks/ets/ani/include/manager/ani_slot.h | 4 ++-- frameworks/ets/ani/include/sts_action_button.h | 6 ++---- frameworks/ets/ani/include/sts_bundle_option.h | 5 ++--- frameworks/ets/ani/include/sts_common.h | 4 ++-- frameworks/ets/ani/include/sts_convert_other.h | 4 ++-- frameworks/ets/ani/include/sts_disturb_mode.h | 5 ++--- frameworks/ets/ani/include/sts_notification_content.h | 4 ++-- frameworks/ets/ani/include/sts_notification_flag.h | 4 ++-- frameworks/ets/ani/include/sts_notification_manager.h | 4 ++-- frameworks/ets/ani/include/sts_request.h | 4 ++-- frameworks/ets/ani/include/sts_slot.h | 4 ++-- frameworks/ets/ani/include/sts_sorting.h | 4 ++-- frameworks/ets/ani/include/sts_sorting_map.h | 4 ++-- frameworks/ets/ani/include/sts_subscribe.h | 4 ++-- frameworks/ets/ani/include/sts_subscribe_info.h | 4 ++-- frameworks/ets/ani/include/sts_subscriber.h | 4 ++-- frameworks/ets/ani/include/sts_template.h | 4 ++-- frameworks/ets/ani/include/sts_throw_erro.h | 4 ++-- frameworks/ets/ani/include/sts_user_input.h | 4 ++-- frameworks/ets/ani/include/subscribe/ani_remove.h | 5 +++-- frameworks/ets/ani/include/subscribe/ani_subscribe.h | 4 ++-- frameworks/ets/ets/@ohos.notificationManager.ets | 2 +- 30 files changed, 61 insertions(+), 63 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_cance.h b/frameworks/ets/ani/include/manager/ani_cance.h index d1f71d4cc..0ba94d339 100644 --- a/frameworks/ets/ani/include/manager/ani_cance.h +++ b/frameworks/ets/ani/include/manager/ani_cance.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_CANCE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_CANCE_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_display_badge.h b/frameworks/ets/ani/include/manager/ani_display_badge.h index 32c00b23e..a9489f60b 100644 --- a/frameworks/ets/ani/include/manager/ani_display_badge.h +++ b/frameworks/ets/ani/include/manager/ani_display_badge.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DISPLAY_BADGE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DISPLAY_BADGE_H +#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 { 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 index 7da166437..686fbc491 100644 --- a/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h +++ b/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DO_NOT_DISTURB_PROFILE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_DO_NOT_DISTURB_PROFILE_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_get_active.h b/frameworks/ets/ani/include/manager/ani_get_active.h index 67c375b5f..b2d18712d 100644 --- a/frameworks/ets/ani/include/manager/ani_get_active.h +++ b/frameworks/ets/ani/include/manager/ani_get_active.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_GET_ACTIVE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_GET_ACTIVE_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_local_live_view.h b/frameworks/ets/ani/include/manager/ani_local_live_view.h index d4fb91a7c..35cb1275e 100644 --- a/frameworks/ets/ani/include/manager/ani_local_live_view.h +++ b/frameworks/ets/ani/include/manager/ani_local_live_view.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_LOCAL_LIVE_VIEW_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_LOCAL_LIVE_VIEW_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_manager.h b/frameworks/ets/ani/include/manager/ani_manager.h index faab4a7fe..fd52141fa 100644 --- a/frameworks/ets/ani/include/manager/ani_manager.h +++ b/frameworks/ets/ani/include/manager/ani_manager.h @@ -13,9 +13,10 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_MANAGER_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_MANAGER_H +#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); diff --git a/frameworks/ets/ani/include/manager/ani_notification_enable.h b/frameworks/ets/ani/include/manager/ani_notification_enable.h index c24accc63..49c4f7a3b 100644 --- a/frameworks/ets/ani/include/manager/ani_notification_enable.h +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_ENABLE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_ENABLE_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_publish.h b/frameworks/ets/ani/include/manager/ani_publish.h index 134d900a2..fd216d5ff 100644 --- a/frameworks/ets/ani/include/manager/ani_publish.h +++ b/frameworks/ets/ani/include/manager/ani_publish.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_PUBLISH_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_PUBLISH_H +#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 { diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h index 7e419a6af..5b7ba12b8 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SLOT_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SLOT_H +#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 { diff --git a/frameworks/ets/ani/include/sts_action_button.h b/frameworks/ets/ani/include/sts_action_button.h index 047a3259c..3a690d2d6 100644 --- a/frameworks/ets/ani/include/sts_action_button.h +++ b/frameworks/ets/ani/include/sts_action_button.h @@ -13,9 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ACTION_BUTTON_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ACTION_BUTTON_H - +#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" @@ -24,7 +23,6 @@ #include "notification_user_input.h" #include "notification_action_button.h" - namespace OHOS { namespace NotificationSts { using namespace OHOS::AppExecFwk; diff --git a/frameworks/ets/ani/include/sts_bundle_option.h b/frameworks/ets/ani/include/sts_bundle_option.h index c149dc228..a1bc56061 100644 --- a/frameworks/ets/ani/include/sts_bundle_option.h +++ b/frameworks/ets/ani/include/sts_bundle_option.h @@ -13,9 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_BUNDLE_OPTION_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_BUNDLE_OPTION_H - +#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" diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 16987dd35..00a039835 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_H +#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 diff --git a/frameworks/ets/ani/include/sts_convert_other.h b/frameworks/ets/ani/include/sts_convert_other.h index d89acd5e6..0d6cd1b20 100644 --- a/frameworks/ets/ani/include/sts_convert_other.h +++ b/frameworks/ets/ani/include/sts_convert_other.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_OTHER_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_OTHER_H +#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" diff --git a/frameworks/ets/ani/include/sts_disturb_mode.h b/frameworks/ets/ani/include/sts_disturb_mode.h index b01efa564..eb208a289 100644 --- a/frameworks/ets/ani/include/sts_disturb_mode.h +++ b/frameworks/ets/ani/include/sts_disturb_mode.h @@ -13,10 +13,9 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DISTURB_MODE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DISTURB_MODE_H +#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; diff --git a/frameworks/ets/ani/include/sts_notification_content.h b/frameworks/ets/ani/include/sts_notification_content.h index 645619473..57f8adc80 100644 --- a/frameworks/ets/ani/include/sts_notification_content.h +++ b/frameworks/ets/ani/include/sts_notification_content.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_NOTIFICATION_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONVERT_NOTIFICATION_H +#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" diff --git a/frameworks/ets/ani/include/sts_notification_flag.h b/frameworks/ets/ani/include/sts_notification_flag.h index a85baa69f..33b3e7238 100644 --- a/frameworks/ets/ani/include/sts_notification_flag.h +++ b/frameworks/ets/ani/include/sts_notification_flag.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_FLAG_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_FLAG_H +#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" diff --git a/frameworks/ets/ani/include/sts_notification_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h index 363f6c21f..8c9a089fb 100644 --- a/frameworks/ets/ani/include/sts_notification_manager.h +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_MANAGER_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_MANAGER_H +#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" diff --git a/frameworks/ets/ani/include/sts_request.h b/frameworks/ets/ani/include/sts_request.h index e6449af4f..893d6ce46 100644 --- a/frameworks/ets/ani/include/sts_request.h +++ b/frameworks/ets/ani/include/sts_request.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_REQUEST_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_REQUEST_H +#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" diff --git a/frameworks/ets/ani/include/sts_slot.h b/frameworks/ets/ani/include/sts_slot.h index 934519c34..33fedea24 100644 --- a/frameworks/ets/ani/include/sts_slot.h +++ b/frameworks/ets/ani/include/sts_slot.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SLOT_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SLOT_H +#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" diff --git a/frameworks/ets/ani/include/sts_sorting.h b/frameworks/ets/ani/include/sts_sorting.h index 029e017c5..7011db231 100644 --- a/frameworks/ets/ani/include/sts_sorting.h +++ b/frameworks/ets/ani/include/sts_sorting.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_SORTING_H #include "ani.h" #include "notification_sorting.h" diff --git a/frameworks/ets/ani/include/sts_sorting_map.h b/frameworks/ets/ani/include/sts_sorting_map.h index 3c51d775d..814d370c2 100644 --- a/frameworks/ets/ani/include/sts_sorting_map.h +++ b/frameworks/ets/ani/include/sts_sorting_map.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_MAP_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_MAP_H +#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" diff --git a/frameworks/ets/ani/include/sts_subscribe.h b/frameworks/ets/ani/include/sts_subscribe.h index ec780e460..02416bb62 100644 --- a/frameworks/ets/ani/include/sts_subscribe.h +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBE_H +#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" diff --git a/frameworks/ets/ani/include/sts_subscribe_info.h b/frameworks/ets/ani/include/sts_subscribe_info.h index d77c54b4f..5342188b8 100644 --- a/frameworks/ets/ani/include/sts_subscribe_info.h +++ b/frameworks/ets/ani/include/sts_subscribe_info.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SORTING_H +#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" diff --git a/frameworks/ets/ani/include/sts_subscriber.h b/frameworks/ets/ani/include/sts_subscriber.h index d2b375f9b..2999c285d 100644 --- a/frameworks/ets/ani/include/sts_subscriber.h +++ b/frameworks/ets/ani/include/sts_subscriber.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBER_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_SUBSCRIBER_H +#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" diff --git a/frameworks/ets/ani/include/sts_template.h b/frameworks/ets/ani/include/sts_template.h index 4427c6b37..fd9431cb4 100644 --- a/frameworks/ets/ani/include/sts_template.h +++ b/frameworks/ets/ani/include/sts_template.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_TEMPLATE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_TEMPLATE_H +#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" diff --git a/frameworks/ets/ani/include/sts_throw_erro.h b/frameworks/ets/ani/include/sts_throw_erro.h index de62ad197..2727fd54a 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONTENT_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_CONTENT_H +#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 diff --git a/frameworks/ets/ani/include/sts_user_input.h b/frameworks/ets/ani/include/sts_user_input.h index d94a7e887..9aebd2404 100644 --- a/frameworks/ets/ani/include/sts_user_input.h +++ b/frameworks/ets/ani/include/sts_user_input.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_USER_INPUT_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_USER_INPUT_H +#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" diff --git a/frameworks/ets/ani/include/subscribe/ani_remove.h b/frameworks/ets/ani/include/subscribe/ani_remove.h index 830000329..a60aa5ab8 100644 --- a/frameworks/ets/ani/include/subscribe/ani_remove.h +++ b/frameworks/ets/ani/include/subscribe/ani_remove.h @@ -13,9 +13,10 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SUBSCRIBE_REMOVE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_SUBSCRIBE_REMOVE_H +#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); diff --git a/frameworks/ets/ani/include/subscribe/ani_subscribe.h b/frameworks/ets/ani/include/subscribe/ani_subscribe.h index 212697561..5f7859b29 100644 --- a/frameworks/ets/ani/include/subscribe/ani_subscribe.h +++ b/frameworks/ets/ani/include/subscribe/ani_subscribe.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_SUBSCRIBE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_ANI_NOTIFICATION_SUBSCRIBE_H +#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 diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 91a4694de..ccf81490f 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -129,7 +129,7 @@ export default namespace notificationManager { export native function nativeSetNotificationEnableSlot( bundle: BundleOption, type: SlotType, enable: boolean): void; export native function nativeSetNotificationEnableSlotWithForce( - bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): void; + bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean): void; export native function nativeIsNotificationEnabled(): boolean; export native function nativeIsNotificationEnabledWithId(userId : number): boolean; -- Gitee From f28ddd5fbab37037049f8c740710fc18856684e5 Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 15 May 2025 18:47:33 +0800 Subject: [PATCH 08/52] modify Signed-off-by: heguokai --- .../manager/ani_do_not_disturb_profile.h | 3 +-- frameworks/ets/ani/include/manager/ani_slot.h | 4 ++-- frameworks/ets/ani/include/sts_sorting.h | 2 +- frameworks/ets/ani/src/manager/ani_slot.cpp | 21 +++++-------------- 4 files changed, 9 insertions(+), 21 deletions(-) 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 index 686fbc491..b4a0ac997 100644 --- a/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h +++ b/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h @@ -23,5 +23,4 @@ void AniAddDoNotDisturbProfile(ani_env *env, ani_object obj); void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj); } } -#endif - +#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 index 5b7ba12b8..127dcfff8 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -25,8 +25,8 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj); 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_object isForceControl); +void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, + ani_boolean enable, ani_boolean isForceControl); } // namespace NotificationManagerSts } // namespace OHOS #endif diff --git a/frameworks/ets/ani/include/sts_sorting.h b/frameworks/ets/ani/include/sts_sorting.h index 7011db231..eff754a03 100644 --- a/frameworks/ets/ani/include/sts_sorting.h +++ b/frameworks/ets/ani/include/sts_sorting.h @@ -14,7 +14,7 @@ */ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_SORTING_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_SORTING_H #include "ani.h" #include "notification_sorting.h" diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index c03126d5b..644db64d9 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -84,11 +84,9 @@ void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enu } void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, - ani_object isForceControl) + ani_boolean isForceControl) { ANS_LOGD("AniSetNotificationEnableSlotWithForce enter "); - ani_boolean isUndefined = false; - ani_boolean res = 0.0; Notification::NotificationBundleOption option; Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; if (!(NotificationSts::SlotTypeEtsToC(env, type, slotType)) @@ -97,19 +95,10 @@ void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption return; } int returncode = 0; - env->Reference_IsUndefined(isForceControl, &isUndefined); - if(isUndefined) { - bool forceControl = false; - returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, - NotificationSts::AniBooleanToBool(enable), forceControl); - } else { - if (ANI_OK !=env->Object_CallMethodByName_Boolean(isForceControl, "booleanValue", nullptr, &res)){ - NotificationSts::ThrowStsErroWithLog(env, "SetNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); - return; - } - returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, - NotificationSts::AniBooleanToBool(enable), NotificationSts::AniBooleanToBool(res)); - } + + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, + NotificationSts::AniBooleanToBool(enable), NotificationSts::AniBooleanToBool(isForceControl)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); -- Gitee From 08be7bba512e39a69cfbab1b1c53d3023ceb196a Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 15 May 2025 20:50:56 +0800 Subject: [PATCH 09/52] modify Signed-off-by: heguokai --- .../include/manager/ani_notification_enable.h | 2 +- .../src/manager/ani_notification_enable.cpp | 2 +- .../ets/ets/@ohos.notificationManager.ets | 28 +++++++++++++------ 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_notification_enable.h b/frameworks/ets/ani/include/manager/ani_notification_enable.h index 49c4f7a3b..3fdb7013d 100644 --- a/frameworks/ets/ani/include/manager/ani_notification_enable.h +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.h @@ -20,7 +20,7 @@ namespace OHOS { namespace NotificationManagerSts { ani_boolean AniIsNotificationEnabled(ani_env *env); -ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_int userId); +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); } // namespace NotificationManagerSts diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index 672df8ba7..7d0bf7ecf 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -37,7 +37,7 @@ ani_boolean AniIsNotificationEnabled(ani_env *env) return NotificationSts::BoolToAniBoolean(allowed); } -ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_int userId) +ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_double userId) { ANS_LOGD("AniIsNotificationEnabledWithId call"); bool allowed = false; diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index ccf81490f..cc95f5462 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -151,10 +151,12 @@ export default namespace notificationManager { export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { - }) + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); } export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void @@ -245,16 +247,19 @@ export default namespace notificationManager { { let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }); } export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise { + let forceControl:boolean = isForceControl != undefined ? isForceControl : false; let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); }); + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, forceControl); }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -268,9 +273,11 @@ export default namespace notificationManager { { let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } @@ -293,9 +300,12 @@ export default namespace notificationManager { let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + 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); }) } @@ -587,7 +597,7 @@ export default namespace notificationManager { export function cancel(id: number, label: string, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { }) @@ -596,7 +606,7 @@ export default namespace notificationManager { export function cancel(id: number, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { }) @@ -629,7 +639,7 @@ export default namespace notificationManager { export function cancelAll(callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelAll(); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { }) -- Gitee From 19dee2f016d8aa4b1679c31f4f44388de8895ada Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 15 May 2025 21:40:56 +0800 Subject: [PATCH 10/52] modify Signed-off-by: heguokai --- frameworks/ets/ets/@ohos.notificationManager.ets | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index cc95f5462..02c2c817e 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -257,7 +257,10 @@ export default namespace notificationManager { export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise { - let forceControl:boolean = isForceControl != undefined ? isForceControl : false; + 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 => { -- Gitee From 4171cb39db4a417ad3a7c01ea74df8ecd7d7f7a6 Mon Sep 17 00:00:00 2001 From: heguokai <275503077@qq.com> Date: Fri, 16 May 2025 18:41:44 +0800 Subject: [PATCH 11/52] =?UTF-8?q?ani=20=E7=9B=B8=E5=85=B3=E6=8F=90?= =?UTF-8?q?=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: heguokai --- frameworks/ets/ani/BUILD.gn | 7 + .../include/manager/ani_ans_dialog_callback.h | 84 +++++ .../ani/include/manager/ani_request_enable.h | 25 ++ frameworks/ets/ani/include/sts_common.h | 1 + frameworks/ets/ani/include/sts_subscribe.h | 1 + .../src/manager/ani_ans_dialog_callback.cpp | 174 ++++++++++ .../ets/ani/src/manager/ani_manager.cpp | 7 +- .../ani/src/manager/ani_request_enable.cpp | 220 ++++++++++++ frameworks/ets/ani/src/sts_common.cpp | 47 ++- .../ets/ani/src/sts_notification_manager.cpp | 28 +- frameworks/ets/ani/src/sts_subscribe.cpp | 189 +++++------ frameworks/ets/ani/src/sts_subscriber.cpp | 12 +- .../ets/ani/src/subscribe/ani_remove.cpp | 54 ++- .../ets/ani/src/subscribe/ani_subscribe.cpp | 43 ++- .../ets/ets/@ohos.notificationSubscribe.ets | 313 ++++-------------- .../notification/notificationSubscriber.ets | 4 +- 16 files changed, 804 insertions(+), 405 deletions(-) create mode 100755 frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h create mode 100755 frameworks/ets/ani/include/manager/ani_request_enable.h create mode 100755 frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp create mode 100755 frameworks/ets/ani/src/manager/ani_request_enable.cpp diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn index 358cf28eb..fa0771b8a 100644 --- a/frameworks/ets/ani/BUILD.gn +++ b/frameworks/ets/ani/BUILD.gn @@ -54,6 +54,8 @@ ohos_shared_library("notification_manager_ani") { "./src/manager/ani_do_not_disturb_profile.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", ] cflags = [] @@ -80,6 +82,11 @@ ohos_shared_library("notification_manager_ani") { "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", ] innerapi_tags = [ "platformsdk" ] 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 000000000..191f6fdc9 --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h @@ -0,0 +1,84 @@ +/* + * 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_request_enable.h b/frameworks/ets/ani/include/manager/ani_request_enable.h new file mode 100755 index 000000000..3e4592c6a --- /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/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 00a039835..7c37c3255 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -26,6 +26,7 @@ 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); +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); diff --git a/frameworks/ets/ani/include/sts_subscribe.h b/frameworks/ets/ani/include/sts_subscribe.h index 02416bb62..fc0650dae 100644 --- a/frameworks/ets/ani/include/sts_subscribe.h +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -35,6 +35,7 @@ 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_; 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 000000000..3e612fac8 --- /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_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index a597b22af..0e59b31f4 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -23,6 +23,7 @@ #include "ani_get_active.h" #include "ani_publish.h" #include "ani_local_live_view.h" +#include "ani_request_enable.h" namespace OHOS { namespace NotificationManagerSts { @@ -86,7 +87,11 @@ void AniNotificationManagerRegistryInit(ani_env *env) reinterpret_cast(AniIsNotificationEnabledWithId)}, ani_native_function {"nativeIsNotificationEnabledWithBundleOption", nullptr, reinterpret_cast(AniIsNotificationEnabledWithBundleOption)}, - ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(AniSetNotificationEnable)}, + ani_native_function {"nativeSetNotificationEnable", + nullptr, reinterpret_cast(AniSetNotificationEnable)}, + ani_native_function {"nativeRequestEnableNotification", + "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", + reinterpret_cast(AniRequestEnableNotification)}, }; status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); 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 000000000..5e2286b09 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_request_enable.cpp @@ -0,0 +1,220 @@ +/* + * 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"); + 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"); + if (content == nullptr) { + ANS_LOGD("content is nullptr"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, + OHOS::NotificationSts::FindAnsErrMsg(ERROR_PARAM_INVALID)); + return nullptr; + } + 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/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index bda214501..3ac5b5cda 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ #include "sts_common.h" - #include "ans_log_wrapper.h" +#include "ani_common_util.h" namespace OHOS { namespace NotificationSts { @@ -217,15 +217,15 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na ani_object GetAniStringArrayByVectorString(ani_env *env, std::vector &strs) { - if (strs.empty()) { - return nullptr; - } int length = strs.size(); ani_object arrayObj = newArrayClass(env, length); + if (strs.empty()) { + return arrayObj; + } ani_size i = 0; for (auto &str : strs) { ani_string aniStr; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, str, aniStr) != ANI_OK); + RETURN_NULL_IF_FALSE((GetAniStringByString(env, str, aniStr) == ANI_OK)); if (aniStr == nullptr) { return nullptr; } @@ -417,14 +417,13 @@ ani_object newRecordClass(ani_env *env) ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values) { - if (values.empty()) { - return nullptr; - } ani_object arrayObj = newArrayClass(env, values.size()); if (arrayObj == nullptr) { return nullptr; } - + if (values.empty()) { + return arrayObj; + } for (size_t i = 0; i < values.size(); i++) { ani_object intObj = CreateDouble(env, static_cast(values[i])); if (intObj == nullptr) { @@ -443,9 +442,6 @@ ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector &values) { - if (values.empty()) { - return false; - } ani_field field = nullptr; ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); if (status != ANI_OK) { @@ -475,5 +471,32 @@ bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &c ANI_FAILED_AND_RETURN(env->Object_New(cls, ctor, &outAniObj)); return true; } + +bool CreateDate(ani_env *env, int64_t time, ani_object &outObj) +{ + ani_class cls; + ani_status status; + ani_object obj; + ani_method ctor; + if (ANI_OK != (status = env->FindClass("Lescompat/Date;", &cls))) { + ANS_LOGD("error. not find class name 'Lescompat/Date;'. status %{public}d", status); + return false; + } + 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, &obj, timeObj))) { + ANS_LOGD("Object_New faild. status %{public}d", status); + return false; + } + outObj = obj; + 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 index bfdce45b4..32dcb4803 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -13,11 +13,25 @@ * limitations under the License. */ #include "sts_notification_manager.h" - #include "sts_common.h" +#include "ani_common_util.h" namespace OHOS { namespace NotificationSts { +bool SetDate(ani_env *env, ani_object obj, ani_class cls, const char *name, int64_t time) +{ + ani_object timeObj; + if (!CreateDate(env, time, timeObj)) { + ANS_LOGD("CreateDate faild."); + return false; + } + if (!CallSetter(env, cls, obj, name, timeObj)) { + ANS_LOGD("set '%{public}s' faild.", name); + return false; + } + return true; +} + bool StsSlotTypeUtils::StsToC(const STSSlotType inType, SlotType &outType) { switch (inType) { @@ -296,7 +310,7 @@ bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem) STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; StsSlotTypeUtils::CToSts(slotType, stsSlotType); EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/#SlotType;", stsSlotType, enumItem); + "L@ohos/notificationManager/notificationManager/SlotType;", stsSlotType, enumItem); return true; } @@ -312,7 +326,7 @@ bool SlotLevelCToEts(ani_env *env, SlotLevel slotLevel, ani_enum_item &enumItem) STSSlotLevel stsSlotLevel = STSSlotLevel::LEVEL_NONE; StsSlotLevelUtils::CToSts(slotLevel, stsSlotLevel); EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/#SlotLevel;", stsSlotLevel, enumItem); + "L@ohos/notificationManager/notificationManager/SlotLevel;", stsSlotLevel, enumItem); return true; } @@ -331,7 +345,7 @@ bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enu STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; StsContentTypeUtils::CToSts(contentType, stsContentType); if(EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/#ContentType", stsContentType, enumItem)) { + "L@ohos/notificationManager/notificationManager/ContentType;", stsContentType, enumItem)) { return true; } return false; @@ -389,12 +403,12 @@ bool WarpNotificationDoNotDisturbDate( ANS_LOGD("set type faild."); return false; } - if (!CallSetter(env, cls, obj, "begin", date->GetBeginDate())) { + if (!SetDate(env, obj, cls, "begin", date->GetBeginDate())) { ANS_LOGD("SetDate 'begin' faild."); return false; } - if (!CallSetter(env, cls, obj, "end", date->GetBeginDate())) { - ANS_LOGD("SetDate 'begin' faild."); + if (!SetDate(env, obj, cls, "end", date->GetEndDate())) { + ANS_LOGD("SetDate 'end' faild."); return false; } outObj = obj; diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index c21bbecc7..1857ae735 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -21,6 +21,7 @@ #include "sts_common.h" #include "sts_sorting_map.h" #include "sts_subscribe_info.h" +#include "ani_common_util.h" namespace OHOS { namespace NotificationSts { @@ -33,9 +34,6 @@ void StsDistributedOperationCallback::OnOperationCallback(const int32_t operatio { std::lock_guard l(lock_); if (isCall_) return; - ANS_LOGD("OnOperationCallback ENTER"); - int32_t externalCode = OHOS::CJSystemapi::Notification::ErrorToExternal(operationResult); - ANS_LOGD("operationResult %{public}d, externalCode %{public}d", operationResult, externalCode); if (etsVm_ == nullptr) { ANS_LOGD("etsVm_ is null"); return; @@ -48,21 +46,7 @@ void StsDistributedOperationCallback::OnOperationCallback(const int32_t operatio ANS_LOGD("StsDistributedOperationCallback AttachCurrentThread error. result: %{public}d.", aniResult); return; } - - if (operationResult == 0) { - ANS_LOGD("OnOperationCallback Resolve"); - ani_ref ref {}; - if (ANI_OK != (aniResult = etsEnv->PromiseResolver_Resolve(resolver_, ref))) { - ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", aniResult); - } - } else { - ANS_LOGD("OnOperationCallback reject"); - std::string errMsg = FindAnsErrMsg(externalCode); - ani_error rejection = static_cast(OHOS::AbilityRuntime::CreateStsError(etsEnv, externalCode, errMsg)); - if (ANI_OK != (aniResult = etsEnv->PromiseResolver_Reject(resolver_, rejection))) { - ANS_LOGD("PromiseResolver_Resolve faild. status %{public}d", aniResult); - } - } + OnStsOperationCallback(etsEnv, operationResult); aniResult = etsVm_->DetachCurrentThread(); if (aniResult != ANI_OK) { ANS_LOGD("StsDistributedOperationCallback DetachCurrentThread error. result: %{public}d.", aniResult); @@ -71,6 +55,37 @@ void StsDistributedOperationCallback::OnOperationCallback(const int32_t operatio 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; @@ -86,6 +101,7 @@ void StsSubscriberInstance::OnCanceled( int32_t deleteReason) { ANS_LOGD("enter"); +#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -108,12 +124,14 @@ void StsSubscriberInstance::OnCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } +#endif } void StsSubscriberInstance::OnConsumed( const std::shared_ptr &request, const std::shared_ptr &sortingMap) { ANS_LOGD("enter"); +#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -136,6 +154,7 @@ void StsSubscriberInstance::OnConsumed( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } +#endif } void StsSubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) { @@ -347,6 +366,7 @@ void StsSubscriberInstance::OnBatchCanceled( const std::shared_ptr &sortingMap, int32_t deleteReason) { ANS_LOGD("enter"); +#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -369,6 +389,7 @@ void StsSubscriberInstance::OnBatchCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } +#endif } bool StsSubscriberInstance::HasOnBatchCancelCallback() { @@ -460,11 +481,11 @@ bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::ve ANS_LOGD("Object_GetFieldByName_Ref '%{public}s' error. result: %{public}d.", func, aniResult); return false; } - ani_boolean flag = false; - if (ANI_OK != env->Reference_IsUndefined(fn_ref, &flag)) { - ANS_LOGD("Reference_IsUndefined faild"); + 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; } - ANS_LOGD("[%{public}s] %{public}d. %{public}d", __func__, __LINE__, (int32_t)flag); ani_ref fnReturnVal; aniResult = env->FunctionalObject_Call( static_cast(fn_ref), parm.size(), parm.data(), &fnReturnVal); @@ -472,7 +493,6 @@ bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::ve ANS_LOGD("FunctionalObject_Call error. result: %{public}d.", aniResult); return false; } - ANS_LOGD("[%{public}s] %{public}d", __func__, __LINE__); return true; } @@ -565,6 +585,8 @@ bool SubscriberInstanceManager::HasNotificationSubscriber( bool isInfoUndefine = IsUndefine(env, info); if (isSubscribeUndefine) { ANS_LOGD("subscriber is undefine"); + std::string msg = "subscriber is undefine"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return false; } sptr SubscribeInfo = @@ -572,6 +594,8 @@ bool SubscriberInstanceManager::HasNotificationSubscriber( if (!isInfoUndefine) { if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); + std::string msg = "UnwarpNotificationSubscribeInfo faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return false; } } @@ -579,10 +603,14 @@ bool SubscriberInstanceManager::HasNotificationSubscriber( if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { ANS_LOGD("GetNotificationSubscriber faild"); + std::string msg = "GetNotificationSubscriber faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); return false; } if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { ANS_LOGD("AddSubscriberInstancesInfo faild"); + std::string msg = "GetNotificationSubscriber faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); return false; } } @@ -593,81 +621,15 @@ bool SubscriberInstanceManager::HasNotificationSubscriber( status = NotificationHelper::SubscribeNotification(stsSubscriber); } if (status != 0) { + 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, OHOS::CJSystemapi::Notification::ErrorToExternal(status)); + status, externalErrorCode); + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); return false; } -// testThread = std::thread([stsSubscriber](){ -// std::shared_ptr data = std::make_shared(); -// std::shared_ptr callbackData = std::make_shared(); -// std::shared_ptr badgeData = std::make_shared(); -// sptr callbackDataSptr = new EnabledNotificationCallbackData(); -// -// std::string groupKeyOverride = "GroupKeyOverride"; -// int32_t importance = 10; -// uint64_t ranking = 20; -// int32_t visibleness =30; -// bool isDisplayBadge = false; -// bool isHiddenNotification = true; -// NotificationSorting sorting; -// sorting.SetGroupKeyOverride(groupKeyOverride); -// sorting.SetImportance(importance); -// sorting.SetRanking(ranking); -// sorting.SetVisiblenessOverride(visibleness); -// sorting.SetDisplayBadge(isDisplayBadge); -// sorting.SetHiddenNotification(isHiddenNotification); -// std::vector VSorting; -// for (int i = 0; i < 5; i++) { -// sorting.SetKey(std::to_string(i)); -// VSorting.emplace_back(sorting); -// } -// std::shared_ptr sortingMap = std::make_shared(VSorting); -// data->SetBeginDate(1746588038); -// data->SetEndDate(1746588038); -// data->SetDoNotDisturbType(NotificationConstant::DoNotDisturbType::DAILY); -// ANS_LOGD("%{public}d", __LINE__); -// stsSubscriber->onDoNotDisturbChanged(data); -// ANS_LOGD("%{public}d", __LINE__); -// -// callbackData->SetBundle("hello world"); -// callbackData->SetUid(10010); -// callbackData->SetEnable(true); -// ANS_LOGD("%{public}d", __LINE__); -// stsSubscriber->OnEnabledNotificationChanged(callbackData); -// ANS_LOGD("%{public}d", __LINE__); -// -// badgeData->SetAppInstanceKey("SetAppInstanceKey"); -// badgeData->SetBadgeNumber(10086); -// badgeData->SetBundle("hello world"); -// badgeData->SetUid(100100); -// badgeData->SetInstanceKey(111000); -// ANS_LOGD("%{public}d", __LINE__); -// stsSubscriber->OnBadgeChanged(badgeData); -// ANS_LOGD("%{public}d", __LINE__); -// -// callbackDataSptr->SetBundle("hello world"); -// callbackDataSptr->SetUid(10010); -// callbackDataSptr->SetEnable(true); -// ANS_LOGD("%{public}d", __LINE__); -// stsSubscriber->OnBadgeEnabledChanged(callbackDataSptr); -// ANS_LOGD("%{public}d", __LINE__); -// -// stsSubscriber->OnUpdate(sortingMap); -// ANS_LOGD("%{public}d", __LINE__); -// -// std::shared_ptr request = std::make_shared(new NotificationRequest()); -// request->SetRemindType(NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); -// stsSubscriber->OnCanceled(request, sortingMap, 123); -// ANS_LOGD("%{public}d", __LINE__); -// stsSubscriber->OnConsumed(request, sortingMap); -// -// ANS_LOGD("%{public}d", __LINE__); -// std::vector> requestLists; -// requestLists.emplace_back(request); -// stsSubscriber->OnBatchCanceled(requestLists, sortingMap, 10086); -// ANS_LOGD("%{public}d", __LINE__); -// }); -// testThread.detach(); return true; } @@ -687,17 +649,42 @@ bool SubscriberInstanceManager::HasNotificationSubscriber( if (ret) { int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); if (status != 0) { - ANS_LOGD("errorCode is not ERR_OK. %{public}d ErrorToExternal %{public}d", - status, OHOS::CJSystemapi::Notification::ErrorToExternal(status)); + 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 { - // ERR_ANS_SUBSCRIBER_IS_DELETING + 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 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; @@ -725,12 +712,12 @@ bool UnWarpNotificationKey(ani_env *env, const ani_object obj, NotificationKey & { ani_boolean isUndefined = ANI_TRUE; ani_double idDouble = 0.0; - if (GetPropertyDouble(env, obj, "id", isUndefined, idDouble) != ANI_OK || isUndefined == ANI_TRUE) { - ANS_LOGD("UnWarpNotificationKey GetPropertyDouble id fail"); + 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"); diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index a78c3301b..2b8b2cbe7 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -165,7 +165,9 @@ bool WarpSubscribeCallbackDataArray( bool WarpEnabledNotificationCallbackData(ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj) { + ANS_LOGD("enter"); ani_class cls; + ani_status status; const char *className = "Lnotification/notificationSubscriber/EnabledNotificationCallbackDataInner;"; if (!CreateClassObjByClassName(env, className, cls, outObj)) { ANS_LOGD("CreateClassObjByClassName faild"); @@ -179,15 +181,17 @@ bool WarpEnabledNotificationCallbackData(ani_env *env, const std::shared_ptrGetEnable())) { - ANS_LOGD("Set enable faild."); - return false; - } + if (ANI_OK != (status = env->Object_SetPropertyByName_Boolean( + outObj, "enable", BoolToAniBoolean(callbackData->GetEnable())))) { + ANS_LOGD("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"); ani_class cls; ani_object instanceKeyObj; const char *className = "Lnotification/notificationSubscriber/BadgeNumberCallbackDataInner;"; diff --git a/frameworks/ets/ani/src/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp index dfb53a80f..a3c00c7e4 100644 --- a/frameworks/ets/ani/src/subscribe/ani_remove.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -25,31 +25,45 @@ 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; - Notification::NotificationKey key; + NotificationKey key; int32_t reasonType = -1; if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { ANS_LOGD("bundle is valid"); + std::string msg = "UnwrapBundleOption faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::UnWarpNotificationKey(env, notificationKey, key)) { ANS_LOGD("notificationKey is valid"); + std::string msg = "UnWarpNotificationKey faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { ANS_LOGD("enum convert failed"); + std::string msg = "UnWarpReasonEnum faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { ANS_LOGD("reasonType is valid"); + std::string msg = "reasonType is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } - int ret = Notification::NotificationHelper::RemoveNotification(option, key.id, key.label, reasonType); - ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", - ret, CJSystemapi::Notification::ErrorToExternal(ret)); + int ret = NotificationHelper::RemoveNotification(option, key.id, key.label, reasonType); + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + if (ret != ERR_OK) { + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } } void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEnum) @@ -59,20 +73,30 @@ void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEn std::string hashCodeStd; if (ANI_OK != NotificationSts::GetStringByAniString(env, hashCode, hashCodeStd)) { ANS_LOGD("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_LOGD("enum convert failed"); + std::string msg = "UnWarpReasonEnum faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { ANS_LOGD("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 = Notification::NotificationHelper::RemoveNotification(hashCodeStd, reasonType); - ANS_LOGD("StsRemoveForHashCode ret %{public}d. ErrorToExternal %{public}d", - ret, CJSystemapi::Notification::ErrorToExternal(ret)); + int ret = NotificationHelper::RemoveNotification(hashCodeStd, reasonType); + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForHashCode ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + if (ret != ERR_OK) { + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } } void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reasonEnum) @@ -82,19 +106,29 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason int32_t reasonType; if (ANI_OK != NotificationSts::GetStringArrayByAniObj(env, hashCodes, hashCodesStd)) { ANS_LOGD("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_LOGD("enum convert failed"); + std::string msg = "UnWarpReasonEnum faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { ANS_LOGD("reasonType is valid"); + std::string msg = "reasonType is valid"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } - int ret = Notification::NotificationHelper::RemoveNotifications(hashCodesStd, reasonType); - ANS_LOGD("StsRemoveForHashCodes ret %{public}d. ErrorToExternal %{public}d", - ret, CJSystemapi::Notification::ErrorToExternal(ret)); + int ret = NotificationHelper::RemoveNotifications(hashCodesStd, reasonType); + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForHashCodes ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + if (ret != ERR_OK) { + 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 index 302f5fb30..3f6063938 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -34,11 +34,11 @@ static const char *cRemoveForHashCodesSignature = "Lescompat/Array;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; static const char *cDistributeOperationSignature = "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/OperationInfo;:Lstd/core/Promise;"; -//static const char *cSubscribeSignature = -// "Lnotification/notificationSubscriber/NotificationSubscriber;" -// "Lnotification/notificationSubscribeInfo/NotificationSubscribeInfo;:V"; -//static const char *cUnSubscribeSignature = -// "Lnotification/notificationSubscriber/NotificationSubscriber;:V"; +static const char *cSubscribeSignature = + "Lnotification/notificationSubscriber/NotificationSubscriber;" + "Lnotification/notificationSubscribeInfo/NotificationSubscribeInfo;:V"; +static const char *cUnSubscribeSignature = + "Lnotification/notificationSubscriber/NotificationSubscriber;:V"; ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo) { @@ -69,20 +69,27 @@ ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object return nullptr; } callback->SetVm(vm); - std::thread t = std::thread([noWithOperationInfo, callback, info]() { - sptr callback_ = callback; - sptr info_ = info; - 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->OnOperationCallback(result); - } - }); - t.detach(); + 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 AniSubScribeRegistryInit(ani_env *env) { ANS_LOGD("AniSubScribeRegistryInit call"); @@ -98,8 +105,8 @@ void AniSubScribeRegistryInit(ani_env *env) ani_native_function {"nativeRemove", cRemoveForHashCodeSignature, reinterpret_cast(AniRemoveForHashCode)}, ani_native_function {"nativeRemove", cRemoveForHashCodesSignature, reinterpret_cast(AniRemoveForHashCodes)}, ani_native_function {"nativeDistributeOperation", cDistributeOperationSignature, reinterpret_cast(AniDistributeOperation)}, -// ani_native_function {"nativeSubscribe", cSubscribeSignature, reinterpret_cast(StsSubscribe)}, -// ani_native_function {"nativeUnSubscribe", cUnSubscribeSignature, reinterpret_cast(StsUnSubscribe)}, + ani_native_function {"nativeSubscribe", cSubscribeSignature, reinterpret_cast(AniSubscribe)}, + ani_native_function {"nativeUnSubscribe", cUnSubscribeSignature, reinterpret_cast(AniUnSubscribe)}, }; ANS_LOGD("Start bind native methods to '%{public}s'", npName); diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index 7fa6fd4d2..d7d7294d7 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -21,7 +21,14 @@ import { NotificationSubscriber } from 'notification.notificationSubscriber'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; +const rejectInternalError: BusinessError = {code: 160001, data: "Internal error."}; +const callbackInternalError: BusinessError = {code: 160001, data: undefined}; +const successCallbackError: BusinessError = {code: 0, data: undefined}; +// ERROR_PARAM_INVALID = 401 +const errorParamInvalid: BusinessError = {code: 401, data: "Invalid parameter"}; + export default namespace notificationSubscribe { + loadLibrary("notification_subscribe_ani.z") export interface NotificationKey { id: number; label?: string; @@ -43,18 +50,23 @@ export default namespace notificationSubscribe { 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 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 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: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); } ) } @@ -63,16 +75,24 @@ export default namespace notificationSubscribe { 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: Object): 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( @@ -87,17 +107,25 @@ export default namespace notificationSubscribe { } 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: Object): 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( @@ -117,6 +145,9 @@ export default namespace notificationSubscribe { 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); }); @@ -125,6 +156,8 @@ export default namespace notificationSubscribe { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); } ) } @@ -134,6 +167,9 @@ export default namespace notificationSubscribe { 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); @@ -150,6 +186,9 @@ export default namespace notificationSubscribe { } 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); }); @@ -158,11 +197,16 @@ export default namespace notificationSubscribe { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): 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); @@ -179,6 +223,9 @@ export default namespace notificationSubscribe { } 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); }); @@ -187,11 +234,16 @@ export default namespace notificationSubscribe { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): 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); @@ -208,32 +260,32 @@ export default namespace notificationSubscribe { } export function distributeOperation(hashcode: string, operationInfo?: OperationInfo): Promise { + if (hashcode == undefined) { + throw errorParamInvalid; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - console.log("===============================1111"); - let p = taskpool.execute((): Object => { + let p = taskpool.execute((): Promise => { if (operationInfo == undefined) { return notificationSubscribe.nativeDistributeOperation(hashcode); } else { return notificationSubscribe.nativeDistributeOperation(hashcode, operationInfo); } }); - console.log("===============================2222"); p.then( (e: NullishType): void => { - try { - console.log("===============================3333"); - let stsPromise = e as String; - console.log("==================================================================== data", stsPromise); + if (e == undefined) { + reject(rejectInternalError); + } + let result: int = e as int; + if (result != 0) { + reject(rejectInternalError); + } else { resolve(undefined); - } catch(error) { - console.log("===============================6666. error", JSON.stringify(error)); } }, (error: Object): void => { - console.log("===============================4444"); reject(error); } ) - console.log("===============================5555"); }); return pPromise; } @@ -248,240 +300,3 @@ export default namespace notificationSubscribe { public userInput?: string; } } -/* -loadLibrary("notification_subscribe_ani_kit.z"); -let TAG = 'SUB_NOTIFICATION_ANS_SYSTEM_API_TEST ===>' -function StsRemoveForHashCodeAsyncCallback() -{ - console.log("StsRemoveForHashCodeAsyncCallback START"); - try { - notificationSubscribe.remove("device_0_1", notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { - if (err) { - console.info(`${TAG} StsRemoveForHashCode AsyncCallback errCode: ${err.code}`) - } else { - console.info(`${TAG} StsRemoveForHashCode AsyncCallback success`) - } - }); - } catch(error) { - console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForHashCodeAsyncCallback END`); -} - -function StsRemoveForHashCodePromise() -{ - console.log("StsRemoveForHashCodeAsyncCallback START"); - try { - let p = notificationSubscribe.remove("device_0_1", notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); - p.then( - (data: NullishType): void => { - console.info(`${TAG} StsRemoveForHashCodePromise suc..`); - }, (error: Object): void => { - console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); - } - ) - } catch(error) { - console.info("StsRemoveForHashCodeAsyncCallback error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForHashCodeAsyncCallback END`); -} - -function StsRemoveForBundleAsyncCallback() -{ - console.log("StsRemoveForBundleAsyncCallback START"); - let option: BundleOption = { bundle: 'device_0_1', uid: 10001 }; - let key: notificationSubscribe.NotificationKey = { id: 2001, label: 'label' }; - try { - notificationSubscribe.remove(option, key, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { - if (err) { - console.info(`${TAG} StsRemoveForBundleAsyncCallback errCode: ${err.code}`) - } else { - console.info(`${TAG} StsRemoveForBundleAsyncCallback success`) - } - }); - } catch(error) { - console.info("StsRemoveForBundleAsyncCallback error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForBundleAsyncCallback END`); -} - -function StsRemoveForBundlePromise() -{ - console.log("StsRemoveForBundlePromise START"); - let option: BundleOption = { bundle: 'device_0_1', uid: 10001 }; - let key: notificationSubscribe.NotificationKey = { id: 2001, label: 'label' }; - try { - let p = notificationSubscribe.remove(option, key, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); - p.then( - (data: NullishType): void => { - console.info(`${TAG} StsRemoveForBundlePromise suc..`); - }, (error: Object): void => { - console.info("StsRemoveForBundlePromise error ", JSON.stringify(error)); - } - ) - } catch(error) { - console.info("StsRemoveForBundlePromise error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForBundlePromise END`); -} - -function StsRemoveForHashCodesAsyncCallback() -{ - console.log("StsRemoveForHashCodesAsyncCallback START"); - let hasCodes = ['str1', 'str2', 'str3']; - try { - notificationSubscribe.remove(hasCodes, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE, (err: BusinessError, data: NullishType): void => { - if (err) { - console.info(`${TAG} StsRemoveForHashCodesAsyncCallback errCode: ${err.code}`) - } else { - console.info(`${TAG} StsRemoveForHashCodesAsyncCallback success`) - } - }); - } catch(error) { - console.info("StsRemoveForHashCodesAsyncCallback error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForHashCodesAsyncCallback END`); -} - -function StsRemoveForHashCodesPromise() -{ - console.log("StsRemoveForHashCodesPromise START"); - let hasCodes = ['str1', 'str2', 'str3']; - try { - let p = notificationSubscribe.remove(hasCodes, notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE); - p.then( - (data: NullishType): void => { - console.info(`${TAG} StsRemoveForHashCodesPromise suc..`); - }, (error: Object): void => { - console.info("StsRemoveForHashCodesPromise error ", JSON.stringify(error)); - } - ) - } catch(error) { - console.info("StsRemoveForHashCodesPromise error ", JSON.stringify(error)); - } - console.info(`${TAG} StsRemoveForHashCodesPromise END`); -} - -function StsDistributeOperationPromise() -{ - console.log("StsDistributeOperationPromise START"); - let hasCode = "hasCode"; - let info: notificationSubscribe.OperationInfo = { - actionName: "actionName", - userInput: "userInput" - } - try { - console.info(`${TAG} StsDistributeOperationPromise THEN Before `); - let p = notificationSubscribe.distributeOperation(hasCode, info); - console.info(`${TAG} StsDistributeOperationPromise THEN After`); - p.then( - (data: NullishType): void => { - console.info(`${TAG} StsDistributeOperationPromise suc..`); - }, (error: Object): void => { - console.info("StsDistributeOperationPromise error ", JSON.stringify(error)); - } - ) - } catch(error) { - console.info("StsDistributeOperationPromise error ", JSON.stringify(error)); - } - console.info(`${TAG} StsDistributeOperationPromise END`); -} - -function StsSubscribeAsyncCallback() -{ - try { - let sub: NotificationSubscriber = { - - } - console.info("StsSubscribeAsyncCallback Before"); - notificationSubscribe.subscribe(sub, (err: BusinessError, data: NullishType): void => { - console.log('StsSubscribeAsyncCallback suc...'); - }); - console.info("StsSubscribeAsyncCallback After"); - } catch(error) { - console.info("StsSubscribeAsyncCallback error ", JSON.stringify(error)); - } -} - -// type FnOnDisconnect = onDisconnect: () => void; - -class TestNotificationSubscriber implements NotificationSubscriber { - onDisconnect?: () => void = () => { - console.log('====================== onDisconnect'); - } - - onConnect?: () => void = () => { - console.log('====================== onConnect'); - } - - onDestroy?: () => void = () => { - console.log('====================== onDestroy'); - } -} - -function StsSubscribeForInfoAsynCallback() -{ - try { - let sub: NotificationSubscriber = new TestNotificationSubscriber; - - let info: NotificationSubscribeInfo = { - bundleNames: ['zxh', 'xhz', 'hzx'], - userId: 1000, - deviceType: 'deviceType test', - filterLimit: 1001 - } - console.info("StsSubscribeForInfoAsynCallback Before"); - notificationSubscribe.subscribe(sub, info, (err: BusinessError, data: NullishType): void => { - console.log('StsSubscribeForInfoAsynCallback suc...'); - }); - console.info("StsSubscribeForInfoAsynCallback After"); - } catch(error) { - console.info("StsSubscribeForInfoAsynCallback error ", JSON.stringify(error)); - } -} - -function StsSubscribePromise() -{ - try { - let sub: NotificationSubscriber = { - - } - - let info: NotificationSubscribeInfo = { - bundleNames: ['zxh', 'xhz', 'hzx'], - userId: 1000, - deviceType: 'deviceType test', - filterLimit: 1001 - } - console.log(JSON.stringify(info)); - console.info("StsSubscribePromise Before"); - let p = notificationSubscribe.subscribe(sub, info); - p.then( - (e: NullishType): void => { - console.info("StsSubscribePromise suc.."); - }, (error: Object): void => { - console.info("StsSubscribePromise error ", JSON.stringify(error)); - } - ) - - let p1 = notificationSubscribe.unsubscribe(sub); - p1.then( - (e: NullishType): void => { - console.info("un StsSubscribePromise suc.. "); - }, (error: Object): void => { - console.info("un StsSubscribePromise error ", JSON.stringify(error)); - } - ) - } catch(error) { - console.info("StsSubscribePromise error ", JSON.stringify(error)); - } -} - -function main() -{ - StsDistributeOperationPromise(); - StsSubscribeAsyncCallback(); - StsSubscribeForInfoAsynCallback(); - StsSubscribePromise(); -} -*/ \ No newline at end of file diff --git a/frameworks/ets/ets/notification/notificationSubscriber.ets b/frameworks/ets/ets/notification/notificationSubscriber.ets index 3dc212b86..be7f25257 100644 --- a/frameworks/ets/ets/notification/notificationSubscriber.ets +++ b/frameworks/ets/ets/notification/notificationSubscriber.ets @@ -63,9 +63,7 @@ export class NotificationSubscriberInner implements NotificationSubscriber { onConnect?: () => void; - onDisconnect?: () => void = ()=>{ - - }; + onDisconnect?: () => void; onDestroy?: () => void; -- Gitee From 9058e3c78ca65bb383563fc723aae1aefd3924d2 Mon Sep 17 00:00:00 2001 From: heguokai Date: Sun, 18 May 2025 00:15:59 +0800 Subject: [PATCH 12/52] modify Signed-off-by: heguokai --- .../ets/ani/src/manager/ani_manager.cpp | 6 +- frameworks/ets/ani/src/sts_action_button.cpp | 94 ++++-- frameworks/ets/ani/src/sts_bundle_option.cpp | 21 +- .../ets/ets/@ohos.notificationManager.ets | 278 +++++++++++++++++- .../ets/ets/@ohos.notificationSubscribe.ets | 2 +- 5 files changed, 349 insertions(+), 52 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 0e59b31f4..d5e0b91d7 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -89,9 +89,9 @@ void AniNotificationManagerRegistryInit(ani_env *env) 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 {"nativeRequestEnableNotification", + // "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", + // reinterpret_cast(AniRequestEnableNotification)}, }; status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index 9dc131976..a84a7b63b 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -22,37 +22,60 @@ namespace OHOS { namespace NotificationSts { -ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, +void GetStsActionButtonByOther(StsActionButton &actionButton) +{ + actionButton.icon = nullptr; + actionButton.semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + actionButton.autoCreatedReplies = true; + actionButton.mimeTypeOnlyInputs = {}; + actionButton.isContextual = false; +} +ani_status GetStsActionButtonByWantAgent(ani_env *env, ani_object param, StsActionButton &actionButton) { - 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) { - return ANI_INVALID_ARGS; - } ani_ref wantAgentRef; WantAgent* pWantAgent = nullptr; - if(ANI_OK == GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) && isUndefind == ANI_FALSE) { + if (ANI_OK == GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) && isUndefind == ANI_FALSE) { UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); } else { + delete wantAgentRef; + wantAgentRef = nullptr; + delete pWantAgent; + pWantAgent = nullptr; return ANI_INVALID_ARGS; } if (pWantAgent == nullptr) { - return ANI_INVALID_ARGS; + return ANI_INVALID_ARGS; } std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + actionButton.wantAgent = wantAgent; + delete wantAgentRef; + wantAgentRef = nullptr; + return ANI_OK; +} - isUndefind = ANI_TRUE; +ani_status GetStsActionButtonByWantParams(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ani_boolean isUndefind = ANI_TRUE; WantParams wantParams = {}; ani_ref extrasRef; - if(ANI_OK == GetPropertyRef(env, param, "extras", isUndefind, extrasRef) && isUndefind == ANI_FALSE) { + if (ANI_OK == GetPropertyRef(env, param, "extras", isUndefind, extrasRef) && isUndefind == ANI_FALSE) { UnwrapWantParams(env, extrasRef, wantParams); } else { return ANI_INVALID_ARGS; } std::shared_ptr extras = std::make_shared(wantParams); - + actionButton.extras = extras; + delete extrasRef; + extrasRef = nullptr; + return ANI_OK; +} +ani_status GetStsActionButtonByUserInput(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + 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) { @@ -61,15 +84,29 @@ ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, if (userInput == nullptr) { userInput = {}; } - actionButton.icon = nullptr; - actionButton.title = title; - actionButton.wantAgent = wantAgent; - actionButton.extras = extras; - actionButton.semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; - actionButton.autoCreatedReplies = true; - actionButton.mimeTypeOnlyInputs = {}; actionButton.userInput = userInput; - actionButton.isContextual = false; + delete userInputRef; + userInputRef = nullptr; + return ANI_OK; +} + +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + 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) { + return ANI_INVALID_ARGS; + } + actionButton.title = title; + if (ANI_OK != GetStsActionButtonByWantAgent(env, param, actionButton)) { + return ANI_INVALID_ARGS; + } + if (ANI_OK != GetStsActionButtonByWantParams(env, param, actionButton)) { + return ANI_INVALID_ARGS; + } + GetStsActionButtonByOther(actionButton); return status; } @@ -89,7 +126,6 @@ ani_object WrapNotificationActionButton(ani_env* env, RETURN_NULL_IF_FALSE(GetAniStringByString(env, actionButton->GetTitle(), stringValue)); RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)); // wantAgent: WantAgent; - //napi处理过程 std::shared_ptr agent = actionButton->GetWantAgent(); if (agent == nullptr) { ANS_LOGI("agent is null"); @@ -98,16 +134,12 @@ ani_object WrapNotificationActionButton(ani_env* env, ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); } - - // need to do - // extras?: Record; napi中没有处理它的过程? - //napi位置:notification_distributed_notification_service-OpenHarmony_feature_20250328\frameworks\js\napi\src\common_convert_request.cpp 419行 - // // icon?: image.PixelMap 未找到ETS属性 - - // userInput?: NotificationUserInput -> inputKey: string; + // extras?: Record + ani_ref extras = WrapWantParams(env, *(actionButton->GetAdditionalData().get())); + CallSetter(env, iconButtonCls, iconButtonObject, "extras", extras); + // userInput?: NotificationUserInput ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)); - + CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject); return iconButtonObject; } @@ -169,8 +201,10 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, for (auto &button : actionButtons) { ani_object item = WrapNotificationActionButton(env, button); RETURN_NULL_IF_NULL(item); - if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + delete arrayObj; + arrayObj = nullptr; return nullptr; } index ++; diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index c55396dbb..57d76f342 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -29,16 +29,15 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification return false; } option.SetBundleName(bundleName); - ANS_LOGD("WrapBundleOption bundleName: %{public}s", bundleName.c_str()); - ani_double result = 0.0; - if(GetPropertyDouble(env, obj, "uid", isUndefined, result) != ANI_OK || isUndefined == ANI_TRUE) { + if(GetPropertyDouble(env, obj, "uid", isUndefined, result) == ANI_OK && isUndefined == ANI_FALSE) { + int32_t uid = static_cast(result); + option.SetUid(uid); + } else { ANS_LOGE("Wrong argument type or uid is Undefined."); - return false; } - int32_t uid = static_cast(result); - ANS_LOGD("WrapBundleOption bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), uid); - option.SetUid(uid); + ANS_LOGD( + "WrapBundleOption bundleName: %{public}s uid: %{public}d", option.GetBundleName().c_str(), option.GetUid()); return true; } @@ -59,15 +58,21 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector(optionRef), option)) { ANS_LOGD("Get BundleOption failed, index: %{public}d", i); + delete optionRef; + optionRef = nullptr; return false; } options.push_back(option); ANS_LOGD("GetOptions index: %{public}d", i); + delete optionRef; + optionRef = nullptr; } return true; } @@ -90,6 +95,8 @@ bool WrapBundleOption(ani_env* env, // uid?: number; uint32_t uid = bundleOption->GetUid(); RETURN_FALSE_IF_FALSE(CallSetterOptional(env, bundleCls, bundleObject, "uid", uid)); + delete bundleCls; + bundleCls = nullptr; return true; } } diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 02c2c817e..0616504f5 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -136,7 +136,58 @@ export default namespace notificationManager { export native function nativeIsNotificationEnabledWithBundleOption(bundleOption: BundleOption): boolean; export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; - export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { + function isInvalidParameter(bundle: BundleOption): BusinessError + { + let error: BusinessError = { + code: 0, + message: "" + } + if (bundle == null) { + error = { + code: 401, + message: "BundleOption must be not Null" + } + return error; + } + if (bundle.bundle == null || bundle.bundle?.length === 0) { + error = { + code: 401, + message: "Incorrect parameter types. The type of bundle must be string." + } + return error; + } + return error; + } + + function isInvalidParameter(option: ButtonOptions): BusinessError + { + let error: BusinessError = { + code: 0, + message: "" + } + if (option == null) { + error = { + code: 401, + message: "ButtonOptions must be not Null" + } + return error; + } + if (option.buttonName == null || option.buttonName?.length === 0) { + error = { + code: 401, + message: "Incorrect parameter types. The type of buttonName must be string." + } + return error; + } + return error; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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 => { @@ -148,7 +199,17 @@ export default namespace notificationManager { return pPromise; } - export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -161,6 +222,15 @@ export default namespace notificationManager { export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundleOption); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; @@ -175,8 +245,14 @@ export default namespace notificationManager { export function isNotificationEnabled(bundleOption: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundleOption); + if (error.code !== 0) { + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); }); + let p = taskpool.execute( + (): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); + }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); @@ -189,6 +265,13 @@ export default namespace notificationManager { export function isNotificationEnabled(userId: number, callback: AsyncCallback): void { + if (callback == null) { + let error: BusinessError = { + code: 410, + message : "callback must be not null" + } + throw error; + } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithId(userId); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; @@ -217,6 +300,13 @@ export default namespace notificationManager { export function isNotificationEnabled(callback: AsyncCallback): void { + if (callback == null) { + let error: BusinessError = { + code: 410, + message : "callback must be not null" + } + throw error; + } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; @@ -243,9 +333,25 @@ export default namespace notificationManager { return pPromise; } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void + export function setNotificationEnableSlot( + bundle: BundleOption, + type: SlotType, + enable: boolean, + isForceControl: boolean, + callback: AsyncCallback): void { - let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); }); + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } + 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); @@ -255,14 +361,21 @@ export default namespace notificationManager { }); } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise + export function setNotificationEnableSlot( + bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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); }); + let p = taskpool.execute( + (): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, forceControl); + }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -272,8 +385,18 @@ export default namespace notificationManager { return pPromise; } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void + export function setNotificationEnableSlot( + bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -286,6 +409,10 @@ export default namespace notificationManager { export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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 => { @@ -300,6 +427,15 @@ export default namespace notificationManager { export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; @@ -312,7 +448,17 @@ export default namespace notificationManager { }) } - export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { + export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); p.then((data: NullishType): void => { let slots : Array = data as Array; @@ -325,8 +471,14 @@ export default namespace notificationManager { }) } - export function getSlotsByBundle(bundle: BundleOption): Promise> { - let pPromise = new Promise>((resolve: ResolveCallback>, reject: RejectCallback): void => { + export function getSlotsByBundle(bundle: BundleOption): Promise> + { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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; @@ -339,6 +491,10 @@ export default namespace notificationManager { } export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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 => { @@ -351,6 +507,10 @@ export default namespace notificationManager { } export function getSlotFlagsByBundle(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): number => { return nativeGetSlotFlagsByBundle(bundle); }); p.then((data: NullishType): void => { @@ -412,6 +572,14 @@ export default namespace notificationManager { export function triggerSystemLiveView( bundle: BundleOption, notificationId: number, buttonOptions: ButtonOptions): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + error = isInvalidParameter(buttonOptions); + if (error.code !== 0) { + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeTriggerSystemLiveView(bundle, notificationId, buttonOptions); @@ -439,6 +607,13 @@ export default namespace notificationManager { } export function removeDoNotDisturbProfile(templates: Array): Promise { + if (!templates || templates.length === 0) { + let error: BusinessError = { + code: 401, + message: "templates must be not null" + } + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { @@ -451,6 +626,13 @@ export default namespace notificationManager { } export function addDoNotDisturbProfile(templates: Array): Promise { + if (!templates || templates.length === 0) { + let error: BusinessError = { + code: 401, + message: "templates must be not null" + } + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { @@ -463,6 +645,13 @@ export default namespace notificationManager { } export function getAllActiveNotifications(callback: AsyncCallback>): void { + if (!callback) { + let error: BusinessError = { + code: 401, + message: "callback must be not null" + } + throw error; + } let p = taskpool.execute((): Array => { return nativeGetAllActiveNotifications(); }); p.then((data: NullishType): void => { let ret : Array = data as Array; @@ -501,6 +690,13 @@ export default namespace notificationManager { } export function getActiveNotifications(callback: AsyncCallback>): void { + if (!callback) { + let error: BusinessError = { + code: 401, + message: "callback must be not null" + } + throw error; + } let p = taskpool.execute((): Array => { return nativeGetActiveNotifications(); }); p.then((data: NullishType): void => { let ret : Array = data as Array; @@ -525,6 +721,15 @@ export default namespace notificationManager { } export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); p.then((e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -536,6 +741,10 @@ export default namespace notificationManager { } export function displayBadge(bundle: BundleOption, enable: boolean): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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 => { @@ -548,6 +757,10 @@ export default namespace notificationManager { } export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; @@ -561,6 +774,10 @@ export default namespace notificationManager { } export function isBadgeDisplayed(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); p.then((data: NullishType): void => { @@ -574,6 +791,10 @@ export default namespace notificationManager { } export function cancel(bundle: BundleOption, id: number): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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 => { @@ -586,6 +807,13 @@ export default namespace notificationManager { } export function cancel(id: number, label: string): Promise { + if (label == null || label?.length === 0) { + let error: BusinessError = { + code: 401, + message: "Incorrect parameter types. The type of label must be string." + } + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { @@ -598,6 +826,20 @@ export default namespace notificationManager { } export function cancel(id: number, label: string, callback: AsyncCallback): void { + if (label == null || label?.length === 0) { + let error: BusinessError = { + code: 401, + message: "Incorrect parameter types. The type of label must be string." + } + throw error; + } + if (callback == null) { + let error: BusinessError = { + code: 410, + message : "callback must be not null" + } + throw error; + } let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -607,6 +849,13 @@ export default namespace notificationManager { } export function cancel(id: number, callback: AsyncCallback): void { + if (callback == null) { + let error: BusinessError = { + code: 410, + message : "callback must be not null" + } + throw error; + } let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -640,6 +889,13 @@ export default namespace notificationManager { } export function cancelAll(callback: AsyncCallback): void { + if (callback == null) { + let error: BusinessError = { + code: 410, + message : "callback must be not null" + } + throw error; + } let p = taskpool.execute((): void => { return nativeCancelAll(); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index d7d7294d7..eb72f0d80 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -299,4 +299,4 @@ export default namespace notificationSubscribe { public actionName?: string; public userInput?: string; } -} +} \ No newline at end of file -- Gitee From acb3cdb423a9725f82ec656e93e11152fbd66274 Mon Sep 17 00:00:00 2001 From: heguokai Date: Sun, 18 May 2025 01:10:05 +0800 Subject: [PATCH 13/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/include/sts_common.h | 2 +- frameworks/ets/ani/include/sts_slot.h | 1 - frameworks/ets/ani/include/sts_throw_erro.h | 3 +-- .../ani/src/manager/ani_ans_dialog_callback.cpp | 4 ++-- .../ets/ani/src/manager/ani_display_badge.cpp | 2 +- .../ani/src/manager/ani_do_not_disturb_profile.cpp | 4 ++-- frameworks/ets/ani/src/manager/ani_get_active.cpp | 3 +-- frameworks/ets/ani/src/manager/ani_manager.cpp | 4 ++-- .../ani/src/manager/ani_notification_enable.cpp | 2 +- frameworks/ets/ani/src/manager/ani_publish.cpp | 7 ++++--- .../ets/ani/src/manager/ani_request_enable.cpp | 8 +------- frameworks/ets/ani/src/manager/ani_slot.cpp | 14 +++++++------- 12 files changed, 23 insertions(+), 31 deletions(-) diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 7c37c3255..5464a4497 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -70,7 +70,7 @@ inline ani_boolean BoolToAniBoolean(bool value) 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) { + if (env == nullptr || cls == nullptr || object == nullptr) { return false; } std::string setterName(""); diff --git a/frameworks/ets/ani/include/sts_slot.h b/frameworks/ets/ani/include/sts_slot.h index 33fedea24..f9d311058 100644 --- a/frameworks/ets/ani/include/sts_slot.h +++ b/frameworks/ets/ani/include/sts_slot.h @@ -33,7 +33,6 @@ bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &ob bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj); bool WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, ani_object &outAniObj); - } // 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 index 2727fd54a..70634972f 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -60,7 +60,7 @@ inline std::string FindAnsErrMsg(const int32_t errCode) { auto findMsg = ERROR_CODE_TO_MESSAGE.find(errCode); if (findMsg == ERROR_CODE_TO_MESSAGE.end()) { - ANSR_LOGI("FindAnsErrMsg Inner error."); + ANSR_LOGE("FindAnsErrMsg Inner error."); return "Inner error."; } return findMsg->second; @@ -69,7 +69,6 @@ inline std::string FindAnsErrMsg(const int32_t errCode) inline void ThrowStsErroWithLog(ani_env *env, std::string logMsg) { OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); - ANS_LOGE("%{public}s", logMsg.c_str()); } } // namespace NotificationSts } // OHOS diff --git a/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp b/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp index 3e612fac8..b288966f2 100755 --- a/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp +++ b/frameworks/ets/ani/src/manager/ani_ans_dialog_callback.cpp @@ -21,7 +21,8 @@ namespace OHOS { namespace NotificationManagerSts { -bool StsAnsDialogCallback::Init(ani_env *env, std::shared_ptr info, StsAnsDialogCallbackComplete *complete) +bool StsAnsDialogCallback::Init( + ani_env *env, std::shared_ptr info, StsAnsDialogCallbackComplete *complete) { if (env == nullptr || info == nullptr || complete == nullptr) { ANS_LOGE("invalid data"); @@ -169,6 +170,5 @@ void ModalExtensionCallback::ReleaseOrErrorHandle(int32_t code) ANS_LOGD("ReleaseOrErrorHandle end"); return; } - } } \ 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 index 16ec7f616..dd146afc9 100644 --- a/frameworks/ets/ani/src/manager/ani_display_badge.cpp +++ b/frameworks/ets/ani/src/manager/ani_display_badge.cpp @@ -31,7 +31,7 @@ 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)) { + if (NotificationSts::UnwrapBundleOption(env, obj, option)) { returncode = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, NotificationSts::AniBooleanToBool(enable)); } else { 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 index ab0842aef..17bcf2b13 100644 --- a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -28,7 +28,7 @@ void AniAddDoNotDisturbProfile(ani_env *env, ani_object obj) ANS_LOGD("AniAddDoNotDisturbProfile call"); int returncode = 0; std::vector> profiles; - if(NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { + if (NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { returncode = Notification::NotificationHelper::AddDoNotDisturbProfiles(profiles); } else { OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, @@ -50,7 +50,7 @@ void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj) ANS_LOGD("AniRemoveDoNotDisturbProfile call"); int returncode = 0; std::vector> profiles; - if(NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { + if (NotificationSts::UnwrapArrayDoNotDisturbProfile(env, obj, profiles)) { returncode = Notification::NotificationHelper::RemoveDoNotDisturbProfiles(profiles); } else { OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, diff --git a/frameworks/ets/ani/src/manager/ani_get_active.cpp b/frameworks/ets/ani/src/manager/ani_get_active.cpp index 0bd09a533..8ae3e8957 100644 --- a/frameworks/ets/ani/src/manager/ani_get_active.cpp +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -33,7 +33,7 @@ ani_double AniGetActiveNotificationCount(ani_env *env) if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); - return -1; + return 0; } return retNum; } @@ -79,6 +79,5 @@ ani_object AniGetActiveNotifications(ani_env *env) ANS_LOGD("sts AniGetAllActiveNotifications end"); return arrayRequestObj; } - } // 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 index d5e0b91d7..4ff2e53ab 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -38,7 +38,7 @@ void AniNotificationManagerRegistryInit(ani_env *env) ani_namespace ns; status = env->FindNamespace("L@ohos/notificationManager/notificationManager;", &ns); if (status != ANI_OK) { - ANS_LOGD("FindNamespace notificationManager failed status : %{public}d", status); + ANS_LOGE("FindNamespace notificationManager failed status : %{public}d", status); return; } std::array kitFunctions = { @@ -114,7 +114,7 @@ ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) ani_status status = ANI_ERROR; status = vm->GetEnv(ANI_VERSION_1, &env); if (status != ANI_OK) { - ANS_LOGD("GetEnv failed status : %{public}d", status); + ANS_LOGE("GetEnv failed status : %{public}d", status); return ANI_NOT_FOUND; } diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index 7d0bf7ecf..46acb35cd 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -57,7 +57,7 @@ ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bu int returncode = 0; bool allowed = false; BundleOption option; - if(NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { returncode = Notification::NotificationHelper::IsAllowedNotify(option, allowed); } else { NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); diff --git a/frameworks/ets/ani/src/manager/ani_publish.cpp b/frameworks/ets/ani/src/manager/ani_publish.cpp index 944077959..df0aa3557 100644 --- a/frameworks/ets/ani/src/manager/ani_publish.cpp +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -38,8 +38,8 @@ void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj int returncode = NotificationHelper::PublishNotification(*notificationRequest); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniPublish error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } ANS_LOGD("AniPublish end"); } @@ -47,6 +47,7 @@ void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, 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) { @@ -58,10 +59,10 @@ void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_obje int returncode = NotificationHelper::PublishNotification(*notificationRequest); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniPublishWithId error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } - ANS_LOGD("AniPublishWithId leave"); + ANS_LOGD("AniPublishWithId end"); } } // namespace NotificationManagerSts } // namespace OHOS \ 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 index 5e2286b09..ec42defc3 100755 --- a/frameworks/ets/ani/src/manager/ani_request_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_request_enable.cpp @@ -12,8 +12,8 @@ * 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" @@ -112,7 +112,6 @@ bool CreateUIExtension(std::shared_ptr &info) ANS_LOGE("Get context failed"); return false; } - std::shared_ptr abilityContext = OHOS::AbilityRuntime::Context::ConvertTo(info->context); if (abilityContext == nullptr) { @@ -124,16 +123,13 @@ bool CreateUIExtension(std::shared_ptr &info) 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); @@ -147,10 +143,8 @@ bool CreateUIExtension(std::shared_ptr &info) .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) { diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index 644db64d9..94a9d7b72 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -34,7 +34,7 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) int returncode = 0; std::vector> slots; BundleOption option; - if(NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { + if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { returncode = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); } else { NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); @@ -43,8 +43,8 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("sts GetSlotsByBundle error, errorCode: %{public}d", externalCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); return nullptr; } ani_object outAniObj; @@ -76,8 +76,8 @@ void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enu int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniSetNotificationEnableSlot error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); return; } ANS_LOGD("AniSetNotificationEnableSlot end"); @@ -101,8 +101,8 @@ void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } } @@ -121,8 +121,8 @@ ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, int returncode = Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("IsNotificationSlotEnabled -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } return isEnable ? ANI_TRUE : ANI_FALSE; } @@ -139,8 +139,8 @@ ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj) int returncode = Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniGetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } return slotFlags; } @@ -157,8 +157,8 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj) int returncode = Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { - AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniSetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); + AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } } } -- Gitee From a6336979c6b144badcaf3477bf429fad989c55dc Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 19 May 2025 00:22:52 +0800 Subject: [PATCH 14/52] modify for memmery Signed-off-by: heguokai --- frameworks/ets/ani/include/sts_common.h | 38 ++ .../ets/ani/include/sts_convert_other.h | 2 +- frameworks/ets/ani/src/sts_action_button.cpp | 119 ++++-- frameworks/ets/ani/src/sts_bundle_option.cpp | 49 ++- frameworks/ets/ani/src/sts_common.cpp | 297 ++++++++++---- frameworks/ets/ani/src/sts_convert_other.cpp | 384 +++++++++++++----- .../ets/ani/src/sts_notification_content.cpp | 49 +-- frameworks/ets/ani/src/sts_request.cpp | 74 ++-- .../ets/ani/src/subscribe/ani_remove.cpp | 22 +- 9 files changed, 717 insertions(+), 317 deletions(-) diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 5464a4497..660481a23 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -17,6 +17,7 @@ #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_STS_COMMON_H #include "ani.h" +#include #include #include #include "ans_log_wrapper.h" @@ -195,6 +196,43 @@ static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &resu } } +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) { diff --git a/frameworks/ets/ani/include/sts_convert_other.h b/frameworks/ets/ani/include/sts_convert_other.h index 0d6cd1b20..91c6ae9b8 100644 --- a/frameworks/ets/ani/include/sts_convert_other.h +++ b/frameworks/ets/ani/include/sts_convert_other.h @@ -27,7 +27,7 @@ namespace NotificationSts { using namespace OHOS::Media; using namespace OHOS::AbilityRuntime::WantAgent; -void UnwrapWantAgent(ani_env *env, ani_object agent, void** result); +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); diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index a84a7b63b..be9d46948 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -35,23 +35,16 @@ ani_status GetStsActionButtonByWantAgent(ani_env *env, ani_object param, { ani_boolean isUndefind = ANI_TRUE; ani_ref wantAgentRef; - WantAgent* pWantAgent = nullptr; - if (ANI_OK == GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) && isUndefind == ANI_FALSE) { - UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); - } else { - delete wantAgentRef; - wantAgentRef = nullptr; - delete pWantAgent; - pWantAgent = nullptr; + if (ANI_OK != GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) || isUndefind == ANI_TRUE) { + deletePoint(wantAgentRef); return ANI_INVALID_ARGS; } - if (pWantAgent == nullptr) { + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + deletePoint(wantAgentRef); + if (wantAgent == nullptr) { return ANI_INVALID_ARGS; } - std::shared_ptr wantAgent = std::make_shared(*pWantAgent); actionButton.wantAgent = wantAgent; - delete wantAgentRef; - wantAgentRef = nullptr; return ANI_OK; } @@ -64,12 +57,11 @@ ani_status GetStsActionButtonByWantParams(ani_env *env, ani_object param, if (ANI_OK == GetPropertyRef(env, param, "extras", isUndefind, extrasRef) && isUndefind == ANI_FALSE) { UnwrapWantParams(env, extrasRef, wantParams); } else { + deletePoint(extrasRef); return ANI_INVALID_ARGS; } std::shared_ptr extras = std::make_shared(wantParams); actionButton.extras = extras; - delete extrasRef; - extrasRef = nullptr; return ANI_OK; } ani_status GetStsActionButtonByUserInput(ani_env *env, ani_object param, @@ -85,8 +77,6 @@ ani_status GetStsActionButtonByUserInput(ani_env *env, ani_object param, userInput = {}; } actionButton.userInput = userInput; - delete userInputRef; - userInputRef = nullptr; return ANI_OK; } @@ -110,36 +100,83 @@ ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, return status; } -ani_object WrapNotificationActionButton(ani_env* env, +bool SetNotificationActionButtonByRequiredParameter( + ani_env *env, + ani_class iconButtonCls, + ani_object &iconButtonObject, const std::shared_ptr &actionButton) { - if (actionButton == nullptr) { - ANS_LOGE("actionButton is null"); - return nullptr; - } - ani_object iconButtonObject = nullptr; - ani_class iconButtonCls = nullptr; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)); + ani_string stringValue; // title: string; - ani_string stringValue = nullptr; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, actionButton->GetTitle(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)); + if (!GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { + deletePoint(stringValue); + return false; + } + if (!CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)) { + deletePoint(stringValue); + return false; + } // wantAgent: WantAgent; std::shared_ptr agent = actionButton->GetWantAgent(); if (agent == nullptr) { ANS_LOGI("agent is null"); - return nullptr; + deletePoint(stringValue); + return false; } else { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); + if (!CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)) { + deletePoint(stringValue); + return false; + } } + return true; +} + +void SetNotificationActionButtonByOptionalParameter( + ani_env *env, + ani_class iconButtonCls, + ani_object &iconButtonObject, + const std::shared_ptr &actionButton) +{ // extras?: Record ani_ref extras = WrapWantParams(env, *(actionButton->GetAdditionalData().get())); - CallSetter(env, iconButtonCls, iconButtonObject, "extras", extras); + if (!CallSetter(env, iconButtonCls, iconButtonObject, "extras", extras)) { + deletePoint(extras); + } // userInput?: NotificationUserInput ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); - CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject); + if (!CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)) { + deletePoint(userInputObject); + } +} + +void deletePointOfWrapNotificationActionButton( + ani_object iconButtonObject, ani_class iconButtonCls, ani_string stringValue) { + deletePoint(iconButtonObject); + deletePoint(iconButtonCls); + deletePoint(stringValue); +} + +ani_object WrapNotificationActionButton(ani_env* env, + const std::shared_ptr &actionButton) +{ + if (actionButton == nullptr) { + ANS_LOGE("actionButton is null"); + return nullptr; + } + ani_object iconButtonObject = nullptr; + ani_class iconButtonCls = nullptr; + ani_string stringValue = nullptr; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)) { + deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); + return nullptr; + } + if (!SetNotificationActionButtonByRequiredParameter(env, iconButtonCls, iconButtonObject, actionButton)) { + deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); + return nullptr; + } + SetNotificationActionButtonByOptionalParameter(env, iconButtonCls, iconButtonObject, actionButton); return iconButtonObject; } @@ -151,14 +188,15 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, ani_status status; ani_double length; StsActionButton actionButton; - if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { ANS_LOGI("status : %{public}d , %{public}s : may be undefined", status, name); + deletePoint(arrayObj); return ANI_INVALID_ARGS; } status = GetPropertyDouble(env, static_cast(arrayObj), "length", isUndefined, length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); + deletePoint(arrayObj); return status; } @@ -167,12 +205,16 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); if (status != ANI_OK) { + deletePoint(arrayObj); + deletePoint(buttonRef); ANS_LOGI("status : %{public}d, index: %{public}d", status, i); return status; } status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton); if (status != ANI_OK) { ANS_LOGI("ActionButton failed, index: %{public}d", i); + deletePoint(arrayObj); + deletePoint(buttonRef); return status; } std::shared_ptr button @@ -195,16 +237,21 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, ani_object arrayObj = newArrayClass(env, actionButtons.size()); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is empty"); + deletePoint(arrayObj); return nullptr; } ani_size index = 0; for (auto &button : actionButtons) { ani_object item = WrapNotificationActionButton(env, button); - RETURN_NULL_IF_NULL(item); + if (item == nullptr) { + deletePoint(arrayObj); + deletePoint(item); + return nullptr; + } if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; - delete arrayObj; - arrayObj = nullptr; + deletePoint(arrayObj); + deletePoint(item); return nullptr; } index ++; diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index 57d76f342..97e394b31 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -24,17 +24,17 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification ANS_LOGD("UnwrapBundleOption call"); std::string bundleName; ani_boolean isUndefined = ANI_ERROR; - if(GetPropertyString(env, obj, "bundle", isUndefined, bundleName) !=ANI_OK || isUndefined == ANI_TRUE) { + if (GetPropertyString(env, obj, "bundle", isUndefined, bundleName) !=ANI_OK || isUndefined == ANI_TRUE) { ANS_LOGE("get bundle failed, bundle must be string."); return false; } option.SetBundleName(bundleName); ani_double result = 0.0; - if(GetPropertyDouble(env, obj, "uid", isUndefined, result) == ANI_OK && isUndefined == ANI_FALSE) { + if (GetPropertyDouble(env, obj, "uid", isUndefined, result) == ANI_OK && isUndefined == ANI_FALSE) { int32_t uid = static_cast(result); option.SetUid(uid); } else { - ANS_LOGE("Wrong argument type or uid is Undefined."); + ANS_LOGD("Wrong argument type or uid is Undefined."); } ANS_LOGD( "WrapBundleOption bundleName: %{public}s uid: %{public}d", option.GetBundleName().c_str(), option.GetUid()); @@ -47,7 +47,7 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vectorObject_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { - ANS_LOGD("status : %{public}d", status); + ANS_LOGE("status : %{public}d", status); return false; } @@ -58,21 +58,18 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector(optionRef), option)) { ANS_LOGD("Get BundleOption failed, index: %{public}d", i); - delete optionRef; - optionRef = nullptr; + deletePoint(optionRef); return false; } options.push_back(option); ANS_LOGD("GetOptions index: %{public}d", i); - delete optionRef; - optionRef = nullptr; + deletePoint(optionRef); } return true; } @@ -85,18 +82,34 @@ bool WrapBundleOption(ani_env* env, return false; } ani_class bundleCls = nullptr; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject)); - RETURN_FALSE_IF_FALSE(bundleCls != nullptr && bundleObject != nullptr); + if (!CreateClassObjByClassName(env, + "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject)) { + deletePoint(bundleCls); + return false; + } + if (bundleCls == nullptr || bundleObject == nullptr) { + deletePoint(bundleCls); + deletePoint(bundleObject); + return false; + } // bundle: string; ani_string stringValue = nullptr; - RETURN_FALSE_IF_FALSE(GetAniStringByString(env, bundleOption->GetBundleName(), stringValue)); - RETURN_FALSE_IF_FALSE(CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)); + if (!GetAniStringByString(env, bundleOption->GetBundleName(), stringValue)) { + deletePoint(bundleCls); + deletePoint(bundleObject); + deletePoint(stringValue); + return false; + } + if (!CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { + deletePoint(bundleCls); + deletePoint(bundleObject); + deletePoint(stringValue); + return false; + } // uid?: number; uint32_t uid = bundleOption->GetUid(); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, bundleCls, bundleObject, "uid", uid)); - delete bundleCls; - bundleCls = nullptr; + CallSetterOptional(env, bundleCls, bundleObject, "uid", uid); + deletePoint(bundleCls); return true; } } diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 3ac5b5cda..04d46295b 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ #include "sts_common.h" + #include "ans_log_wrapper.h" #include "ani_common_util.h" @@ -23,9 +24,13 @@ constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; bool IsUndefine(ani_env *env, const ani_object &obj) { + if (env == nullptr || obj == nullptr) { + ANS_LOGE("IsUndefine fail, has nullptr"); + return false; + } ani_boolean isUndefined; - if (ANI_OK != env->Reference_IsUndefined(obj,&isUndefined)) { - ANS_LOGD("Reference_IsUndefined faild"); + if (ANI_OK != env->Reference_IsUndefined(obj, &isUndefined)) { + ANS_LOGE("Reference_IsUndefined faild"); return true; } return (isUndefined == ANI_TRUE) ? true : false; @@ -33,9 +38,14 @@ bool IsUndefine(ani_env *env, const ani_object &obj) ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& aniStr) { + if (env == nullptr || str.empty()) { + ANS_LOGE("GetAniStringByString fail, env is nullptr or str is empty"); + 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); + deletePoint(aniStr); return status; } return status; @@ -43,15 +53,19 @@ ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& 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_LOGD("status : %{public}d", status); + 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_LOGD("status : %{public}d", status); + ANS_LOGE("status : %{public}d", status); return status; } res.resize(sz); @@ -60,10 +74,14 @@ 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) { + 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_LOGD("Object_GetPropertyByName_Double faild. status %{public}d", status); + ANS_LOGE("Object_GetPropertyByName_Double faild. status %{public}d", status); return false; } for (int i = 0; i < int(length); i++) { @@ -71,11 +89,14 @@ bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector< status = env->Object_CallMethodByName_Ref(ani_obj, "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); if (status != ANI_OK) { - ANS_LOGD("status : %{public}d", status); - } + ANS_LOGE("status : %{public}d", status); + deletePoint(stringEntryRef); + return false; + } std::string std_string; if (!GetStringByAniString(env, static_cast(stringEntryRef), std_string)) { - ANS_LOGD("GetStdString faild"); + ANS_LOGE("GetStdString faild"); + deletePoint(stringEntryRef); return false; } stdVString.emplace_back(std_string); @@ -86,23 +107,31 @@ bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector< 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; + } ani_status status = ANI_ERROR; ani_ref strRef; if ((status =env->Object_GetPropertyByName_Ref(obj, name, &strRef)) != ANI_OK) { - ANS_LOGD("Object_GetField_Ref bundle fail, status: %{public}d", status); + ANS_LOGE("Object_GetField_Ref bundle fail, status: %{public}d", status); + deletePoint(strRef); return status; } status = env->Reference_IsUndefined(strRef, &isUndefined); if (status != ANI_OK) { - ANS_LOGD("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + ANS_LOGE("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + deletePoint(strRef); return status; } if(isUndefined == ANI_TRUE) { - ANS_LOGI("%{public}s is undefined", name); + ANS_LOGE("%{public}s is undefined", name); + deletePoint(strRef); return status; } if ((status = GetStringByAniString(env, reinterpret_cast(strRef), outStr)) != ANI_OK) { - ANS_LOGD("GetStdString failed"); + ANS_LOGE("GetStdString failed"); + deletePoint(strRef); return status; } return status; @@ -111,26 +140,38 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, ani_boolean isUndefined, bool outvalue) { + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyBool fail, has nullptr"); + return ANI_INVALID_ARGS; + } ani_ref refObj = nullptr; ani_status status = ANI_ERROR; ani_ref uidRef; status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef); if (ANI_OK != status) { - ANS_LOGD("Object_GetPropertyByName_Ref fail, status: %{public}d", status); + ANS_LOGE("Object_GetPropertyByName_Ref fail, status: %{public}d", status); + deletePoint(refObj); + deletePoint(uidRef); return status; } if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { - ANS_LOGD("Reference_IsUndefined failed, status : %{public}d", status); + ANS_LOGE("Reference_IsUndefined failed, status : %{public}d", status); + deletePoint(refObj); + deletePoint(uidRef); return status; } if (isUndefined) { - ANS_LOGI("%{public}s is undefined", name); + ANS_LOGE("%{public}s is undefined", name); + deletePoint(refObj); + deletePoint(uidRef); return ANI_INVALID_ARGS; } ani_boolean result = ANI_FALSE; if ((status = env->Object_CallMethodByName_Boolean(static_cast(refObj), "unboxed", ":Z", &result)) != ANI_OK) { - ANS_LOGD("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + ANS_LOGE("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + deletePoint(refObj); + deletePoint(uidRef); return status; } outvalue = (result == ANI_TRUE); @@ -140,38 +181,43 @@ ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, 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 start %{public}s", name); ani_status status = ANI_ERROR; ani_ref uidRef; - if ((status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef)) != ANI_OK) { - ANS_LOGI("Object_GetPropertyByName_Ref fail, status: %{public}d", status); - return status; - } - if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { - ANS_LOGI("Reference_IsUndefined failed, status : %{public}d", status); - return status; - } - if (isUndefined) { - ANS_LOGI("%{public}s is undefined", name); + status = GetPropertyRef(env, obj, name, isUndefined, uidRef); + if (status != ANI_OK || isUndefined) { + ANS_LOGE("%{public}s is undefined", name); + deletePoint(uidRef); return ANI_INVALID_ARGS; } - status = env->Object_CallMethodByName_Double(static_cast(uidRef), "doubleValue", nullptr, &outvalue); - if (ANI_OK != status) { - ANS_LOGI("Object_CallMethodByName_Double uid fail, status: %{public}d", status); + if ((status = env->Object_CallMethodByName_Double( + reinterpret_cast(uidRef), "doubleValue", nullptr, &outvalue)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + deletePoint(uidRef); 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) { + if (env == nullptr || obj == nullptr || name == nullptr) { + ANS_LOGE("GetPropertyRef fail, has nullptr"); + return ANI_INVALID_ARGS; + } ani_status status = env->Object_GetPropertyByName_Ref(obj, name, &outRef); if (status != ANI_OK) { - ANS_LOGI("Failed to get property '%{public}s', status: %{public}d", name, status); + ANS_LOGE("Failed to get property '%{public}s', status: %{public}d", name, status); return status; } status = env->Reference_IsUndefined(outRef, &isUndefined); if (status != ANI_OK) { - ANS_LOGI("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + ANS_LOGE("Failed to check undefined for '%{public}s', status: %{public}d", name, status); } return status; } @@ -179,60 +225,80 @@ ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_bo 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; + } ani_ref arrayObj = nullptr; ani_status status; ani_double length; - std::string str; 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); + deletePoint(arrayObj); return ANI_INVALID_ARGS; } status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { - ANS_LOGI("status : %{public}d", status); + ANS_LOGE("status : %{public}d", status); + deletePoint(arrayObj); 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_LOGI("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("status : %{public}d, index: %{public}d", status, i); + deletePoint(arrayObj); + deletePoint(stringEntryRef); return status; } - - str = ""; status = GetStringByAniString(env, static_cast(stringEntryRef), str); if (status != ANI_OK) { - ANS_LOGI("GetStdString failed, index: %{public}d", i); + ANS_LOGE("GetStdString failed, index: %{public}d", i); + deletePoint(arrayObj); + deletePoint(stringEntryRef); return status; } - res.push_back(str); - ANS_LOGI("GetStdString index: %{public}d %{public}s", i, str.c_str()); + ANS_LOGD("GetStdString index: %{public}d %{public}s", i, str.c_str()); } 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 (strs.empty()) { - return arrayObj; + if (arrayObj == nullptr) { + deletePoint(arrayObj); + return nullptr; } ani_size i = 0; for (auto &str : strs) { ani_string aniStr; - RETURN_NULL_IF_FALSE((GetAniStringByString(env, str, aniStr) == ANI_OK)); + if ((GetAniStringByString(env, str, aniStr) == ANI_OK)) { + deletePoint(arrayObj); + deletePoint(aniStr); + return nullptr; + } if (aniStr == nullptr) { + deletePoint(arrayObj); + deletePoint(aniStr); 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); + deletePoint(arrayObj); + deletePoint(aniStr); return nullptr; } i++; @@ -243,40 +309,43 @@ ani_object GetAniStringArrayByVectorString(ani_env *env, std::vectorClass_FindField(cls, fieldName.c_str(), &field); - ANS_LOGD("SetFieldString fieldName : %{public}s", fieldName.c_str()); - - if (status != ANI_OK) { + if (status != ANI_OK || field == nullptr) { ANS_LOGE("SetFieldString status : %{public}d", status); + deletePoint(string); 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); + deletePoint(string); + deletePoint(nullRef); return false; } if ((status = env->Object_SetField_Ref(object, field, nullRef)) != ANI_OK) { ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + deletePoint(string); + deletePoint(nullRef); 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); + deletePoint(string); return false; } - if ((status = env->Object_SetField_Ref(object, field, string)) != ANI_OK) { ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + deletePoint(string); return false; } return true; @@ -285,9 +354,10 @@ bool SetFieldString(ani_env *env, ani_class cls, ani_object &object, bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, const std::string fieldName, bool value) { - RETURN_FALSE_IF_NULL(env); - RETURN_FALSE_IF_NULL(cls); - RETURN_FALSE_IF_NULL(object); + 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) { @@ -296,11 +366,15 @@ bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, return false; } ani_object boolObj = CreateBoolean(env, BoolToAniBoolean(value)); - RETURN_FALSE_IF_NULL(boolObj); + if (boolObj == nullptr) { + deletePoint(boolObj); + 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()); + deletePoint(boolObj); return false; } return true; @@ -309,9 +383,10 @@ bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, const std::string fieldName, double value) { - RETURN_FALSE_IF_NULL(env); - RETURN_FALSE_IF_NULL(cls); - RETURN_FALSE_IF_NULL(object); + 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) { @@ -320,11 +395,15 @@ bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, return false; } ani_object doubleObj = CreateDouble(env, value); - RETURN_FALSE_IF_NULL(doubleObj); + if (doubleObj == nullptr) { + deletePoint(doubleObj); + 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()); + deletePoint(doubleObj); return false; } return true; @@ -332,64 +411,90 @@ bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, ani_object CreateBoolean(ani_env *env, bool value) { + if (env == nullptr) { + ANS_LOGE("CreateBoolean fail, env is nullptr"); + return nullptr; + } ani_class boolCls; ani_status status = ANI_ERROR; if ((status = env->FindClass(CLASSNAME_BOOLEAN, &boolCls)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(boolCls); return nullptr; } ani_method boolCtor; if ((status = env->Class_FindMethod(boolCls, "", "Z:V", &boolCtor)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(boolCls); return nullptr; } ani_object boolObj; if ((status = env->Object_New(boolCls, boolCtor, &boolObj, value ? ANI_TRUE : ANI_FALSE)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(boolCls); + deletePoint(boolObj); return nullptr; } + deletePoint(boolCls); return boolObj; } 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); + deletePoint(doubleCls); return nullptr; } ani_method doubleCtor; if ((status = env->Class_FindMethod(doubleCls, "", "D:V", &doubleCtor)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(doubleCls); return nullptr; } ani_object doubleObj; if ((status = env->Object_New(doubleCls, doubleCtor, &doubleObj, static_cast(value))) != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(doubleCls); + deletePoint(doubleObj); return nullptr; } + deletePoint(doubleCls); 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"); + deletePoint(arrayCls); return nullptr; } ani_method arrayCtor; - if(ANI_OK != env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor)){ + if (ANI_OK != env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor)){ ANS_LOGE("Class_FindMethod Failed"); + deletePoint(arrayCls); return nullptr; } ani_object arrayObj = nullptr; - if(ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)){ + if (ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)){ ANS_LOGE("Object_New Array Faild"); - return arrayObj; + deletePoint(arrayCls); + deletePoint(arrayObj); + return nullptr; } ANS_LOGD("newArrayClass end"); return arrayObj; @@ -398,17 +503,28 @@ ani_object newArrayClass(ani_env *env, int length) 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; - ani_method ctor; - if (ANI_OK != env->FindClass("Lescompat/Record;", &recordCls)) { + if (ANI_OK != (status = env->FindClass("Lescompat/Record;", &recordCls))) { + ANS_LOGE("newRecordClass fail, FindClass status = %{public}d", status); + deletePoint(recordCls); return nullptr; } - - if (ANI_OK != env->Class_FindMethod(recordCls, "", nullptr, &ctor)) { + ani_method ctor; + if (ANI_OK != (status = env->Class_FindMethod(recordCls, "", nullptr, &ctor))) { + ANS_LOGE("newRecordClass fail, Class_FindMethod status = %{public}d", status); + deletePoint(recordCls); return nullptr; } ani_object recordObj = {}; - if (ANI_OK != env->Object_New(recordCls, ctor, &recordObj)) { + if (ANI_OK != (status = env->Object_New(recordCls, ctor, &recordObj))) { + ANS_LOGE("newRecordClass fail, Object_New status = %{public}d", status); + deletePoint(recordCls); + deletePoint(recordObj); return nullptr; } ANS_LOGD("newRecordClass end"); @@ -417,22 +533,28 @@ ani_object newRecordClass(ani_env *env) ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values) { + if (env == nullptr || values.empty()) { + ANS_LOGE("ConvertArrayDoubleToAniObj fail, env is nullptr or values is empty"); + return nullptr; + } ani_object arrayObj = newArrayClass(env, values.size()); if (arrayObj == nullptr) { + deletePoint(arrayObj); return nullptr; } - if (values.empty()) { - return arrayObj; - } 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"); + deletePoint(arrayObj); + deletePoint(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); + deletePoint(arrayObj); + deletePoint(intObj); return nullptr; } } @@ -442,6 +564,10 @@ ani_object ConvertArrayDoubleToAniObj(ani_env *env, 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) { @@ -452,11 +578,13 @@ bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, ani_object arrayObj = ConvertArrayDoubleToAniObj(env, values); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is nullptr."); + deletePoint(arrayObj); return false; } status = env->Object_SetField_Ref(object, field, arrayObj); if (status != ANI_OK) { ANS_LOGE("status : %{public}d", status); + deletePoint(arrayObj); return false; } return true; @@ -464,7 +592,15 @@ bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj) { - ANI_FAILED_AND_RETURN(env->FindClass(className, &cls)); + if (env == nullptr || className == nullptr) { + ANS_LOGE("CreateClassObjByClassName fail, has nullptr"); + return false; + } + if (ANI_OK != env->FindClass(className, &cls)) { + deletePoint(cls); + deletePoint(outAniObj); + return false; + } ani_method ctor; ANI_FAILED_AND_RETURN(env->Class_FindMethod(cls, "", nullptr, &ctor)); outAniObj = {}; @@ -474,28 +610,37 @@ bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &c 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; - ani_object obj; - ani_method ctor; if (ANI_OK != (status = env->FindClass("Lescompat/Date;", &cls))) { ANS_LOGD("error. not find class name 'Lescompat/Date;'. status %{public}d", status); + deletePoint(cls); 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); + deletePoint(cls); return false; } ani_object timeObj = CreateDouble(env, static_cast(time)); if (timeObj == nullptr) { ANS_LOGD("createDouble faild"); + deletePoint(cls); + deletePoint(timeObj); return false; } - if (ANI_OK != (status = env->Object_New(cls, ctor, &obj, timeObj))) { + if (ANI_OK != (status = env->Object_New(cls, ctor, &outObj, timeObj))) { ANS_LOGD("Object_New faild. status %{public}d", status); + deletePoint(cls); + deletePoint(timeObj); + deletePoint(outObj); return false; } - outObj = obj; return true; } } // namespace NotificationSts diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index 3010668ad..f602addd3 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -19,34 +19,37 @@ namespace OHOS { namespace NotificationSts { -void UnwrapWantAgent(ani_env *env, ani_object agent, void** result) +std::shared_ptr UnwrapWantAgent(ani_env *env, ani_object agent) { - ANS_LOGI("called"); - if (agent == nullptr) { - ANS_LOGI("agent null"); - return; + ANS_LOGD("UnwrapWantAgent called"); + if (env == nullptr || agent == nullptr) { + ANS_LOGE("UnwrapWantAgent failed, has nullPtr"); + return nullptr; } - ani_long param_value; ani_status status = ANI_ERROR; - ani_class cls = nullptr; - ani_method method {}; - if ((status = env->FindClass("Lstd/core/Long;", &cls)) != ANI_OK) { - ANS_LOGI("status : %{public}d", status); - return; - } - if ((status = env->Class_FindMethod(cls, "unboxed", nullptr, &method)) != ANI_OK) { - ANS_LOGI("status : %{public}d", status); - return; + 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; } - if ((status = env->Object_CallMethod_Long(agent, method, ¶m_value)) != ANI_OK) { - ANS_LOGI("status : %{public}d", status); - return; + WantAgent* wantAgent = reinterpret_cast(nativeObj); + if (wantAgent == nullptr) { + ANS_LOGI("UnwrapWantAgent wantAgent nullptr"); + return nullptr; } - *result = reinterpret_cast(param_value); + 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; @@ -57,24 +60,27 @@ ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resourc resource.bundleName = bundleName; std::string moduleName = ""; - if((status = GetPropertyString(env, obj, "moduleName", isUndefined, moduleName)) != ANI_OK + 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 + 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) { - if (pixelMap == nullptr) { + ANS_LOGD("CreateAniPixelMap call"); + if (env == nullptr || pixelMap == nullptr) { + ANS_LOGE("CreateAniPixelMap failed, has nullPtr"); return nullptr; } return PixelMapAni::CreatePixelMap(env, pixelMap); @@ -82,27 +88,39 @@ ani_object CreateAniPixelMap(ani_env* env, std::shared_ptr 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("[GetPixelMapFromEnv] Object_GetField_Long fetch failed"); + ANS_LOGI("GetPixelMapFromEnvSp Object_GetField_Long fetch failed"); return nullptr; } - PixelMapAni* pixelmapAni = reinterpret_cast(nativeObj); - if (!pixelmapAni) { - ANS_LOGI("[GetPixelMapFromEnv] pixelmapAni nullptr"); + PixelMap* pixelmap = reinterpret_cast(nativeObj); + if (pixelmap == nullptr) { + ANS_LOGI("GetPixelMapFromEnvSp pixelmap nullptr"); return nullptr; } - return pixelmapAni->nativePixelMap_; + 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_LOGI("status : %{public}d", status); + ANS_LOGE("GetPixelMapArrayByRef: status : %{public}d", status); return status; } @@ -111,290 +129,456 @@ ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vectorObject_CallMethodByName_Ref(static_cast(param), "$_get", "I:Lstd/core/Object;", &pixelMapRef, (ani_int)i); if (status != ANI_OK) { - ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("GetPixelMapArrayByRef:status : %{public}d, index: %{public}d", status, i); + deletePoint(pixelMapRef); + pixelMaps.clear(); return status; } - std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pixelMapRef)); if (pixelMap == nullptr) { - return ANI_INVALID_ARGS; + ANS_LOGE("GetPixelMapArrayByRef: GetPixelMapFromEnvSp failed."); + deletePoint(pixelMapRef); + 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) { + deletePoint(arrayObj); return ANI_INVALID_ARGS; } if ((status = GetPixelMapArrayByRef(env, arrayObj, pixelMaps)) != ANI_OK) { + deletePoint(arrayObj); + 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) { + deletePoint(arrayObj); + 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_LOGI("status : %{public}d", status); + ANS_LOGE("GetResourceArray : status : %{public}d", status); + deletePoint(arrayObj); 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) { - ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + deletePoint(arrayObj); + deletePoint(iconRef); + 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_LOGI("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("GetResourceArray : status = %{public}d, index= %{public}d", status, i); + deletePoint(arrayObj); + deletePoint(iconRef); + 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_LOGI("status : %{public}d, index: %{public}d", status, index); + ANS_LOGE("status : %{public}d, index: %{public}d", status, index); + deletePoint(stringEntryRef); 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) { + 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"); + deletePoint(picturesArrayRef); + deleteVectorWithArraySpPoints(pictureMap); return status; } std::vector> pixelMaps = {}; if((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { + ANS_LOGE("GetPixelMapByKeys : GetPixelMapArrayByRef failed"); + deletePoint(picturesArrayRef); + deleteVectorWithSpPoints(pixelMaps); + deleteVectorWithArraySpPoints(pictureMap); return status; } std::string str = ""; if((status = GetStringByAniString(env, anikey, str)) != ANI_OK) { + ANS_LOGE("GetPixelMapByKeys : GetStringByAniString failed"); + deletePoint(picturesArrayRef); + 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); + deletePoint(strAni); + deleteVectorWithPoints(keys); + 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; - RETURN_ANI_STATUS_IF_NOT_OK(status = env->FindClass("Lnotification/notificationContent/RecordTools;", &cls), - "failed to find class -> Lnotification/notificationContent/RecordTools;"); + 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"); + deletePoint(cls); return ANI_INVALID_TYPE; } ani_static_method keysMethod = nullptr; - RETURN_ANI_STATUS_IF_NOT_OK(status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod), - "find Method GetKeys failed."); + if (ANI_OK != (status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod))) { + deletePoint(cls); + ANS_LOGE("GetMapOfPictureInfo : Class_FindStaticMethod status = %{public}d", status); + return status; + } ani_ref keysStrArrayRef = nullptr; - RETURN_ANI_STATUS_IF_NOT_OK(status = env->Class_CallStaticMethod_Ref(cls, keysMethod, &keysStrArrayRef, obj), - "failed to call method GetKeys"); - ani_boolean isUndefined = ANI_TRUE; - if ((status = env->Reference_IsUndefined(keysStrArrayRef, &isUndefined)) != ANI_OK) { + if (ANI_OK != (status = env->Class_CallStaticMethod_Ref(cls, keysMethod, &keysStrArrayRef, obj))) { + deletePoint(cls); + deletePoint(keysStrArrayRef); + ANS_LOGE("GetMapOfPictureInfo : Class_CallStaticMethod_Ref status = %{public}d", status); return status; } - if (isUndefined) { + if (IsUndefine(env, static_cast(keysStrArrayRef))) { + deletePoint(cls); + deletePoint(keysStrArrayRef); + ANS_LOGE("GetMapOfPictureInfo : keysStrArrayRef IsUndefined"); return ANI_INVALID_ARGS; } - ani_double length; - RETURN_ANI_STATUS_IF_NOT_OK( - status = env->Object_GetPropertyByName_Double(static_cast(keysStrArrayRef), "length", &length), - "get length ok keys failed."); - 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) { - return status; - } - keys.push_back(strAni); + if (ANI_OK != (status = GetPixelMapByRef(env, obj, keysStrArrayRef, pictureMap))) { + deletePoint(cls); + deletePoint(keysStrArrayRef); + deleteVectorWithArraySpPoints(pictureMap); + ANS_LOGE("GetMapOfPictureInfo : GetPixelMapByRef status = %{public}d", status); } - status = GetPixelMapByKeys(env, obj, keys, pictureMap); + 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; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "Lglobal/resourceInner/ResourceInner;", resourceCls, resourceObject)); - // bundleName: string; + if (!CreateClassObjByClassName(env, + "Lglobal/resourceInner/ResourceInner;", resourceCls, resourceObject)) { + ANS_LOGE("GetAniResource : CreateClassObjByClassName failed"); + deletePoint(resourceCls); + deletePoint(resourceObject); + return nullptr; + } ani_string stringValue = nullptr; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, resource->bundleName, stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "bundleName", stringValue)); - // moduleName: string; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, resource->moduleName, stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "moduleName", stringValue)); - // id: number; - RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "id", resource->id)); + 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); + deletePoint(resourceCls); + deletePoint(resourceObject); + deletePoint(stringValue); + 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); + deletePoint(resourceCls); + deletePoint(resourceObject); + deletePoint(stringValue); + return nullptr; + } + if (!CallSetter(env, resourceCls, resourceObject, "id", resource->id)) { + ANS_LOGE("GetAniResource : set moduleName failed, status = %{public}d", status); + deletePoint(resourceObject); + } + deletePoint(resourceCls); + deletePoint(stringValue); + ANS_LOGD("GetAniResource end"); return resourceObject; } ani_object GetAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps) { - RETURN_NULL_IF_NULL(env); - if (pixelMaps.empty()) { + 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"); + deletePoint(arrayObj); return nullptr; } ani_size i = 0; for (auto &pixelMap : pixelMaps) { ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, pixelMap); if (pixelMapObject == nullptr) { - ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); + ANS_LOGE("GetAniArrayPixelMap : pixelMapObject is nullptr"); + deletePoint(pixelMapObject); + deletePoint(arrayObj); return nullptr; } ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, pixelMapObject); if (status != ANI_OK) { - ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + deletePoint(pixelMapObject); + deletePoint(arrayObj); + 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) { - RETURN_NULL_IF_NULL(env); - if (resources.empty()) { - ANS_LOGE("resources is empty"); + 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"); + deletePoint(arrayObj); return nullptr; } ani_size i = 0; for (auto &resource : resources) { ani_object resourceObject = GetAniResource(env, resource); if (resourceObject == nullptr) { - ANS_LOGE("GetAniResource failed, resourceObject is nullptr"); + ANS_LOGE("GetAniArrayResource : resourceObject is nullPtr"); + deletePoint(resourceObject); + deletePoint(arrayObj); return nullptr; } ani_status status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, resourceObject); if (status != ANI_OK) { - ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + ANS_LOGE("GetAniArrayResource : Object_CallMethodByName_Void failed %{public}d", status); + deletePoint(resourceObject); + deletePoint(arrayObj); return nullptr; } i++; } + ANS_LOGD("GetAniArrayResource end"); return arrayObj; } bool GetAniPictrueInfo(ani_env *env, std::map>> pictureMap, ani_object &pictureInfoObj) { - if (pictureMap.empty()) { + 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"); + deletePoint(pictureInfoObj); + 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"); + deletePoint(aniKey); + deletePoint(pictureInfoObj); return false; } ani_object aniPictrueArray = GetAniArrayPixelMap(env, value); if (aniPictrueArray == nullptr) { + ANS_LOGE("GetAniPictrueInfo : GetAniArrayPixelMap failed"); + deletePoint(aniKey); + deletePoint(aniPictrueArray); + deletePoint(pictureInfoObj); 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"); + deletePoint(aniKey); + deletePoint(aniPictrueArray); + deletePoint(pictureInfoObj); 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; } - return AppExecFwk::WrapWantAgent(env, wantAgent.get()); + ani_object wantAgentObj = AppExecFwk::WrapWantAgent(env, wantAgent.get()); + if (wantAgentObj == nullptr) { + ANS_LOGE("WarpWantAgent : wantAgentObj is nullptr"); + deletePoint(wantAgentObj); + } + 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; - ani_method arrayCtor; - ani_object arrayObj; - status = env->FindClass("Lescompat/Array;", &arrayCls); - if (status != ANI_OK) { - ANS_LOGE("status : %{public}d", status); + if (ANI_OK != (status = env->FindClass("Lescompat/Array;", &arrayCls))) { + ANS_LOGE("GetAniWantAgentArray : FindClass status = %{public}d", status); + deletePoint(arrayCls); return nullptr; } - status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); - if (status != ANI_OK) { - ANS_LOGE("status : %{public}d", status); + ani_method arrayCtor; + if (ANI_OK != (status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor))) { + ANS_LOGE("GetAniWantAgentArray : Class_FindMethod status = %{public}d", status); + deletePoint(arrayCls); return nullptr; } - status = env->Object_New(arrayCls, arrayCtor, &arrayObj, wantAgents.size()); - if (status != ANI_OK) { - ANS_LOGE("status : %{public}d", status); + ani_object arrayObj; + if (ANI_OK != (status = env->Object_New(arrayCls, arrayCtor, &arrayObj, wantAgents.size()))) { + ANS_LOGE("GetAniWantAgentArray : Object_New status = %{public}d", status); + deletePoint(arrayCls); + deletePoint(arrayObj); return nullptr; } ani_size index = 0; for (auto &wantAgent : wantAgents) { - ani_object item = AppExecFwk::WrapWantAgent(env, wantAgent.get()); - RETURN_NULL_IF_NULL(item); - if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ - std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; - return nullptr; + 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"); + deletePoint(arrayCls); + deletePoint(arrayObj); + deletePoint(item); + return nullptr; } index ++; } + ANS_LOGD("GetAniWantAgentArray end"); return arrayObj; } } // namespace NotificationSts diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index 1cdaae424..b1cd20380 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -781,14 +781,12 @@ bool SetNotificationLongTextContent( RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLongTextContentInner;", contentCls, contentObj)); RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); - std::shared_ptr basicContent = nContent->GetNotificationContent(); - RETURN_FALSE_IF_NULL(basicContent); - NotificationLongTextContent *content = static_cast(basicContent.get()); + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { ANS_LOGE("TextContent is null"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); ani_string aniStr; if(GetAniStringByString(env, content->GetLongText(), aniStr)) { @@ -812,14 +810,12 @@ bool SetNotificationPictureContent( RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationPictureContentInner;", contentCls, contentObj)); RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); - std::shared_ptr basicContent = nContent->GetNotificationContent(); - RETURN_FALSE_IF_NULL(basicContent); - NotificationPictureContent *content = static_cast(basicContent.get()); + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { - ANS_LOGE("TextContent is null"); + ANS_LOGE("content is null"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); ani_string aniStr; if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { @@ -844,14 +840,12 @@ bool SetNotificationMultiLineContent( RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationMultiLineContentInner;", contentCls, contentObj)); RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); - std::shared_ptr basicContent = nContent->GetNotificationContent(); - RETURN_FALSE_IF_NULL(basicContent); - NotificationMultiLineContent *content = static_cast(basicContent.get()); + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { - ANS_LOGE("Content is null"); + ANS_LOGE("content is null"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); ani_string aniStr; if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { @@ -881,14 +875,12 @@ bool SetNotificationLocalLiveViewContent( RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", contentCls, contentObj)); RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); - std::shared_ptr basicContent = nContent->GetNotificationContent(); - RETURN_FALSE_IF_NULL(basicContent); - NotificationLocalLiveViewContent *content = static_cast(basicContent.get()); + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { - ANS_LOGE("Content is null"); + ANS_LOGE("content is null"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); CallSetterOptional(env, contentCls, contentObj, "typeCode", content->GetType()); @@ -943,14 +935,12 @@ bool SetNotificationLiveViewContent( RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", contentCls, contentObj)); RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); - std::shared_ptr basicContent = nContent->GetNotificationContent(); - RETURN_FALSE_IF_NULL(basicContent); - NotificationLiveViewContent *content = static_cast(basicContent.get()); + auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { - ANS_LOGE("Content is null"); + ANS_LOGE("content is null"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); ani_object lockScreenPicObj = CreateAniPixelMap(env, content->GetLockScreenPicture()); if (lockScreenPicObj != nullptr) { @@ -992,22 +982,13 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr n return SetNotificationLongTextContent(env, ncCls, ncContent, ncObj); case ContentType::PICTURE: // picture?: NotificationPictureContent return SetNotificationPictureContent(env, ncCls, ncContent, ncObj); - // need to do - //case ContentType::CONVERSATION: // conversation?: NotificationConversationalContent - //ret = SetNotificationConversationalContent(env, basicContent.get(), contentResult); - // break; case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent return SetNotificationMultiLineContent(env, ncCls, ncContent, ncObj); case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent return SetNotificationLocalLiveViewContent(env, ncCls, ncContent, ncObj); break; case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent -// RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, -// "Lnotification/notificationContent/NotificationLiveViewContentInner;", clsContent, aniContext)); -// RETURN_FALSE_IF_NULL(clsContent); -// RETURN_FALSE_IF_NULL(aniContext); -// RETURN_FALSE_IF_FALSE(SetNotificationLiveViewContent(env, clsContent, basicContent.get(), aniContext)); -// RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "liveView", aniContext)); + return SetNotificationLiveViewContent(env, ncCls, ncContent, ncObj); break; default: ANS_LOGE("ContentType is does not exist"); diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 8f2bb71fe..0e0a11a57 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -22,6 +22,7 @@ #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" @@ -34,28 +35,28 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption { bool isDistributed = false; ani_boolean isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isDistributed", isUndefined, isDistributed) + if (ANI_OK == GetPropertyBool(env, obj, "isDistributed", isUndefined, isDistributed) && isUndefined == ANI_FALSE) { distributedOptions.isDistributed = isDistributed; } std::vector supportDisplayDevices = {}; isUndefined = ANI_TRUE; - if(GetPropertyStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK + if (GetPropertyStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK && isUndefined == ANI_FALSE) { distributedOptions.supportDisplayDevices = supportDisplayDevices; } std::vector supportOperateDevices = {}; isUndefined = ANI_TRUE; - if(GetPropertyStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK + if (GetPropertyStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK && isUndefined == ANI_FALSE) { distributedOptions.supportOperateDevices = supportOperateDevices; } ani_double remindType = 0.0; isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyDouble(env, obj, "remindType", isUndefined, remindType) + if (ANI_OK == GetPropertyDouble(env, obj, "remindType", isUndefined, remindType) && isUndefined == ANI_FALSE) { distributedOptions.remindType = static_cast(remindType); } @@ -103,43 +104,43 @@ void GetNotificationRequestByBooleanOne(ani_env *env, ani_object obj, bool mbool = false; ani_boolean isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isOngoing", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "isOngoing", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetInProgress(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isUnremovable", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "isUnremovable", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetUnremovable(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "updateOnly", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "updateOnly", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetUpdateOnly(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "tapDismissed", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "tapDismissed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetTapDismissed(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "colorEnabled", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "colorEnabled", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetColorEnabled(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isAlertOnce", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "isAlertOnce", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetAlertOneTime(mbool); } isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isStopwatch", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "isStopwatch", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetShowStopwatch(mbool); } @@ -221,9 +222,12 @@ void GetNotificationRequestByString(ani_env *env, ani_object obj, void GetNotificationRequestByNumber(ani_env *env, ani_object obj, std::shared_ptr &request) { + ANS_LOGD("GetNotificationRequestByNumber start"); ani_double mDouble = 0.0; ani_boolean isUndefined = ANI_TRUE; - + if (obj == nullptr) { + ANS_LOGD("GetNotificationRequestByNumber obj is nullptr"); + } if(ANI_OK == GetPropertyDouble(env, obj, "id", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetNotificationId(static_cast(mDouble)); } else { @@ -260,6 +264,7 @@ void GetNotificationRequestByNumber(ani_env *env, ani_object obj, && isUndefined == ANI_FALSE) { request->SetNotificationControlFlags(static_cast(mDouble)); } + ANS_LOGD("GetNotificationRequestByNumber end"); } bool GetNotificationNormalContent(ani_env *env, ani_object obj, ani_ref contentRef, @@ -357,7 +362,6 @@ bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, case ContentType::LIVE_VIEW: return GetNotificationLiveViewContent(env, obj, contentRef, request); case ContentType::CONVERSATION: - // need to add break; default: break; @@ -415,15 +419,14 @@ void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptrObject_GetPropertyByName_Ref(obj, "wantAgent", &wantAgentRef))!= ANI_OK) { + deletePoint(wantAgentRef); return; } - WantAgent* pWantAgent = nullptr; - UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); - if (pWantAgent == nullptr) { - return; + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + deletePoint(wantAgentRef); + if (wantAgent == nullptr) { + return; } - - std::shared_ptr wantAgent = std::make_shared(*pWantAgent); request->SetWantAgent(wantAgent); } @@ -448,16 +451,15 @@ void GetNotificationRemovalWantAgent(ani_env *env, ani_object obj, { ani_status status = ANI_ERROR; ani_ref wantAgentRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "removalWantAgent", &wantAgentRef))!= ANI_OK) { + if ((status = env->Object_GetPropertyByName_Ref(obj, "removalWantAgent", &wantAgentRef))!= ANI_OK) { + deletePoint(wantAgentRef); return; } - WantAgent* pWantAgent = nullptr; - UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); - if (pWantAgent == nullptr) { - return; + std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); + deletePoint(wantAgentRef); + if (wantAgent == nullptr) { + return; } - - std::shared_ptr wantAgent = std::make_shared(*pWantAgent); request->SetRemovalWantAgent(wantAgent); } @@ -613,7 +615,6 @@ ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, if(status != ANI_OK) { return ANI_INVALID_ARGS; } - GetNotificationSlotType(env, obj, notificationRequest); GetNotificationWantAgent(env, obj, notificationRequest); GetNotificationExtraInfo(env, obj, notificationRequest); @@ -626,20 +627,16 @@ ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, GetNotificationTemplate(env, obj, notificationRequest); GetNotificationUnifiedGroupInfo(env, obj, notificationRequest); GetNotificationBundleOption(env, obj, notificationRequest); -// // need to do GetNotificationMaxScreenWantAgent 没看明白 -// /* -// // maxScreenWantAgent?: WantAgent -// if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { -// return nullptr; -// } -// */ - - return status; + 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"); + } ani_status status = ANI_ERROR; GetNotificationRequestByNumber(env, obj, notificationRequest); GetNotificationRequestByString(env, obj, notificationRequest); @@ -690,11 +687,6 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Not if (GetAniStringByString(env, request->GetClassification(), stringValue)) { CallSetter(env, cls, object, "classification", stringValue); } - // need to do ets中没有找到statusBarText属性 - // statusBarText?: string - // if (StringToAniStr(env, request->GetStatusBarText(), stringValue)) { - // RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, STATUS_BAR_TEXT, stringValue)); - // } // label?: string if (GetAniStringByString(env, request->GetLabel(), stringValue)) { CallSetter(env, cls, object, "label", stringValue); diff --git a/frameworks/ets/ani/src/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp index a3c00c7e4..7f04ae109 100644 --- a/frameworks/ets/ani/src/subscribe/ani_remove.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -32,27 +32,27 @@ void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notification ANS_LOGD("AniRemoveForBundle enter"); BundleOption option; NotificationKey key; - int32_t reasonType = -1; + int32_t reasonType = 0; if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { - ANS_LOGD("bundle is valid"); + ANS_LOGE("bundle is valid"); std::string msg = "UnwrapBundleOption faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::UnWarpNotificationKey(env, notificationKey, key)) { - ANS_LOGD("notificationKey is valid"); + ANS_LOGE("notificationKey is valid"); std::string msg = "UnWarpNotificationKey faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { - ANS_LOGD("enum convert failed"); + ANS_LOGE("enum convert failed"); std::string msg = "UnWarpReasonEnum faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { - ANS_LOGD("reasonType is valid"); + ANS_LOGE("reasonType is valid"); std::string msg = "reasonType is valid"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; @@ -72,19 +72,19 @@ void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEn int32_t reasonType = -1; std::string hashCodeStd; if (ANI_OK != NotificationSts::GetStringByAniString(env, hashCode, hashCodeStd)) { - ANS_LOGD("hashCode is valid"); + 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_LOGD("enum convert failed"); + ANS_LOGE("enum convert failed"); std::string msg = "UnWarpReasonEnum faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { - ANS_LOGD("reasonType is valid"); + ANS_LOGE("reasonType is valid"); std::string msg = "reasonType is valid"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; @@ -105,19 +105,19 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason std::vector hashCodesStd; int32_t reasonType; if (ANI_OK != NotificationSts::GetStringArrayByAniObj(env, hashCodes, hashCodesStd)) { - ANS_LOGD("hashCodes is valid"); + 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_LOGD("enum convert failed"); + ANS_LOGE("enum convert failed"); std::string msg = "UnWarpReasonEnum faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } if (!NotificationSts::IsValidRemoveReason(reasonType)) { - ANS_LOGD("reasonType is valid"); + ANS_LOGE("reasonType is valid"); std::string msg = "reasonType is valid"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; -- Gitee From b3539674fbf3793e0443c5d456c73fac2b5637e4 Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 19 May 2025 00:34:14 +0800 Subject: [PATCH 15/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_action_button.cpp | 1 - frameworks/ets/ani/src/sts_common.cpp | 2 -- frameworks/ets/ani/src/sts_convert_other.cpp | 2 +- frameworks/ets/ani/src/sts_notification_content.cpp | 1 - frameworks/ets/ani/src/sts_request.cpp | 2 -- 5 files changed, 1 insertion(+), 7 deletions(-) diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index be9d46948..f66c4e343 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -249,7 +249,6 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, return nullptr; } if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { - std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; deletePoint(arrayObj); deletePoint(item); return nullptr; diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 04d46295b..abc393a34 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -237,7 +237,6 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na deletePoint(arrayObj); return ANI_INVALID_ARGS; } - status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGE("status : %{public}d", status); @@ -574,7 +573,6 @@ bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, ANS_LOGE("status : %{public}d", status); return false; } - ani_object arrayObj = ConvertArrayDoubleToAniObj(env, values); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is nullptr."); diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index f602addd3..f9854a1ca 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -568,7 +568,7 @@ ani_object GetAniWantAgentArray(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { ANS_LOGE("GetAniWantAgentArray : set WantAgent failed"); deletePoint(arrayCls); diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index b1cd20380..ebc66d618 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -417,7 +417,6 @@ ani_object GetAniIconButtonArray(ani_env *env, const std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ - std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; return nullptr; } index ++; diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 0e0a11a57..90c781fcd 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -928,7 +928,6 @@ ani_object GetAniNotificationRequestArray(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)){ - std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; return nullptr; } index ++; @@ -955,7 +954,6 @@ ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vect env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)); RETURN_NULL_IF_NULL(requestObj); if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)){ - std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; return nullptr; } index ++; -- Gitee From 5944130013ee4ceb4aaead0acdbb9a005544d563 Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 19 May 2025 23:27:59 +0800 Subject: [PATCH 16/52] modify Signed-off-by: heguokai --- .../ets/ani/include/manager/ani_publish.h | 5 +- .../ets/ani/src/manager/ani_publish.cpp | 5 +- frameworks/ets/ani/src/sts_action_button.cpp | 111 +++++- frameworks/ets/ani/src/sts_bundle_option.cpp | 54 +-- frameworks/ets/ani/src/sts_common.cpp | 38 +- frameworks/ets/ani/src/sts_disturb_mode.cpp | 32 +- frameworks/ets/ani/src/sts_request.cpp | 348 +++++++++++------- 7 files changed, 384 insertions(+), 209 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_publish.h b/frameworks/ets/ani/include/manager/ani_publish.h index fd216d5ff..fd18fc59c 100644 --- a/frameworks/ets/ani/include/manager/ani_publish.h +++ b/frameworks/ets/ani/include/manager/ani_publish.h @@ -19,9 +19,8 @@ namespace OHOS { namespace NotificationManagerSts { -void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj); -void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj, - ani_double userId); +void AniPublish(ani_env *env, ani_object obj); +void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId); } // namespace NotificationManagerSts } // namespace OHOS #endif \ 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 index df0aa3557..af5506b9a 100644 --- a/frameworks/ets/ani/src/manager/ani_publish.cpp +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -26,7 +26,7 @@ namespace OHOS { namespace NotificationManagerSts { using namespace OHOS::Notification; -void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj) +void AniPublish(ani_env *env, ani_object obj) { ANS_LOGD("AniPublish call"); std::shared_ptr notificationRequest = std::make_shared(); @@ -44,8 +44,7 @@ void AniPublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj ANS_LOGD("AniPublish end"); } -void AniPublishWithId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj, - ani_double userId) +void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId) { ANS_LOGD("AniPublishWithId start"); //NotificationRequest request; diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index f66c4e343..0ed3541c2 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -17,6 +17,7 @@ #include "sts_common.h" #include "sts_convert_other.h" #include "ani_common_want.h" +#include "ans_log_wrapper.h" #include "sts_user_input.h" @@ -24,79 +25,114 @@ 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"); deletePoint(wantAgentRef); return ANI_INVALID_ARGS; } std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); deletePoint(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"); deletePoint(extrasRef); 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; } @@ -106,29 +142,45 @@ bool SetNotificationActionButtonByRequiredParameter( 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 (!GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { deletePoint(stringValue); + ANS_LOGE("SetActionButtonByRequiredParameter: Get title failed"); return false; } if (!CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)) { deletePoint(stringValue); + ANS_LOGE("SetActionButtonByRequiredParameter: Set title failed"); return false; } // wantAgent: WantAgent; std::shared_ptr agent = actionButton->GetWantAgent(); if (agent == nullptr) { - ANS_LOGI("agent is null"); + ANS_LOGE("SetActionButtonByRequiredParameter:agent is null"); deletePoint(stringValue); return false; } else { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + if (wantAgent == nullptr) { + ANS_LOGE("SetActionButtonByRequiredParameter: wantAgent is nullptr"); + deletePoint(stringValue); + deletePoint(wantAgent); + return false; + } if (!CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)) { + ANS_LOGE("SetActionButtonByRequiredParameter: Set wantAgent failed"); deletePoint(stringValue); + deletePoint(wantAgent); return false; } } + ANS_LOGD("SetActionButtonByRequiredParameter end"); return true; } @@ -138,20 +190,29 @@ void SetNotificationActionButtonByOptionalParameter( 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"); deletePoint(extras); } // userInput?: NotificationUserInput ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); if (!CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)) { + ANS_LOGD("SetActionButtonByOptionalParameter : Set userInput failed"); deletePoint(userInputObject); } + ANS_LOGD("SetActionButtonByOptionalParameter end"); } void deletePointOfWrapNotificationActionButton( ani_object iconButtonObject, ani_class iconButtonCls, ani_string stringValue) { + ANS_LOGD("deletePointOfWrapNotificationActionButton call"); deletePoint(iconButtonObject); deletePoint(iconButtonCls); deletePoint(stringValue); @@ -160,8 +221,9 @@ void deletePointOfWrapNotificationActionButton( ani_object WrapNotificationActionButton(ani_env* env, const std::shared_ptr &actionButton) { - if (actionButton == nullptr) { - ANS_LOGE("actionButton is null"); + ANS_LOGD("WrapNotificationActionButton call"); + if (env == nullptr || actionButton == nullptr) { + ANS_LOGE("WrapNotificationActionButton failed, has nullptr"); return nullptr; } ani_object iconButtonObject = nullptr; @@ -169,50 +231,56 @@ ani_object WrapNotificationActionButton(ani_env* env, ani_string stringValue = nullptr; if (!CreateClassObjByClassName(env, "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)) { + ANS_LOGE("WrapNotificationActionButton : CreateClassObjByClassName failed"); deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); return nullptr; } if (!SetNotificationActionButtonByRequiredParameter(env, iconButtonCls, iconButtonObject, actionButton)) { + ANS_LOGE("WrapNotificationActionButton : SetRequiredParameter failed"); deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); 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_LOGI("status : %{public}d , %{public}s : may be undefined", status, name); + ANS_LOGE("GetActionButtonArray: GetPropertyRef name = %{public}s, status = %{public}d", name, status); deletePoint(arrayObj); return ANI_INVALID_ARGS; } - status = GetPropertyDouble(env, static_cast(arrayObj), "length", isUndefined, length); - if (status != ANI_OK) { - ANS_LOGI("status : %{public}d", status); + if (ANI_OK!= (status = GetPropertyDouble(env, static_cast(arrayObj), "length", isUndefined, length))) { + ANS_LOGE("GetActionButtonArray: GetPropertyDouble name = %{public}s, status = %{public}d", name, status); deletePoint(arrayObj); return status; } - - for (int i = 0; i < static_cast(length); i++) { + for (int dex = 0; dex < static_cast(length); dex++) { ani_ref buttonRef; - status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), - "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); - if (status != ANI_OK) { + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)dex))) { deletePoint(arrayObj); deletePoint(buttonRef); - ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("GetActionButtonArray: get ref failed, status = %{public}d, index = %{public}d", status, dex); return status; } - status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton); - if (status != ANI_OK) { - ANS_LOGI("ActionButton failed, index: %{public}d", i); + if (ANI_OK + != (status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton))) { + ANS_LOGE("GetActionButtonArray: UnwrapActionButton failed, status = %{public}d, index = %{public}d", + status, dex); deletePoint(arrayObj); deletePoint(buttonRef); return status; @@ -224,19 +292,21 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, actionButton.userInput, actionButton.isContextual); res.push_back(button); } + ANS_LOGD("GetActionButtonArray end"); return status; } ani_object GetAniArrayNotificationActionButton(ani_env* env, const std::vector> &actionButtons) { - if (actionButtons.empty()) { - ANS_LOGE("actionButtons is empty"); + 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("arrayObj is empty"); + ANS_LOGE("GetAniArrayActionButton: arrayObj is nullptr"); deletePoint(arrayObj); return nullptr; } @@ -244,17 +314,20 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, for (auto &button : actionButtons) { ani_object item = WrapNotificationActionButton(env, button); if (item == nullptr) { + ANS_LOGE("GetAniArrayActionButton: item is nullptr"); deletePoint(arrayObj); deletePoint(item); return nullptr; } if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { + ANS_LOGE("GetAniArrayActionButton: Object_CallMethodByName_Void failed"); deletePoint(arrayObj); deletePoint(item); return nullptr; } index ++; } + ANS_LOGD("GetAniArrayActionButton end"); return arrayObj; } } diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index 97e394b31..ad141e948 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -22,10 +22,14 @@ 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_ERROR; if (GetPropertyString(env, obj, "bundle", isUndefined, bundleName) !=ANI_OK || isUndefined == ANI_TRUE) { - ANS_LOGE("get bundle failed, bundle must be string."); + ANS_LOGE("UnwrapBundleOption Get bundle failed"); return false; } option.SetBundleName(bundleName); @@ -34,73 +38,70 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification int32_t uid = static_cast(result); option.SetUid(uid); } else { - ANS_LOGD("Wrong argument type or uid is Undefined."); + ANS_LOGD("UnwrapBundleOption get uid failed"); } - ANS_LOGD( - "WrapBundleOption bundleName: %{public}s uid: %{public}d", option.GetBundleName().c_str(), option.GetUid()); + ANS_LOGD("UnwrapBundleOption end"); return true; } 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("status : %{public}d", status); + ANS_LOGE("UnwrapArrayBundleOption: get length failed, status = %{public}d", status); return false; } - Notification::NotificationBundleOption option; - for (int i = 0; i < static_cast(length); i++) { + for (int dex = 0; dex < static_cast(length); dex++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), - "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)i); + "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)dex); if (status != ANI_OK) { - ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("UnwrapArrayBundleOption: get bundleOptionRef failed, status = %{public}d", status); deletePoint(optionRef); return false; } - if (!UnwrapBundleOption(env, static_cast(optionRef), option)) { - ANS_LOGD("Get BundleOption failed, index: %{public}d", i); + ANS_LOGE("UnwrapArrayBundleOption: get option status = %{public}d, index = %{public}d", status, dex); deletePoint(optionRef); return false; } options.push_back(option); - ANS_LOGD("GetOptions index: %{public}d", i); deletePoint(optionRef); } + ANS_LOGD("UnwrapArrayBundleOption end"); return true; } bool WrapBundleOption(ani_env* env, const std::shared_ptr &bundleOption, ani_object &bundleObject) { - if (bundleOption == nullptr) { - ANS_LOGE("agentBundle is null"); + 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)) { - deletePoint(bundleCls); - return false; - } - if (bundleCls == nullptr || bundleObject == nullptr) { + "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject) + || bundleCls == nullptr || bundleObject == nullptr) { + ANS_LOGE("WrapBundleOption: create BundleOption failed"); deletePoint(bundleCls); deletePoint(bundleObject); return false; } // bundle: string; ani_string stringValue = nullptr; - if (!GetAniStringByString(env, bundleOption->GetBundleName(), stringValue)) { - deletePoint(bundleCls); - deletePoint(bundleObject); - deletePoint(stringValue); - return false; - } - if (!CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { + if (!GetAniStringByString(env, bundleOption->GetBundleName(), stringValue) + || !CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { + ANS_LOGE("WrapBundleOption: set bundle failed"); deletePoint(bundleCls); deletePoint(bundleObject); deletePoint(stringValue); @@ -110,6 +111,7 @@ bool WrapBundleOption(ani_env* env, uint32_t uid = bundleOption->GetUid(); CallSetterOptional(env, bundleCls, bundleObject, "uid", uid); deletePoint(bundleCls); + ANS_LOGD("WrapBundleOption end"); return true; } } diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index abc393a34..12165bd8f 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -111,6 +111,7 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, 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) { @@ -140,30 +141,28 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, ani_boolean isUndefined, bool outvalue) { + ANS_LOGE("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; - ani_ref uidRef; - status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef); + status = env->Object_GetPropertyByName_Ref(obj, name, &refObj); if (ANI_OK != status) { ANS_LOGE("Object_GetPropertyByName_Ref fail, status: %{public}d", status); deletePoint(refObj); - deletePoint(uidRef); return status; } - if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { + if ((status = env->Reference_IsUndefined(refObj, &isUndefined)) != ANI_OK) { ANS_LOGE("Reference_IsUndefined failed, status : %{public}d", status); deletePoint(refObj); - deletePoint(uidRef); return status; } if (isUndefined) { ANS_LOGE("%{public}s is undefined", name); deletePoint(refObj); - deletePoint(uidRef); return ANI_INVALID_ARGS; } ani_boolean result = ANI_FALSE; @@ -171,7 +170,6 @@ ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, "unboxed", ":Z", &result)) != ANI_OK) { ANS_LOGE("Object_CallMethodByName_Boolean failed, status : %{public}d", status); deletePoint(refObj); - deletePoint(uidRef); return status; } outvalue = (result == ANI_TRUE); @@ -185,19 +183,19 @@ ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, ANS_LOGE("GetPropertyDouble fail, has nullptr"); return ANI_INVALID_ARGS; } - ANS_LOGD("GetPropertyDouble start %{public}s", name); + ANS_LOGD("GetPropertyDouble: %{public}s", name); ani_status status = ANI_ERROR; - ani_ref uidRef; - status = GetPropertyRef(env, obj, name, isUndefined, uidRef); - if (status != ANI_OK || isUndefined) { + ani_ref refObj; + status = GetPropertyRef(env, obj, name, isUndefined, refObj); + if (status != ANI_OK || isUndefined == ANI_TRUE) { ANS_LOGE("%{public}s is undefined", name); - deletePoint(uidRef); + deletePoint(refObj); return ANI_INVALID_ARGS; } - if ((status = env->Object_CallMethodByName_Double( - reinterpret_cast(uidRef), "doubleValue", nullptr, &outvalue)) != ANI_OK) { - ANS_LOGE("status : %{public}d", status); - deletePoint(uidRef); + if ((status = env->Object_CallMethodByName_Double(static_cast(refObj), + "unboxed", ":D", &outvalue)) != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + deletePoint(refObj); return status; } ANS_LOGD("Object_CallMethodByName_Double sucess, status: %{public}f", outvalue); @@ -206,19 +204,26 @@ ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, 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; } @@ -229,6 +234,7 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na 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; diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp index 3dfe020da..b67ea2ba7 100644 --- a/frameworks/ets/ani/src/sts_disturb_mode.cpp +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -24,24 +24,26 @@ 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 != GetPropertyDouble(env, param, "id", isUndefined, idAni) || isUndefined == ANI_TRUE) { - ANS_LOGE("GetPropertyDouble id : failed"); + ANS_LOGE("UnwrapDoNotDisturbProfile: get id failed"); return false; } std::string nameStr = ""; if (ANI_OK != GetPropertyString(env, param, "name", isUndefined, nameStr) || isUndefined == ANI_TRUE) { - ANS_LOGE("GetPropertyString name : failed"); + ANS_LOGE("UnwrapDoNotDisturbProfile: get name failed"); return false; } profile->SetProfileId(static_cast(idAni)); profile->SetProfileName(nameStr); - ani_ref trustlistRef; if (ANI_OK != GetPropertyRef(env, param, "trustlist", isUndefined, trustlistRef) || isUndefined == ANI_TRUE) { - ANS_LOGD("GetPropertyRef trustlist failed, maybe is isUndefined"); + ANS_LOGE("UnwrapDoNotDisturbProfile: get trustlist failed"); } else { std::vector trustlist = {}; UnwrapArrayBundleOption(env, static_cast(trustlistRef), trustlist); @@ -56,32 +58,34 @@ bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, 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("status : %{public}d", status); + ANS_LOGD("UnwrapArrayDoNotDisturbProfile: status = %{public}d", status); return false; } - sptr profile; - for (int i = 0; i < static_cast(length); i++) { + for (int dex = 0; dex < static_cast(length); dex++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", - "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)i); + "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)dex); if (status != ANI_OK) { - ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + ANS_LOGE("UnwrapArrayDoNotDisturbProfile: status : %{public}d, index: %{public}d", status, dex); return false; } - if (!UnwrapDoNotDisturbProfile(env, static_cast(optionRef), profile)) { - ANS_LOGD("Get profile failed, index: %{public}d", i); + ANS_LOGE("Get profile failed, index: %{public}d", dex); return false; } profiles.push_back(profile); - ANS_LOGD("GetProfiles index: %{public}d", i); } + ANS_LOGD("UnwrapArrayDoNotDisturbProfile end"); return true; } } // namespace NotificationSts diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 90c781fcd..fc170c0dc 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -33,158 +33,174 @@ using namespace OHOS::AppExecFwk; 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; + } 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"); } - 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"); } - 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"); } - 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) { - if (groupInfo == nullptr) { - ANS_LOGE("groupInfo is null"); + ANS_LOGD("WarpNotificationUnifiedGroupInfo start"); + if (env == nullptr || groupInfo == nullptr) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo failed, has nullptr"); return false; } ani_class groupInfoCls = nullptr; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)); + if ((!CreateClassObjByClassName(env, + "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)) + || groupInfoCls == nullptr || groupInfoObject == nullptr) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: create class failed"); + return false; + } // key?: string; ani_string stringValue = nullptr; if (GetAniStringByString(env, groupInfo->GetKey(), stringValue)) { CallSetter(env, groupInfoCls, groupInfoObject, "key", stringValue); + } else { + ANS_LOGD("WarpNotificationUnifiedGroupInfo: set key failed"); } // title?: string; if (GetAniStringByString(env, groupInfo->GetTitle(), stringValue)) { CallSetter(env, groupInfoCls, groupInfoObject, "title", stringValue); + } else { + ANS_LOGD("WarpNotificationUnifiedGroupInfo: get title failed"); } // content?: string; if (GetAniStringByString(env, groupInfo->GetContent(), stringValue)) { CallSetter(env, groupInfoCls, groupInfoObject, "content", stringValue); + } else { + ANS_LOGD("WarpNotificationUnifiedGroupInfo: get content failed"); } // sceneName?: string; if (GetAniStringByString(env, groupInfo->GetSceneName(), stringValue)) { CallSetter(env, groupInfoCls, groupInfoObject, "sceneName", stringValue); + } else { + ANS_LOGD("WarpNotificationUnifiedGroupInfo: get sceneName failed"); } // extraInfo?: Record; std::shared_ptr extraInfo = groupInfo->GetExtraInfo(); if (extraInfo) { ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *extraInfo); CallSetter(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef); + } else { + ANS_LOGD("WarpNotificationUnifiedGroupInfo: get extraInfo failed"); } + 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); } - - isUndefined = ANI_TRUE; if (ANI_OK == GetPropertyBool(env, obj, "isUnremovable", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetUnremovable(mbool); } - - isUndefined = ANI_TRUE; if (ANI_OK == GetPropertyBool(env, obj, "updateOnly", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetUpdateOnly(mbool); } - - isUndefined = ANI_TRUE; if (ANI_OK == GetPropertyBool(env, obj, "tapDismissed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetTapDismissed(mbool); } - - isUndefined = ANI_TRUE; if (ANI_OK == GetPropertyBool(env, obj, "colorEnabled", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetColorEnabled(mbool); } - - isUndefined = ANI_TRUE; if (ANI_OK == GetPropertyBool(env, obj, "isAlertOnce", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetAlertOneTime(mbool); } - - isUndefined = ANI_TRUE; 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); } - - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBool(env, obj, "isFloatingIcon", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetFloatingIcon(mbool); } - - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBool(env, obj, "showDeliveryTime", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetShowDeliveryTime(mbool); } - - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBool(env, obj, "isRemoveAllowed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetRemoveAllowed(mbool); } - - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBool(env, obj, "forceDistributed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetForceDistributed(mbool); } - - isUndefined = ANI_TRUE; 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, @@ -196,70 +212,66 @@ void GetNotificationRequestByBoolean(ani_env *env, ani_object obj, 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) { 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) { request->SetLabel(mString); } - if (ANI_OK == GetPropertyString(env, obj, "groupName", isUndefined, mString) && isUndefined == ANI_FALSE) { 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 (obj == nullptr) { - ANS_LOGD("GetNotificationRequestByNumber obj is nullptr"); - } 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)); @@ -267,100 +279,159 @@ void GetNotificationRequestByNumber(ani_env *env, ani_object obj, ANS_LOGD("GetNotificationRequestByNumber end"); } -bool GetNotificationNormalContent(ani_env *env, ani_object obj, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationNormalContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "normal", &contentRef) != ANI_OK) { + 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, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationLongTextContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "longText", &contentRef) != ANI_OK) { + 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, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationPictureContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "picture", &contentRef) != ANI_OK) { + 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, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationMultiLineContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "multiLine", &contentRef) != ANI_OK) { + 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, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationLocalLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "systemLiveView", &contentRef) != ANI_OK) { + 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, ani_ref contentRef, - std::shared_ptr &request) +bool GetNotificationLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &request) { - if(env->Object_GetPropertyByName_Ref(obj, "liveView", &contentRef) != ANI_OK) { + 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) { - ani_ref contentRef = {}; + 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, contentRef, request); + return GetNotificationNormalContent(env, obj, request); case ContentType::LONG_TEXT: - return GetNotificationLongTextContent(env, obj, contentRef, request); + return GetNotificationLongTextContent(env, obj, request); case ContentType::PICTURE: - return GetNotificationPictureContent(env, obj, contentRef, request); + return GetNotificationPictureContent(env, obj, request); case ContentType::MULTILINE: - return GetNotificationMultiLineContent(env, obj, contentRef, request); + return GetNotificationMultiLineContent(env, obj, request); case ContentType::LOCAL_LIVE_VIEW: - return GetNotificationLocalLiveViewContent(env, obj, contentRef, request); + return GetNotificationLocalLiveViewContent(env, obj, request); case ContentType::LIVE_VIEW: - return GetNotificationLiveViewContent(env, obj, contentRef, request); + return GetNotificationLiveViewContent(env, obj, request); case ContentType::CONVERSATION: break; default: @@ -372,53 +443,69 @@ bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, 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_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref notificationContentRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "content", ¬ificationContentRef))!= ANI_OK) { - return status; + if (ANI_OK != GetPropertyRef(env, obj, "content", isUndefined, notificationContentRef) + || isUndefined == ANI_TRUE) { + ANS_LOGE("GetNotificationContent:get contentRef failed"); + return status; } ani_ref contentTypeRef; - if((status = env->Object_GetPropertyByName_Ref(static_cast(notificationContentRef), - "notificationContentType", &contentTypeRef)) != ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "notificationContentType", isUndefined, contentTypeRef) + || isUndefined == ANI_TRUE || contentTypeRef == nullptr) { + ANS_LOGE("GetNotificationContent:get notificationContentType failed"); return status; } - ani_boolean isUndefined = ANI_TRUE; - if ((status = env->Reference_IsUndefined(contentTypeRef, &isUndefined)) != ANI_OK) { - return status; - } - if (isUndefined == ANI_TRUE) { - return ANI_INCORRECT_REF; - } ContentType type; - if(!ContentTypeEtsToC(env, static_cast(contentTypeRef), 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)) { + if (!GetNotificationContent(env, static_cast(notificationContentRef), type, request)) { + ANS_LOGE("GetNotificationContent:GetNotificationContent failed"); return ANI_INVALID_ARGS; } + ANS_LOGD("GetNotificationContent end"); return status; } 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((status = env->Object_GetPropertyByName_Ref(obj, "notificationSlotType", &slotTypeRef))!= ANI_OK) { - return; + 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)) { + 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_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref wantAgentRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "wantAgent", &wantAgentRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "wantAgent", isUndefined, wantAgentRef) + || isUndefined == ANI_TRUE || wantAgentRef == nullptr) { + ANS_LOGE("GetNotificationWantAgent: get ref failed"); deletePoint(wantAgentRef); return; } @@ -432,26 +519,28 @@ void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptr &request) { - ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref extraInfoRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef) + || isUndefined == ANI_TRUE || extraInfoRef == nullptr) { + ANS_LOGE("GetNotificationExtraInfo: get ref failed"); + deletePoint(extraInfoRef); return; } - ani_boolean isUndefind = ANI_TRUE; WantParams wantParams = {}; - if ((status = env->Reference_IsUndefined(extraInfoRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { - UnwrapWantParams(env, extraInfoRef, wantParams); - std::shared_ptr extras = std::make_shared(wantParams); - request->SetAdditionalData(extras); - } + 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_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref wantAgentRef = {}; - if ((status = env->Object_GetPropertyByName_Ref(obj, "removalWantAgent", &wantAgentRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "removalWantAgent", isUndefined, wantAgentRef) + || isUndefined == ANI_TRUE || wantAgentRef == nullptr) { + ANS_LOGE("GetNotificationRemovalWantAgent: get ref failed"); deletePoint(wantAgentRef); return; } @@ -476,49 +565,49 @@ void GetNotificationActionButtons(ani_env *env, ani_object obj, std::shared_ptr< void GetNotificationSmallIcon(ani_env *env, ani_object obj, std::shared_ptr &request) { - ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref smallIconRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "smallIcon", &smallIconRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "smallIcon", isUndefined, smallIconRef) + || isUndefined == ANI_TRUE || smallIconRef == nullptr) { + ANS_LOGE("GetNotificationSmallIcon: get ref failed"); + deletePoint(smallIconRef); return; } - ani_boolean isUndefind = ANI_TRUE; - if ((status = env->Reference_IsUndefined(smallIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { - std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(smallIconRef)); - if (pixelMap != nullptr) { - request->SetLittleIcon(pixelMap); - } + 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_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref largeIconRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "largeIcon", &largeIconRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "largeIcon", isUndefined, largeIconRef) + || isUndefined == ANI_TRUE || largeIconRef == nullptr) { + ANS_LOGE("GetNotificationLargeIcon: get ref failed"); + deletePoint(largeIconRef); return; } - ani_boolean isUndefind = ANI_TRUE; - if ((status = env->Reference_IsUndefined(largeIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { - std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(largeIconRef)); - if (pixelMap != nullptr) { - request->SetBigIcon(pixelMap); - } + 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_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; ani_ref overlayIconRef = {}; - if((status = env->Object_GetPropertyByName_Ref(obj, "overlayIcon", &overlayIconRef))!= ANI_OK) { + if (ANI_OK != GetPropertyRef(env, obj, "overlayIcon", isUndefined, overlayIconRef) + || isUndefined == ANI_TRUE || overlayIconRef == nullptr) { + ANS_LOGE("GetNotificationOverlayIcon: get ref failed"); + deletePoint(overlayIconRef); return; } - ani_boolean isUndefind = ANI_TRUE; - if ((status = env->Reference_IsUndefined(overlayIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { - std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(overlayIconRef)); - if (pixelMap != nullptr) { - request->SetOverlayIcon(pixelMap); - } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(overlayIconRef)); + if (pixelMap != nullptr) { + request->SetOverlayIcon(pixelMap); } } @@ -528,7 +617,7 @@ void GetNotificationRequestDistributedOptions(ani_env *env, ani_object obj, ani_status status = ANI_ERROR; ani_ref optionRef = {}; ani_boolean isUndefind = ANI_TRUE; - status = GetPropertyRef(env, obj, "distributedOptionRef", isUndefind, optionRef); + status = GetPropertyRef(env, obj, "distributedOption", isUndefind, optionRef); if (status == ANI_OK && isUndefind == ANI_FALSE) { StsDistributedOptions options; UnWarpDistributedOptions(env, static_cast(optionRef), options); @@ -558,11 +647,10 @@ void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, ani_status status = ANI_ERROR; ani_ref infoRef = {}; ani_boolean isUndefind = ANI_TRUE; - status = GetPropertyRef(env, obj, "template", isUndefind, infoRef); + 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) @@ -636,19 +724,21 @@ ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, 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 (request == nullptr) { + if (env == nullptr || cls == nullptr || object == nullptr || request == nullptr) { ANS_LOGE("request is nullptr"); return false; } @@ -895,18 +985,20 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not 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; } RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)); + //RETURN_FALSE_IF_FALSE(SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)); RETURN_FALSE_IF_FALSE(SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)); RETURN_FALSE_IF_FALSE(SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)); RETURN_FALSE_IF_FALSE(SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)); RETURN_FALSE_IF_FALSE(SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)); RETURN_FALSE_IF_FALSE(SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)); + ANS_LOGD("WarpNotificationRequest end"); return true; } -- Gitee From d2d83a0d0fb618974b5580da5126af8f5d335b5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Tue, 20 May 2025 11:08:59 +0800 Subject: [PATCH 17/52] =?UTF-8?q?=E8=A1=A5=E5=85=A8ets=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- .../ets/ani/src/manager/ani_manager.cpp | 6 +- .../ets/ets/@ohos.notificationManager.ets | 66 +++++++++++++++++++ .../ets/ets/@ohos.notificationSubscribe.ets | 14 ++-- 3 files changed, 78 insertions(+), 8 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 4ff2e53ab..ba8528993 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -89,9 +89,9 @@ void AniNotificationManagerRegistryInit(ani_env *env) 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 {"nativeRequestEnableNotification", + "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", + reinterpret_cast(AniRequestEnableNotification)}, }; status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 0616504f5..be33866fe 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -17,10 +17,21 @@ import { BundleOption } from 'notification.NotificationCommonDef'; import { BusinessError, AsyncCallback } from '@ohos.base'; import { NotificationSlot } from 'notification.notificationSlot'; import { NotificationRequest } from 'notification.notificationRequest'; +import UIAbilityContext from 'application.UIAbilityContext'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => 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"}; + export default namespace notificationManager { loadLibrary("notification_manager_ani.z") export enum SlotType { @@ -135,6 +146,7 @@ export default namespace notificationManager { 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; function isInvalidParameter(bundle: BundleOption): BusinessError { @@ -903,4 +915,58 @@ export default namespace notificationManager { }, (error: Object): void => { }) } + + 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: Object): 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: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + } + ) + } } \ No newline at end of file diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index eb72f0d80..b6f139162 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -21,11 +21,15 @@ import { NotificationSubscriber } from 'notification.notificationSubscriber'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; -const rejectInternalError: BusinessError = {code: 160001, data: "Internal error."}; -const callbackInternalError: BusinessError = {code: 160001, data: undefined}; -const successCallbackError: BusinessError = {code: 0, data: undefined}; -// ERROR_PARAM_INVALID = 401 -const errorParamInvalid: BusinessError = {code: 401, data: "Invalid parameter"}; +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"}; export default namespace notificationSubscribe { loadLibrary("notification_subscribe_ani.z") -- Gitee From a64e5b87844c851f94cc5e6c3e362c8a1772ed97 Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 20 May 2025 14:14:05 +0800 Subject: [PATCH 18/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_common.cpp | 59 ++++++++----- .../ets/ani/src/sts_notification_content.cpp | 12 +-- frameworks/ets/ani/src/sts_request.cpp | 83 +++++++++++-------- 3 files changed, 94 insertions(+), 60 deletions(-) diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 12165bd8f..8492de5bf 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -38,8 +38,8 @@ bool IsUndefine(ani_env *env, const ani_object &obj) ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& aniStr) { - if (env == nullptr || str.empty()) { - ANS_LOGE("GetAniStringByString fail, env is nullptr or str is empty"); + 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); @@ -416,35 +416,55 @@ bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, ani_object CreateBoolean(ani_env *env, bool value) { - if (env == nullptr) { - ANS_LOGE("CreateBoolean fail, env is nullptr"); - return nullptr; - } - ani_class boolCls; + ani_class persion_cls; ani_status status = ANI_ERROR; - if ((status = env->FindClass(CLASSNAME_BOOLEAN, &boolCls)) != ANI_OK) { + if ((status = env->FindClass(CLASSNAME_BOOLEAN, &persion_cls)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(boolCls); return nullptr; } - ani_method boolCtor; - if ((status = env->Class_FindMethod(boolCls, "", "Z:V", &boolCtor)) != ANI_OK) { + ani_method personInfoCtor; + if ((status = env->Class_FindMethod(persion_cls, "", "Z:V", &personInfoCtor)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(boolCls); return nullptr; } - ani_object boolObj; - if ((status = env->Object_New(boolCls, boolCtor, &boolObj, value ? ANI_TRUE : ANI_FALSE)) - != ANI_OK) { + 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); - deletePoint(boolCls); - deletePoint(boolObj); return nullptr; } - deletePoint(boolCls); - return boolObj; + return personInfoObj; } +// ani_object CreateBoolean(ani_env *env, bool value) +// { +// if (env == nullptr) { +// ANS_LOGE("CreateBoolean fail, env is nullptr"); +// return nullptr; +// } +// ani_class boolCls; +// ani_status status = ANI_ERROR; +// if ((status = env->FindClass(CLASSNAME_BOOLEAN, &boolCls)) != ANI_OK) { +// ANS_LOGE("status : %{public}d", status); +// deletePoint(boolCls); +// return nullptr; +// } +// ani_method boolCtor; +// if ((status = env->Class_FindMethod(boolCls, "", "Z:V", &boolCtor)) != ANI_OK) { +// ANS_LOGE("status : %{public}d", status); +// deletePoint(boolCls); +// return nullptr; +// } +// ani_object boolObj; +// if ((status = env->Object_New(boolCls, boolCtor, &boolObj, value ? ANI_TRUE : ANI_FALSE)) +// != ANI_OK) { +// ANS_LOGE("status : %{public}d", status); +// deletePoint(boolCls); +// deletePoint(boolObj); +// return nullptr; +// } +// return boolObj; +// } + ani_object CreateDouble(ani_env *env, double value) { if (env == nullptr) { @@ -471,7 +491,6 @@ ani_object CreateDouble(ani_env *env, double value) deletePoint(doubleObj); return nullptr; } - deletePoint(doubleCls); return doubleObj; } diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index ebc66d618..a47fc57ef 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -137,7 +137,7 @@ bool WarpNotificationProgress(ani_env *env, const NotificationProgress &progress RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "currentValue", progress.GetCurrentValue())); // isPercentage?: boolean; - RETURN_FALSE_IF_FALSE(CallSetter(env, progressClass, progressObject, "isPercentage", + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "isPercentage", BoolToAniBoolean(progress.GetIsPercentage()))); return true; } @@ -185,13 +185,13 @@ bool WarpNotificationTime(ani_env *env, const NotificationTime &time, bool isIni time.GetInitialTime())); } // isCountDown?: boolean; - RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isCountDown", + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isCountDown", BoolToAniBoolean(time.GetIsCountDown()))); // isPaused?: boolean; - RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isPaused", + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isPaused", BoolToAniBoolean(time.GetIsPaused()))); // isInTitle?: boolean; - RETURN_FALSE_IF_FALSE(CallSetter(env, timeClass, timeObject, "isInTitle", + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isInTitle", BoolToAniBoolean(time.GetIsInTitle()))); return true; } @@ -384,8 +384,8 @@ ani_object WarpNotificationIconButton(ani_env *env, const NotificationIconButton RETURN_NULL_IF_FALSE(GetAniStringByString(env, button.GetText(), stringValue)); RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "text", stringValue)); // hidePanel?: boolean; - RETURN_NULL_IF_FALSE(CallSetter( - env, iconButtonCls, iconButtonObject, "hidePanel", BoolToAniBoolean(button.GetHidePanel()))); + RETURN_NULL_IF_FALSE(SetOptionalFieldBoolean( + env, iconButtonCls, iconButtonObject, "hidePanel", button.GetHidePanel())); // iconResource: IconType; type IconType = Resource | image.PixelMap; std::shared_ptr icon = button.GetIconImage(); if (icon) { diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index fc170c0dc..f6a53266f 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -743,25 +743,25 @@ bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notif return false; } // isOngoing?: boolean - CallSetter(env, cls, object, "isOngoing", BoolToAniBoolean(request->IsInProgress())); + SetOptionalFieldBoolean(env, cls, object, "isOngoing", request->IsInProgress()); // isUnremovable?: boolean - CallSetter(env, cls, object, "isUnremovable", BoolToAniBoolean(request->IsUnremovable())); + SetOptionalFieldBoolean(env, cls, object, "isUnremovable", request->IsUnremovable()); // tapDismissed?: boolean - CallSetter(env, cls, object, "tapDismissed", BoolToAniBoolean(request->IsTapDismissed())); + SetOptionalFieldBoolean(env, cls, object, "tapDismissed", request->IsTapDismissed()); // colorEnabled?: boolean - CallSetter(env, cls, object, "colorEnabled", BoolToAniBoolean(request->IsColorEnabled())); + SetOptionalFieldBoolean(env, cls, object, "colorEnabled", request->IsColorEnabled()); // isAlertOnce?: boolean - CallSetter(env, cls, object, "isAlertOnce", BoolToAniBoolean(request->IsAlertOneTime())); + SetOptionalFieldBoolean(env, cls, object, "isAlertOnce", request->IsAlertOneTime()); // isStopwatch?: boolean - CallSetter(env, cls, object, "isStopwatch", BoolToAniBoolean(request->IsShowStopwatch())); + SetOptionalFieldBoolean(env, cls, object, "isStopwatch", request->IsShowStopwatch()); // isCountDown?: boolean - CallSetter(env, cls, object, "isCountDown", BoolToAniBoolean(request->IsCountdownTimer())); + SetOptionalFieldBoolean(env, cls, object, "isCountDown", request->IsCountdownTimer()); // isFloatingIcon?: boolean - CallSetter(env, cls, object, "isFloatingIcon", BoolToAniBoolean(request->IsFloatingIcon())); + SetOptionalFieldBoolean(env, cls, object, "isFloatingIcon", request->IsFloatingIcon()); // showDeliveryTime?: boolean - CallSetter(env, cls, object, "showDeliveryTime", BoolToAniBoolean(request->IsShowDeliveryTime())); + SetOptionalFieldBoolean(env, cls, object, "showDeliveryTime", request->IsShowDeliveryTime()); // updateOnly?: boolean - CallSetter(env, cls, object, "updateOnly", BoolToAniBoolean(request->IsUpdateOnly())); + SetOptionalFieldBoolean(env, cls, object, "updateOnly", request->IsUpdateOnly()); return true; } @@ -774,27 +774,27 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Not } ani_string stringValue = nullptr; // classification?: string - if (GetAniStringByString(env, request->GetClassification(), stringValue)) { + if (GetAniStringByString(env, request->GetClassification(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "classification", stringValue); } // label?: string - if (GetAniStringByString(env, request->GetLabel(), stringValue)) { + if (GetAniStringByString(env, request->GetLabel(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "label", stringValue); } // groupName?: string - if (GetAniStringByString(env, request->GetGroupName(), stringValue)) { + if (GetAniStringByString(env, request->GetGroupName(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "groupName", stringValue); } // readonly creatorBundleName?: string - if (GetAniStringByString(env, request->GetCreatorBundleName(), stringValue)) { + if (GetAniStringByString(env, request->GetCreatorBundleName(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "creatorBundleName", stringValue); } // readonly sound?: string - if (GetAniStringByString(env, request->GetSound(), stringValue)) { + if (GetAniStringByString(env, request->GetSound(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "sound", stringValue); } // readonly appInstanceKey?: string - if (GetAniStringByString(env, request->GetAppInstanceKey(), stringValue)) { + if (GetAniStringByString(env, request->GetAppInstanceKey(), stringValue) && stringValue != nullptr) { CallSetter(env, cls, object, "appInstanceKey", stringValue); } return true; @@ -812,7 +812,7 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Not // slotType?: SlotType ani_enum_item slotTypeItem {}; if(SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { - CallSetter(env, cls, object, "slotType", slotTypeItem); + CallSetter(env, cls, object, "notificationSlotType", slotTypeItem); } // deliveryTime?: number @@ -846,25 +846,19 @@ bool SetNotificationRequestByWantAgent(ani_env* env, ani_class cls, std::shared_ptr agent = request->GetWantAgent(); if (agent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "wantAgent", wantAgent)); - } else { - RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "wantAgent")); + CallSetter(env, cls, object, "wantAgent", wantAgent); } // removalWantAgent?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, removalAgent.get()); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "removalWantAgent", wantAgent)); - } else { - RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "removalWantAgent")); + CallSetter(env, cls, object, "removalWantAgent", wantAgent); } // maxScreenWantAgent?: WantAgent std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); if (maxScreenAgent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, maxScreenAgent.get()); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "maxScreenWantAgent", wantAgent)); - } else { - RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "maxScreenWantAgent")); + CallSetter(env, cls, object, "maxScreenWantAgent", wantAgent); } return true; } @@ -990,14 +984,35 @@ bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::Notificatio ANS_LOGE("notification is null"); return false; } - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)); - //RETURN_FALSE_IF_FALSE(SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)); - RETURN_FALSE_IF_FALSE(SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)); + 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; } -- Gitee From 45864c9d701aee85e040ded13f5e11cd82819f4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Tue, 20 May 2025 17:34:02 +0800 Subject: [PATCH 19/52] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20SetProperty=20?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E5=B0=81=E8=A3=85=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/include/sts_common.h | 8 ++ frameworks/ets/ani/src/sts_common.cpp | 103 ++++++++++++++++++++++++ 2 files changed, 111 insertions(+) diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 660481a23..b96b584c4 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -27,6 +27,7 @@ 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); @@ -56,6 +57,13 @@ bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, 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) diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 8492de5bf..56fdceef9 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -21,6 +21,7 @@ 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) { @@ -666,5 +667,107 @@ bool CreateDate(ani_env *env, int64_t time, ani_object &outObj) } 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 -- Gitee From 1b9785b6a62c36ac83b7402963e7413076e20680 Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 21 May 2025 11:47:49 +0800 Subject: [PATCH 20/52] modify Signed-off-by: heguokai --- .../ets/ani/src/sts_notification_content.cpp | 1042 +++++++++++------ 1 file changed, 712 insertions(+), 330 deletions(-) diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index a47fc57ef..1a85f5a42 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -28,6 +28,7 @@ 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; @@ -50,6 +51,7 @@ bool StsLiveViewStatusUtils::StsToC(const STSLiveViewStatus inType, LiveViewStat 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; @@ -72,190 +74,261 @@ bool StsLiveViewStatusUtils::CToSts(const LiveViewStatus inType, STSLiveViewStat 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); - return true; + if (!EnumConvertAniToNative(env, enumItem, stsLiveViewStatus) + || !StsLiveViewStatusUtils::StsToC(stsLiveViewStatus, liveViewStatus)) { + ANS_LOGE("LiveViewStatusEtsToC failed"); + return false; } - 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; - StsLiveViewStatusUtils::CToSts(liveViewStatus, stsLiveViewStatus); - if(EnumConvertNativeToAni(env, + if (!StsLiveViewStatusUtils::CToSts(liveViewStatus, stsLiveViewStatus) + || !EnumConvertNativeToAni(env, "Lnotification/notificationContent/#LiveViewStatus", stsLiveViewStatus, enumItem)) { - return true; + ANS_LOGE("LiveViewStatusCToEts failed"); + return false; } - 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) +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 + 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 + 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; - isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isPercentage", isUndefined, isPercentage) + 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; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationProgressInner;", progressClass, progressObject)); + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationProgressInner;", progressClass, progressObject) + || progressObject == nullptr) { + ANS_LOGE("WarpNotificationProgress: create class failed"); + return false; + } // maxValue?: number; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "maxValue", - progress.GetMaxValue())); + if (!SetPropertyOptionalByDouble(env, progressObject, "maxValue", progress.GetMaxValue())) { + ANS_LOGD("WarpNotificationProgress: set maxValue failed"); + } // currentValue?: number; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "currentValue", - progress.GetCurrentValue())); + if (!SetPropertyOptionalByDouble(env, progressObject, "currentValue",progress.GetCurrentValue())) { + ANS_LOGD("WarpNotificationProgress: set currentValue failed"); + } // isPercentage?: boolean; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "isPercentage", - BoolToAniBoolean(progress.GetIsPercentage()))); + 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; - isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, isCountDown) + 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; - isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isPaused", isUndefined, isPaused) + 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) + 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; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationTimeInner;", timeClass, timeObject)); + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationTimeInner;", timeClass, timeObject) + || timeObject == nullptr) { + ANS_LOGE("WarpNotificationTime: create class failed"); + return false; + } // initialTime?: number; if (isInitialTimeExist) { - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "initialTime", - time.GetInitialTime())); + if (!SetPropertyOptionalByDouble(env, timeObject, "initialTime", time.GetInitialTime())) { + ANS_LOGD("WarpNotificationTime: set initialTime failed"); + } } // isCountDown?: boolean; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isCountDown", - BoolToAniBoolean(time.GetIsCountDown()))); + if (!SetPropertyOptionalByBoolean(env, timeObject, "isCountDown", time.GetIsCountDown())) { + ANS_LOGD("WarpNotificationTime: set isCountDown failed"); + } // isPaused?: boolean; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isPaused", - BoolToAniBoolean(time.GetIsPaused()))); + if (!SetPropertyOptionalByBoolean(env, timeObject, "isPaused", time.GetIsPaused())) { + ANS_LOGD("WarpNotificationTime: set isPaused failed"); + } // isInTitle?: boolean; - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isInTitle", - BoolToAniBoolean(time.GetIsInTitle()))); + 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) +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) { + 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 = env->Object_GetPropertyByName_Ref(obj, "iconResource", &iconRef)) != ANI_OK) { - return status; + 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)) { + 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 = ""; - isUndefined = ANI_TRUE; - if(GetPropertyString(env, obj, "text", isUndefined, text) == ANI_OK && isUndefined == ANI_FALSE) { + 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; - isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "hidePanel", isUndefined, hidePanel) + 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), @@ -264,46 +337,72 @@ ani_status GetIconButtonArray(ani_env *env, ANS_LOGI("status : %{public}d, index: %{public}d", status, i); return status; } - NotificationIconButton button; - if(UnWarpNotificationIconButton(env, static_cast(buttonRef), button) == ANI_OK) { + 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; - if(GetPropertyStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { + // 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)) { + 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)) { + 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; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationButtonInner;", buttonClass, buttonObject)); + 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); @@ -311,7 +410,10 @@ bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLi ANS_LOGE("namesObjectArray is nullptr"); return false; } - RETURN_FALSE_IF_FALSE(CallSetter(env, buttonClass, buttonObject, "names", namesObjectArray)); + 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); @@ -319,7 +421,10 @@ bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLi ANS_LOGE("iconsObjectArray is nullptr"); return false; } - RETURN_FALSE_IF_FALSE(CallSetter(env, buttonClass, buttonObject, "icons", iconsObjectArray)); + 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); @@ -327,113 +432,177 @@ bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLi ANS_LOGE("resourceObjectArray is nullptr"); return false; } - return CallSetter(env, buttonClass, buttonObject, "iconsResource", resourceObjectArray); + 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_FALSE && iconRef != nullptr) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap != nullptr) { + capsule.SetIcon(pixelMap); + } else { + ANS_LOGD("UnWarpNotificationCapsule: get icon failed"); + } + } else { + ANS_LOGD("UnWarpNotificationCapsule: get icon ref 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) { + 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 + 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) { + 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) { + if (GetPropertyDouble(env, obj, "time", isUndefined, time) == ANI_OK && isUndefined == ANI_FALSE) { capsule.SetTime(static_cast(time)); + } else { + ANS_LOGE("UnWarpNotificationCapsule: get time failed"); } - - ani_ref iconRef = {}; - if(GetPropertyRef(env, obj, "time", isUndefined, iconRef) == ANI_OK && isUndefined == ANI_FALSE) { - std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); - if (pixelMap != nullptr) { - capsule.SetIcon(pixelMap); - } - } - - std::vector iconButtons = {}; - if (GetIconButtonArray(env, obj, "capsuleButtons", iconButtons) == ANI_OK && !(iconButtons.empty())) { - capsule.SetCapsuleButton(iconButtons); - } + 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; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationIconButtonInner;", iconButtonCls, iconButtonObject)); + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationIconButtonInner;", iconButtonCls, iconButtonObject) + || iconButtonObject == nullptr) { + ANS_LOGE("WarpNotificationIconButton: create class failed"); + return nullptr; + } // name: string - ani_string stringValue = nullptr; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, button.GetName(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "name", stringValue)); - // text?: string; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, button.GetText(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "text", stringValue)); - // hidePanel?: boolean; - RETURN_NULL_IF_FALSE(SetOptionalFieldBoolean( - env, iconButtonCls, iconButtonObject, "hidePanel", button.GetHidePanel())); + 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("CreatePixelMap failed, pixelMapObject is nullptr"); + ANS_LOGE("WarpNotificationIconButton: pixelMapObject is nullptr"); + return nullptr; + } + if (!SetPropertyByRef(env, iconButtonObject, "iconResource", pixelMapObject)) { + ANS_LOGE("WarpNotificationIconButton: set iconResource failed"); return nullptr; } - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", pixelMapObject)); } else { ani_object resourceObject = GetAniResource(env, button.GetIconResource()); if (resourceObject == nullptr) { - ANS_LOGE("SetResourceObject failed, resourceObject is nullptr"); + ANS_LOGE("WarpNotificationIconButton: resourceObject is nullptr"); + return nullptr; + } + if (!SetPropertyByRef(env, iconButtonObject, "iconResource", resourceObject)) { + ANS_LOGE("WarpNotificationIconButton: set iconResource failed"); return nullptr; } - RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", resourceObject)); } + // 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) { - if (buttons.empty()) { + 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); - RETURN_NULL_IF_NULL(item); - if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + 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; - RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationCapsuleInner;", capsuleClass, capsuleObject)); - // title?: string; - ani_string stringValue = nullptr; - if(GetAniStringByString(env, capsule.GetTitle(), stringValue)) { - CallSetter(env, capsuleClass, capsuleObject, "title", stringValue); + 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) { @@ -441,560 +610,773 @@ bool WarpNotificationCapsule(ani_env *env, const NotificationCapsule &capsule, a if (pixelMapObject == nullptr) { ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); } else { - CallSetter(env, capsuleClass, capsuleObject, "icon", pixelMapObject); + SetPropertyByRef(env, capsuleObject, "icon", pixelMapObject); } } // backgroundColor?: string; - if(GetAniStringByString(env, capsule.GetBackgroundColor(), stringValue)) { - CallSetter(env, capsuleClass, capsuleObject, "backgroundColor", stringValue); + if (!SetPropertyOptionalByString(env, capsuleObject, "backgroundColor", capsule.GetBackgroundColor())) { + ANS_LOGD("WarpNotificationCapsule: set backgroundColor failed"); } //content?: string; - if(GetAniStringByString(env, capsule.GetContent(), stringValue)) { - CallSetter(env, capsuleClass, capsuleObject, "content", stringValue); + if (!SetPropertyOptionalByString(env, capsuleObject, "content", capsule.GetContent())) { + ANS_LOGD("WarpNotificationCapsule: set content failed"); } // time?: number; - CallSetterOptional(env, capsuleClass, capsuleObject, "time", capsule.GetTime()); + 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) { - CallSetter(env, capsuleClass, capsuleObject, "capsuleButtons", buttonsObjectArray); + 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_LOGI("UnWarpNotificationBasicContent call"); + 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) { + 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; - isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, obj, "text", isUndefined, text)) != ANI_OK || isUndefined == ANI_TRUE) { + 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; - isUndefined = ANI_TRUE; - if(GetPropertyString(env, obj, "additionalText", isUndefined, additionalText) == ANI_OK + 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)) { + 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) { + 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) { + 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 + 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; - isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + 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; - isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + 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) { + 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 + 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 + 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 + 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) { + 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) { + 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 + 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; - isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + 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 = env->Object_GetPropertyByName_Ref(obj, "picture", &pictureRef)) != ANI_OK) { - return status; + 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; } -ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, - std::shared_ptr &liveViewContent) -{ - ani_status status =ANI_ERROR; - if((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { - return status; - } - - ani_ref statusRef; - if((status = env->Object_GetPropertyByName_Ref(obj, "status", &statusRef)) != ANI_OK) { - return status; - } - LiveViewStatus liveViewStatus = LiveViewStatus::LIVE_VIEW_CREATE; - if(!LiveViewStatusEtsToC(env, static_cast(statusRef), liveViewStatus)) { - return ANI_INVALID_ARGS; +void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent) { + ANS_LOGD("UnWarpNotificationLiveViewContentByOther call"); + if (env == nullptr || obj == nullptr || liveViewContent == nullptr) { + ANS_LOGE("UnWarpNotificationLiveViewContentByOther failed, has nullptr"); + return; } - liveViewContent->SetLiveViewStatus(liveViewStatus); - - ani_double versionAni = 0.0; + ani_status status =ANI_ERROR; ani_boolean isUndefined = ANI_TRUE; + ani_double versionAni = 0.0; if (GetPropertyDouble(env, obj, "version", isUndefined, versionAni) == ANI_OK && isUndefined == ANI_FALSE) { liveViewContent->SetVersion(static_cast(versionAni)); + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get version failed"); } - ani_ref extraInfoRef; - isUndefined = ANI_TRUE; - if (ANI_OK == (status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef)) - && env->Reference_IsUndefined(extraInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + if (ANI_OK == (status = GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef)) + && isUndefined == ANI_FALSE && extraInfoRef != nullptr) { AAFwk::WantParams wantParams = {}; if(UnwrapWantParams(env, extraInfoRef, wantParams)) { std::shared_ptr extraInfo = std::make_shared(wantParams); liveViewContent->SetExtraInfo(extraInfo); + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo by ref failed"); } + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo failed"); } - ani_ref pictureInfoRef; isUndefined = ANI_TRUE; - if (ANI_OK == env->Object_GetPropertyByName_Ref(obj, "pictureInfo", &pictureInfoRef) - && env->Reference_IsUndefined(pictureInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + + if (ANI_OK == GetPropertyRef(env, obj, "pictureInfo", isUndefined, pictureInfoRef) + && isUndefined == ANI_FALSE && pictureInfoRef != nullptr) { std::map>> pictureMap; if(GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { liveViewContent->SetPicture(pictureMap); + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo by ref failed"); } + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); } - bool isLocalUpdateOnly = true; - isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) + if (ANI_OK == GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) && isUndefined == ANI_FALSE) { liveViewContent->SetIsOnlyLocalUpdate(isLocalUpdateOnly); + } else { + ANS_LOGD("UnWarpNotificationLiveViewContent: get isLocalUpdateOnly failed"); } - return status; + ANS_LOGD("UnWarpNotificationLiveViewContentByOther end"); } -ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, - std::shared_ptr &localLiveViewContent) +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, localLiveViewContent)) != ANI_OK) { + if ((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { + ANS_LOGE("UnWarpNotificationLiveViewContent: 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) { + 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; } - localLiveViewContent->SetType(static_cast(typeCode)); + 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(env->Object_GetPropertyByName_Ref(obj, "capsule", &capsuleRef) == ANI_OK) { + 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(env->Object_GetPropertyByName_Ref(obj, "button", &buttonRef) == ANI_OK) { + 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) { + 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(env->Object_GetPropertyByName_Ref(obj, "time", &timeRef) == ANI_OK) { + 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(env->Object_GetPropertyByName_Ref(obj, "progress", &progressRef) == ANI_OK) { + 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(env->Object_GetPropertyByName_Ref(obj, "liveViewType", &liveViewTypeRef) == ANI_OK) { + if (GetPropertyRef(env, obj, "liveViewType", isUndefined, liveViewTypeRef) == ANI_OK + && isUndefined == ANI_FALSE && liveViewTypeRef != nullptr) { LiveViewTypes liveViewTypes = LiveViewTypes::LIVE_VIEW_ACTIVITY; if(LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { localLiveViewContent->SetLiveViewType(liveViewTypes); + } 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, ani_class contentCls, const NotificationBasicContent *basicContent, ani_object &object) + ani_env* env, const NotificationBasicContent *basicContent, ani_object &object) { - ANS_LOGD("enter"); - if (basicContent == nullptr) { - ANS_LOGE("basicContent is null"); + ANS_LOGD("SetNotificationBasicContent call"); + if (env == nullptr || basicContent == nullptr || object == nullptr) { + ANS_LOGE("SetNotificationBasicContent failed, has nullptr"); return false; } - ani_string aniStr; - if(GetAniStringByString(env, basicContent->GetTitle(), aniStr)) { - CallSetter(env, contentCls, object, "title", aniStr); + if (!SetPropertyOptionalByString(env, object, "title", basicContent->GetTitle())) { + ANS_LOGE("SetNotificationBasicContent: set title failed"); + return false; } - if(GetAniStringByString(env, basicContent->GetText(), aniStr)) { - CallSetter(env, contentCls, object, "text", aniStr); + if (!SetPropertyOptionalByString(env, object, "text", basicContent->GetText())) { + ANS_LOGE("SetNotificationBasicContent: set text failed"); + return false; } - if(GetAniStringByString(env, basicContent->GetAdditionalText(), aniStr)) { - CallSetter(env, contentCls, object, "additionalText", aniStr); + if (!SetPropertyOptionalByString(env, object, "additionalText", basicContent->GetAdditionalText())) { + ANS_LOGD("SetNotificationBasicContent: set additionalText failed"); } - ani_object lockScreenPicObj = CreateAniPixelMap(env, basicContent->GetLockScreenPicture()); - if (lockScreenPicObj != nullptr) { - CallSetter(env, contentCls, object, "lockScreenPicture", lockScreenPicObj); + 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, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationBasicContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + 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(); - RETURN_FALSE_IF_NULL(basicContent); - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, basicContent.get(), contentObj)); - return CallSetter(env, ncCls, ncObj, "normal", contentObj); + 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, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) { - ANS_LOGD("enter SetNotificationLongTextContent"); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationLongTextContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + 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("TextContent is null"); + ANS_LOGE("SetNotificationLongTextContent: get LongTextContent failed"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); - - ani_string aniStr; - if(GetAniStringByString(env, content->GetLongText(), aniStr)) { - CallSetter(env, contentCls, contentObj, "longText", aniStr); + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationLongTextContent: set BasicContent failed"); + return false; } - if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { - CallSetter(env, contentCls, contentObj, "briefText", aniStr); + if (!SetPropertyOptionalByString(env, contentObj, "longText", content->GetLongText())) { + ANS_LOGE("SetNotificationLongTextContent: set longText failed"); + return false; } - if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { - CallSetter(env, contentCls, contentObj, "expandedTitle", aniStr); + if (!SetPropertyOptionalByString(env, contentObj, "briefText", content->GetBriefText())) { + ANS_LOGE("SetNotificationLongTextContent: set briefText failed"); + return false; } - return CallSetter(env, ncCls, ncObj, "longText", contentObj); + 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, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) { - ANS_LOGD("enter SetNotificationPictureContent"); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationPictureContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + 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("content is null"); + ANS_LOGE("SetNotificationPictureContent: get PictureContent failed"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); - - ani_string aniStr; - if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { - CallSetter(env, contentCls, contentObj, "briefText", aniStr); + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationPictureContent: set BasicContent failed"); + return false; } - if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { - CallSetter(env, contentCls, contentObj, "expandedTitle", aniStr); + 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) { - CallSetter(env, contentCls, contentObj, "picture", pictureObj); + if (pictureObj == nullptr || !SetPropertyByRef(env, contentObj, "picture", pictureObj)) { + ANS_LOGD("SetNotificationPictureContent: set picture failed"); } - return CallSetter(env, ncCls, ncObj, "picture", contentObj); + return SetPropertyByRef(env, ncObj, "picture", contentObj); } bool SetNotificationMultiLineContent( - ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) { - ANS_LOGD("enter SetNotificationMultiLineContent"); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationMultiLineContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + 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("content is null"); + ANS_LOGE("SetNotificationMultiLineContent: get MultiLineContent failed"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); - - ani_string aniStr; - if(GetAniStringByString(env, content->GetBriefText(), aniStr)) { - CallSetter(env, contentCls, contentObj, "briefText", aniStr); + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationMultiLineContent: set BasicContent failed"); + return false; } - if(GetAniStringByString(env, content->GetExpandedTitle(), aniStr)) { - CallSetter(env, contentCls, contentObj, "longTitle", aniStr); + 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) { - CallSetter(env, contentCls, contentObj, "lines", allLinesObject); + if (allLinesObject == nullptr || !SetPropertyByRef(env, contentObj, "lines", allLinesObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set lines failed"); } ani_object lineWantAgentsObject = GetAniWantAgentArray(env, content->GetLineWantAgents()); - if(lineWantAgentsObject != nullptr) { - CallSetter(env, contentCls, contentObj, "lineWantAgents", lineWantAgentsObject); + if (lineWantAgentsObject == nullptr + || !SetPropertyByRef(env, contentObj, "lineWantAgents", lineWantAgentsObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set lineWantAgents failed"); } - return CallSetter(env, ncCls, ncObj, "multiLine", contentObj); + return SetPropertyByRef(env, ncObj, "multiLine", contentObj); } bool SetNotificationLocalLiveViewContent( - ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) { - ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", 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("content is null"); + ANS_LOGE("SetNotificationMultiLineContent: get LocalLiveViewContent failed"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); - - CallSetterOptional(env, contentCls, contentObj, "typeCode", content->GetType()); + 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"); + } if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { ani_object capsuleObject = nullptr; - if(WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) && capsuleObject != nullptr) { - CallSetter(env, contentCls, contentObj, "capsule", capsuleObject); + if (!WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) + || capsuleObject == nullptr || !SetPropertyByRef(env, contentObj, "capsule", capsuleObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set capsule failed"); } } if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::BUTTON)) { ani_object buttonObject = nullptr; - if(WarpNotificationLocalLiveViewButton(env, content->GetButton(), buttonObject) && buttonObject != nullptr) { - CallSetter(env, contentCls, contentObj, "button", buttonObject); + if (!WarpNotificationLocalLiveViewButton(env, content->GetButton(), buttonObject) + || buttonObject == nullptr || !SetPropertyByRef(env, contentObj, "button", buttonObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set button failed"); } } if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CARD_BUTTON)) { std::vector buttons = content->GetCardButton(); ani_object buttonsObjectArray = GetAniIconButtonArray(env, buttons); - if (buttonsObjectArray != nullptr) { - CallSetter(env, contentCls, contentObj, "cardButtons", buttonsObjectArray); + if (buttonsObjectArray == nullptr || !SetPropertyByRef(env, contentObj, "cardButtons", buttonsObjectArray)) { + ANS_LOGD("SetNotificationMultiLineContent: set cardButtons failed"); } } - ani_enum_item enumItem = nullptr; - if (LiveViewTypesCToEts(env, content->GetLiveViewType(), enumItem) && enumItem != nullptr) { - CallSetter(env, contentCls, contentObj, "liveViewType", enumItem); + if (!LiveViewTypesCToEts(env, content->GetLiveViewType(), enumItem) + || enumItem == nullptr || !SetPropertyByRef(env, contentObj, "liveViewType", enumItem)) { + ANS_LOGD("SetNotificationMultiLineContent: set liveViewType failed"); } - if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::PROGRESS)) { ani_object progressObject = nullptr; - if (WarpNotificationProgress(env, content->GetProgress(), progressObject) && progressObject != nullptr) { - CallSetter(env, contentCls, contentObj, "progress", progressObject); + if (!WarpNotificationProgress(env, content->GetProgress(), progressObject) + || progressObject == nullptr || !SetPropertyByRef(env, contentObj, "progress", progressObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set progress failed"); } } - 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) { - CallSetter(env, contentCls, contentObj, "time", timeObject); + if (!WarpNotificationTime(env, content->GetTime(), flag, timeObject) + || timeObject == nullptr || !SetPropertyByRef(env, contentObj, "time", timeObject)) { + ANS_LOGD("SetNotificationMultiLineContent: set time failed"); } } - return CallSetter(env, ncCls, ncObj, "systemLiveView", contentObj); + return SetPropertyByRef(env, ncObj, "systemLiveView", contentObj); } bool SetNotificationLiveViewContent( - ani_env* env, ani_class ncCls, std::shared_ptr nContent, ani_object &ncObj) + ani_env* env, std::shared_ptr nContent, ani_object &ncObj) { - ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationLiveViewContentInner;", contentCls, contentObj)); - RETURN_FALSE_IF_FALSE(contentCls != nullptr && contentObj != nullptr); + if (!CreateClassObjByClassName( + env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", contentCls, contentObj) + || contentObj == nullptr) { + ANS_LOGE("SetNotificationLiveViewContent: create class failed"); + return false; + } auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); if (content == nullptr) { - ANS_LOGE("content is null"); + ANS_LOGE("SetNotificationLiveViewContent: get LiveViewContent failed"); + return false; + } + if (!SetNotificationBasicContent(env, content.get(), contentObj)) { + ANS_LOGE("SetNotificationLiveViewContent: set BasicContent failed"); return false; } - RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, contentCls, content.get(), contentObj)); - ani_object lockScreenPicObj = CreateAniPixelMap(env, content->GetLockScreenPicture()); - if (lockScreenPicObj != nullptr) { - CallSetter(env, contentCls, contentObj, "lockScreenPicture", lockScreenPicObj); + 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) { - CallSetter(env, contentCls, contentObj, "status", enumItem); + 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"); } - CallSetterOptional(env, contentCls, contentObj, "version", static_cast(content->GetVersion())); std::shared_ptr extraInfoData = content->GetExtraInfo(); if (extraInfoData != nullptr) { ani_ref extraInfoObj = WrapWantParams(env, *extraInfoData); - if (extraInfoObj != nullptr) { - CallSetter(env, contentCls, contentObj, "extraInfo", extraInfoObj); + if (extraInfoObj == nullptr || !SetPropertyByRef(env, contentObj, "extraInfo", extraInfoObj)) { + ANS_LOGD("SetNotificationLiveViewContent: set extraInfo by ref failed"); } + } else { + ANS_LOGD("SetNotificationLiveViewContent: set extraInfo failed"); } ani_object pictureInfoObj = nullptr; - if (GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) && pictureInfoObj != nullptr) { - CallSetter(env, contentCls, contentObj, "pictureInfo", pictureInfoObj); + if (!GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) + || pictureInfoObj == nullptr || SetPropertyByRef(env, contentObj, "pictureInfo", pictureInfoObj)) { + ANS_LOGD("SetNotificationLiveViewContent: set pictureInfo failed"); } - return CallSetter(env, ncCls, ncObj, "liveView", contentObj); + 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; - RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationContentInner;", ncCls, ncObj)); + if (!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationContentInner;", ncCls, ncObj) + || ncObj == nullptr) { + ANS_LOGE("SetNotificationContent: create class failed"); + return false; + } // notificationContentType?: notificationManager.ContentType; ContentType contentType = ncContent->GetContentType(); ani_enum_item contentTypeItem {}; - RETURN_FALSE_IF_FALSE(ContentTypeCToEts(env, contentType, contentTypeItem)); - RETURN_FALSE_IF_FALSE(CallSetter(env, ncCls, ncObj, "notificationContentType", 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 - return SetNotificationNormalContent(env, ncCls, ncContent, ncObj); + result = SetNotificationNormalContent(env, ncContent, ncObj); + break; case ContentType::LONG_TEXT: // longText?: NotificationLongTextContent - return SetNotificationLongTextContent(env, ncCls, ncContent, ncObj); + result = SetNotificationLongTextContent(env, ncContent, ncObj); + break; case ContentType::PICTURE: // picture?: NotificationPictureContent - return SetNotificationPictureContent(env, ncCls, ncContent, ncObj); + result = SetNotificationPictureContent(env, ncContent, ncObj); + break; case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent - return SetNotificationMultiLineContent(env, ncCls, ncContent, ncObj); + result = SetNotificationMultiLineContent(env, ncContent, ncObj); + break; case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent - return SetNotificationLocalLiveViewContent(env, ncCls, ncContent, ncObj); + result = SetNotificationLocalLiveViewContent(env, ncContent, ncObj); break; case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent - return SetNotificationLiveViewContent(env, ncCls, ncContent, ncObj); + result = SetNotificationLiveViewContent(env, ncContent, ncObj); break; default: ANS_LOGE("ContentType is does not exist"); - return false; + result = false; + break; } - return true; + if (!result) { + ANS_LOGE("SetNotificationContent failed"); + } + ANS_LOGD("SetNotificationContent end"); + return result; } - } // namespace NotificationSts } // OHOS -- Gitee From 8796fa9fed168c86c15d693f11578443ae8a5315 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Wed, 21 May 2025 14:05:21 +0800 Subject: [PATCH 21/52] =?UTF-8?q?ani=20=E7=9A=84=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/src/sts_common.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 305 +++++++++++++++------- frameworks/ets/ani/src/sts_subscriber.cpp | 12 +- 3 files changed, 214 insertions(+), 105 deletions(-) diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 56fdceef9..378074abb 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -27,7 +27,7 @@ bool IsUndefine(ani_env *env, const ani_object &obj) { if (env == nullptr || obj == nullptr) { ANS_LOGE("IsUndefine fail, has nullptr"); - return false; + return true; } ani_boolean isUndefined; if (ANI_OK != env->Reference_IsUndefined(obj, &isUndefined)) { diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index f6a53266f..44b15c695 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -38,6 +38,7 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption 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) @@ -46,6 +47,7 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption } else { ANS_LOGD("UnWarpDistributedOptions: isDistributed get failed"); } + // supportDisplayDevices?: Array; std::vector supportDisplayDevices = {}; isUndefined = ANI_TRUE; if (GetPropertyStringArray(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK @@ -54,6 +56,7 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption } else { ANS_LOGD("UnWarpDistributedOptions: supportDisplayDevices get failed"); } + // supportOperateDevices?: Array; std::vector supportOperateDevices = {}; isUndefined = ANI_TRUE; if (GetPropertyStringArray(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK @@ -62,6 +65,7 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption } 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) @@ -89,37 +93,41 @@ bool WarpNotificationUnifiedGroupInfo(ani_env* env, return false; } // key?: string; - ani_string stringValue = nullptr; - if (GetAniStringByString(env, groupInfo->GetKey(), stringValue)) { - CallSetter(env, groupInfoCls, groupInfoObject, "key", stringValue); - } else { - ANS_LOGD("WarpNotificationUnifiedGroupInfo: set key failed"); - } + if (!groupInfo->GetKey().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "key", groupInfo->GetKey())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set key failed"); + return false; + } // title?: string; - if (GetAniStringByString(env, groupInfo->GetTitle(), stringValue)) { - CallSetter(env, groupInfoCls, groupInfoObject, "title", stringValue); - } else { - ANS_LOGD("WarpNotificationUnifiedGroupInfo: get title failed"); - } + if (!groupInfo->GetTitle().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "title", groupInfo->GetTitle())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set title failed"); + return false; + } // content?: string; - if (GetAniStringByString(env, groupInfo->GetContent(), stringValue)) { - CallSetter(env, groupInfoCls, groupInfoObject, "content", stringValue); - } else { - ANS_LOGD("WarpNotificationUnifiedGroupInfo: get content failed"); - } + if (!groupInfo->GetContent().empty() + && !SetPropertyOptionalByString(env, groupInfoObject, "content", groupInfo->GetContent())) { + ANS_LOGE("WarpNotificationUnifiedGroupInfo: set content failed"); + return false; + } // sceneName?: string; - if (GetAniStringByString(env, groupInfo->GetSceneName(), stringValue)) { - CallSetter(env, groupInfoCls, groupInfoObject, "sceneName", stringValue); - } else { - ANS_LOGD("WarpNotificationUnifiedGroupInfo: get sceneName failed"); - } + 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); - CallSetter(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef); - } else { - ANS_LOGD("WarpNotificationUnifiedGroupInfo: get extraInfo failed"); + 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; @@ -435,6 +443,7 @@ bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, case ContentType::CONVERSATION: break; default: + ANS_LOGD("ContentType not find. type %{public}d", static_cast(outType)); break; } return true; @@ -506,12 +515,11 @@ void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); - deletePoint(wantAgentRef); if (wantAgent == nullptr) { + ANS_LOGD("wantAgent is null"); return; } request->SetWantAgent(wantAgent); @@ -524,7 +532,6 @@ void GetNotificationExtraInfo(ani_env *env, ani_object obj, std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); - deletePoint(wantAgentRef); if (wantAgent == nullptr) { + ANS_LOGD("wantAgent is null"); return; } request->SetRemovalWantAgent(wantAgent); @@ -570,7 +576,6 @@ void GetNotificationSmallIcon(ani_env *env, ani_object obj, std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(smallIconRef)); @@ -586,7 +591,6 @@ void GetNotificationLargeIcon(ani_env *env, ani_object obj, std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(largeIconRef)); @@ -602,7 +606,6 @@ void GetNotificationOverlayIcon(ani_env *env, ani_object obj, std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(overlayIconRef)); @@ -688,6 +691,8 @@ void GetNotificationBundleOption(ani_env *env, ani_object obj, 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; @@ -743,25 +748,55 @@ bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notif return false; } // isOngoing?: boolean - SetOptionalFieldBoolean(env, cls, object, "isOngoing", request->IsInProgress()); + if (!SetPropertyOptionalByBoolean(env, object, "isOngoing", request->IsInProgress())) { + ANS_LOGE("SetNotificationRequest set 'isOngoing' faild"); + return false; + } // isUnremovable?: boolean - SetOptionalFieldBoolean(env, cls, object, "isUnremovable", request->IsUnremovable()); + if (!SetPropertyOptionalByBoolean(env, object, "isUnremovable", request->IsUnremovable())) { + ANS_LOGE("SetNotificationRequest set 'isUnremovable' faild"); + return false; + } // tapDismissed?: boolean - SetOptionalFieldBoolean(env, cls, object, "tapDismissed", request->IsTapDismissed()); + if (!SetPropertyOptionalByBoolean(env, object, "tapDismissed", request->IsTapDismissed())) { + ANS_LOGE("SetNotificationRequest set 'tapDismissed' faild"); + return false; + } // colorEnabled?: boolean - SetOptionalFieldBoolean(env, cls, object, "colorEnabled", request->IsColorEnabled()); + if (!SetPropertyOptionalByBoolean(env, object, "colorEnabled", request->IsColorEnabled())) { + ANS_LOGE("SetNotificationRequest set 'colorEnabled' faild"); + return false; + } // isAlertOnce?: boolean - SetOptionalFieldBoolean(env, cls, object, "isAlertOnce", request->IsAlertOneTime()); + if (!SetPropertyOptionalByBoolean(env, object, "isAlertOnce", request->IsAlertOneTime())) { + ANS_LOGE("SetNotificationRequest set 'isAlertOnce' faild"); + return false; + } // isStopwatch?: boolean - SetOptionalFieldBoolean(env, cls, object, "isStopwatch", request->IsShowStopwatch()); + if (!SetPropertyOptionalByBoolean(env, object, "isStopwatch", request->IsShowStopwatch())) { + ANS_LOGE("SetNotificationRequest set 'isStopwatch' faild"); + return false; + } // isCountDown?: boolean - SetOptionalFieldBoolean(env, cls, object, "isCountDown", request->IsCountdownTimer()); + if (!SetPropertyOptionalByBoolean(env, object, "isCountDown", request->IsCountdownTimer())) { + ANS_LOGE("SetNotificationRequest set 'isCountDown' faild"); + return false; + } // isFloatingIcon?: boolean - SetOptionalFieldBoolean(env, cls, object, "isFloatingIcon", request->IsFloatingIcon()); + if (!SetPropertyOptionalByBoolean(env, object, "isFloatingIcon", request->IsFloatingIcon())) { + ANS_LOGE("SetNotificationRequest set 'isFloatingIcon' faild"); + return false; + } // showDeliveryTime?: boolean - SetOptionalFieldBoolean(env, cls, object, "showDeliveryTime", request->IsShowDeliveryTime()); + if (!SetPropertyOptionalByBoolean(env, object, "showDeliveryTime", request->IsShowDeliveryTime())) { + ANS_LOGE("SetNotificationRequest set 'showDeliveryTime' faild"); + return false; + } // updateOnly?: boolean - SetOptionalFieldBoolean(env, cls, object, "updateOnly", request->IsUpdateOnly()); + if (!SetPropertyOptionalByBoolean(env, object, "updateOnly", request->IsUpdateOnly())) { + ANS_LOGE("SetNotificationRequest set 'updateOnly' faild"); + return false; + } return true; } @@ -772,30 +807,41 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Not ANS_LOGE("request is nullptr"); return false; } - ani_string stringValue = nullptr; // classification?: string - if (GetAniStringByString(env, request->GetClassification(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "classification", stringValue); + std::string value = request->GetClassification(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "classification", value)) { + ANS_LOGE("SetNotificationRequest set '' faild"); + return false; } // label?: string - if (GetAniStringByString(env, request->GetLabel(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "label", stringValue); + value = request->GetLabel(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "label", value)) { + ANS_LOGE("SetNotificationRequest set 'label' faild"); + return false; } // groupName?: string - if (GetAniStringByString(env, request->GetGroupName(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "groupName", stringValue); + value = request->GetGroupName(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "groupName", value)) { + ANS_LOGE("SetNotificationRequest set 'groupName' faild"); + return false; } // readonly creatorBundleName?: string - if (GetAniStringByString(env, request->GetCreatorBundleName(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "creatorBundleName", stringValue); + value = request->GetCreatorBundleName(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "creatorBundleName", value)) { + ANS_LOGE("SetNotificationRequest set 'creatorBundleName' faild"); + return false; } // readonly sound?: string - if (GetAniStringByString(env, request->GetSound(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "sound", stringValue); + value = request->GetSound(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "sound", value)) { + ANS_LOGE("SetNotificationRequest set 'sound' faild"); + return false; } // readonly appInstanceKey?: string - if (GetAniStringByString(env, request->GetAppInstanceKey(), stringValue) && stringValue != nullptr) { - CallSetter(env, cls, object, "appInstanceKey", stringValue); + value = request->GetAppInstanceKey(); + if (!value.empty() && !SetPropertyOptionalByString(env, object, "appInstanceKey", value)) { + ANS_LOGE("SetNotificationRequest set 'appInstanceKey' faild"); + return false; } return true; } @@ -808,7 +854,7 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Not return false; } // id?: number - CallSetterOptional(env, cls, object, "id", request->GetNotificationId()); + SetPropertyOptionalByDouble(env, object, "id", request->GetNotificationId()); // slotType?: SlotType ani_enum_item slotTypeItem {}; if(SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { @@ -816,22 +862,22 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Not } // deliveryTime?: number - CallSetterOptional(env, cls, object, "deliveryTime", request->GetDeliveryTime()); + SetPropertyOptionalByDouble(env, object, "id", request->GetDeliveryTime()); // autoDeletedTime?: number - CallSetterOptional(env, cls, object, "autoDeletedTime", request->GetAutoDeletedTime()); + SetPropertyOptionalByDouble(env, object, "autoDeletedTime", request->GetAutoDeletedTime()); // color ?: number - CallSetterOptional(env, cls, object, "color", request->GetColor()); + SetPropertyOptionalByDouble(env, object, "color", request->GetColor()); // badgeIconStyle ?: number - CallSetterOptional(env, cls, object, "badgeIconStyle", + SetPropertyOptionalByDouble(env, object, "badgeIconStyle", static_cast(request->GetBadgeIconStyle())); // readonly creatorUid?: number - CallSetterOptional(env, cls, object, "creatorUid", request->GetCreatorUid()); + SetPropertyOptionalByDouble(env, object, "creatorUid", request->GetCreatorUid()); // readonly creatorPid?: number - CallSetterOptional(env, cls, object, "creatorPid", request->GetCreatorPid()); + SetPropertyOptionalByDouble(env, object, "creatorPid", request->GetCreatorPid()); // badgeNumber?: number - CallSetterOptional(env, cls, object, "badgeNumber", request->GetBadgeNumber()); + SetPropertyOptionalByDouble(env, object, "badgeNumber", request->GetBadgeNumber()); // readonly creatorInstanceKey?: number - CallSetterOptional(env, cls, object, "creatorInstanceKey", request->GetCreatorInstanceKey()); + SetPropertyOptionalByDouble(env, object, "creatorInstanceKey", request->GetCreatorInstanceKey()); return true; } @@ -846,19 +892,40 @@ bool SetNotificationRequestByWantAgent(ani_env* env, ani_class cls, std::shared_ptr agent = request->GetWantAgent(); if (agent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); - CallSetter(env, cls, object, "wantAgent", wantAgent); + if (wantAgent == nullptr) { + ANS_LOGE("SetNotificationRequest Wrap 'wantAgent' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "wantAgent", wantAgent)) { + ANS_LOGE("SetNotificationRequest set 'wantAgent' faild"); + return false; + } } // removalWantAgent?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, removalAgent.get()); - CallSetter(env, cls, object, "removalWantAgent", wantAgent); + if (wantAgent == nullptr) { + ANS_LOGE("SetNotificationRequest Wrap 'removalWantAgent' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "removalWantAgent", wantAgent)) { + ANS_LOGE("SetNotificationRequest set 'removalWantAgent' faild"); + return false; + } } // maxScreenWantAgent?: WantAgent std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); if (maxScreenAgent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, maxScreenAgent.get()); - CallSetter(env, cls, object, "maxScreenWantAgent", wantAgent); + if (wantAgent == nullptr) { + ANS_LOGE("SetNotificationRequest Wrap 'maxScreenWantAgent' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "maxScreenWantAgent", wantAgent)) { + ANS_LOGE("SetNotificationRequest set 'maxScreenWantAgent' faild"); + return false; + } } return true; } @@ -875,10 +942,13 @@ bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const Notific if (littleIcon) { ani_object smallIconResult = CreateAniPixelMap(env, littleIcon); if (smallIconResult == nullptr) { - ANS_LOGE("CreatePixelMap failed,, smallIconResult is nullptr "); + ANS_LOGE("CreatePixelMap failed, smallIconResult is nullptr "); + return false; + } + if (!SetPropertyByRef(env, object, "smallIcon", smallIconResult)) { + ANS_LOGE("SetNotificationRequest set 'smallIcon' faild"); return false; } - CallSetter(env, cls, object, "smallIcon", smallIconResult); } // largeIcon?: image.PixelMap std::shared_ptr largeIcon = request->GetBigIcon(); @@ -888,7 +958,10 @@ bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const Notific ANS_LOGE("CreatePixelMap failed, largeIconResult is nullptr"); return false; } - CallSetter(env, cls, object, "largeIcon", largeIconResult); + if (!SetPropertyByRef(env, object, "largeIcon", largeIconResult)) { + ANS_LOGE("SetNotificationRequest set 'largeIcon' faild"); + return false; + } } // overlayIcon?: image.PixelMap std::shared_ptr overlayIcon = request->GetOverlayIcon(); @@ -898,7 +971,10 @@ bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const Notific ANS_LOGE("CreatePixelMap failed, overlayIconResult is nullptr"); return false; } - CallSetter(env, cls, object, "overlayIcon", overlayIconResult); + if (!SetPropertyByRef(env, object, "overlayIcon", overlayIconResult)) { + ANS_LOGE("SetNotificationRequest set 'overlayIcon' faild"); + return false; + } } return true; } @@ -910,12 +986,20 @@ bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, ANS_LOGE("request is nullptr"); return false; } - std::shared_ptr content = request->GetContent(); ani_object contentObj; - RETURN_FALSE_IF_FALSE(SetNotificationContent(env, content, contentObj)); - RETURN_FALSE_IF_FALSE(contentObj == nullptr); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "content", contentObj)); + if (!SetNotificationContent(env, content, contentObj)) { + ANS_LOGE("SetNotificationContent faild"); + return false; + } + if (contentObj == nullptr) { + ANS_LOGE("contentObj is nullptr"); + return false; + } + if (!SetPropertyByRef(env, object, "content", contentObj)) { + ANS_LOGE("SetNotificationRequestByNotificationContent. set content faild"); + return false; + } return true; } @@ -927,50 +1011,76 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not return false; } // content: NotificationContent - RETURN_FALSE_IF_FALSE(SetNotificationRequestByNotificationContent(env, cls, request, object)); + if (!SetNotificationRequestByNotificationContent(env, cls, request, object)) { + ANS_LOGE("SetNotificationRequestByCustom: set content failed"); + return false; + } // extraInfo?: {[key:string] : any} std::shared_ptr additionalData = request->GetAdditionalData(); if (additionalData) { ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "extraInfo", extraInfo)); + if (extraInfo == nullptr || !SetPropertyByRef(env, object, "extraInfo", extraInfo)) { + ANS_LOGE("SetNotificationRequestByCustom: set extraInfo failed"); + return false; + } } - // actionButtons?: Array std::vector> actionButtons = request->GetActionButtons(); ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); - if (actionButtonsArrayObj != nullptr) { - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "actionButtons", actionButtonsArrayObj)); + if (actionButtonsArrayObj != nullptr && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { + ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); + return false; } // template?: NotificationTemplate std::shared_ptr templ = request->GetTemplate(); if (templ) { ani_object templateObject = WrapNotificationTemplate(env, templ); - if (templateObject != nullptr) { - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "template", templateObject)); + if (templateObject == nullptr) { + ANS_LOGE("SetNotificationRequest Warp 'template' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "template", templateObject)) { + ANS_LOGE("SetNotificationRequest set 'template' faild"); + return false; } } // readonly notificationFlags?: NotificationFlags std::shared_ptr flags = request->GetFlags(); if (flags) { ani_object flagsObject = nullptr; - if (WarpNotificationFlags(env, flags, flagsObject) && flagsObject != nullptr) { - CallSetter(env, cls, object, "notificationFlags", flagsObject); + 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; } } // readonly agentBundle?: agentBundle std::shared_ptr agentBundle = request->GetAgentBundle(); if (agentBundle) { ani_object agentBundleObject = nullptr; - if (WrapBundleOption(env, agentBundle, agentBundleObject) && agentBundleObject != nullptr) { - CallSetter(env, cls, object, "agentBundle", agentBundleObject); + 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; } } // unifiedGroupInfo?: unifiedGroupInfo std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); if (groupInfo) { ani_object infoObject = nullptr; - if(WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) && infoObject != nullptr) { - CallSetter(env, cls, object, "unifiedGroupInfo", infoObject); + if(!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { + ANS_LOGE("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "unifiedGroupInfo", infoObject)) { + ANS_LOGE("SetNotificationRequest set 'unifiedGroupInfo' faild"); + return false; } } return true; @@ -1032,11 +1142,14 @@ ani_object GetAniNotificationRequestArray(ani_env *env, std::vectorObject_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; @@ -1057,10 +1170,14 @@ ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vect for (auto &request : requests) { ani_class requestCls; ani_object requestObj; - RETURN_NULL_IF_FALSE(WarpNotificationRequest( - env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)); - RETURN_NULL_IF_NULL(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 ++; diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index 2b8b2cbe7..4e3313c5a 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -44,25 +44,17 @@ bool WarpSubscribeCallbackData( } // request: NotificationRequest - // TODO - // Warp NotificationRequest ani_object requestObj; ani_class requestCls; if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)) { + ANS_LOGE("WarpNotificationRequest faild"); return false; } if (requestObj == nullptr) { - ANS_LOGD("WarpNotificationRequest faild"); + ANS_LOGE("requestObj is nullptr"); return false; } - // for test - // if (!CreateClassObjByClassName( - // env, "Lnotification/notificationRequest/NotificationRequestInner;", requestCls, requestObj)) { - // ANS_LOGD("create NotificationRequest faild."); - // return false; - // } - if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "request", requestObj))) { ANS_LOGD("set request faild. status %{public}d", status); return false; -- Gitee From e9a459b3b30b424b1935ed733b55e939e7f3405c Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 21 May 2025 14:44:25 +0800 Subject: [PATCH 22/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_action_button.cpp | 34 ------- frameworks/ets/ani/src/sts_bundle_option.cpp | 9 -- frameworks/ets/ani/src/sts_common.cpp | 96 -------------------- frameworks/ets/ani/src/sts_convert_other.cpp | 63 +------------ 4 files changed, 1 insertion(+), 201 deletions(-) diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index 0ed3541c2..21e78f01e 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -45,11 +45,9 @@ ani_status GetStsActionButtonByWantAgent(ani_env *env, ani_object param, ani_ref wantAgentRef; if (ANI_OK != GetPropertyRef(env, param, "wantAgent", isUndefind, wantAgentRef) || isUndefind == ANI_TRUE) { ANS_LOGE("GetStsActionButtonByWantAgent: GetPropertyRef wantAgent failed"); - deletePoint(wantAgentRef); return ANI_INVALID_ARGS; } std::shared_ptr wantAgent = UnwrapWantAgent(env, static_cast(wantAgentRef)); - deletePoint(wantAgentRef); if (wantAgent == nullptr) { ANS_LOGE("GetStsActionButtonByWantAgent: wantAgent is nullptr"); return ANI_INVALID_ARGS; @@ -74,7 +72,6 @@ ani_status GetStsActionButtonByWantParams(ani_env *env, ani_object param, UnwrapWantParams(env, extrasRef, wantParams); } else { ANS_LOGE("GetStsActionButtonByWantParams: GetPropertyRef extras failed"); - deletePoint(extrasRef); return ANI_INVALID_ARGS; } std::shared_ptr extras = std::make_shared(wantParams); @@ -150,12 +147,10 @@ bool SetNotificationActionButtonByRequiredParameter( ani_string stringValue; // title: string; if (!GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { - deletePoint(stringValue); ANS_LOGE("SetActionButtonByRequiredParameter: Get title failed"); return false; } if (!CallSetter(env, iconButtonCls, iconButtonObject, "title", stringValue)) { - deletePoint(stringValue); ANS_LOGE("SetActionButtonByRequiredParameter: Set title failed"); return false; } @@ -163,20 +158,15 @@ bool SetNotificationActionButtonByRequiredParameter( std::shared_ptr agent = actionButton->GetWantAgent(); if (agent == nullptr) { ANS_LOGE("SetActionButtonByRequiredParameter:agent is null"); - deletePoint(stringValue); return false; } else { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); if (wantAgent == nullptr) { ANS_LOGE("SetActionButtonByRequiredParameter: wantAgent is nullptr"); - deletePoint(stringValue); - deletePoint(wantAgent); return false; } if (!CallSetter(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)) { ANS_LOGE("SetActionButtonByRequiredParameter: Set wantAgent failed"); - deletePoint(stringValue); - deletePoint(wantAgent); return false; } } @@ -199,25 +189,15 @@ void SetNotificationActionButtonByOptionalParameter( ani_ref extras = WrapWantParams(env, *(actionButton->GetAdditionalData().get())); if (!CallSetter(env, iconButtonCls, iconButtonObject, "extras", extras)) { ANS_LOGD("SetActionButtonByOptionalParameter : Set extras failed"); - deletePoint(extras); } // userInput?: NotificationUserInput ani_object userInputObject = WarpUserInput(env, actionButton->GetUserInput()); if (!CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)) { ANS_LOGD("SetActionButtonByOptionalParameter : Set userInput failed"); - deletePoint(userInputObject); } ANS_LOGD("SetActionButtonByOptionalParameter end"); } -void deletePointOfWrapNotificationActionButton( - ani_object iconButtonObject, ani_class iconButtonCls, ani_string stringValue) { - ANS_LOGD("deletePointOfWrapNotificationActionButton call"); - deletePoint(iconButtonObject); - deletePoint(iconButtonCls); - deletePoint(stringValue); -} - ani_object WrapNotificationActionButton(ani_env* env, const std::shared_ptr &actionButton) { @@ -228,16 +208,13 @@ ani_object WrapNotificationActionButton(ani_env* env, } ani_object iconButtonObject = nullptr; ani_class iconButtonCls = nullptr; - ani_string stringValue = nullptr; if (!CreateClassObjByClassName(env, "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)) { ANS_LOGE("WrapNotificationActionButton : CreateClassObjByClassName failed"); - deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); return nullptr; } if (!SetNotificationActionButtonByRequiredParameter(env, iconButtonCls, iconButtonObject, actionButton)) { ANS_LOGE("WrapNotificationActionButton : SetRequiredParameter failed"); - deletePointOfWrapNotificationActionButton(iconButtonObject, iconButtonCls, stringValue); return nullptr; } SetNotificationActionButtonByOptionalParameter(env, iconButtonCls, iconButtonObject, actionButton); @@ -260,20 +237,16 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, 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); - deletePoint(arrayObj); 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); - deletePoint(arrayObj); return status; } for (int dex = 0; dex < static_cast(length); dex++) { ani_ref buttonRef; if (ANI_OK != (status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)dex))) { - deletePoint(arrayObj); - deletePoint(buttonRef); ANS_LOGE("GetActionButtonArray: get ref failed, status = %{public}d, index = %{public}d", status, dex); return status; } @@ -281,8 +254,6 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, != (status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton))) { ANS_LOGE("GetActionButtonArray: UnwrapActionButton failed, status = %{public}d, index = %{public}d", status, dex); - deletePoint(arrayObj); - deletePoint(buttonRef); return status; } std::shared_ptr button @@ -307,7 +278,6 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, ani_object arrayObj = newArrayClass(env, actionButtons.size()); if (arrayObj == nullptr) { ANS_LOGE("GetAniArrayActionButton: arrayObj is nullptr"); - deletePoint(arrayObj); return nullptr; } ani_size index = 0; @@ -315,14 +285,10 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, ani_object item = WrapNotificationActionButton(env, button); if (item == nullptr) { ANS_LOGE("GetAniArrayActionButton: item is nullptr"); - deletePoint(arrayObj); - deletePoint(item); return nullptr; } if (ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { ANS_LOGE("GetAniArrayActionButton: Object_CallMethodByName_Void failed"); - deletePoint(arrayObj); - deletePoint(item); return nullptr; } index ++; diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index ad141e948..cc25b1732 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -65,16 +65,13 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector(optionRef), option)) { ANS_LOGE("UnwrapArrayBundleOption: get option status = %{public}d, index = %{public}d", status, dex); - deletePoint(optionRef); return false; } options.push_back(option); - deletePoint(optionRef); } ANS_LOGD("UnwrapArrayBundleOption end"); return true; @@ -93,8 +90,6 @@ bool WrapBundleOption(ani_env* env, "Lnotification/NotificationCommonDef/BundleOptionInner;", bundleCls, bundleObject) || bundleCls == nullptr || bundleObject == nullptr) { ANS_LOGE("WrapBundleOption: create BundleOption failed"); - deletePoint(bundleCls); - deletePoint(bundleObject); return false; } // bundle: string; @@ -102,15 +97,11 @@ bool WrapBundleOption(ani_env* env, if (!GetAniStringByString(env, bundleOption->GetBundleName(), stringValue) || !CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { ANS_LOGE("WrapBundleOption: set bundle failed"); - deletePoint(bundleCls); - deletePoint(bundleObject); - deletePoint(stringValue); return false; } // uid?: number; uint32_t uid = bundleOption->GetUid(); CallSetterOptional(env, bundleCls, bundleObject, "uid", uid); - deletePoint(bundleCls); ANS_LOGD("WrapBundleOption end"); return true; } diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 378074abb..52d10f01d 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -46,7 +46,6 @@ ani_status GetAniStringByString(ani_env* env, const std::string str, ani_string& ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); if (status != ANI_OK) { ANS_LOGE("String_NewUTF8 failed %{public}d", status); - deletePoint(aniStr); return status; } return status; @@ -91,13 +90,11 @@ bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector< "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(stringEntryRef); return false; } std::string std_string; if (!GetStringByAniString(env, static_cast(stringEntryRef), std_string)) { ANS_LOGE("GetStdString faild"); - deletePoint(stringEntryRef); return false; } stdVString.emplace_back(std_string); @@ -117,23 +114,19 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, 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); - deletePoint(strRef); 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); - deletePoint(strRef); return status; } if(isUndefined == ANI_TRUE) { ANS_LOGE("%{public}s is undefined", name); - deletePoint(strRef); return status; } if ((status = GetStringByAniString(env, reinterpret_cast(strRef), outStr)) != ANI_OK) { ANS_LOGE("GetStdString failed"); - deletePoint(strRef); return status; } return status; @@ -153,24 +146,20 @@ ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, status = env->Object_GetPropertyByName_Ref(obj, name, &refObj); if (ANI_OK != status) { ANS_LOGE("Object_GetPropertyByName_Ref fail, status: %{public}d", status); - deletePoint(refObj); return status; } if ((status = env->Reference_IsUndefined(refObj, &isUndefined)) != ANI_OK) { ANS_LOGE("Reference_IsUndefined failed, status : %{public}d", status); - deletePoint(refObj); return status; } if (isUndefined) { ANS_LOGE("%{public}s is undefined", name); - deletePoint(refObj); 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); - deletePoint(refObj); return status; } outvalue = (result == ANI_TRUE); @@ -190,13 +179,11 @@ ani_status GetPropertyDouble(ani_env *env, ani_object obj, const char *name, status = GetPropertyRef(env, obj, name, isUndefined, refObj); if (status != ANI_OK || isUndefined == ANI_TRUE) { ANS_LOGE("%{public}s is undefined", name); - deletePoint(refObj); 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); - deletePoint(refObj); return status; } ANS_LOGD("Object_CallMethodByName_Double sucess, status: %{public}f", outvalue); @@ -241,13 +228,11 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na 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); - deletePoint(arrayObj); return ANI_INVALID_ARGS; } status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(arrayObj); return status; } std::string str = ""; @@ -257,15 +242,11 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGE("status : %{public}d, index: %{public}d", status, i); - deletePoint(arrayObj); - deletePoint(stringEntryRef); return status; } status = GetStringByAniString(env, static_cast(stringEntryRef), str); if (status != ANI_OK) { ANS_LOGE("GetStdString failed, index: %{public}d", i); - deletePoint(arrayObj); - deletePoint(stringEntryRef); return status; } res.push_back(str); @@ -283,28 +264,21 @@ ani_object GetAniStringArrayByVectorString(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, aniStr); if (status != ANI_OK) { ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); - deletePoint(arrayObj); - deletePoint(aniStr); return nullptr; } i++; @@ -325,33 +299,26 @@ bool SetFieldString(ani_env *env, ani_class cls, ani_object &object, ANS_LOGD("SetFieldString fieldName : %{public}s", fieldName.c_str()); if (status != ANI_OK || field == nullptr) { ANS_LOGE("SetFieldString status : %{public}d", status); - deletePoint(string); 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); - deletePoint(string); - deletePoint(nullRef); return false; } if ((status = env->Object_SetField_Ref(object, field, nullRef)) != ANI_OK) { ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); - deletePoint(string); - deletePoint(nullRef); 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); - deletePoint(string); return false; } if ((status = env->Object_SetField_Ref(object, field, string)) != ANI_OK) { ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); - deletePoint(string); return false; } return true; @@ -373,14 +340,12 @@ bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object &object, } ani_object boolObj = CreateBoolean(env, BoolToAniBoolean(value)); if (boolObj == nullptr) { - deletePoint(boolObj); 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()); - deletePoint(boolObj); return false; } return true; @@ -402,14 +367,12 @@ bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object &object, } ani_object doubleObj = CreateDouble(env, value); if (doubleObj == nullptr) { - deletePoint(doubleObj); 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()); - deletePoint(doubleObj); return false; } return true; @@ -435,37 +398,6 @@ ani_object CreateBoolean(ani_env *env, bool value) } return personInfoObj; } - -// ani_object CreateBoolean(ani_env *env, bool value) -// { -// if (env == nullptr) { -// ANS_LOGE("CreateBoolean fail, env is nullptr"); -// return nullptr; -// } -// ani_class boolCls; -// ani_status status = ANI_ERROR; -// if ((status = env->FindClass(CLASSNAME_BOOLEAN, &boolCls)) != ANI_OK) { -// ANS_LOGE("status : %{public}d", status); -// deletePoint(boolCls); -// return nullptr; -// } -// ani_method boolCtor; -// if ((status = env->Class_FindMethod(boolCls, "", "Z:V", &boolCtor)) != ANI_OK) { -// ANS_LOGE("status : %{public}d", status); -// deletePoint(boolCls); -// return nullptr; -// } -// ani_object boolObj; -// if ((status = env->Object_New(boolCls, boolCtor, &boolObj, value ? ANI_TRUE : ANI_FALSE)) -// != ANI_OK) { -// ANS_LOGE("status : %{public}d", status); -// deletePoint(boolCls); -// deletePoint(boolObj); -// return nullptr; -// } -// return boolObj; -// } - ani_object CreateDouble(ani_env *env, double value) { if (env == nullptr) { @@ -476,20 +408,16 @@ ani_object CreateDouble(ani_env *env, double value) ani_status status = ANI_ERROR; if ((status = env->FindClass(CLASSNAME_DOUBLE, &doubleCls)) != ANI_OK) { ANS_LOGE( "status : %{public}d", status); - deletePoint(doubleCls); return nullptr; } ani_method doubleCtor; if ((status = env->Class_FindMethod(doubleCls, "", "D:V", &doubleCtor)) != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(doubleCls); return nullptr; } ani_object doubleObj; if ((status = env->Object_New(doubleCls, doubleCtor, &doubleObj, static_cast(value))) != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(doubleCls); - deletePoint(doubleObj); return nullptr; } return doubleObj; @@ -505,20 +433,16 @@ ani_object newArrayClass(ani_env *env, int length) ani_class arrayCls = nullptr; if (ANI_OK != env->FindClass("Lescompat/Array;", &arrayCls)){ ANS_LOGE("FindClass Lescompat/Array; Failed"); - deletePoint(arrayCls); return nullptr; } ani_method arrayCtor; if (ANI_OK != env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor)){ ANS_LOGE("Class_FindMethod Failed"); - deletePoint(arrayCls); return nullptr; } ani_object arrayObj = nullptr; if (ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)){ ANS_LOGE("Object_New Array Faild"); - deletePoint(arrayCls); - deletePoint(arrayObj); return nullptr; } ANS_LOGD("newArrayClass end"); @@ -536,20 +460,16 @@ ani_object newRecordClass(ani_env *env) ani_class recordCls; if (ANI_OK != (status = env->FindClass("Lescompat/Record;", &recordCls))) { ANS_LOGE("newRecordClass fail, FindClass status = %{public}d", status); - deletePoint(recordCls); 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); - deletePoint(recordCls); 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); - deletePoint(recordCls); - deletePoint(recordObj); return nullptr; } ANS_LOGD("newRecordClass end"); @@ -564,22 +484,17 @@ ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector(values[i])); if (intObj == nullptr) { ANS_LOGE("null intObj"); - deletePoint(arrayObj); - deletePoint(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); - deletePoint(arrayObj); - deletePoint(intObj); return nullptr; } } @@ -602,13 +517,11 @@ bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, ani_object arrayObj = ConvertArrayDoubleToAniObj(env, values); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is nullptr."); - deletePoint(arrayObj); return false; } status = env->Object_SetField_Ref(object, field, arrayObj); if (status != ANI_OK) { ANS_LOGE("status : %{public}d", status); - deletePoint(arrayObj); return false; } return true; @@ -621,8 +534,6 @@ bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &c return false; } if (ANI_OK != env->FindClass(className, &cls)) { - deletePoint(cls); - deletePoint(outAniObj); return false; } ani_method ctor; @@ -642,27 +553,20 @@ bool CreateDate(ani_env *env, int64_t time, ani_object &outObj) 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); - deletePoint(cls); 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); - deletePoint(cls); return false; } ani_object timeObj = CreateDouble(env, static_cast(time)); if (timeObj == nullptr) { ANS_LOGD("createDouble faild"); - deletePoint(cls); - deletePoint(timeObj); return false; } if (ANI_OK != (status = env->Object_New(cls, ctor, &outObj, timeObj))) { ANS_LOGD("Object_New faild. status %{public}d", status); - deletePoint(cls); - deletePoint(timeObj); - deletePoint(outObj); return false; } return true; diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index f9854a1ca..00aa22968 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -130,14 +130,12 @@ ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector pixelMap = GetPixelMapFromEnvSp(env, static_cast(pixelMapRef)); if (pixelMap == nullptr) { ANS_LOGE("GetPixelMapArrayByRef: GetPixelMapFromEnvSp failed."); - deletePoint(pixelMapRef); pixelMaps.clear(); return ANI_INVALID_ARGS; } @@ -159,12 +157,10 @@ ani_status GetPixelMapArray(ani_env *env, ani_boolean isUndefined = ANI_TRUE; ani_status status = ANI_ERROR; if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { - deletePoint(arrayObj); return ANI_INVALID_ARGS; } if ((status = GetPixelMapArrayByRef(env, arrayObj, pixelMaps)) != ANI_OK) { - deletePoint(arrayObj); pixelMaps.clear(); return status; } @@ -185,14 +181,12 @@ ani_status GetResourceArray(ani_env *env, ani_status status; ani_double length; if ((status = GetPropertyRef(env, param, name, isUndefined, arrayObj)) != ANI_OK || isUndefined == ANI_TRUE) { - deletePoint(arrayObj); 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); - deletePoint(arrayObj); return status; } for (int i = 0; i < static_cast(length); i++) { @@ -200,8 +194,6 @@ ani_status GetResourceArray(ani_env *env, status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &iconRef, (ani_int)i); if (status != ANI_OK) { - deletePoint(arrayObj); - deletePoint(iconRef); res.clear(); ANS_LOGE("GetResourceArray: status = %{public}d, index = %{public}d", status, i); return status; @@ -209,8 +201,6 @@ ani_status GetResourceArray(ani_env *env, ResourceManager::Resource resource; if(ANI_OK != UnwrapResource(env, static_cast(iconRef), resource)) { ANS_LOGE("GetResourceArray : status = %{public}d, index= %{public}d", status, i); - deletePoint(arrayObj); - deletePoint(iconRef); res.clear(); return status; } @@ -233,7 +223,6 @@ ani_status GetKeyString(ani_env *env, ani_object obj, int index, ani_string &str "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)index); if (status != ANI_OK) { ANS_LOGE("status : %{public}d, index: %{public}d", status, index); - deletePoint(stringEntryRef); return status; } str = static_cast(stringEntryRef); @@ -254,14 +243,12 @@ ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vectorObject_CallMethodByName_Ref(obj, "$_get", nullptr, &picturesArrayRef, anikey))) { ANS_LOGE("GetPixelMapByKeys : Object_CallMethodByName_Ref failed"); - deletePoint(picturesArrayRef); deleteVectorWithArraySpPoints(pictureMap); return status; } std::vector> pixelMaps = {}; if((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { ANS_LOGE("GetPixelMapByKeys : GetPixelMapArrayByRef failed"); - deletePoint(picturesArrayRef); deleteVectorWithSpPoints(pixelMaps); deleteVectorWithArraySpPoints(pictureMap); return status; @@ -269,7 +256,6 @@ ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vector(length); i++) { if((status = GetKeyString(env, static_cast(keysStrArrayRef), i, strAni)) != ANI_OK) { ANS_LOGE("GetPixelMapByRef : GetKeyString status = %{public}d", status); - deletePoint(strAni); - deleteVectorWithPoints(keys); + keys.clear(); return status; } keys.push_back(strAni); @@ -328,31 +313,23 @@ ani_status GetMapOfPictureInfo(ani_env *env, ani_object obj, } if (cls == nullptr) { ANS_LOGE("GetMapOfPictureInfo : cls is nullptr"); - deletePoint(cls); return ANI_INVALID_TYPE; } ani_static_method keysMethod = nullptr; if (ANI_OK != (status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod))) { - deletePoint(cls); 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))) { - deletePoint(cls); - deletePoint(keysStrArrayRef); ANS_LOGE("GetMapOfPictureInfo : Class_CallStaticMethod_Ref status = %{public}d", status); return status; } if (IsUndefine(env, static_cast(keysStrArrayRef))) { - deletePoint(cls); - deletePoint(keysStrArrayRef); ANS_LOGE("GetMapOfPictureInfo : keysStrArrayRef IsUndefined"); return ANI_INVALID_ARGS; } if (ANI_OK != (status = GetPixelMapByRef(env, obj, keysStrArrayRef, pictureMap))) { - deletePoint(cls); - deletePoint(keysStrArrayRef); deleteVectorWithArraySpPoints(pictureMap); ANS_LOGE("GetMapOfPictureInfo : GetPixelMapByRef status = %{public}d", status); } @@ -373,33 +350,22 @@ ani_object GetAniResource(ani_env *env, const std::shared_ptrbundleName, stringValue)) || !CallSetter(env, resourceCls, resourceObject, "bundleName", stringValue)) { ANS_LOGE("GetAniResource : set bundleName failed, status = %{public}d", status); - deletePoint(resourceCls); - deletePoint(resourceObject); - deletePoint(stringValue); 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); - deletePoint(resourceCls); - deletePoint(resourceObject); - deletePoint(stringValue); return nullptr; } if (!CallSetter(env, resourceCls, resourceObject, "id", resource->id)) { ANS_LOGE("GetAniResource : set moduleName failed, status = %{public}d", status); - deletePoint(resourceObject); } - deletePoint(resourceCls); - deletePoint(stringValue); ANS_LOGD("GetAniResource end"); return resourceObject; } @@ -415,7 +381,6 @@ ani_object GetAniArrayPixelMap(ani_env *env, const std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, pixelMapObject); if (status != ANI_OK) { - deletePoint(pixelMapObject); - deletePoint(arrayObj); ANS_LOGE("GetAniArrayPixelMap : Object_CallMethodByName_Void failed %{public}d", status); return nullptr; } @@ -453,7 +414,6 @@ ani_object GetAniArrayResource(ani_env *env, ani_object arrayObj = newArrayClass(env, length); if (arrayObj == nullptr) { ANS_LOGE("GetAniArrayResource : arrayObj is nullPtr"); - deletePoint(arrayObj); return nullptr; } ani_size i = 0; @@ -461,16 +421,12 @@ ani_object GetAniArrayResource(ani_env *env, ani_object resourceObject = GetAniResource(env, resource); if (resourceObject == nullptr) { ANS_LOGE("GetAniArrayResource : resourceObject is nullPtr"); - deletePoint(resourceObject); - deletePoint(arrayObj); 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); - deletePoint(resourceObject); - deletePoint(arrayObj); return nullptr; } i++; @@ -490,31 +446,22 @@ bool GetAniPictrueInfo(ani_env *env, std::mapObject_CallMethodByName_Void(pictureInfoObj, "$_set", "Lstd/core/Object;Lstd/core/Object;:V", aniKey, aniPictrueArray)) { ANS_LOGE("GetAniPictrueInfo : Object_CallMethodByName_Void failed"); - deletePoint(aniKey); - deletePoint(aniPictrueArray); - deletePoint(pictureInfoObj); return false; } } @@ -532,7 +479,6 @@ ani_object WarpWantAgent(ani_env *env, std::shared_ptr wantAgent) ani_object wantAgentObj = AppExecFwk::WrapWantAgent(env, wantAgent.get()); if (wantAgentObj == nullptr) { ANS_LOGE("WarpWantAgent : wantAgentObj is nullptr"); - deletePoint(wantAgentObj); } ANS_LOGD("WarpWantAgent end"); return wantAgentObj; @@ -549,20 +495,16 @@ ani_object GetAniWantAgentArray(ani_env *env, std::vectorFindClass("Lescompat/Array;", &arrayCls))) { ANS_LOGE("GetAniWantAgentArray : FindClass status = %{public}d", status); - deletePoint(arrayCls); 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); - deletePoint(arrayCls); 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); - deletePoint(arrayCls); - deletePoint(arrayObj); return nullptr; } ani_size index = 0; @@ -571,9 +513,6 @@ ani_object GetAniWantAgentArray(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { ANS_LOGE("GetAniWantAgentArray : set WantAgent failed"); - deletePoint(arrayCls); - deletePoint(arrayObj); - deletePoint(item); return nullptr; } index ++; -- Gitee From 7850ce85d46c9f9e0bbacfa0bc1214ec81be1fd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Wed, 21 May 2025 17:23:09 +0800 Subject: [PATCH 23/52] =?UTF-8?q?=E4=B8=80=E9=83=A8=E5=88=86=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/src/manager/ani_request_enable.cpp | 10 ++++------ frameworks/ets/ani/src/sts_common.cpp | 6 ++---- frameworks/ets/ani/src/sts_request.cpp | 10 ++++++---- frameworks/ets/ani/src/sts_sorting_map.cpp | 3 ++- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_request_enable.cpp b/frameworks/ets/ani/src/manager/ani_request_enable.cpp index ec42defc3..8cb183d83 100755 --- a/frameworks/ets/ani/src/manager/ani_request_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_request_enable.cpp @@ -28,6 +28,10 @@ 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); @@ -187,12 +191,6 @@ void RequestEnableComplete(ani_env *env, std::shared_ptr ani_object AniRequestEnableNotification(ani_env *env, ani_object content) { ANS_LOGD("enter"); - if (content == nullptr) { - ANS_LOGD("content is nullptr"); - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, - OHOS::NotificationSts::FindAnsErrMsg(ERROR_PARAM_INVALID)); - return nullptr; - } std::shared_ptr info = std::make_shared(); if (!GetEnableNotificationInfo(env, content, info)) { ANS_LOGD("GetEnableNotificationInfo"); diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 52d10f01d..711870cec 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -269,10 +269,8 @@ ani_object GetAniStringArrayByVectorString(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 44b15c695..6b461dace 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -1026,10 +1026,12 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not } // actionButtons?: Array std::vector> actionButtons = request->GetActionButtons(); - ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); - if (actionButtonsArrayObj != nullptr && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { - ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); - return false; + if (!actionButtons.empty()) { + ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); + if (actionButtonsArrayObj != nullptr && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { + ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); + return false; + } } // template?: NotificationTemplate std::shared_ptr templ = request->GetTemplate(); diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp index 23136d821..3b8017ecc 100644 --- a/frameworks/ets/ani/src/sts_sorting_map.cpp +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -31,7 +31,8 @@ bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptr Date: Wed, 21 May 2025 19:22:47 +0800 Subject: [PATCH 24/52] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- .../ets/ani/include/manager/ani_cance.h | 7 +- frameworks/ets/ani/include/sts_sorting.h | 2 +- frameworks/ets/ani/src/manager/ani_cance.cpp | 47 +++++++++--- .../ets/ani/src/manager/ani_manager.cpp | 1 + .../ets/ani/src/sts_notification_flag.cpp | 38 +++++++--- frameworks/ets/ani/src/sts_sorting.cpp | 19 ++--- frameworks/ets/ani/src/sts_sorting_map.cpp | 32 ++++---- frameworks/ets/ani/src/sts_subscribe.cpp | 6 -- frameworks/ets/ani/src/sts_subscribe_info.cpp | 13 +++- frameworks/ets/ani/src/sts_subscriber.cpp | 75 ++++++++++--------- frameworks/ets/ani/src/sts_template.cpp | 39 ++++++++-- frameworks/ets/ani/src/sts_user_input.cpp | 31 ++++++-- 12 files changed, 199 insertions(+), 111 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_cance.h b/frameworks/ets/ani/include/manager/ani_cance.h index 0ba94d339..5e3f19fd6 100644 --- a/frameworks/ets/ani/include/manager/ani_cance.h +++ b/frameworks/ets/ani/include/manager/ani_cance.h @@ -20,9 +20,10 @@ namespace OHOS { namespace NotificationManagerSts { void AniCancelAll(ani_env* env); -void AniCancelWithId(ani_env* env, ani_int id); -void AniCancelWithIdLabel(ani_env* env, ani_int id, ani_string label); -void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id); +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); } // namespace NotificationManagerSts } // namespace OHOS #endif diff --git a/frameworks/ets/ani/include/sts_sorting.h b/frameworks/ets/ani/include/sts_sorting.h index eff754a03..9c77a2600 100644 --- a/frameworks/ets/ani/include/sts_sorting.h +++ b/frameworks/ets/ani/include/sts_sorting.h @@ -20,7 +20,7 @@ namespace OHOS { namespace NotificationSts { -bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting sorting, ani_object &outObj); +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/src/manager/ani_cance.cpp b/frameworks/ets/ani/src/manager/ani_cance.cpp index 6f6e6c549..e8a02f0b4 100644 --- a/frameworks/ets/ani/src/manager/ani_cance.cpp +++ b/frameworks/ets/ani/src/manager/ani_cance.cpp @@ -35,10 +35,10 @@ void AniCancelAll(ani_env* env) ANS_LOGD("AniCancelAll notifications end"); } -void AniCancelWithId(ani_env* env, ani_int id) +void AniCancelWithId(ani_env* env, ani_double id) { - ANS_LOGD("AniCancelWithId call,id : %{public}d", id); - int returncode = Notification::NotificationHelper::CancelNotification(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)); @@ -47,7 +47,7 @@ void AniCancelWithId(ani_env* env, ani_int id) ANS_LOGD("AniCancelWithId notifications end"); } -void AniCancelWithIdLabel(ani_env* env, ani_int id, ani_string label) +void AniCancelWithIdLabel(ani_env* env, ani_double id, ani_string label) { ANS_LOGD("AniCancelWithIdLabel call"); std::string labelStr; @@ -56,8 +56,8 @@ void AniCancelWithIdLabel(ani_env* env, ani_int id, ani_string label) return; } - ANS_LOGD("Cancel by label id:%{public}d label:%{public}s", id, labelStr.c_str()); - int returncode = Notification::NotificationHelper::CancelNotification(labelStr, id); + 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)); @@ -66,7 +66,7 @@ void AniCancelWithIdLabel(ani_env* env, ani_int id, ani_string label) ANS_LOGD("AniCancelWithIdLabel end"); } -void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id) +void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_double id) { ANS_LOGD("AniCancelWithBundle call"); Notification::NotificationBundleOption option; @@ -75,9 +75,9 @@ void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id) return; } - ANS_LOGD("Cancel by bundle:%{public}s id:%{public}d", + ANS_LOGD("Cancel by bundle:%{public}s id:%{public}lf", option.GetBundleName().c_str(), id); - int returncode = Notification::NotificationHelper::CancelAsBundle(option, 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)); @@ -85,5 +85,34 @@ void AniCancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id) } 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); +} } // 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 index ba8528993..64cec4ecd 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -43,6 +43,7 @@ void AniNotificationManagerRegistryInit(ani_env *env) } std::array kitFunctions = { ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, + // ani_native_function {"nativeGetActiveNotifications", 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)}, diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp index cdbc798f2..122963d0b 100644 --- a/frameworks/ets/ani/src/sts_notification_flag.cpp +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "sts_notification_flag.h" - #include "sts_common.h" namespace OHOS { @@ -25,24 +24,41 @@ bool WarpNotificationFlags(ani_env* env, const std::shared_ptr(flags->IsSoundEnabled()); ani_enum_item enumItem = nullptr; - RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", - soundEnabled, enumItem)); - RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "soundEnabled", enumItem)); + 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()); - RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", - vibrationEnabled, enumItem)); - RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "vibrationEnabled", enumItem)); + 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(); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, flagsCls, flagsObject, "reminderFlags", reminderFlags)); + if (SetPropertyOptionalByDouble(env, flagsObject, "reminderFlags", reminderFlags)) { + ANS_LOGD("WarpNotificationFlags set 'reminderFlags' faild"); + } return true; } diff --git a/frameworks/ets/ani/src/sts_sorting.cpp b/frameworks/ets/ani/src/sts_sorting.cpp index 12f1026a1..fa2a6ad76 100644 --- a/frameworks/ets/ani/src/sts_sorting.cpp +++ b/frameworks/ets/ani/src/sts_sorting.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace NotificationSts { -bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting sorting, ani_object &outObj) +bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting &sorting, ani_object &outObj) { ani_class cls; ani_object obj; @@ -29,38 +29,35 @@ bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting sor ani_string hashCodeObj; std::string hashCode; if (env == nullptr) { - ANS_LOGD("faild. env is nullptr"); + ANS_LOGE("invalid parameter value"); return false; } if (!CreateClassObjByClassName(env, "Lnotification/notificationSorting/NotificationSortingInner;", cls, obj)) { - ANS_LOGD("Create obj faild. NotificationSortingInner"); + ANS_LOGE("Create obj faild. NotificationSortingInner"); return false; } - - // TODO // readonly slot: NotificationSlot - // sptr slot = new NotificationSlot(*sorting.GetSlot()); if (!WrapNotificationSlot(env, sorting.GetSlot(), slotObj)) { - ANS_LOGD("WrapNotificationSlot faild"); + ANS_LOGE("WrapNotificationSlot faild"); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(obj, "slot", slotObj))) { - ANS_LOGD("set slot faild. status %{public}d", status); + 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_LOGD("set hashCode faild. status %{public}d", status); + 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_LOGD("set ranking faild. status %{public}d", status); + ANS_LOGE("set ranking faild. status %{public}d", status); return false; } outObj = obj; diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp index 3b8017ecc..4a30751b8 100644 --- a/frameworks/ets/ani/src/sts_sorting_map.cpp +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -26,19 +26,19 @@ bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptrGetNotificationSorting(it, sorting)) { ani_string keyString; if (ANI_OK != GetAniStringByString(env, it, keyString)) { - ANS_LOGD("GetAniStringByString faild. key: %{public}s", it.c_str()); - continue; + ANS_LOGE("GetAniStringByString faild. key: %{public}s", it.c_str()); + return false; } ani_object sortingObj; if (!WarpNotificationSorting(env, sorting, sortingObj)) { - ANS_LOGD("WarpNotificationSorting faild. key: %{public}s", it.c_str()); - continue; + ANS_LOGE("WarpNotificationSorting faild. key: %{public}s", it.c_str()); + return false; } - if (keyString == nullptr) { - ANS_LOGD("GetAniString faild. key: %{public}s", it.c_str()); - continue; + 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_LOGD("set key value faild. key: %{public}s status %{public}d", it.c_str(), status); - continue; + ANS_LOGE("set key value faild. key: %{public}s status %{public}d", it.c_str(), status); + return false; } } } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortings", recordObj))) { - ANS_LOGD("Object_SetPropertyByName_Ref sortings faild. status %{public}d", status); + ANS_LOGE("Object_SetPropertyByName_Ref sortings faild. status %{public}d", status); return false; } arrayObj = GetAniStringArrayByVectorString(env, keys); if (arrayObj == nullptr) { - ANS_LOGD("WarpVectorStringToSts sortedHashCode faild"); + ANS_LOGE("WarpVectorStringToSts sortedHashCode faild"); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortedHashCode", arrayObj))) { - ANS_LOGD("Object_SetPropertyByName_Ref sortedHashCode faild. status %{public}d", status); + ANS_LOGE("Object_SetPropertyByName_Ref sortedHashCode faild. status %{public}d", status); return false; } return true; diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 1857ae735..67a4938c9 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -101,7 +101,6 @@ void StsSubscriberInstance::OnCanceled( int32_t deleteReason) { ANS_LOGD("enter"); -#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -124,14 +123,12 @@ void StsSubscriberInstance::OnCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } -#endif } void StsSubscriberInstance::OnConsumed( const std::shared_ptr &request, const std::shared_ptr &sortingMap) { ANS_LOGD("enter"); -#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -154,7 +151,6 @@ void StsSubscriberInstance::OnConsumed( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } -#endif } void StsSubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) { @@ -366,7 +362,6 @@ void StsSubscriberInstance::OnBatchCanceled( const std::shared_ptr &sortingMap, int32_t deleteReason) { ANS_LOGD("enter"); -#if 0 std::lock_guard l(lock_); ani_env* etsEnv; ani_status aniResult = ANI_ERROR; @@ -389,7 +384,6 @@ void StsSubscriberInstance::OnBatchCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } -#endif } bool StsSubscriberInstance::HasOnBatchCancelCallback() { diff --git a/frameworks/ets/ani/src/sts_subscribe_info.cpp b/frameworks/ets/ani/src/sts_subscribe_info.cpp index 53cffd756..4b5c4a891 100644 --- a/frameworks/ets/ani/src/sts_subscribe_info.cpp +++ b/frameworks/ets/ani/src/sts_subscribe_info.cpp @@ -21,6 +21,11 @@ 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; @@ -29,16 +34,16 @@ bool UnwarpNotificationSubscribeInfo(ani_env *env, ani_object value, Notificatio if (ANI_OK != GetPropertyStringArray(env, value, "bundleNames", isUndefined, res) || isUndefined == ANI_TRUE || res.empty()) { - ANS_LOGD("UnWarpStringArrayOrUndefinedByProperty faild"); + ANS_LOGE("UnWarpStringArrayOrUndefinedByProperty faild"); } if (ANI_OK != GetPropertyDouble(env, value, "userId", isUndefined, userId) || isUndefined == ANI_TRUE) { - ANS_LOGD("GetDoubleOrUndefined faild"); + ANS_LOGE("GetDoubleOrUndefined faild"); } if (ANI_OK != GetPropertyString(env, value, "deviceType", isUndefined, deviceType) || isUndefined == ANI_TRUE) { - ANS_LOGD("GetStringOrUndefined faild"); + ANS_LOGE("GetStringOrUndefined faild"); } if (ANI_OK != GetPropertyDouble(env, value, "filterLimit", isUndefined, filterLimit) || isUndefined == ANI_TRUE) { - ANS_LOGD("GetDoubleOrUndefined faild"); + ANS_LOGE("GetDoubleOrUndefined faild"); } info.AddAppNames(res); info.AddAppUserId(static_cast(userId)); diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index 4e3313c5a..3147d559f 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -32,17 +32,15 @@ bool WarpSubscribeCallbackData( ani_object sortingMapObj; ani_status status; ani_class cls; - if (env == nullptr) { - ANS_LOGD("env is nullptr"); + if (env == nullptr || request == nullptr || sortingMap == nullptr) { + ANS_LOGE("invalid parameter value"); return false; } - if (!CreateClassObjByClassName( env, "Lnotification/notificationSubscriber/SubscribeCallbackDataInner;", cls, outObj)) { - ANS_LOGD("CreateClassObjByClassName faild"); + ANS_LOGE("CreateClassObjByClassName faild"); return false; } - // request: NotificationRequest ani_object requestObj; ani_class requestCls; @@ -54,67 +52,61 @@ bool WarpSubscribeCallbackData( ANS_LOGE("requestObj is nullptr"); return false; } - if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "request", requestObj))) { - ANS_LOGD("set request faild. status %{public}d", status); + ANS_LOGE("set request faild. status %{public}d", status); return false; } - // sortingMap?: NotificationSortingMap if (!WarpNotificationSortingMap(env, sortingMap, sortingMapObj)) { - ANS_LOGD("WarpNotificationSortingMap faild"); + ANS_LOGE("WarpNotificationSortingMap faild"); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sortingMap", sortingMapObj))) { - ANS_LOGD("set sortingMap faild. status %{public}d", status); + ANS_LOGE("set sortingMap faild. status %{public}d", status); return false; } - // reason?: number if (deleteReason != -1) { ani_object reason = CreateDouble(env, static_cast(deleteReason)); if (reason == nullptr) { - ANS_LOGD("reason Create faild"); + ANS_LOGE("reason Create faild"); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "reason", reason))) { - ANS_LOGD("set reason faild. status %{public}d", status); + ANS_LOGE("set reason faild. status %{public}d", status); return false; } } - // sound?: string if (request->EnableSound()) { std::string sound = request->GetSound().ToString(); ani_string soundObj; if (ANI_OK != GetAniStringByString(env, sound, soundObj) || soundObj == nullptr) { - ANS_LOGD("sound create faild"); + ANS_LOGE("sound create faild"); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "sound", soundObj))) { - ANS_LOGD("set sound faild. status %{public}d", status); + ANS_LOGE("set sound faild. status %{public}d", status); } } - // vibrationValues?: Array if (request->EnableVibrate()) { ani_object vibrationValuesObj; const std::vector vibrationValues = request->GetVibrationStyle(); vibrationValuesObj = newArrayClass(env, vibrationValues.size()); if (vibrationValuesObj == nullptr) { - ANS_LOGD("CreateArray faild"); + 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_LOGD("faild. status : %{public}d", status); + ANS_LOGE("faild. status : %{public}d", status); return false; } } - if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "vibrationValues", vibrationValuesObj))) { - ANS_LOGD("set vibrationValuesObj faild. status %{public}d", status); + ANS_LOGE("set vibrationValuesObj faild. status %{public}d", status); return false; } } @@ -129,26 +121,29 @@ bool WarpSubscribeCallbackDataArray( 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_LOGD("env is nullptr"); + ANS_LOGE("env is nullptr"); return false; } outObj = newArrayClass(env, requestList.size()); if (outObj == nullptr) { - ANS_LOGD("CreateArray faild"); + 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_LOGD("WarpSubscribeCallbackData faild"); + ANS_LOGE("WarpSubscribeCallbackData faild"); return false; } if (ANI_OK != (status = env->Object_CallMethodByName_Void( outObj, "$_set", "ILstd/core/Object;:V", i, obj))) { - ANS_LOGD("set object faild. index %{public}d status %{public}d", i, status); + ANS_LOGE("set object faild. index %{public}d status %{public}d", i, status); return false; } } @@ -158,24 +153,28 @@ bool WarpSubscribeCallbackDataArray( 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_LOGD("CreateClassObjByClassName faild"); + ANS_LOGE("CreateClassObjByClassName faild"); return false; } if (!SetFieldString(env, cls, outObj, "bundle", callbackData->GetBundle())) { - ANS_LOGD("SetFieldString bundle faild"); + ANS_LOGE("SetFieldString bundle faild"); return false; } if (!CallSetter(env, cls, outObj, "uid", static_cast(callbackData->GetUid()))) { - ANS_LOGD("uid set faild."); + ANS_LOGE("uid set faild."); return false; } if (ANI_OK != (status = env->Object_SetPropertyByName_Boolean( outObj, "enable", BoolToAniBoolean(callbackData->GetEnable())))) { - ANS_LOGD("set enable faild. status %{public}d", status); + ANS_LOGE("set enable faild. status %{public}d", status); return false; } return true; @@ -184,33 +183,37 @@ bool WarpEnabledNotificationCallbackData(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_LOGD("CreateClassObjByClassName faild"); + ANS_LOGE("CreateClassObjByClassName faild"); return false; } if (!SetFieldString(env, cls, outObj, "bundle", badgeData->GetBundle())) { - ANS_LOGD("SetFieldString bundle faild"); + ANS_LOGE("SetFieldString bundle faild"); return false; } if (!CallSetter(env, cls, outObj, "uid", static_cast(badgeData->GetUid()))) { - ANS_LOGD("uid set faild."); + ANS_LOGE("uid set faild."); return false; } if (!CallSetter(env, cls, outObj, "badgeNumber", static_cast(badgeData->GetBadgeNumber()))) { - ANS_LOGD("badgeNumber set faild"); + 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_LOGD("instanceKey set faild."); + ANS_LOGE("instanceKey set faild."); return false; } } else { - ANS_LOGD("instanceKeyObj createDouble faild"); + ANS_LOGE("instanceKeyObj createDouble faild"); } if (!SetFieldString(env, cls, outObj, "appInstanceKey", badgeData->GetAppInstanceKey())) { ANS_LOGD("SetFieldString appInstanceKey faild"); diff --git a/frameworks/ets/ani/src/sts_template.cpp b/frameworks/ets/ani/src/sts_template.cpp index 33092a9de..031acd5db 100644 --- a/frameworks/ets/ani/src/sts_template.cpp +++ b/frameworks/ets/ani/src/sts_template.cpp @@ -25,21 +25,29 @@ 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); @@ -49,23 +57,40 @@ ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, Notificat ani_object WrapNotificationTemplate(ani_env* env, const std::shared_ptr &templ) { - if (templ == nullptr) { - ANS_LOGE("templ is null"); + if (templ == nullptr || env == nullptr) { + ANS_LOGE("invalid parameter value"); return nullptr; } ani_object templateObject = nullptr; ani_class templateCls = nullptr; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationTemplate/NotificationTemplateInner;", templateCls, templateObject)); + 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; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, templ->GetTemplateName(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, templateCls, templateObject, "name", stringValue)); + 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); - RETURN_NULL_IF_FALSE(CallSetter(env, templateCls, templateObject, "data", valueRef)); + 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; } diff --git a/frameworks/ets/ani/src/sts_user_input.cpp b/frameworks/ets/ani/src/sts_user_input.cpp index 30f97fc89..ec758e74d 100644 --- a/frameworks/ets/ani/src/sts_user_input.cpp +++ b/frameworks/ets/ani/src/sts_user_input.cpp @@ -21,26 +21,45 @@ 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) { - return ANI_INVALID_ARGS; - } + 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; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "Lnotification/notificationUserInput/NotificationUserInputInner;", userInputCls, userInputObject)); + ani_status status = ANI_OK; + if (!CreateClassObjByClassName(env, + "Lnotification/notificationUserInput/NotificationUserInputInner;", userInputCls, userInputObject)) { + ANS_LOGE("Create faild"); + return nullptr; + } ani_string stringValue; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, userInput->GetInputKey(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, userInputCls, userInputObject, "inputKey", 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; } } -- Gitee From 2881c4cc8a7ddc61ebb32f573a834d5c31606034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Wed, 21 May 2025 19:53:38 +0800 Subject: [PATCH 25/52] =?UTF-8?q?ets=E7=9B=B8=E5=85=B3=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- .../ets/ani/src/manager/ani_manager.cpp | 2 +- .../ets/ets/@ohos.notificationManager.ets | 353 +++++++++++++++++- 2 files changed, 338 insertions(+), 17 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 64cec4ecd..2b6ff6045 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -43,7 +43,7 @@ void AniNotificationManagerRegistryInit(ani_env *env) } std::array kitFunctions = { ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, - // ani_native_function {"nativeGetActiveNotifications", nullptr, reinterpret_cast(AniCancelWithIdOptinalLabel)}, + 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)}, diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index be33866fe..89d07423e 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -18,6 +18,16 @@ import { BusinessError, AsyncCallback } from '@ohos.base'; import { NotificationSlot } from 'notification.notificationSlot'; import { NotificationRequest } 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 image from '@ohos.multimedia.image'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; @@ -30,7 +40,7 @@ const rejectInternalError: BusinessError = {code: ERROR_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"}; +const errorParamInvalid: BusinessError = {code: ERROR_PARAM_INVALID, message: "Invalid parameter"}; export default namespace notificationManager { loadLibrary("notification_manager_ani.z") @@ -113,6 +123,7 @@ export default namespace notificationManager { 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; @@ -193,6 +204,288 @@ export default namespace notificationManager { } 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?.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?.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?.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?.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?.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 = { + code: 0, + message: "" + } + if (request == null) { + error = { + code: 401, + message: "request must be not Null" + } + return error; + } + if(request.content == null || request.content == undefined) { + error = { + code: 401, + message: "request.content must be not Null" + } + 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; + } + return error; + } export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { @@ -536,6 +829,15 @@ export default namespace notificationManager { } export function publish(request: NotificationRequest, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): void => { return nativePublish(request); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -547,6 +849,10 @@ export default namespace notificationManager { } export function publish(request: NotificationRequest): Promise { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== 0) { + throw error; + } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativePublish(request); }); p.then((data: NullishType): void => { @@ -559,6 +865,15 @@ export default namespace notificationManager { } export function publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== 0) { + throw error; + } + if (callback == null) { + error.code = 401; + error.message = "callback must be not null"; + throw error; + } let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; @@ -570,6 +885,10 @@ export default namespace notificationManager { } export function publish(request: NotificationRequest, userId: number): Promise { + let error: BusinessError = isInvalidParameter(request); + if (error.code !== 0) { + 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 => { @@ -607,6 +926,9 @@ export default namespace notificationManager { 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 => { @@ -670,6 +992,9 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let retData : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, retData); }) } @@ -715,7 +1040,9 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { - + let retData : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, retData); }) } @@ -818,7 +1145,7 @@ export default namespace notificationManager { return pPromise; } - export function cancel(id: number, label: string): Promise { + export function cancel(id: number, label?: string): Promise { if (label == null || label?.length === 0) { let error: BusinessError = { code: 401, @@ -827,7 +1154,7 @@ export default namespace notificationManager { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + let p = taskpool.execute((): void => { return nativeCancelWithIdOptionalLabel(id, label); }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -857,6 +1184,8 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } @@ -873,21 +1202,11 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function cancel(id: number): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); - p.then((data: NullishType): void => { - resolve(undefined); - }, (error: Object): void => { - reject(error); - }); - }); - return pPromise; - } - export function cancelAll(): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeCancelAll(); }); @@ -913,6 +1232,8 @@ export default namespace notificationManager { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } -- Gitee From 4e5ab008420395b9d01bb095b79696f7dc9aba99 Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 21 May 2025 20:20:23 +0800 Subject: [PATCH 26/52] modify Signed-off-by: heguokai --- .../ets/ani/src/sts_notification_flag.cpp | 2 +- .../ets/ani/src/sts_notification_manager.cpp | 146 ++++++++++++------ frameworks/ets/ani/src/sts_slot.cpp | 124 +++++++++------ 3 files changed, 175 insertions(+), 97 deletions(-) diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp index 122963d0b..6e14d7490 100644 --- a/frameworks/ets/ani/src/sts_notification_flag.cpp +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -20,6 +20,7 @@ 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; @@ -61,6 +62,5 @@ bool WarpNotificationFlags(ani_env* env, const std::shared_ptr buttonOption) { + ANS_LOGD("OnResponse call"); std::string functionName = "OnResponse"; ani_env *env = GetAniEnv(); if (env == nullptr || stsSubscriber_ == nullptr) { @@ -237,12 +244,12 @@ void StsNotificationLocalLiveViewSubscriber::OnResponse(int32_t notificationId, ani_status status = ANI_OK; ani_object stsSubscriberObj = reinterpret_cast(stsSubscriber_->aniRef); ani_ref funRef; - status = env->Object_GetPropertyByName_Ref(stsSubscriberObj, functionName.c_str(), &funRef); - if (status != ANI_OK) { + 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) { @@ -254,9 +261,8 @@ void StsNotificationLocalLiveViewSubscriber::OnResponse(int32_t notificationId, 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_LOGD("FunctionalObject_Call failed, status: %{public}d", status); + ANS_LOGE("FunctionalObject_Call failed, status: %{public}d", status); return; } } @@ -264,34 +270,41 @@ void StsNotificationLocalLiveViewSubscriber::OnResponse(int32_t notificationId, 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; - if (stsSubscriber_ == nullptr) { - return; - } 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; @@ -299,119 +312,154 @@ ani_env* StsNotificationLocalLiveViewSubscriber::GetAniEnv() bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType) { + ANS_LOGD("SlotTypeEtsToC call"); STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; - EnumConvertAniToNative(env, enumItem, stsSlotType); - StsSlotTypeUtils::StsToC(stsSlotType, slotType); + 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; - StsSlotTypeUtils::CToSts(slotType, stsSlotType); - EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/SlotType;", stsSlotType, enumItem); + 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; - EnumConvertAniToNative(env, enumItem, stsSlotLevel); - StsSlotLevelUtils::StsToC(stsSlotLevel, slotLevel); + 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; - StsSlotLevelUtils::CToSts(slotLevel, stsSlotLevel); - EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/SlotLevel;", stsSlotLevel, enumItem); + 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); - return true; + if (!EnumConvertAniToNative(env, enumItem, stsContentType) + || !StsContentTypeUtils::StsToC(stsContentType, contentType)) { + ANS_LOGE("ContentTypeEtsToC failed"); + return false; } - 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; - StsContentTypeUtils::CToSts(contentType, stsContentType); - if(EnumConvertNativeToAni(env, + if (!StsContentTypeUtils::CToSts(contentType, stsContentType) + || !EnumConvertNativeToAni(env, "L@ohos/notificationManager/notificationManager/ContentType;", stsContentType, enumItem)) { - return true; + ANS_LOGE("ContentTypeCToEts failed"); + return false; } - return false; + return true; } 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) { - if (buttonOption == nullptr) { - ANS_LOGE("buttonOption is null"); + 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; - RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, - "L@ohos/notificationManager/notificationManager/ButtonOptionsInner;", optCls, optObj)); + if (!CreateClassObjByClassName(env, + "L@ohos/notificationManager/notificationManager/ButtonOptionsInner;", optCls, optObj) || optObj == nullptr) { + ANS_LOGE("WarpNotificationButtonOption: create class failed"); + return nullptr; + } // title: string; - ani_string stringValue = nullptr; - RETURN_NULL_IF_FALSE(GetAniStringByString(env, buttonOption->GetButtonName(), stringValue)); - RETURN_NULL_IF_FALSE(CallSetter(env, optCls, optObj, "buttonName", stringValue)); + 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_object obj; ani_enum_item stsEnumValue; const char *className = "L@ohos/notificationManager/notificationManager/DoNotDisturbDateInner;"; - if (!CreateClassObjByClassName(env, className, cls, obj)) { - ANS_LOGD("CreateClassObjByClassName faild"); + 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_LOGD("EnumConvert_NativeToSts faild"); + ANS_LOGE("EnumConvert_NativeToSts faild"); return false; } - if (!CallSetter(env, cls, obj, "type", stsEnumValue)) { - ANS_LOGD("set type faild."); + if (!SetPropertyByRef(env, outObj, "type", stsEnumValue)) { + ANS_LOGE("set type faild."); return false; } - if (!SetDate(env, obj, cls, "begin", date->GetBeginDate())) { - ANS_LOGD("SetDate 'begin' faild."); + if (!SetDate(env, outObj, "begin", date->GetBeginDate())) { + ANS_LOGE("SetDate 'begin' faild."); return false; } - if (!SetDate(env, obj, cls, "end", date->GetEndDate())) { - ANS_LOGD("SetDate 'end' faild."); + if (!SetDate(env, outObj, "end", date->GetEndDate())) { + ANS_LOGE("SetDate 'end' faild."); return false; } - outObj = obj; + ANS_LOGD("WarpNotificationDoNotDisturbDate end"); return true; } } // namespace NotificationSts diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 5df8a44d2..24d9fc14c 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -24,6 +24,11 @@ namespace NotificationSts { bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotType value) { + ANS_LOGD("WrapNotificationSlot call"); + if (env == nullptr || cls == nullptr) { + ANS_LOGE("WrapNotificationSlot failed, has nullptr"); + return false; + } RETURN_FALSE_IF_NULL(env); RETURN_FALSE_IF_NULL(cls); RETURN_FALSE_IF_NULL(object); @@ -49,72 +54,95 @@ bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &obj } return true; } - -bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj) -{ - ANS_LOGD("WrapNotificationSlot call"); - if (slot == nullptr) { - ANS_LOGE("slot is null"); +bool WrapNotificationSlotByBoolean(ani_env *env, sptr slot, ani_object &outAniObj) { + if (!SetPropertyOptionalByBoolean(env, outAniObj, "badgeFlag", slot->IsShowBadge())) { + ANS_LOGE("Set badgeFlag fail"); return false; } - ani_class cls; - if (!CreateClassObjByClassName(env, NOTIFICATION_SOLT_CLASSNAME, cls, outAniObj)) { - ANS_LOGE("CreateClassObjByClassName fail"); + if (!SetPropertyOptionalByBoolean(env, outAniObj, "bypassDnd", slot->IsEnableBypassDnd())) { + ANS_LOGE("Set bypassDnd fail"); return false; } - if (!SetOptionalFieldSlotType(env, cls, outAniObj, "notificationType", slot->GetType())) { - ANS_LOGE("Set notificationType fail"); + if (!SetPropertyOptionalByBoolean(env, outAniObj, "vibrationEnabled", slot->CanVibrate())) { + ANS_LOGE("Set vibrationEnabled fail"); return false; } - if (!SetFieldString(env, cls, outAniObj, "desc", slot->GetDescription())) { - ANS_LOGE("Set desc fail"); + if (!SetPropertyOptionalByBoolean(env, outAniObj, "lightEnabled", slot->CanEnableLight())) { + ANS_LOGE("Set lightEnabled fail"); return false; } - if (!SetOptionalFieldBoolean(env, cls, outAniObj, "badgeFlag", slot->IsShowBadge())) { - ANS_LOGE("Set badgeFlag fail"); + if (!SetPropertyOptionalByBoolean(env, outAniObj, "enabled", slot->GetEnable())) { + ANS_LOGE("Set enabled fail"); return false; } - if (!SetOptionalFieldBoolean(env, cls, outAniObj, "bypassDnd", slot->IsEnableBypassDnd())) { - ANS_LOGE("Set bypassDnd fail"); + 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; } - if (!SetOptionalFieldDouble(env, cls, outAniObj, "lockscreenVisibility", - static_cast(slot->GetLockScreenVisibleness()))) { + 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 (!SetOptionalFieldBoolean(env, cls, outAniObj, "vibrationEnabled", slot->CanVibrate())) { - ANS_LOGE("Set vibrationEnabled fail"); + if (!SetPropertyOptionalByDouble(env, outAniObj, "lightColor", static_cast(slot->GetLedLightColor()))) { + ANS_LOGE("Set lightColor fail"); return false; } - if (!SetFieldString(env, cls, outAniObj, "sound", slot->GetSound().ToString().c_str())) { - ANS_LOGE("Set sound fail"); + if (!SetPropertyOptionalByDouble(env, outAniObj, "reminderMode", static_cast(slot->GetReminderMode()))) { + ANS_LOGE("Set reminderMode fail"); return false; } - if (!SetOptionalFieldBoolean(env, cls, outAniObj, "lightEnabled", slot->CanEnableLight())) { - ANS_LOGE("Set lightEnabled fail"); + if (!SetPropertyOptionalByDouble( + env, outAniObj, "authorizedStatus", static_cast(slot->GetAuthorizedStatus()))) { + ANS_LOGE("Set authorizedStatus fail"); return false; } - if (!SetOptionalFieldDouble(env, cls, outAniObj, "lightColor", static_cast(slot->GetLedLightColor()))) { - ANS_LOGE("Set lightColor fail"); + 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; } - if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) - { - ANS_LOGE("Set vibrationValues fail"); + ani_class cls; + if (!CreateClassObjByClassName(env, NOTIFICATION_SOLT_CLASSNAME, cls, outAniObj)) { + ANS_LOGE("CreateClassObjByClassName fail"); return false; } - if (!SetOptionalFieldBoolean(env, cls, outAniObj, "enabled", slot->GetEnable())) { - ANS_LOGE("Set enabled fail"); + if (!SetOptionalFieldSlotType(env, cls, outAniObj, "notificationType", slot->GetType())) { + ANS_LOGE("Set notificationType fail"); return false; } - if (!SetOptionalFieldDouble(env, cls, outAniObj, "reminderMode", static_cast(slot->GetReminderMode()))) { - ANS_LOGE("Set reminderMode fail"); + if (!WrapNotificationSlotByBoolean(env, slot, outAniObj)) { + ANS_LOGE("set Boolean params fail"); return false; } - if (!SetOptionalFieldDouble(env, cls, outAniObj, "authorizedStatus", - static_cast(slot->GetAuthorizedStatus()))) { - ANS_LOGE("Set authorizedStatus fail"); + 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"); @@ -124,9 +152,11 @@ bool WrapNotificationSlot(ani_env *env, sptr slo bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotLevel value) { - RETURN_FALSE_IF_NULL(env); - RETURN_FALSE_IF_NULL(cls); - RETURN_FALSE_IF_NULL(object); + ANS_LOGD("SetOptionalFieldSlotLevel call"); + if (env == nullptr) { + ANS_LOGE("SetOptionalFieldSlotLevel failed, env is nullptr"); + return false; + } ani_field field = nullptr; ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); if (status != ANI_OK || field == nullptr) { @@ -135,10 +165,9 @@ bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &ob return false; } ani_enum_item enumItem = nullptr; - NotificationSts::SlotLevelCToEts(env, value, enumItem); - if (enumItem == nullptr) + if (!NotificationSts::SlotLevelCToEts(env, value, enumItem) || enumItem == nullptr) { - ANS_LOGE("null enumItem"); + ANS_LOGE("get enumItem failed"); return false; } status = env->Object_SetField_Ref(object, field, enumItem); @@ -166,15 +195,16 @@ bool WrapNotificationSlotArray(ani_env *env, const std::vectorObject_CallMethodByName_Void(outAniObj, - "$_set", "ILstd/core/Object;:V", index, infoObj)); + 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; } -- Gitee From dbf8caf80f1af55d05aa19cad6dde1377c21e80c Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 21 May 2025 21:48:26 +0800 Subject: [PATCH 27/52] codex Signed-off-by: heguokai --- frameworks/ets/ani/include/sts_common.h | 85 +----- .../ani/include/sts_notification_content.h | 2 +- frameworks/ets/ani/include/sts_subscribe.h | 2 +- .../ets/ani/src/manager/ani_display_badge.cpp | 11 +- .../manager/ani_do_not_disturb_profile.cpp | 4 +- .../ani/src/manager/ani_local_live_view.cpp | 2 +- .../ets/ani/src/manager/ani_manager.cpp | 3 +- .../src/manager/ani_notification_enable.cpp | 2 +- frameworks/ets/ani/src/sts_action_button.cpp | 12 +- frameworks/ets/ani/src/sts_bundle_option.cpp | 8 +- frameworks/ets/ani/src/sts_common.cpp | 24 +- frameworks/ets/ani/src/sts_convert_other.cpp | 10 +- frameworks/ets/ani/src/sts_disturb_mode.cpp | 8 +- .../ets/ani/src/sts_notification_content.cpp | 35 ++- .../ets/ani/src/sts_notification_manager.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 50 ++-- frameworks/ets/ani/src/sts_slot.cpp | 23 +- frameworks/ets/ani/src/sts_sorting.cpp | 3 +- frameworks/ets/ani/src/sts_sorting_map.cpp | 2 +- frameworks/ets/ani/src/sts_subscribe.cpp | 281 +++++++++--------- frameworks/ets/ani/src/sts_subscriber.cpp | 10 +- frameworks/ets/ani/src/sts_template.cpp | 2 +- .../ets/ani/src/subscribe/ani_subscribe.cpp | 9 +- .../notification/notificationActionButton.ets | 2 +- .../ets/notification/notificationContent.ets | 2 +- .../notification/notificationUserInput.ets | 2 +- 26 files changed, 257 insertions(+), 339 deletions(-) diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index b96b584c4..56a34a697 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -105,63 +105,6 @@ static bool CallSetter(ani_env* env, ani_class cls, ani_object object, const cha return true; } -template -static bool CallSetterOptional( - ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) -{ - if(env == nullptr || cls == nullptr || object == nullptr) { - return false; - } - if constexpr (std::is_pointer_v && std::is_base_of_v<__ani_ref, std::remove_pointer_t>) { - return CallSetter(env, cls, object, propertyName, value); - } - const char* valueClassName = nullptr; - const char* ctorSig = nullptr; - if constexpr (std::is_same_v) { - valueClassName = "Lstd/core/Boolean;"; - ctorSig = "Z:V"; - } else if constexpr (std::is_same_v) { - valueClassName = "Lstd/core/Char;"; - ctorSig = "C:V"; - } else 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) { - valueClassName = "Lstd/core/Double;"; - ctorSig = "D:V"; - } else { - ANS_LOGE("Classname %{public}s Unsupported", propertyName); - return false; - } - ani_class valueClass = nullptr; - ani_status status = env->FindClass(valueClassName, &valueClass); - if (status != ANI_OK) { - ANS_LOGE("FindClass %{public}s %{public}s failed %{public}d", propertyName, valueClassName, status); - return false; - } - ani_method ctor = nullptr; - status = env->Class_FindMethod(valueClass, "", ctorSig, &ctor); - if (status != ANI_OK) { - ANS_LOGE("Class_FindMethod %{public}s failed %{public}d", propertyName, status); - return false; - } - ani_object valueObj = nullptr; - 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) { - status = env->Object_New(valueClass, ctor, &valueObj, static_cast(value)); - } else { - ANS_LOGE("Classname %{public}s Unsupported", propertyName); - return false; - } - if (status != ANI_OK) { - ANS_LOGE("Object_New %{public}s failed %{public}d", propertyName, status); - return false; - } - return CallSetter(env, cls, object, propertyName, valueObj); -} - [[maybe_unused]]static bool CallSetterNull(ani_env* env, ani_class cls, ani_object object, const char* propertyName) { ani_ref nullRef = nullptr; @@ -205,7 +148,8 @@ static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &resu } template -void deletePoint(T &result) { +void deletePoint(T &result) +{ delete result; result = nullptr; } @@ -277,17 +221,6 @@ static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T e return false; } -#define ANI_FAILED_AND_RETURN(status) \ -do \ -{ \ - ani_status const local_status = (status); \ - if (ani_status::ANI_OK != local_status) \ - { \ - ANS_LOGE("check status error: %{public}d", (int)local_status); \ - return false; \ - } \ -} while (0) - #define RETURN_NULL_IF_NULL(ptr) \ do { \ if ((ptr) == nullptr) { \ @@ -302,26 +235,12 @@ do return false; \ } \ } while (0) -#define RETURN_NULL_IF_FALSE(condition) \ - do { \ - if (!(condition)) { \ - ANS_LOGE("condition is false"); \ - return nullptr; \ - } \ - } while (0) #define RETURN_FALSE_IF_FALSE(condition) \ do { \ if (!(condition)) { \ return false; \ } \ } while (0) -#define RETURN_ANI_STATUS_IF_NOT_OK(res, err) \ - do { \ - if ((res) != ANI_OK) { \ - ANS_LOGE(err); \ - return res; \ - } \ - } while (0) } // namespace NotificationSts } // OHOS diff --git a/frameworks/ets/ani/include/sts_notification_content.h b/frameworks/ets/ani/include/sts_notification_content.h index 57f8adc80..e1902b385 100644 --- a/frameworks/ets/ani/include/sts_notification_content.h +++ b/frameworks/ets/ani/include/sts_notification_content.h @@ -66,7 +66,7 @@ bool WarpNotificationTime(ani_env *env, const NotificationTime &time, bool isIni 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_status GetIconButtonArray(ani_env *env, ani_object param, const char *name, std::vector &res); ani_object GetAniIconButtonArray(ani_env *env, const std::vector buttons); diff --git a/frameworks/ets/ani/include/sts_subscribe.h b/frameworks/ets/ani/include/sts_subscribe.h index fc0650dae..46e583aa4 100644 --- a/frameworks/ets/ani/include/sts_subscribe.h +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -114,7 +114,7 @@ public: bool Subscribe(ani_env *env, ani_object subscriber, ani_object info); bool UnSubscribe(ani_env *env, ani_object subscriber); private: - SubscriberInstanceManager(){} + SubscriberInstanceManager() {} bool GetNotificationSubscriber( ani_env *env, ani_object value, std::shared_ptr &subscriberInfo); diff --git a/frameworks/ets/ani/src/manager/ani_display_badge.cpp b/frameworks/ets/ani/src/manager/ani_display_badge.cpp index dd146afc9..7cba58762 100644 --- a/frameworks/ets/ani/src/manager/ani_display_badge.cpp +++ b/frameworks/ets/ani/src/manager/ani_display_badge.cpp @@ -41,8 +41,7 @@ void AniDisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) return; } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("sts DisplayBadge error, errorCode: %{public}d", externalCode); return; @@ -59,7 +58,7 @@ ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj) returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); } else { BundleOption option; - if(NotificationSts::UnwrapBundleOption(env, obj, option)) { + if (NotificationSts::UnwrapBundleOption(env, obj, option)) { returncode = Notification::NotificationHelper::GetShowBadgeEnabledForBundle(option, isDisplayed); } else { OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, @@ -70,8 +69,7 @@ ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj) } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("sts IsBadgeDisplayed error, errorCode: %{public}d", externalCode); return NotificationSts::BoolToAniBoolean(false); @@ -81,5 +79,4 @@ ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj) return NotificationSts::BoolToAniBoolean(isDisplayed); } } -} - +} \ 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 index 17bcf2b13..8907087ee 100644 --- a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -67,6 +67,4 @@ void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj) ANS_LOGD("AniRemoveDoNotDisturbProfile end"); } } -} - - +} \ 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 index 3e8c0fbff..d2b76a4ed 100644 --- a/frameworks/ets/ani/src/manager/ani_local_live_view.cpp +++ b/frameworks/ets/ani/src/manager/ani_local_live_view.cpp @@ -43,7 +43,7 @@ void AniTriggerSystemLiveView( return; } int returncode = OHOS::Notification::NotificationHelper::TriggerLocalLiveView(bundleOption, - static_cast(notificationId), buttonOption); + static_cast(notificationId), buttonOption); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 2b6ff6045..755ab662c 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -43,7 +43,8 @@ void AniNotificationManagerRegistryInit(ani_env *env) } std::array kitFunctions = { ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, - ani_native_function {"nativeCancelWithIdOptionalLabel", nullptr, reinterpret_cast(AniCancelWithIdOptinalLabel)}, + 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)}, diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index 46acb35cd..823cb00d1 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -89,7 +89,7 @@ void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniSetNotificationEnable -> error, errorCode: %{public}d", externalCode); - } + } ANS_LOGD("AniSetNotificationEnable end"); } } // namespace NotificationManagerSts diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index 21e78f01e..f3d482f47 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -90,7 +90,7 @@ ani_status GetStsActionButtonByUserInput(ani_env *env, ani_object param, 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) { + 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"); @@ -243,17 +243,17 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, ANS_LOGE("GetActionButtonArray: GetPropertyDouble name = %{public}s, status = %{public}d", name, status); return status; } - for (int dex = 0; dex < static_cast(length); dex++) { + 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)dex))) { - ANS_LOGE("GetActionButtonArray: get ref failed, status = %{public}d, index = %{public}d", status, dex); + "$_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, dex); + status, i); return status; } std::shared_ptr button @@ -290,7 +290,7 @@ ani_object GetAniArrayNotificationActionButton(ani_env* env, 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"); diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index cc25b1732..d420f0209 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -59,16 +59,16 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector(length); dex++) { + for (int32_t i = 0; i < static_cast(length); i++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), - "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)dex); + "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &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, dex); + ANS_LOGE("UnwrapArrayBundleOption: get option status = %{public}d, index = %{public}d", status, i); return false; } options.push_back(option); @@ -101,7 +101,7 @@ bool WrapBundleOption(ani_env* env, } // uid?: number; uint32_t uid = bundleOption->GetUid(); - CallSetterOptional(env, bundleCls, bundleObject, "uid", uid); + SetPropertyOptionalByDouble(env, bundleObject, "uid", uid); ANS_LOGD("WrapBundleOption end"); return true; } diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 711870cec..88d4b48d2 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -121,7 +121,7 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, ANS_LOGE("Failed to check undefined for '%{public}s', status: %{public}d", name, status); return status; } - if(isUndefined == ANI_TRUE) { + if (isUndefined == ANI_TRUE) { ANS_LOGE("%{public}s is undefined", name); return status; } @@ -390,7 +390,8 @@ ani_object CreateBoolean(ani_env *env, bool value) return nullptr; } ani_object personInfoObj; - if ((status = env->Object_New(persion_cls, personInfoCtor, &personInfoObj, value ? ANI_TRUE : ANI_FALSE)) != ANI_OK) { + if ((status = env->Object_New(persion_cls, personInfoCtor, &personInfoObj, value ? ANI_TRUE : ANI_FALSE)) + != ANI_OK) { ANS_LOGE("status : %{public}d", status); return nullptr; } @@ -405,7 +406,7 @@ ani_object CreateDouble(ani_env *env, double value) ani_class doubleCls; ani_status status = ANI_ERROR; if ((status = env->FindClass(CLASSNAME_DOUBLE, &doubleCls)) != ANI_OK) { - ANS_LOGE( "status : %{public}d", status); + ANS_LOGE("status : %{public}d", status); return nullptr; } ani_method doubleCtor; @@ -429,17 +430,17 @@ ani_object newArrayClass(ani_env *env, int length) return nullptr; } ani_class arrayCls = nullptr; - if (ANI_OK != env->FindClass("Lescompat/Array;", &arrayCls)){ + 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)){ + 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)){ + if (ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)) { ANS_LOGE("Object_New Array Faild"); return nullptr; } @@ -532,12 +533,19 @@ bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &c return false; } if (ANI_OK != env->FindClass(className, &cls)) { + ANS_LOGE("FindClass fail"); return false; } ani_method ctor; - ANI_FAILED_AND_RETURN(env->Class_FindMethod(cls, "", nullptr, &ctor)); + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + ANS_LOGE("FindMethod fail"); + return false; + } outAniObj = {}; - ANI_FAILED_AND_RETURN(env->Object_New(cls, ctor, &outAniObj)); + if (ANI_OK != env->Object_New(cls, ctor, &outAniObj)) { + ANS_LOGE("Object_New fail"); + return false; + } return true; } diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index 00aa22968..12652073b 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -145,7 +145,7 @@ ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector> &pixelMaps) { ANS_LOGD("GetPixelMapArray call"); @@ -247,14 +247,14 @@ ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vector> pixelMaps = {}; - if((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { + 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) { + if ((status = GetStringByAniString(env, anikey, str)) != ANI_OK) { ANS_LOGE("GetPixelMapByKeys : GetStringByAniString failed"); deleteVectorWithSpPoints(pixelMaps); deleteVectorWithArraySpPoints(pictureMap); @@ -285,7 +285,7 @@ ani_status GetPixelMapByRef( 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) { + if ((status = GetKeyString(env, static_cast(keysStrArrayRef), i, strAni)) != ANI_OK) { ANS_LOGE("GetPixelMapByRef : GetKeyString status = %{public}d", status); keys.clear(); return status; @@ -450,7 +450,7 @@ bool GetAniPictrueInfo(ani_env *env, std::map profile; - for (int dex = 0; dex < static_cast(length); dex++) { + for (int i = 0; i < static_cast(length); i++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", - "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)dex); + "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)i); if (status != ANI_OK) { - ANS_LOGE("UnwrapArrayDoNotDisturbProfile: status : %{public}d, index: %{public}d", status, dex); + ANS_LOGE("UnwrapArrayDoNotDisturbProfile: status : %{public}d, index: %{public}d", status, i); return false; } if (!UnwrapDoNotDisturbProfile(env, static_cast(optionRef), profile)) { - ANS_LOGE("Get profile failed, index: %{public}d", dex); + ANS_LOGE("Get profile failed, index: %{public}d", i); return false; } profiles.push_back(profile); diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index 1a85f5a42..c437e84b5 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -171,7 +171,7 @@ bool WarpNotificationProgress(ani_env *env, const NotificationProgress &progress ANS_LOGD("WarpNotificationProgress: set maxValue failed"); } // currentValue?: number; - if (!SetPropertyOptionalByDouble(env, progressObject, "currentValue",progress.GetCurrentValue())) { + if (!SetPropertyOptionalByDouble(env, progressObject, "currentValue", progress.GetCurrentValue())) { ANS_LOGD("WarpNotificationProgress: set currentValue failed"); } // isPercentage?: boolean; @@ -293,7 +293,7 @@ ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, Notificati } std::string text = ""; if (GetPropertyString(env, obj, "text", isUndefined, text) == ANI_OK && isUndefined == ANI_FALSE) { - iconButton.SetName(text); + iconButton.SetName(text); } else { ANS_LOGD("UnWarpNotificationIconButton: get text failed"); } @@ -370,7 +370,7 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, // icons?: Array std::vector> icons = {}; if (ANI_OK == GetPixelMapArray(env, obj, "icons", icons)) { - for(auto icon: icons) { + for (auto icon : icons) { button.addSingleButtonIcon(icon); } } else { @@ -499,7 +499,7 @@ void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule } ani_double time = 0.0; if (GetPropertyDouble(env, obj, "time", isUndefined, time) == ANI_OK && isUndefined == ANI_FALSE) { - capsule.SetTime(static_cast(time)); + capsule.SetTime(static_cast(time)); } else { ANS_LOGE("UnWarpNotificationCapsule: get time failed"); } @@ -706,7 +706,7 @@ ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationLongTextContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, longTextContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationLongTextContent:get BasicContent failed"); return status; @@ -745,7 +745,7 @@ ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationMultiLineContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, multiLineContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationMultiLineContent: get BasicContent failed"); return status; @@ -834,7 +834,7 @@ void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationLiveViewContentByOther failed, has nullptr"); return; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; ani_boolean isUndefined = ANI_TRUE; ani_double versionAni = 0.0; if (GetPropertyDouble(env, obj, "version", isUndefined, versionAni) == ANI_OK @@ -844,8 +844,10 @@ void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, ANS_LOGD("UnWarpNotificationLiveViewContent: get version failed"); } ani_ref extraInfoRef; - if (ANI_OK == (status = GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef)) - && isUndefined == ANI_FALSE && extraInfoRef != nullptr) { + if (ANI_OK != (status = GetPropertyRef(env, obj, "extraInfo", isUndefined, extraInfoRef)) + || isUndefined == ANI_TRUE || extraInfoRef == nullptr) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo failed"); + } else { AAFwk::WantParams wantParams = {}; if(UnwrapWantParams(env, extraInfoRef, wantParams)) { std::shared_ptr extraInfo = std::make_shared(wantParams); @@ -853,22 +855,19 @@ void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, } else { ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo by ref failed"); } - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo failed"); } ani_ref pictureInfoRef; isUndefined = ANI_TRUE; - - if (ANI_OK == GetPropertyRef(env, obj, "pictureInfo", isUndefined, pictureInfoRef) - && isUndefined == ANI_FALSE && pictureInfoRef != nullptr) { + if (ANI_OK != GetPropertyRef(env, obj, "pictureInfo", isUndefined, pictureInfoRef) + || isUndefined == ANI_TRUE || pictureInfoRef == nullptr) { + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); + } else { std::map>> pictureMap; if(GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { liveViewContent->SetPicture(pictureMap); } else { ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo by ref failed"); } - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); } bool isLocalUpdateOnly = true; if (ANI_OK == GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) @@ -978,7 +977,7 @@ void GetLocalLiveViewContentByTwo(ani_env *env, ani_object obj, if (GetPropertyRef(env, obj, "liveViewType", isUndefined, liveViewTypeRef) == ANI_OK && isUndefined == ANI_FALSE && liveViewTypeRef != nullptr) { LiveViewTypes liveViewTypes = LiveViewTypes::LIVE_VIEW_ACTIVITY; - if(LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { + if (LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { localLiveViewContent->SetLiveViewType(liveViewTypes); } else { ANS_LOGD("GetLocalLiveViewContentByTwo: get liveViewType by ref failed"); @@ -997,7 +996,7 @@ ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationLocalLiveViewContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, localLiveViewContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationLocalLiveViewContent: get BasicContent failed"); return status; diff --git a/frameworks/ets/ani/src/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index 23fe0110b..53eac2f1f 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -393,7 +393,7 @@ ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonO ani_status status = ANI_ERROR; ani_boolean isUndefind = ANI_TRUE; std::string buttonName = ""; - if((status = GetPropertyString(env, buttonOptionObj, "buttonName", isUndefind, buttonName)) != ANI_OK + if ((status = GetPropertyString(env, buttonOptionObj, "buttonName", isUndefind, buttonName)) != ANI_OK || isUndefind == ANI_TRUE) { ANS_LOGE("UnWarpNotificationButtonOption: get buttonName failed"); return ANI_INVALID_ARGS; diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 6b461dace..c0b1ebc7a 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -21,7 +21,7 @@ #include "sts_notification_content.h" #include "sts_action_button.h" #include "sts_bundle_option.h" -#include "sts_template.h" +#include "sts_template.h" #include "ans_log_wrapper.h" #include "want_params.h" #include "ani_common_want.h" @@ -184,27 +184,27 @@ void GetNotificationRequestByBooleanTwo(ani_env *env, ani_object obj, } bool mbool = false; ani_boolean isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "isCountDown", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetCountdownTimer(mbool); } - if(ANI_OK == GetPropertyBool(env, obj, "isFloatingIcon", isUndefined, 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) + if (ANI_OK == GetPropertyBool(env, obj, "showDeliveryTime", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetShowDeliveryTime(mbool); } - if(ANI_OK == GetPropertyBool(env, obj, "isRemoveAllowed", isUndefined, 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) + if (ANI_OK == GetPropertyBool(env, obj, "forceDistributed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetForceDistributed(mbool); } - if(ANI_OK == GetPropertyBool(env, obj, "notDistributed", isUndefined, mbool) + if (ANI_OK == GetPropertyBool(env, obj, "notDistributed", isUndefined, mbool) && isUndefined == ANI_FALSE) { request->SetNotDistributed(mbool); } @@ -254,33 +254,33 @@ void GetNotificationRequestByNumber(ani_env *env, ani_object obj, } ani_double mDouble = 0.0; ani_boolean isUndefined = ANI_TRUE; - if(ANI_OK == GetPropertyDouble(env, obj, "id", isUndefined, mDouble) && isUndefined == ANI_FALSE) { + 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) + 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) + 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) + 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) + 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) + 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) + if (ANI_OK == GetPropertyDouble(env, obj, "notificationControlFlags", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetNotificationControlFlags(static_cast(mDouble)); } @@ -563,7 +563,7 @@ void GetNotificationActionButtons(ani_env *env, ani_object obj, std::shared_ptr< std::vector> buttons = {}; ani_status status = GetNotificationActionButtonArray(env, obj, "actionButtons", buttons); if (status == ANI_OK) { - for(auto button: buttons) { + for (auto button : buttons) { request->AddActionButton(button); } } @@ -653,7 +653,7 @@ void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, 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) @@ -690,13 +690,13 @@ void GetNotificationBundleOption(ani_env *env, ani_object obj, ani_ref optionRef = {}; ani_boolean isUndefind = ANI_TRUE; status = GetPropertyRef(env, obj, "representativeBundle", isUndefind, optionRef); - if(status != ANI_OK || isUndefind == ANI_TRUE) { + 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)) { + if (ANI_OK == UnwrapBundleOption(env, static_cast(optionRef), option)) { request->SetBundleOption(std::make_shared(option)); } } @@ -705,7 +705,7 @@ ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, std::shared_ptr ¬ificationRequest) { ani_status status = GetNotificationContent(env, obj, notificationRequest); - if(status != ANI_OK) { + if (status != ANI_OK) { return ANI_INVALID_ARGS; } GetNotificationSlotType(env, obj, notificationRequest); @@ -857,10 +857,9 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Not SetPropertyOptionalByDouble(env, object, "id", request->GetNotificationId()); // slotType?: SlotType ani_enum_item slotTypeItem {}; - if(SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { + if (SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { CallSetter(env, cls, object, "notificationSlotType", slotTypeItem); } - // deliveryTime?: number SetPropertyOptionalByDouble(env, object, "id", request->GetDeliveryTime()); // autoDeletedTime?: number @@ -1047,7 +1046,7 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not } } // readonly notificationFlags?: NotificationFlags - std::shared_ptr flags = request->GetFlags(); + std::shared_ptr flags = request->GetFlags(); if (flags) { ani_object flagsObject = nullptr; if (!WarpNotificationFlags(env, flags, flagsObject) || flagsObject == nullptr) { @@ -1076,7 +1075,7 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); if (groupInfo) { ani_object infoObject = nullptr; - if(!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { + if (!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { ANS_LOGE("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); return false; } @@ -1172,13 +1171,14 @@ ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vect for (auto &request : requests) { ani_class requestCls; ani_object requestObj; - if(!WarpNotificationRequest( + 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)){ + 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; } diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 24d9fc14c..8268c2aa0 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -41,11 +41,10 @@ bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &obj } ani_enum_item enumItem = nullptr; NotificationSts::SlotTypeCToEts(env, value, enumItem); - if (enumItem == nullptr) - { + 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", @@ -54,7 +53,9 @@ bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &obj } return true; } -bool WrapNotificationSlotByBoolean(ani_env *env, sptr slot, ani_object &outAniObj) { + +bool WrapNotificationSlotByBoolean(ani_env *env, sptr slot, ani_object &outAniObj) +{ if (!SetPropertyOptionalByBoolean(env, outAniObj, "badgeFlag", slot->IsShowBadge())) { ANS_LOGE("Set badgeFlag fail"); return false; @@ -78,7 +79,8 @@ bool WrapNotificationSlotByBoolean(ani_env *env, sptr slot, ani_object &outAniObj) { +bool WrapNotificationSlotByString(ani_env *env, sptr slot, ani_object &outAniObj) +{ if (!SetPropertyOptionalByString(env, outAniObj, "desc", slot->GetDescription())) { ANS_LOGE("Set desc fail"); return false; @@ -90,7 +92,8 @@ bool WrapNotificationSlotByString(ani_env *env, sptr slot, ani_object &outAniObj) { +bool WrapNotificationSlotByDouble(ani_env *env, sptr slot, ani_object &outAniObj) +{ if (!SetPropertyOptionalByDouble( env, outAniObj, "lockscreenVisibility", static_cast(slot->GetLockScreenVisibleness()))) { ANS_LOGE("Set lockscreenVisibility fail"); @@ -140,8 +143,7 @@ bool WrapNotificationSlot(ani_env *env, sptr slo ANS_LOGE("set String params fail"); return false; } - if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) - { + if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { ANS_LOGE("Set vibrationValues fail"); return false; } @@ -165,11 +167,10 @@ bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &ob return false; } ani_enum_item enumItem = nullptr; - if (!NotificationSts::SlotLevelCToEts(env, value, enumItem) || enumItem == nullptr) - { + if (!NotificationSts::SlotLevelCToEts(env, value, enumItem) || enumItem == nullptr) { ANS_LOGE("get enumItem failed"); 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", diff --git a/frameworks/ets/ani/src/sts_sorting.cpp b/frameworks/ets/ani/src/sts_sorting.cpp index fa2a6ad76..603b6cbd8 100644 --- a/frameworks/ets/ani/src/sts_sorting.cpp +++ b/frameworks/ets/ani/src/sts_sorting.cpp @@ -56,7 +56,8 @@ bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting &so return false; } // readonly ranking: number; - if (ANI_OK != (status = env->Object_SetPropertyByName_Double(obj, "ranking", static_cast(sorting.GetRanking())))) { + 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; } diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp index 4a30751b8..2418ab1b8 100644 --- a/frameworks/ets/ani/src/sts_sorting_map.cpp +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -61,7 +61,7 @@ bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptrObject_CallMethodByName_Void( - recordObj, "$_set", "Lstd/core/Object;Lstd/core/Object;:V", keyString, sortingObj))) { + 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; } diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 67a4938c9..3a55f5f32 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -26,7 +26,7 @@ namespace OHOS { namespace NotificationSts { StsDistributedOperationCallback::StsDistributedOperationCallback(ani_object promise, ani_resolver resolver) -:resolver_(resolver) + : resolver_(resolver) { } @@ -491,174 +491,167 @@ bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::ve } 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; - } + 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; } - - 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; + 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; } - - 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; - } + 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; } - - 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; + 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; } - - 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; + 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); } +} - 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"); + std::string msg = "subscriber is undefine"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return false; } - - 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"); - std::string msg = "subscriber is undefine"; + sptr SubscribeInfo = + new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); + if (!isInfoUndefine) { + if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { + ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); + std::string msg = "UnwarpNotificationSubscribeInfo faild"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return false; } - sptr SubscribeInfo = - new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); - if (!isInfoUndefine) { - if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { - ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); - std::string msg = "UnwarpNotificationSubscribeInfo faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); - return false; - } - } - std::shared_ptr stsSubscriber = nullptr; - if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { - if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { - ANS_LOGD("GetNotificationSubscriber faild"); - std::string msg = "GetNotificationSubscriber faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); - return false; - } - if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { - ANS_LOGD("AddSubscriberInstancesInfo faild"); - std::string msg = "GetNotificationSubscriber faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); - return false; - } + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("GetNotificationSubscriber faild"); + std::string msg = "GetNotificationSubscriber faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); + return false; } - ErrCode status = 0; - if (!isInfoUndefine) { - status = NotificationHelper::SubscribeNotification(stsSubscriber, SubscribeInfo); - } else { - status = NotificationHelper::SubscribeNotification(stsSubscriber); + if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { + ANS_LOGD("AddSubscriberInstancesInfo faild"); + std::string msg = "GetNotificationSubscriber faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); + return false; } + } + ErrCode status = 0; + if (!isInfoUndefine) { + status = NotificationHelper::SubscribeNotification(stsSubscriber, SubscribeInfo); + } else { + status = NotificationHelper::SubscribeNotification(stsSubscriber); + } + if (status != 0) { + 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)) { + return false; + } + std::shared_ptr stsSubscriber = nullptr; + if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { + ANS_LOGD("Subscriber not found"); + // ERR_ANS_INVALID_PARAM + return false; + } + bool ret = AddDeletingSubscriber(stsSubscriber); + if (ret) { + int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); if (status != 0) { 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", + 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); - return false; - } - return true; - } - - bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) - { - ANS_LOGD("enter"); - if (IsUndefine(env, subscriber)) { - return false; - } - std::shared_ptr stsSubscriber = nullptr; - if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { - ANS_LOGD("Subscriber not found"); - // ERR_ANS_INVALID_PARAM - return false; - } - bool ret = AddDeletingSubscriber(stsSubscriber); - if (ret) { - int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); - if (status != 0) { - 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; + DelDeletingSubscriber(stsSubscriber); } - return true; + } 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 GetDoubleValueByClassName(ani_env *env, ani_object param, const char *className, const char *name, ani_double &value) { diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index 3147d559f..1e8a8a7e3 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -44,14 +44,11 @@ bool WarpSubscribeCallbackData( // request: NotificationRequest ani_object requestObj; ani_class requestCls; - if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj)) { + if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj) + || requestObj == nullptr) { ANS_LOGE("WarpNotificationRequest faild"); return false; } - if (requestObj == nullptr) { - ANS_LOGE("requestObj is nullptr"); - return false; - } if (ANI_OK != (status = env->Object_SetPropertyByName_Ref(outObj, "request", requestObj))) { ANS_LOGE("set request faild. status %{public}d", status); return false; @@ -150,7 +147,8 @@ bool WarpSubscribeCallbackDataArray( return true; } -bool WarpEnabledNotificationCallbackData(ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj) +bool WarpEnabledNotificationCallbackData( + ani_env *env, const std::shared_ptr &callbackData, ani_object &outObj) { ANS_LOGD("enter"); if (env == nullptr || callbackData == nullptr) { diff --git a/frameworks/ets/ani/src/sts_template.cpp b/frameworks/ets/ani/src/sts_template.cpp index 031acd5db..b89272242 100644 --- a/frameworks/ets/ani/src/sts_template.cpp +++ b/frameworks/ets/ani/src/sts_template.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "sts_template.h" +#include "sts_template.h" #include "sts_common.h" #include "want_params.h" diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp index 3f6063938..5a1bd9d60 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -102,9 +102,12 @@ void AniSubScribeRegistryInit(ani_env *env) std::array methods = { ani_native_function {"nativeRemove", cRemoveForBundleSignature, reinterpret_cast(AniRemoveForBundle)}, - ani_native_function {"nativeRemove", cRemoveForHashCodeSignature, reinterpret_cast(AniRemoveForHashCode)}, - ani_native_function {"nativeRemove", cRemoveForHashCodesSignature, reinterpret_cast(AniRemoveForHashCodes)}, - ani_native_function {"nativeDistributeOperation", cDistributeOperationSignature, reinterpret_cast(AniDistributeOperation)}, + ani_native_function {"nativeRemove", + cRemoveForHashCodeSignature, reinterpret_cast(AniRemoveForHashCode)}, + ani_native_function {"nativeRemove", + cRemoveForHashCodesSignature, reinterpret_cast(AniRemoveForHashCodes)}, + ani_native_function {"nativeDistributeOperation", + cDistributeOperationSignature, reinterpret_cast(AniDistributeOperation)}, ani_native_function {"nativeSubscribe", cSubscribeSignature, reinterpret_cast(AniSubscribe)}, ani_native_function {"nativeUnSubscribe", cUnSubscribeSignature, reinterpret_cast(AniUnSubscribe)}, }; diff --git a/frameworks/ets/ets/notification/notificationActionButton.ets b/frameworks/ets/ets/notification/notificationActionButton.ets index 509e4a494..c57fda67a 100644 --- a/frameworks/ets/ets/notification/notificationActionButton.ets +++ b/frameworks/ets/ets/notification/notificationActionButton.ets @@ -29,7 +29,7 @@ export interface NotificationActionButton { class NotificationActionButtonInner implements NotificationActionButton { - title: string = ""; + title: string = ''; wantAgent: WantAgent = {}; diff --git a/frameworks/ets/ets/notification/notificationContent.ets b/frameworks/ets/ets/notification/notificationContent.ets index 17286ab57..f2f5eaeaa 100644 --- a/frameworks/ets/ets/notification/notificationContent.ets +++ b/frameworks/ets/ets/notification/notificationContent.ets @@ -288,7 +288,7 @@ class NotificationIconButtonInner implements NotificationIconButton { return image.createPixelMapSync(opts); } - name: string = ""; + name: string = ''; iconResource: IconType = this.CreatePixelMap(); diff --git a/frameworks/ets/ets/notification/notificationUserInput.ets b/frameworks/ets/ets/notification/notificationUserInput.ets index 6ac04f685..96147f320 100644 --- a/frameworks/ets/ets/notification/notificationUserInput.ets +++ b/frameworks/ets/ets/notification/notificationUserInput.ets @@ -18,5 +18,5 @@ export interface NotificationUserInput { } class NotificationUserInputInner implements NotificationUserInput { - inputKey: string = ""; + inputKey: string = ''; } \ No newline at end of file -- Gitee From c55c13c65acc417e1298f5be7b675069222bc56d Mon Sep 17 00:00:00 2001 From: heguokai Date: Wed, 21 May 2025 23:15:18 +0800 Subject: [PATCH 28/52] codex Signed-off-by: heguokai --- .../include/manager/ani_ans_dialog_callback.h | 4 +- .../ets/ani/include/sts_convert_other.h | 3 +- .../ani/include/sts_notification_content.h | 8 +-- frameworks/ets/ani/include/sts_sorting_map.h | 3 +- frameworks/ets/ani/include/sts_subscribe.h | 6 +- frameworks/ets/ani/include/sts_throw_erro.h | 3 +- frameworks/ets/ani/src/manager/ani_cance.cpp | 6 +- .../manager/ani_do_not_disturb_profile.cpp | 6 +- .../src/manager/ani_notification_enable.cpp | 4 +- .../ets/ani/src/manager/ani_publish.cpp | 4 +- .../ani/src/manager/ani_request_enable.cpp | 4 +- frameworks/ets/ani/src/manager/ani_slot.cpp | 20 +++--- frameworks/ets/ani/src/sts_action_button.cpp | 2 +- frameworks/ets/ani/src/sts_bundle_option.cpp | 5 +- frameworks/ets/ani/src/sts_convert_other.cpp | 8 +-- .../ets/ani/src/sts_notification_content.cpp | 62 ++++++++-------- .../ets/ani/src/sts_notification_flag.cpp | 2 +- .../ets/ani/src/sts_notification_manager.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 34 +++++---- frameworks/ets/ani/src/sts_sorting.cpp | 2 +- frameworks/ets/ani/src/sts_sorting_map.cpp | 70 +++++++++++-------- frameworks/ets/ani/src/sts_subscribe.cpp | 17 ++--- frameworks/ets/ani/src/sts_template.cpp | 4 +- frameworks/ets/ani/src/sts_user_input.cpp | 2 +- .../ets/ani/src/subscribe/ani_subscribe.cpp | 2 +- 25 files changed, 146 insertions(+), 137 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h b/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h index 191f6fdc9..9559747e8 100755 --- a/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h +++ b/frameworks/ets/ani/include/manager/ani_ans_dialog_callback.h @@ -27,9 +27,7 @@ namespace OHOS { namespace NotificationManagerSts { using namespace Notification; - -struct EnableNotificationInfo -{ +struct EnableNotificationInfo { int32_t errorCode = ANI_OK; std::string bundleName {""}; bool stageMode = false; diff --git a/frameworks/ets/ani/include/sts_convert_other.h b/frameworks/ets/ani/include/sts_convert_other.h index 91c6ae9b8..2c32dcb83 100644 --- a/frameworks/ets/ani/include/sts_convert_other.h +++ b/frameworks/ets/ani/include/sts_convert_other.h @@ -48,7 +48,8 @@ ani_status GetMapOfPictureInfo(ani_env *env, ani_object obj, 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_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); diff --git a/frameworks/ets/ani/include/sts_notification_content.h b/frameworks/ets/ani/include/sts_notification_content.h index e1902b385..cd6051dbc 100644 --- a/frameworks/ets/ani/include/sts_notification_content.h +++ b/frameworks/ets/ani/include/sts_notification_content.h @@ -39,10 +39,10 @@ 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 + LIVE_VIEW_CREATE = 0, + LIVE_VIEW_INCREMENTAL_UPDATE = 1, + LIVE_VIEW_END = 2, + LIVE_VIEW_FULL_UPDATE = 3 }; class StsLiveViewStatusUtils { diff --git a/frameworks/ets/ani/include/sts_sorting_map.h b/frameworks/ets/ani/include/sts_sorting_map.h index 814d370c2..f8708c996 100644 --- a/frameworks/ets/ani/include/sts_sorting_map.h +++ b/frameworks/ets/ani/include/sts_sorting_map.h @@ -22,7 +22,8 @@ namespace OHOS { namespace NotificationSts { using NotificationSortingMap = OHOS::Notification::NotificationSortingMap; -bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptr &sortingMap, ani_object &outObj); +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 index 46e583aa4..9f948df7e 100644 --- a/frameworks/ets/ani/include/sts_subscribe.h +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -94,10 +94,10 @@ private: std::mutex lock_; }; -class SubscriberInstanceManager -{ +class SubscriberInstanceManager { public: - static SubscriberInstanceManager* GetInstance() { + static SubscriberInstanceManager* GetInstance() + { static SubscriberInstanceManager instance; return &instance; } diff --git a/frameworks/ets/ani/include/sts_throw_erro.h b/frameworks/ets/ani/include/sts_throw_erro.h index 70634972f..6bd3d6d5a 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -66,7 +66,8 @@ inline std::string FindAnsErrMsg(const int32_t errCode) return findMsg->second; } -inline void ThrowStsErroWithLog(ani_env *env, std::string logMsg) { +inline void ThrowStsErroWithMsg(ani_env *env, std::string logMsg) +{ OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); } diff --git a/frameworks/ets/ani/src/manager/ani_cance.cpp b/frameworks/ets/ani/src/manager/ani_cance.cpp index e8a02f0b4..180bedaac 100644 --- a/frameworks/ets/ani/src/manager/ani_cance.cpp +++ b/frameworks/ets/ani/src/manager/ani_cance.cpp @@ -52,7 +52,7 @@ 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::ThrowStsErroWithLog(env, "Label parse failed!"); + NotificationSts::ThrowStsErroWithMsg(env, "Label parse failed!"); return; } @@ -71,7 +71,7 @@ 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::ThrowStsErroWithLog(env, "BundleOption parse failed!"); + NotificationSts::ThrowStsErroWithMsg(env, "BundleOption parse failed!"); return; } @@ -92,7 +92,7 @@ void AniCancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string label) ani_boolean isUndefined = ANI_FALSE; env->Reference_IsUndefined(label, &isUndefined); int32_t ret = -1; - if(isUndefined) { + if (isUndefined) { ANS_LOGE("sts AniCancelWithIdOptinalLabel the label is undefined"); ret = Notification::NotificationHelper::CancelNotification(static_cast(id)); } else { 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 index 8907087ee..0d7158d5f 100644 --- a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -37,8 +37,7 @@ void AniAddDoNotDisturbProfile(ani_env *env, ani_object obj) return; } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniAddDoNotDisturbProfile error, errorCode: %{public}d", externalCode); } @@ -59,8 +58,7 @@ void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj) return; } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniRemoveDoNotDisturbProfile error, errorCode: %{public}d", externalCode); } diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index 823cb00d1..9c987eedc 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -60,7 +60,7 @@ ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bu if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { returncode = Notification::NotificationHelper::IsAllowedNotify(option, allowed); } else { - NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); return ANI_FALSE; } @@ -79,7 +79,7 @@ void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean ANS_LOGD("AniSetNotificationEnable call"); Notification::NotificationBundleOption option; if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { - NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); return ; } std::string deviceId {""}; diff --git a/frameworks/ets/ani/src/manager/ani_publish.cpp b/frameworks/ets/ani/src/manager/ani_publish.cpp index af5506b9a..225be2cd1 100644 --- a/frameworks/ets/ani/src/manager/ani_publish.cpp +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -32,7 +32,7 @@ void AniPublish(ani_env *env, ani_object obj) std::shared_ptr notificationRequest = std::make_shared(); if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { ANS_LOGE("UnWarpNotificationRequest failed"); - NotificationSts::ThrowStsErroWithLog(env, "AniPublish ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "AniPublish ERROR_INTERNAL_ERROR"); return; } int returncode = NotificationHelper::PublishNotification(*notificationRequest); @@ -51,7 +51,7 @@ void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId) std::shared_ptr notificationRequest = std::make_shared(); if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { ANS_LOGE("UnWarpNotificationRequest failed"); - NotificationSts::ThrowStsErroWithLog(env, "AniPublishWithId ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "AniPublishWithId ERROR_INTERNAL_ERROR"); return; } notificationRequest->SetOwnerUserId(static_cast(userId)); diff --git a/frameworks/ets/ani/src/manager/ani_request_enable.cpp b/frameworks/ets/ani/src/manager/ani_request_enable.cpp index 8cb183d83..910cac486 100755 --- a/frameworks/ets/ani/src/manager/ani_request_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_request_enable.cpp @@ -75,9 +75,7 @@ void RequestEnableExecute(std::shared_ptr &info) } else { ANS_LOGD("un stage mode"); std::string deviceId {""}; - info->errorCode = - NotificationHelper::RequestEnableNotification(deviceId, client, - info->callerToken); + info->errorCode = NotificationHelper::RequestEnableNotification(deviceId, client, info->callerToken); } ANS_LOGI("ipcCall done, code is %{public}d.", info->errorCode); } diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index 94a9d7b72..d9ce7326b 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -37,7 +37,7 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { returncode = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); } else { - NotificationSts::ThrowStsErroWithLog(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); return nullptr; } @@ -49,7 +49,7 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) } ani_object outAniObj; if (!NotificationSts::WrapNotificationSlotArray(env, slots, outAniObj)) { - NotificationSts::ThrowStsErroWithLog(env, "GetSlotsByBundle:failed to WrapNotificationSlotArray"); + NotificationSts::ThrowStsErroWithMsg(env, "GetSlotsByBundle:failed to WrapNotificationSlotArray"); return nullptr; } ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", externalCode); @@ -61,12 +61,12 @@ void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enu ANS_LOGD("AniSetNotificationEnableSlot enter "); Notification::NotificationBundleOption option; if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { - NotificationSts::ThrowStsErroWithLog(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); return; } Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; if (!NotificationSts::SlotTypeEtsToC(env, type, slotType)) { - NotificationSts::ThrowStsErroWithLog(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "AniSetNotificationEnableSlot ERROR_INTERNAL_ERROR"); return; } int returncode = 0; @@ -83,15 +83,15 @@ void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enu ANS_LOGD("AniSetNotificationEnableSlot end"); } -void AniSetNotificationEnableSlotWithForce(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, - ani_boolean isForceControl) +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::ThrowStsErroWithLog(env, "SetNotificationEnableSlotWithForce ERROR_INTERNAL_ERROR"); + NotificationSts::ThrowStsErroWithMsg(env, "SetNotificationEnableSlotWithForce ERROR_INTERNAL_ERROR"); return; } int returncode = 0; @@ -113,7 +113,7 @@ ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; if (!NotificationSts::UnwrapBundleOption(env, bundleOption, option) || !NotificationSts::SlotTypeEtsToC(env, type, slotType)) { - NotificationSts::ThrowStsErroWithLog(env, "IsNotificationSlotEnabled : erro arguments."); + NotificationSts::ThrowStsErroWithMsg(env, "IsNotificationSlotEnabled : erro arguments."); return ANI_FALSE; } @@ -132,7 +132,7 @@ ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj) ANS_LOGD("sts getSlotFlagsByBundle call"); Notification::NotificationBundleOption option; if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { - NotificationSts::ThrowStsErroWithLog(env, "AniGetSlotFlagsByBundle : erro arguments."); + NotificationSts::ThrowStsErroWithMsg(env, "AniGetSlotFlagsByBundle : erro arguments."); return ANI_FALSE; } uint32_t slotFlags = 0; @@ -150,7 +150,7 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj) ANS_LOGD("sts setSlotFlagsByBundle call"); Notification::NotificationBundleOption option; if (!NotificationSts::UnwrapBundleOption(env, obj, option)) { - NotificationSts::ThrowStsErroWithLog(env, "AniSetSlotFlagsByBundle : erro arguments."); + NotificationSts::ThrowStsErroWithMsg(env, "AniSetSlotFlagsByBundle : erro arguments."); return; } uint32_t slotFlags = 0; diff --git a/frameworks/ets/ani/src/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index f3d482f47..7b5288f74 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -258,7 +258,7 @@ ani_status GetNotificationActionButtonArray(ani_env *env, ani_object param, } std::shared_ptr button = NotificationActionButton::Create(actionButton.icon, - actionButton.title, actionButton.wantAgent, actionButton.extras, + actionButton.title, actionButton.wantAgent, actionButton.extras, actionButton.semanticActionButton, actionButton.autoCreatedReplies, actionButton.mimeTypeOnlyInputs, actionButton.userInput, actionButton.isContextual); res.push_back(button); diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index d420f0209..4da10d202 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -27,7 +27,7 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification return false; } std::string bundleName; - ani_boolean isUndefined = ANI_ERROR; + 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; @@ -44,7 +44,8 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification return true; } -bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector& options) +bool UnwrapArrayBundleOption(ani_env *env, + ani_ref arrayObj, std::vector& options) { ANS_LOGD("UnwrapArrayBundleOption call"); if (env == nullptr || arrayObj == nullptr) { diff --git a/frameworks/ets/ani/src/sts_convert_other.cpp b/frameworks/ets/ani/src/sts_convert_other.cpp index 12652073b..b316a4859 100644 --- a/frameworks/ets/ani/src/sts_convert_other.cpp +++ b/frameworks/ets/ani/src/sts_convert_other.cpp @@ -53,7 +53,7 @@ ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resourc ani_status status = ANI_ERROR; std::string bundleName = ""; ani_boolean isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, obj, "bundleName", isUndefined, bundleName)) != ANI_OK + if ((status = GetPropertyString(env, obj, "bundleName", isUndefined, bundleName)) != ANI_OK || isUndefined == ANI_TRUE) { return ANI_INVALID_ARGS; } @@ -168,7 +168,7 @@ ani_status GetPixelMapArray(ani_env *env, return status; } -ani_status GetResourceArray(ani_env *env, +ani_status GetResourceArray(ani_env *env, ani_object param, const char *name, std::vector &res) { ANS_LOGD("GetResourceArray call"); @@ -199,7 +199,7 @@ ani_status GetResourceArray(ani_env *env, return status; } ResourceManager::Resource resource; - if(ANI_OK != UnwrapResource(env, static_cast(iconRef), 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; @@ -514,7 +514,7 @@ ani_object GetAniWantAgentArray(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { ANS_LOGE("GetAniWantAgentArray : set WantAgent failed"); return nullptr; - } + } index ++; } ANS_LOGD("GetAniWantAgentArray end"); diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index c437e84b5..1bb4f9172 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -308,7 +308,7 @@ ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, Notificati return status; } -ani_status GetIconButtonArray(ani_env *env, +ani_status GetIconButtonArray(ani_env *env, ani_object param, const char *name, std::vector &res) { ANS_LOGD("GetIconButtonArray call"); @@ -361,7 +361,7 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, ani_boolean isUndefined = ANI_TRUE; // names?: Array if (GetPropertyStringArray(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { - for(auto name: names) { + for (auto name: names) { button.addSingleButtonName(name); } } else { @@ -379,7 +379,7 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, // iconsResource?: Array std::vector resources = {}; if (ANI_OK == GetResourceArray(env, obj, "iconsResource", resources)) { - for(auto res: resources) { + for (auto res : resources) { std::shared_ptr pRes = std::make_shared(res); button.addSingleButtonIconResource(pRes); } @@ -389,7 +389,8 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, ANS_LOGD("UnWarpNotificationLocalLiveViewButton end"); } -bool WarpNotificationLocalLiveViewButton(ani_env *env, const NotificationLocalLiveViewButton &button, ani_object &buttonObject) +bool WarpNotificationLocalLiveViewButton( + ani_env *env, const NotificationLocalLiveViewButton &button, ani_object &buttonObject) { ANS_LOGD("WarpNotificationLocalLiveViewButton call"); if (env == nullptr) { @@ -449,16 +450,16 @@ void UnWarpNotificationCapsuleByOther(ani_env *env, ani_object obj, Notification } ani_boolean isUndefined = ANI_TRUE; ani_ref iconRef = {}; - if (GetPropertyRef(env, obj, "icon", isUndefined, iconRef) == ANI_OK - && isUndefined == ANI_FALSE && iconRef != nullptr) { + 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"); } - } else { - ANS_LOGD("UnWarpNotificationCapsule: get icon ref failed"); } std::vector iconButtons = {}; if (GetIconButtonArray(env, obj, "capsuleButtons", iconButtons) == ANI_OK && !(iconButtons.empty())) { @@ -565,7 +566,7 @@ ani_object GetAniIconButtonArray(ani_env *env, const std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)) { ANS_LOGE("GetAniIconButtonArray: add item failed"); return nullptr; - } + } index ++; } ANS_LOGE("GetAniIconButtonArray end"); @@ -689,7 +690,7 @@ ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationNormalContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, normalContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationNormalContent failed"); return status; @@ -790,7 +791,7 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationPictureContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, pictureContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationPictureContent: get BasicContent failed"); return status; @@ -812,7 +813,7 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, } pictureContent->SetBriefText(briefText); ani_ref pictureRef = {}; - if ((status = GetPropertyRef(env, obj, "picture", isUndefined, pictureRef)) != ANI_OK + 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; @@ -828,7 +829,8 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, } void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, - std::shared_ptr &liveViewContent) { + std::shared_ptr &liveViewContent) +{ ANS_LOGD("UnWarpNotificationLiveViewContentByOther call"); if (env == nullptr || obj == nullptr || liveViewContent == nullptr) { ANS_LOGE("UnWarpNotificationLiveViewContentByOther failed, has nullptr"); @@ -849,7 +851,7 @@ void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo failed"); } else { AAFwk::WantParams wantParams = {}; - if(UnwrapWantParams(env, extraInfoRef, wantParams)) { + if (UnwrapWantParams(env, extraInfoRef, wantParams)) { std::shared_ptr extraInfo = std::make_shared(wantParams); liveViewContent->SetExtraInfo(extraInfo); } else { @@ -860,10 +862,10 @@ void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, isUndefined = ANI_TRUE; if (ANI_OK != GetPropertyRef(env, obj, "pictureInfo", isUndefined, pictureInfoRef) || isUndefined == ANI_TRUE || pictureInfoRef == nullptr) { - ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); + ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo failed"); } else { std::map>> pictureMap; - if(GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { + if (GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { liveViewContent->SetPicture(pictureMap); } else { ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo by ref failed"); @@ -887,7 +889,7 @@ ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, ANS_LOGE("UnWarpNotificationLiveViewContent failed, has nullptr"); return ANI_ERROR; } - ani_status status =ANI_ERROR; + ani_status status = ANI_ERROR; if ((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { ANS_LOGE("UnWarpNotificationLiveViewContent: get BasicContent failed"); return status; @@ -976,9 +978,9 @@ void GetLocalLiveViewContentByTwo(ani_env *env, ani_object obj, ani_ref liveViewTypeRef = {}; if (GetPropertyRef(env, obj, "liveViewType", isUndefined, liveViewTypeRef) == ANI_OK && isUndefined == ANI_FALSE && liveViewTypeRef != nullptr) { - LiveViewTypes liveViewTypes = LiveViewTypes::LIVE_VIEW_ACTIVITY; - if (LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { - localLiveViewContent->SetLiveViewType(liveViewTypes); + 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"); } @@ -1279,9 +1281,8 @@ bool SetNotificationLiveViewContent( } ani_class contentCls; ani_object contentObj; - if (!CreateClassObjByClassName( - env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", contentCls, contentObj) - || contentObj == nullptr) { + if (!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", + contentCls, contentObj) || contentObj == nullptr) { ANS_LOGE("SetNotificationLiveViewContent: create class failed"); return false; } @@ -1307,13 +1308,13 @@ bool SetNotificationLiveViewContent( ANS_LOGD("SetNotificationLiveViewContent: set version failed"); } std::shared_ptr extraInfoData = content->GetExtraInfo(); - if (extraInfoData != nullptr) { + 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"); } - } else { - ANS_LOGD("SetNotificationLiveViewContent: set extraInfo failed"); } ani_object pictureInfoObj = nullptr; if (!GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) @@ -1331,13 +1332,11 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr n return false; } ani_class ncCls; - if (!CreateClassObjByClassName(env, - "Lnotification/notificationContent/NotificationContentInner;", ncCls, ncObj) - || ncObj == nullptr) { + if (!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationContentInner;", + ncCls, ncObj) || ncObj == nullptr) { ANS_LOGE("SetNotificationContent: create class failed"); return false; } - // notificationContentType?: notificationManager.ContentType; ContentType contentType = ncContent->GetContentType(); ani_enum_item contentTypeItem {}; if (!ContentTypeCToEts(env, contentType, contentTypeItem) @@ -1367,7 +1366,6 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr n result = SetNotificationLiveViewContent(env, ncContent, ncObj); break; default: - ANS_LOGE("ContentType is does not exist"); result = false; break; } diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp index 6e14d7490..546561b48 100644 --- a/frameworks/ets/ani/src/sts_notification_flag.cpp +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -26,7 +26,7 @@ bool WarpNotificationFlags(ani_env* env, const std::shared_ptr &request) { + std::shared_ptr &request) +{ ANS_LOGD("GetNotificationRequestByString start"); if (env == nullptr || obj == nullptr || request == nullptr) { ANS_LOGE("GetNotificationRequestByString failed, has nullptr"); @@ -246,7 +247,8 @@ void GetNotificationRequestByString(ani_env *env, ani_object obj, } void GetNotificationRequestByNumber(ani_env *env, ani_object obj, - std::shared_ptr &request) { + std::shared_ptr &request) +{ ANS_LOGD("GetNotificationRequestByNumber start"); if (env == nullptr || obj == nullptr || request == nullptr) { ANS_LOGD("GetNotificationRequestByNumber failed, has nullptr"); @@ -296,7 +298,7 @@ bool GetNotificationNormalContent(ani_env *env, ani_object obj, std::shared_ptr< } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "normal", isUndefined, contentRef) + if (ANI_OK != GetPropertyRef(env, obj, "normal", isUndefined, contentRef) || isUndefined == ANI_TRUE || contentRef == nullptr) { ANS_LOGE("GetNotificationNormalContent get ref failed"); return false; @@ -317,7 +319,7 @@ bool GetNotificationLongTextContent(ani_env *env, ani_object obj, std::shared_pt } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "longText", isUndefined, contentRef) + if (ANI_OK != GetPropertyRef(env, obj, "longText", isUndefined, contentRef) || isUndefined == ANI_TRUE || contentRef == nullptr) { ANS_LOGE("GetNotificationLongTextContent get ref failed"); return false; @@ -339,7 +341,7 @@ bool GetNotificationPictureContent(ani_env *env, ani_object obj, std::shared_ptr } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "picture", isUndefined, contentRef) + if (ANI_OK != GetPropertyRef(env, obj, "picture", isUndefined, contentRef) || isUndefined == ANI_TRUE || contentRef == nullptr) { ANS_LOGE("GetNotificationPictureContent get ref failed"); return false; @@ -361,7 +363,7 @@ bool GetNotificationMultiLineContent(ani_env *env, ani_object obj, std::shared_p } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "multiLine", isUndefined, contentRef) + if (ANI_OK != GetPropertyRef(env, obj, "multiLine", isUndefined, contentRef) || isUndefined == ANI_TRUE || contentRef == nullptr) { ANS_LOGE("GetNotificationMultiLineContent get ref failed"); return false; @@ -383,12 +385,12 @@ bool GetNotificationLocalLiveViewContent(ani_env *env, ani_object obj, std::shar } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "systemLiveView", isUndefined, 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::shared_ptr localLiveView = std::make_shared(); UnWarpNotificationLocalLiveViewContent(env, static_cast(contentRef), localLiveView); request->SetContent(std::make_shared(localLiveView)); @@ -405,7 +407,7 @@ bool GetNotificationLiveViewContent(ani_env *env, ani_object obj, std::shared_pt } ani_boolean isUndefined = ANI_TRUE; ani_ref contentRef = {}; - if (ANI_OK != GetPropertyRef(env, obj, "liveView", isUndefined, contentRef) + if (ANI_OK != GetPropertyRef(env, obj, "liveView", isUndefined, contentRef) || isUndefined == ANI_TRUE || contentRef == nullptr) { ANS_LOGE("GetNotificationLiveViewContent get ref failed"); return false; @@ -426,7 +428,7 @@ bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, ANS_LOGE("GetNotificationContent failed, has nullptr"); return false; } - ANS_LOGD("GetNotificationContent ContentType = %{public}d" , static_cast(outType)); + ANS_LOGD("GetNotificationContent ContentType = %{public}d", static_cast(outType)); switch (outType) { case ContentType::BASIC_TEXT: return GetNotificationNormalContent(env, obj, request); @@ -1002,8 +1004,8 @@ bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, return true; } -bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, - ani_object &object) +bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { ANS_LOGE("request is nullptr"); @@ -1027,7 +1029,8 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Not std::vector> actionButtons = request->GetActionButtons(); if (!actionButtons.empty()) { ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); - if (actionButtonsArrayObj != nullptr && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { + if (actionButtonsArrayObj != nullptr + && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); return false; } @@ -1147,7 +1150,8 @@ ani_object GetAniNotificationRequestArray(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, requestObj)){ + 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; } @@ -1181,7 +1185,7 @@ ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vect != 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; diff --git a/frameworks/ets/ani/src/sts_sorting.cpp b/frameworks/ets/ani/src/sts_sorting.cpp index 603b6cbd8..9d238ce92 100644 --- a/frameworks/ets/ani/src/sts_sorting.cpp +++ b/frameworks/ets/ani/src/sts_sorting.cpp @@ -57,7 +57,7 @@ bool WarpNotificationSorting(ani_env *env, Notification::NotificationSorting &so } // readonly ranking: number; if (ANI_OK != (status = env->Object_SetPropertyByName_Double( - obj, "ranking", static_cast(sorting.GetRanking())))) { + obj, "ranking", static_cast(sorting.GetRanking())))) { ANS_LOGE("set ranking faild. status %{public}d", status); return false; } diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp index 2418ab1b8..e5a434609 100644 --- a/frameworks/ets/ani/src/sts_sorting_map.cpp +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -19,12 +19,45 @@ namespace OHOS { namespace NotificationSts { -bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptr &sortingMap, ani_object &outObj) +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_object arrayObj; ani_status status; if (sortingMap == nullptr || env == nullptr) { ANS_LOGE("invalid parameter value"); @@ -37,41 +70,20 @@ bool WarpNotificationSortingMap(ani_env *env, const std::shared_ptr keys = sortingMap->GetKey(); - for (auto &it : keys) { - Notification::NotificationSorting sorting; - if (sortingMap->GetNotificationSorting(it, sorting)) { - 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; - } - } + 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; } - arrayObj = GetAniStringArrayByVectorString(env, keys); + std::vector keys = sortingMap->GetKey(); + ani_object arrayObj = GetAniStringArrayByVectorString(env, keys); if (arrayObj == nullptr) { ANS_LOGE("WarpVectorStringToSts sortedHashCode faild"); return false; diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 3a55f5f32..09e44f84a 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -572,8 +572,7 @@ bool SubscriberInstanceManager::Subscribe(ani_env *env, ani_object subscriber, a bool isInfoUndefine = IsUndefine(env, info); if (isSubscribeUndefine) { ANS_LOGD("subscriber is undefine"); - std::string msg = "subscriber is undefine"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, "subscriber is undefine"); return false; } sptr SubscribeInfo = @@ -581,8 +580,7 @@ bool SubscriberInstanceManager::Subscribe(ani_env *env, ani_object subscriber, a if (!isInfoUndefine) { if (!UnwarpNotificationSubscribeInfo(env, info, *SubscribeInfo)) { ANS_LOGD("UnwarpNotificationSubscribeInfo faild"); - std::string msg = "UnwarpNotificationSubscribeInfo faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, "UnwarpNotificationSubscribeInfo faild"); return false; } } @@ -590,14 +588,12 @@ bool SubscriberInstanceManager::Subscribe(ani_env *env, ani_object subscriber, a if (!HasNotificationSubscriber(env, subscriber, stsSubscriber)) { if (!GetNotificationSubscriber(env, subscriber, stsSubscriber)) { ANS_LOGD("GetNotificationSubscriber faild"); - std::string msg = "GetNotificationSubscriber faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); return false; } if (!AddSubscriberInstancesInfo(env, stsSubscriber)) { ANS_LOGD("AddSubscriberInstancesInfo faild"); - std::string msg = "GetNotificationSubscriber faild"; - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, msg); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_INTERNAL_ERROR, "GetNotificationSubscriber faild"); return false; } } @@ -653,7 +649,8 @@ bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) return true; } -bool GetDoubleValueByClassName(ani_env *env, ani_object param, const char *className, const char *name, ani_double &value) +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)) { @@ -700,7 +697,7 @@ bool UnWarpNotificationKey(ani_env *env, const ani_object obj, NotificationKey & ani_boolean isUndefined = ANI_TRUE; ani_double idDouble = 0.0; if (!GetDoubleValueByClassName(env, obj, - "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKeyInner;", "id", idDouble)) { + "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKeyInner;", "id", idDouble)) { ANS_LOGD("GetDoubleValueByClassName id fail"); return false; } diff --git a/frameworks/ets/ani/src/sts_template.cpp b/frameworks/ets/ani/src/sts_template.cpp index b89272242..6c4f5fc4f 100644 --- a/frameworks/ets/ani/src/sts_template.cpp +++ b/frameworks/ets/ani/src/sts_template.cpp @@ -31,7 +31,7 @@ ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, Notificat } ani_status status = ANI_ERROR; ani_ref nameRef; - if (ANI_OK != (status = env->Object_CallMethodByName_Ref(aniObj, "name",":Lstd/core/String;", &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; } @@ -46,7 +46,7 @@ ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, Notificat return status; } WantParams wantParams; - if(!UnwrapWantParams(env, dataRef, wantParams)) { + if (!UnwrapWantParams(env, dataRef, wantParams)) { ANS_LOGE("UnwrapWantParams faild"); return ANI_ERROR; } diff --git a/frameworks/ets/ani/src/sts_user_input.cpp b/frameworks/ets/ani/src/sts_user_input.cpp index ec758e74d..1c56a0c66 100644 --- a/frameworks/ets/ani/src/sts_user_input.cpp +++ b/frameworks/ets/ani/src/sts_user_input.cpp @@ -28,7 +28,7 @@ ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, ani_status status = ANI_ERROR; std::string inputKey; ani_boolean isUndefined = ANI_TRUE; - if((status = GetPropertyString(env, param, "inputKey", isUndefined, inputKey)) != ANI_OK + if ((status = GetPropertyString(env, param, "inputKey", isUndefined, inputKey)) != ANI_OK || isUndefined == ANI_TRUE) { ANS_LOGE("GetPropertyString 'inputKey' faild"); return ANI_INVALID_ARGS; diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp index 5a1bd9d60..c25418f5e 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -56,7 +56,7 @@ ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object ANS_LOGE("get distributeOperation object fail"); return nullptr; } - sptr callback + sptr callback = new (std::nothrow) NotificationSts::StsDistributedOperationCallback(aniPromise, aniResolver); if (callback == nullptr) { ANS_LOGE("create callback object fail"); -- Gitee From 8c72909da1c4ae62681ab4f867b08365b84872b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Thu, 22 May 2025 12:06:40 +0800 Subject: [PATCH 29/52] code check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/include/sts_common.h | 21 -- .../ets/ani/src/manager/ani_manager.cpp | 31 +- .../ets/ani/src/sts_notification_content.cpp | 252 ++++++++++----- frameworks/ets/ani/src/sts_request.cpp | 186 +++++++---- frameworks/ets/ani/src/sts_slot.cpp | 26 +- frameworks/ets/ani/src/sts_subscriber.cpp | 104 +++++-- .../ets/ani/src/subscribe/ani_subscribe.cpp | 24 +- .../notification/notificationActionButton.ets | 16 +- .../ets/notification/notificationContent.ets | 292 +++++++++--------- .../ets/notification/notificationFlags.ets | 20 +- .../ets/notification/notificationRequest.ets | 256 +++++++-------- .../ets/ets/notification/notificationSlot.ets | 56 ++-- .../notification/notificationSubscriber.ets | 26 +- .../ets/notification/notificationTemplate.ets | 8 +- .../notification/notificationUserInput.ets | 4 +- 15 files changed, 772 insertions(+), 550 deletions(-) diff --git a/frameworks/ets/ani/include/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 56a34a697..10a56d84a 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -221,27 +221,6 @@ static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T e return false; } -#define RETURN_NULL_IF_NULL(ptr) \ - do { \ - if ((ptr) == nullptr) { \ - ANS_LOGE("ptr is null"); \ - return nullptr; \ - } \ - } while (0) -#define RETURN_FALSE_IF_NULL(ptr) \ - do { \ - if ((ptr) == nullptr) { \ - ANS_LOGE("ptr is null"); \ - return false; \ - } \ - } while (0) -#define RETURN_FALSE_IF_FALSE(condition) \ - do { \ - if (!(condition)) { \ - return false; \ - } \ - } while (0) - } // namespace NotificationSts } // OHOS #endif \ 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 index 755ab662c..88e3a0eb1 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -27,21 +27,7 @@ namespace OHOS { namespace NotificationManagerSts { - -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; - } - std::array kitFunctions = { +static std::array kitManagerFunctions = { ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(AniCancelAll)}, ani_native_function {"nativeCancelWithIdOptionalLabel", nullptr, reinterpret_cast(AniCancelWithIdOptinalLabel)}, @@ -96,7 +82,20 @@ void AniNotificationManagerRegistryInit(ani_env *env) reinterpret_cast(AniRequestEnableNotification)}, }; - status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); +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); } diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index 1bb4f9172..dbd27e9e6 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -828,56 +828,120 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, return status; } -void UnWarpNotificationLiveViewContentByOther(ani_env *env, ani_object obj, - std::shared_ptr &liveViewContent) +bool CheckAniLiveViewContentParam( + ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) { - ANS_LOGD("UnWarpNotificationLiveViewContentByOther call"); - if (env == nullptr || obj == nullptr || liveViewContent == nullptr) { - ANS_LOGE("UnWarpNotificationLiveViewContentByOther failed, has nullptr"); + 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_status status = ANI_ERROR; - ani_boolean isUndefined = ANI_TRUE; ani_double versionAni = 0.0; - if (GetPropertyDouble(env, obj, "version", isUndefined, versionAni) == ANI_OK - && isUndefined == ANI_FALSE) { - liveViewContent->SetVersion(static_cast(versionAni)); - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get version failed"); + 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"); - } else { - AAFwk::WantParams wantParams = {}; - if (UnwrapWantParams(env, extraInfoRef, wantParams)) { - std::shared_ptr extraInfo = std::make_shared(wantParams); - liveViewContent->SetExtraInfo(extraInfo); - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get extraInfo by ref failed"); - } + 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; - isUndefined = ANI_TRUE; + 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"); - } else { - std::map>> pictureMap; - if (GetMapOfPictureInfo(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { - liveViewContent->SetPicture(pictureMap); - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get pictureInfo by ref 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; - if (ANI_OK == GetPropertyBool(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) - && isUndefined == ANI_FALSE) { - liveViewContent->SetIsOnlyLocalUpdate(isLocalUpdateOnly); - } else { - ANS_LOGD("UnWarpNotificationLiveViewContent: get isLocalUpdateOnly failed"); + 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"); } @@ -1198,35 +1262,14 @@ bool SetNotificationMultiLineContent( return SetPropertyByRef(env, ncObj, "multiLine", contentObj); } -bool SetNotificationLocalLiveViewContent( - ani_env* env, std::shared_ptr nContent, ani_object &ncObj) +bool WarpLocalLiveViewContentWithFalg( + ani_env* env, std::shared_ptr nContent, ani_object &contentObj) { - 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; - } 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"); - } - if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { ani_object capsuleObject = nullptr; if (!WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) @@ -1248,11 +1291,6 @@ bool SetNotificationLocalLiveViewContent( ANS_LOGD("SetNotificationMultiLineContent: set cardButtons 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 (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::PROGRESS)) { ani_object progressObject = nullptr; if (!WarpNotificationProgress(env, content->GetProgress(), progressObject) @@ -1268,24 +1306,63 @@ bool SetNotificationLocalLiveViewContent( ANS_LOGD("SetNotificationMultiLineContent: set time failed"); } } - return SetPropertyByRef(env, ncObj, "systemLiveView", contentObj); + return true; } -bool SetNotificationLiveViewContent( + +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("SetNotificationLiveViewContent call"); + ANS_LOGD("SetNotificationMultiLineContent call"); if (env == nullptr || nContent == nullptr || ncObj == nullptr) { - ANS_LOGE("SetNotificationLiveViewContent failed, has nullptr"); + ANS_LOGE("SetNotificationMultiLineContent 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"); + 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"); @@ -1295,6 +1372,21 @@ bool SetNotificationLiveViewContent( 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"); @@ -1321,6 +1413,28 @@ bool SetNotificationLiveViewContent( || 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); } diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 97667ab56..6f5cf801e 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -1004,6 +1004,115 @@ bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, 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_LOGE("SetNotificationRequestByCustom: set extraInfo failed"); + return false; + } + 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_LOGE("SetNotificationRequest set 'actionButtons' faild"); + return false; + } + 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) { + ANS_LOGE("SetNotificationRequest Warp 'template' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "template", templateObject)) { + ANS_LOGE("SetNotificationRequest set 'template' faild"); + return false; + } + 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_LOGE("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); + return false; + } + if (!SetPropertyByRef(env, object, "unifiedGroupInfo", infoObject)) { + ANS_LOGE("SetNotificationRequest set 'unifiedGroupInfo' faild"); + return false; + } + return true; +} + + + bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { @@ -1017,75 +1126,34 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, return false; } // extraInfo?: {[key:string] : any} - std::shared_ptr additionalData = request->GetAdditionalData(); - if (additionalData) { - ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); - if (extraInfo == nullptr || !SetPropertyByRef(env, object, "extraInfo", extraInfo)) { - ANS_LOGE("SetNotificationRequestByCustom: set extraInfo failed"); - return false; - } + if (!SetRequestExtraInfo(env, request, object)) { + ANS_LOGE("set extraInfo faild"); + return false; } // actionButtons?: Array - std::vector> actionButtons = request->GetActionButtons(); - if (!actionButtons.empty()) { - ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); - if (actionButtonsArrayObj != nullptr - && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { - ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); - return false; - } + if (!SetRequestActionButtons(env, request, object)) { + ANS_LOGE("set actionButtons faild"); + return false; } // template?: NotificationTemplate - std::shared_ptr templ = request->GetTemplate(); - if (templ) { - ani_object templateObject = WrapNotificationTemplate(env, templ); - if (templateObject == nullptr) { - ANS_LOGE("SetNotificationRequest Warp 'template' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "template", templateObject)) { - ANS_LOGE("SetNotificationRequest set 'template' faild"); - return false; - } + if (!SetRequestTemplate(env, request, object)) { + ANS_LOGE("set template faild"); + return false; } // readonly notificationFlags?: NotificationFlags - std::shared_ptr flags = request->GetFlags(); - if (flags) { - 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; - } + if (!SetRequestNotificationFlags(env, request, object)) { + ANS_LOGE("set notificationFlags faild"); + return false; } // readonly agentBundle?: agentBundle - std::shared_ptr agentBundle = request->GetAgentBundle(); - if (agentBundle) { - 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; - } + if (!SetRequestAgentBundle(env, request, object)) { + ANS_LOGE("set agentBundle faild"); + return false; } // unifiedGroupInfo?: unifiedGroupInfo - std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); - if (groupInfo) { - ani_object infoObject = nullptr; - if (!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { - ANS_LOGE("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "unifiedGroupInfo", infoObject)) { - ANS_LOGE("SetNotificationRequest set 'unifiedGroupInfo' faild"); - return false; - } + if (!SetRequestUnifiedGroupInfo(env, request, object)) { + ANS_LOGE("set unifiedGroupInfo faild"); + return false; } return true; } diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 8268c2aa0..1059a851d 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -21,17 +21,31 @@ namespace OHOS { namespace NotificationSts { -bool SetOptionalFieldSlotType(ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, - const SlotType value) +bool CheckOptionalFieldSlotTypeParam(const ani_env *env, const ani_class cls, const ani_object &object) +{ + if (env == nullptr) { + ANS_LOGE("env is null"); + return false; + } + if (cls == nullptr) { + ANS_LOGE("cls is null"); + return false; + } + if (object == nullptr) { + ANS_LOGE("object is null"); + 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("WrapNotificationSlot call"); - if (env == nullptr || cls == nullptr) { + if (!CheckOptionalFieldSlotTypeParam(env, cls, object)) { ANS_LOGE("WrapNotificationSlot failed, has nullptr"); return false; } - RETURN_FALSE_IF_NULL(env); - RETURN_FALSE_IF_NULL(cls); - RETURN_FALSE_IF_NULL(object); ani_field field = nullptr; ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); if (status != ANI_OK || field == nullptr) { diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index 1e8a8a7e3..fc0142b74 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -21,27 +21,9 @@ namespace OHOS { namespace NotificationSts { -bool WarpSubscribeCallbackData( - ani_env *env, - const std::shared_ptr &request, - const std::shared_ptr &sortingMap, - int32_t deleteReason, - ani_object &outObj) +bool SetNotificationRequest(ani_env *env, const std::shared_ptr &request, ani_object &outObj) { - ANS_LOGD("enter"); - ani_object sortingMapObj; - ani_status status; - 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 + ani_status status = ANI_OK; ani_object requestObj; ani_class requestCls; if (!WarpNotificationRequest(env, request->GetNotificationRequestPoint().GetRefPtr(), requestCls, requestObj) @@ -53,7 +35,14 @@ bool WarpSubscribeCallbackData( ANS_LOGE("set request faild. status %{public}d", status); return false; } - // sortingMap?: NotificationSortingMap + 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; @@ -62,7 +51,12 @@ bool WarpSubscribeCallbackData( ANS_LOGE("set sortingMap faild. status %{public}d", status); return false; } - // reason?: number + 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) { @@ -74,7 +68,12 @@ bool WarpSubscribeCallbackData( return false; } } - // sound?: string + 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; @@ -86,7 +85,12 @@ bool WarpSubscribeCallbackData( ANS_LOGE("set sound faild. status %{public}d", status); } } - // vibrationValues?: Array + 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(); @@ -96,7 +100,8 @@ bool WarpSubscribeCallbackData( 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])); + 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; @@ -110,6 +115,52 @@ bool WarpSubscribeCallbackData( 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, @@ -178,7 +229,8 @@ bool WarpEnabledNotificationCallbackData( return true; } -bool WarpBadgeNumberCallbackData(ani_env *env, const std::shared_ptr &badgeData, ani_object &outObj) +bool WarpBadgeNumberCallbackData( + ani_env *env, const std::shared_ptr &badgeData, ani_object &outObj) { ANS_LOGD("enter"); if (env == nullptr || badgeData == nullptr) { diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp index c25418f5e..03f5caef5 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -24,20 +24,20 @@ namespace OHOS { namespace NotificationSubScribeSts { -static const char *cRemoveForBundleSignature = +static const char *REMOVE_FOR_BUNDLE_SIGNATURE = "Lnotification/NotificationCommonDef/BundleOption;" "L@ohos/notificationSubscribe/notificationSubscribe/NotificationKey;" "L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; -static const char *cRemoveForHashCodeSignature = +static const char *REMOVE_FOR_HASHCODE_SIGNATURE = "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; -static const char *cRemoveForHashCodesSignature = +static const char *REMOVE_FOR_HASHCODES_SIGNATURE = "Lescompat/Array;L@ohos/notificationSubscribe/notificationSubscribe/RemoveReason;:V"; -static const char *cDistributeOperationSignature = +static const char *DISTRIBUTE_OPERATION_SIGNATURE = "Lstd/core/String;L@ohos/notificationSubscribe/notificationSubscribe/OperationInfo;:Lstd/core/Promise;"; -static const char *cSubscribeSignature = +static const char *SUBSCRIBE_SIGNATURE = "Lnotification/notificationSubscriber/NotificationSubscriber;" "Lnotification/notificationSubscribeInfo/NotificationSubscribeInfo;:V"; -static const char *cUnSubscribeSignature = +static const char *UNSUBSCRIBE_SIGNATURE = "Lnotification/notificationSubscriber/NotificationSubscriber;:V"; ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo) @@ -101,15 +101,15 @@ void AniSubScribeRegistryInit(ani_env *env) } std::array methods = { - ani_native_function {"nativeRemove", cRemoveForBundleSignature, reinterpret_cast(AniRemoveForBundle)}, + ani_native_function {"nativeRemove", REMOVE_FOR_BUNDLE_SIGNATURE, reinterpret_cast(AniRemoveForBundle)}, ani_native_function {"nativeRemove", - cRemoveForHashCodeSignature, reinterpret_cast(AniRemoveForHashCode)}, + REMOVE_FOR_HASHCODE_SIGNATURE, reinterpret_cast(AniRemoveForHashCode)}, ani_native_function {"nativeRemove", - cRemoveForHashCodesSignature, reinterpret_cast(AniRemoveForHashCodes)}, + REMOVE_FOR_HASHCODES_SIGNATURE, reinterpret_cast(AniRemoveForHashCodes)}, ani_native_function {"nativeDistributeOperation", - cDistributeOperationSignature, reinterpret_cast(AniDistributeOperation)}, - ani_native_function {"nativeSubscribe", cSubscribeSignature, reinterpret_cast(AniSubscribe)}, - ani_native_function {"nativeUnSubscribe", cUnSubscribeSignature, reinterpret_cast(AniUnSubscribe)}, + DISTRIBUTE_OPERATION_SIGNATURE, reinterpret_cast(AniDistributeOperation)}, + ani_native_function {"nativeSubscribe", SUBSCRIBE_SIGNATURE, reinterpret_cast(AniSubscribe)}, + ani_native_function {"nativeUnSubscribe", UNSUBSCRIBE_SIGNATURE, reinterpret_cast(AniUnSubscribe)}, }; ANS_LOGD("Start bind native methods to '%{public}s'", npName); diff --git a/frameworks/ets/ets/notification/notificationActionButton.ets b/frameworks/ets/ets/notification/notificationActionButton.ets index c57fda67a..6ae843060 100644 --- a/frameworks/ets/ets/notification/notificationActionButton.ets +++ b/frameworks/ets/ets/notification/notificationActionButton.ets @@ -18,22 +18,22 @@ import { WantAgent } from '@ohos.app.ability.wantAgent'; export interface NotificationActionButton { - title: string; + title: string; - wantAgent: WantAgent; + wantAgent: WantAgent; - extras?: Record; + extras?: Record; - userInput?: NotificationUserInput; + userInput?: NotificationUserInput; } class NotificationActionButtonInner implements NotificationActionButton { - title: string = ''; + public title: string = ''; - wantAgent: WantAgent = {}; + public wantAgent: WantAgent = {}; - extras?: Record | undefined; + public extras?: Record | undefined; - userInput?: NotificationUserInput | 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 index f2f5eaeaa..edd60593c 100644 --- a/frameworks/ets/ets/notification/notificationContent.ets +++ b/frameworks/ets/ets/notification/notificationContent.ets @@ -32,359 +32,359 @@ class RecordTools { export interface NotificationBasicContent { - title: string; + title: string; - text: string; + text: string; - additionalText?: string; + additionalText?: string; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap; } class NotificationBasicContentInner implements NotificationBasicContent { - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string | undefined; + public additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; } export interface NotificationLongTextContent extends NotificationBasicContent { - longText: string; + longText: string; - briefText: string; + briefText: string; - expandedTitle: string; + expandedTitle: string; } class NotificationLongTextContentInner implements NotificationLongTextContent { - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string; + public additionalText?: string; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; - longText: string = ""; + public longText: string = ''; - briefText: string = ""; + public briefText: string = ''; - expandedTitle: string = ""; + public expandedTitle: string = ''; } export enum LiveViewStatus { - LIVE_VIEW_CREATE = 0, + LIVE_VIEW_CREATE = 0, - LIVE_VIEW_INCREMENTAL_UPDATE = 1, + LIVE_VIEW_INCREMENTAL_UPDATE = 1, - LIVE_VIEW_END = 2, + LIVE_VIEW_END = 2, - LIVE_VIEW_FULL_UPDATE = 3 + LIVE_VIEW_FULL_UPDATE = 3 } export enum LiveViewTypes { - LIVE_VIEW_ACTIVITY = 0, + LIVE_VIEW_ACTIVITY = 0, - LIVE_VIEW_INSTANT = 1, + LIVE_VIEW_INSTANT = 1, - LIVE_VIEW_LONG_TERM = 2 + LIVE_VIEW_LONG_TERM = 2 } export interface NotificationLiveViewContent extends NotificationBasicContent { - status: LiveViewStatus; + status: LiveViewStatus; - version?: number; + version?: number; - extraInfo?: Record; + extraInfo?: Record; - pictureInfo?: Record>; + pictureInfo?: Record>; - isLocalUpdateOnly?: boolean; + isLocalUpdateOnly?: boolean; } class NotificationLiveViewContentInner implements NotificationLiveViewContent { - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string | undefined; + public additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; - status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; + public status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; - version?: number | undefined; + public version?: number | undefined; - extraInfo?: Record | undefined; + public extraInfo?: Record | undefined; - pictureInfo?: Record> | undefined; + public pictureInfo?: Record> | undefined; - isLocalUpdateOnly?: boolean | undefined; + public isLocalUpdateOnly?: boolean | undefined; } export interface NotificationMultiLineContent extends NotificationBasicContent { - briefText: string; + briefText: string; - longTitle: string; + longTitle: string; - lines: Array; + lines: Array; } class NotificationMultiLineContentInner implements NotificationMultiLineContent { - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string | undefined; + public additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; - briefText: string = ""; + public briefText: string = ''; - longTitle: string = ""; + public longTitle: string = ''; - lines: Array = {}; + public lines: Array = {}; } export interface NotificationPictureContent extends NotificationBasicContent { - briefText: string; + briefText: string; - expandedTitle: string; + expandedTitle: string; - picture: image.PixelMap; + picture: image.PixelMap; } class NotificationPictureContentInner implements NotificationPictureContent { - private CreatePixelMap() : image.PixelMap { - let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } - return image.createPixelMapSync(opts); - } + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string | undefined; + public additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; - briefText: string = ""; + public briefText: string = ''; - expandedTitle: string = ""; + public expandedTitle: string = ''; - picture: image.PixelMap = this.CreatePixelMap(); + public picture: image.PixelMap = this.CreatePixelMap(); } export interface NotificationSystemLiveViewContent extends NotificationBasicContent { - typeCode: number; + typeCode: number; - capsule?: NotificationCapsule; + capsule?: NotificationCapsule; - button?: NotificationButton; + button?: NotificationButton; - cardButtons?: Array; + cardButtons?: Array; - time?: NotificationTime; + time?: NotificationTime; - progress?: NotificationProgress; + progress?: NotificationProgress; - liveViewType?: LiveViewTypes; + liveViewType?: LiveViewTypes; } class NotificationSystemLiveViewContentInner implements NotificationSystemLiveViewContent { - private CreatePixelMap() : image.PixelMap { - let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } - return image.createPixelMapSync(opts); - } + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } - title: string = ""; + public title: string = ''; - text: string = ""; + public text: string = ''; - additionalText?: string | undefined; + public additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap | undefined; + public lockscreenPicture?: image.PixelMap | undefined; - briefText: string = ""; + public briefText: string = ''; - expandedTitle: string = ""; + public expandedTitle: string = ''; - picture: image.PixelMap = this.CreatePixelMap(); + public picture: image.PixelMap = this.CreatePixelMap(); - typeCode: number = 0; + public typeCode: number = 0; - capsule?: NotificationCapsule | undefined; + public capsule?: NotificationCapsule | undefined; - button?: NotificationButton | undefined; + public button?: NotificationButton | undefined; - cardButtons?: Array | undefined; + public cardButtons?: Array | undefined; - time?: NotificationTime | undefined; + public time?: NotificationTime | undefined; - progress?: NotificationProgress | undefined; + public progress?: NotificationProgress | undefined; - liveViewType?: LiveViewTypes | undefined; + public liveViewType?: LiveViewTypes | undefined; } export interface NotificationCapsule { - title?: string; + title?: string; - icon?: image.PixelMap; + icon?: image.PixelMap; - backgroundColor?: string; + backgroundColor?: string; - content?: string; + content?: string; - time?: number; + time?: number; - capsuleButtons?: Array; + capsuleButtons?: Array; } class NotificationCapsuleInner implements NotificationCapsule { - title?: string | undefined; + public title?: string | undefined; - icon?: image.PixelMap | undefined; + public icon?: image.PixelMap | undefined; - backgroundColor?: string | undefined; + public backgroundColor?: string | undefined; - content?: string | undefined; + public content?: string | undefined; - time?: number | undefined; + public time?: number | undefined; - capsuleButtons?: Array | undefined; + public capsuleButtons?: Array | undefined; } export interface NotificationIconButton { - name: string; + name: string; - iconResource: IconType; + iconResource: IconType; - text?: string; + text?: string; - hidePanel?: boolean; + hidePanel?: boolean; } class NotificationIconButtonInner implements NotificationIconButton { - private CreatePixelMap() : image.PixelMap { - let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } - return image.createPixelMapSync(opts); - } + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } + return image.createPixelMapSync(opts); + } - name: string = ''; + public name: string = ''; - iconResource: IconType = this.CreatePixelMap(); + public iconResource: IconType = this.CreatePixelMap(); - text?: string | undefined; + public text?: string | undefined; - hidePanel?: boolean | undefined; + public hidePanel?: boolean | undefined; } export interface NotificationButton { - names?: Array; + names?: Array; - icons?: Array; + icons?: Array; - iconsResource?: Array; + iconsResource?: Array; } class NotificationButtonInner implements NotificationButton { - names?: Array | undefined; + public names?: Array | undefined; - icons?: Array | undefined; + public icons?: Array | undefined; - iconsResource?: Array | undefined; + public iconsResource?: Array | undefined; } export interface NotificationTime { - initialTime?: number; + initialTime?: number; - isCountDown?: boolean; + isCountDown?: boolean; - isPaused?: boolean; + isPaused?: boolean; - isInTitle?: boolean; + isInTitle?: boolean; } class NotificationTimeInner implements NotificationTime { - initialTime?: number | undefined; + public initialTime?: number | undefined; - isCountDown?: boolean | undefined; + public isCountDown?: boolean | undefined; - isPaused?: boolean | undefined; + public isPaused?: boolean | undefined; - isInTitle?: boolean | undefined; + public isInTitle?: boolean | undefined; } export interface NotificationProgress { - maxValue?: number; + maxValue?: number; - currentValue?: number; + currentValue?: number; - isPercentage?: boolean; + isPercentage?: boolean; } class NotificationProgressInner implements NotificationProgress { - maxValue?: number | undefined; + public maxValue?: number | undefined; - currentValue?: number | undefined; + public currentValue?: number | undefined; - isPercentage?: boolean | undefined; + public isPercentage?: boolean | undefined; } export interface NotificationContent { - notificationContentType?: notificationManager.ContentType; + notificationContentType?: notificationManager.ContentType; - normal?: NotificationBasicContent; + normal?: NotificationBasicContent; - longText?: NotificationLongTextContent; + longText?: NotificationLongTextContent; - multiLine?: NotificationMultiLineContent; + multiLine?: NotificationMultiLineContent; - picture?: NotificationPictureContent; + picture?: NotificationPictureContent; - systemLiveView?: NotificationSystemLiveViewContent; + systemLiveView?: NotificationSystemLiveViewContent; - liveView?: NotificationLiveViewContent; + liveView?: NotificationLiveViewContent; } class NotificationContentInner implements NotificationContent { - notificationContentType?: notificationManager.ContentType | undefined; + public notificationContentType?: notificationManager.ContentType | undefined; - normal?: NotificationBasicContent | undefined; + public normal?: NotificationBasicContent | undefined; - longText?: NotificationLongTextContent | undefined; + public longText?: NotificationLongTextContent | undefined; - multiLine?: NotificationMultiLineContent | undefined; + public multiLine?: NotificationMultiLineContent | undefined; - picture?: NotificationPictureContent | undefined; + public picture?: NotificationPictureContent | undefined; - systemLiveView?: NotificationSystemLiveViewContent | undefined; + public systemLiveView?: NotificationSystemLiveViewContent | undefined; - liveView?: NotificationLiveViewContent | 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 index e5480471a..e090d8d72 100644 --- a/frameworks/ets/ets/notification/notificationFlags.ets +++ b/frameworks/ets/ets/notification/notificationFlags.ets @@ -13,29 +13,29 @@ * limitations under the License. */ - export enum NotificationFlagStatus { +export enum NotificationFlagStatus { - TYPE_NONE = 0, + TYPE_NONE = 0, - TYPE_OPEN = 1, + TYPE_OPEN = 1, - TYPE_CLOSE = 2 + TYPE_CLOSE = 2 } export interface NotificationFlags { - readonly soundEnabled?: NotificationFlagStatus; + readonly soundEnabled?: NotificationFlagStatus; - readonly vibrationEnabled?: NotificationFlagStatus; + readonly vibrationEnabled?: NotificationFlagStatus; - readonly reminderFlags?: number; + readonly reminderFlags?: number; } class NotificationFlagsInner implements NotificationFlags { - soundEnabled?: NotificationFlagStatus | undefined; + public soundEnabled?: NotificationFlagStatus | undefined; - vibrationEnabled?: NotificationFlagStatus| undefined; + public vibrationEnabled?: NotificationFlagStatus| undefined; - reminderFlags?: number | 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 index 493450a41..b966d0b6f 100644 --- a/frameworks/ets/ets/notification/notificationRequest.ets +++ b/frameworks/ets/ets/notification/notificationRequest.ets @@ -23,159 +23,159 @@ import { WantAgent } from '@ohos.app.ability.wantAgent'; import { BundleOption } from 'notification.NotificationCommonDef'; export interface DistributedOptions { - isDistributed?: boolean; - supportDisplayDevices?: Array; - supportOperateDevices?: Array; - readonly remindType?: number; + isDistributed?: boolean; + supportDisplayDevices?: Array; + supportOperateDevices?: Array; + readonly remindType?: number; } class DistributedOptionsInner implements DistributedOptions { - isDistributed?: boolean | undefined; - supportDisplayDevices?: Array | undefined; - supportOperateDevices?: Array | undefined; - readonly remindType?: number | undefined; + 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; + bundle: BundleOption; + notificationKey: notificationSubscribe.NotificationKey; + extraInfoKeys?: Array; } class NotificationFilterInner implements NotificationFilter { - bundle: BundleOption = {}; - notificationKey: notificationSubscribe.NotificationKey = {}; - extraInfoKeys?: Array | undefined; + public bundle: BundleOption = {}; + public notificationKey: notificationSubscribe.NotificationKey = {}; + public extraInfoKeys?: Array | undefined; } export interface NotificationCheckRequest { - contentType: notificationManager.ContentType; - slotType: notificationManager.SlotType; - extraInfoKeys: Array; + contentType: notificationManager.ContentType; + slotType: notificationManager.SlotType; + extraInfoKeys: Array; } class NotificationCheckRequestInner implements NotificationCheckRequest { - contentType: notificationManager.ContentType = notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; - slotType: notificationManager.SlotType = notificationManager.SlotType.OTHER_TYPES; - extraInfoKeys: Array = {}; + 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; + key?: string; + title?: string; + content?: string; + sceneName?: string; + extraInfo?: Record; } class UnifiedGroupInfoInner implements UnifiedGroupInfo { - key?: string | undefined; - title?: string | undefined; - content?: string | undefined; - sceneName?: string | undefined; - extraInfo?: Record | undefined; + 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; - readonly creatorInstanceKey?: 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; + 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; + readonly creatorInstanceKey?: 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 { - content: NotificationContent = {}; - id?: number | undefined; - appMessageId?: string | undefined; - notificationSlotType?: notificationManager.SlotType | undefined; - isOngoing?: boolean | undefined; - isUnremovable?: boolean | undefined; - updateOnly?: boolean | undefined; - deliveryTime?: number | undefined; - tapDismissed?: boolean | undefined; - autoDeletedTime?: number | undefined; - wantAgent?: WantAgent | undefined; - extraInfo?: Record | undefined; - color?: number | undefined; - colorEnabled?: boolean | undefined; - isAlertOnce?: boolean | undefined; - isStopwatch?: boolean | undefined; - isCountDown?: boolean | undefined; - isFloatingIcon?: boolean | undefined; - label?: string | undefined; - badgeIconStyle?: number | undefined; - showDeliveryTime?: boolean | undefined; - actionButtons?: Array | undefined; - smallIcon?: image.PixelMap | undefined; - largeIcon?: image.PixelMap | undefined; - overlayIcon?: image.PixelMap | undefined; - groupName?: string | undefined; - readonly creatorBundleName?: string | undefined; - readonly creatorUid?: number | undefined; - readonly creatorPid?: number | undefined; - readonly creatorUserId?: number | undefined; - readonly creatorInstanceKey?: number | undefined; - sound?: string | undefined; - classification?: string | undefined; - readonly hashCode?: string | undefined; - isRemoveAllowed?: boolean | undefined; - readonly source?: number | undefined; - template?: NotificationTemplate | undefined; - distributedOption?: DistributedOptions | undefined; - readonly deviceId?: string | undefined; - readonly notificationFlags?: NotificationFlags | undefined; - removalWantAgent?: WantAgent | undefined; - badgeNumber?: number | undefined; - representativeBundle?: BundleOption | undefined; - readonly agentBundle?: BundleOption | undefined; - unifiedGroupInfo?: UnifiedGroupInfo | undefined; - notificationControlFlags?: number | undefined; - readonly appInstanceKey?: string | undefined; - forceDistributed?: boolean | undefined; - notDistributed?: boolean | undefined; + 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 readonly creatorInstanceKey?: 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 index 4b3c3c769..6cca29daf 100644 --- a/frameworks/ets/ets/notification/notificationSlot.ets +++ b/frameworks/ets/ets/notification/notificationSlot.ets @@ -15,35 +15,35 @@ 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; + 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 { - 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; + 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/notificationSubscriber.ets b/frameworks/ets/ets/notification/notificationSubscriber.ets index be7f25257..62aef5c5d 100644 --- a/frameworks/ets/ets/notification/notificationSubscriber.ets +++ b/frameworks/ets/ets/notification/notificationSubscriber.ets @@ -41,8 +41,6 @@ export interface NotificationSubscriber { onDestroy?: () => void; - // // onDoNotDisturbDateChange?: (mode: notification.DoNotDisturbDate) => void; - onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; @@ -55,29 +53,27 @@ export interface NotificationSubscriber { } export class NotificationSubscriberInner implements NotificationSubscriber { - onConsume?: (data: SubscribeCallbackData) => void; + public onConsume?: (data: SubscribeCallbackData) => void; - onCancel?: (data: SubscribeCallbackData) => void; + public onCancel?: (data: SubscribeCallbackData) => void; - onUpdate?: (data: NotificationSortingMap) => void; + public onUpdate?: (data: NotificationSortingMap) => void; - onConnect?: () => void; + public onConnect?: () => void; - onDisconnect?: () => void; + public onDisconnect?: () => void; - onDestroy?: () => void; + public onDestroy?: () => void; - // // onDoNotDisturbDateChange?: (mode: notification.DoNotDisturbDate) => void; + public onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; - onDoNotDisturbChanged?: (mode: notificationManager.DoNotDisturbDate) => void; - - onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; + public onEnabledNotificationChanged?: (callbackData: EnabledNotificationCallbackData) => void; - onBadgeChanged?: (data: BadgeNumberCallbackData) => void; + public onBadgeChanged?: (data: BadgeNumberCallbackData) => void; - onBadgeEnabledChanged?: BadgeEnabledChangedCallback; + public onBadgeEnabledChanged?: BadgeEnabledChangedCallback; - onBatchCancel?: (data: Array) => void; + public onBatchCancel?: (data: Array) => void; } export interface SubscribeCallbackData { diff --git a/frameworks/ets/ets/notification/notificationTemplate.ets b/frameworks/ets/ets/notification/notificationTemplate.ets index 8033b7723..1adf3a296 100644 --- a/frameworks/ets/ets/notification/notificationTemplate.ets +++ b/frameworks/ets/ets/notification/notificationTemplate.ets @@ -14,11 +14,11 @@ */ export interface NotificationTemplate { - name: string; - data: Record; + name: string; + data: Record; } class NotificationTemplateInner implements NotificationTemplate { - name: string = ""; - data: Record = {}; + 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 index 96147f320..0b220dc01 100644 --- a/frameworks/ets/ets/notification/notificationUserInput.ets +++ b/frameworks/ets/ets/notification/notificationUserInput.ets @@ -14,9 +14,9 @@ */ export interface NotificationUserInput { - inputKey: string; + inputKey: string; } class NotificationUserInputInner implements NotificationUserInput { - inputKey: string = ''; + public inputKey: string = ''; } \ No newline at end of file -- Gitee From f433b8af4a603b12cc156072e912d8feab1d1154 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Thu, 22 May 2025 12:49:34 +0800 Subject: [PATCH 30/52] code check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- .../ets/ani/src/manager/ani_manager.cpp | 98 +++++++++---------- .../ets/ani/src/sts_notification_content.cpp | 39 ++++++-- frameworks/ets/ani/src/sts_request.cpp | 8 +- .../ets/notification/notificationRequest.ets | 3 +- 4 files changed, 83 insertions(+), 65 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 88e3a0eb1..4cc8d56c2 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -28,59 +28,51 @@ 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 {"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)}, +}; void AniNotificationManagerRegistryInit(ani_env *env) { diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index dbd27e9e6..96fc4cbc6 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -1262,14 +1262,8 @@ bool SetNotificationMultiLineContent( return SetPropertyByRef(env, ncObj, "multiLine", contentObj); } -bool WarpLocalLiveViewContentWithFalg( - ani_env* env, std::shared_ptr nContent, ani_object &contentObj) +void SetCapsule(ani_env *env, std::shared_ptr &content, ani_object &contentObj) { - auto content = std::reinterpret_pointer_cast(nContent->GetNotificationContent()); - if (content == nullptr) { - ANS_LOGE("SetNotificationMultiLineContent: get LocalLiveViewContent failed"); - return false; - } if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { ani_object capsuleObject = nullptr; if (!WarpNotificationCapsule(env, content->GetCapsule(), capsuleObject) @@ -1277,6 +1271,10 @@ bool WarpLocalLiveViewContentWithFalg( 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) @@ -1284,6 +1282,10 @@ bool WarpLocalLiveViewContentWithFalg( 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); @@ -1291,6 +1293,10 @@ bool WarpLocalLiveViewContentWithFalg( 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) @@ -1298,6 +1304,10 @@ bool WarpLocalLiveViewContentWithFalg( 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; @@ -1306,6 +1316,21 @@ bool WarpLocalLiveViewContentWithFalg( 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; } diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 6f5cf801e..a917b3e9d 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -1054,7 +1054,8 @@ bool SetRequestTemplate(ani_env *env, const OHOS::Notification::NotificationRequ return true; } -bool SetRequestNotificationFlags(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +bool SetRequestNotificationFlags( + ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) { std::shared_ptr flags = request->GetFlags(); if (flags == nullptr) { @@ -1092,7 +1093,8 @@ bool SetRequestAgentBundle(ani_env *env, const OHOS::Notification::NotificationR return true; } -bool SetRequestUnifiedGroupInfo(ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) +bool SetRequestUnifiedGroupInfo( + ani_env *env, const OHOS::Notification::NotificationRequest *request, ani_object &object) { std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); if (groupInfo == nullptr) { @@ -1111,8 +1113,6 @@ bool SetRequestUnifiedGroupInfo(ani_env *env, const OHOS::Notification::Notifica return true; } - - bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { diff --git a/frameworks/ets/ets/notification/notificationRequest.ets b/frameworks/ets/ets/notification/notificationRequest.ets index b966d0b6f..5b1993bd1 100644 --- a/frameworks/ets/ets/notification/notificationRequest.ets +++ b/frameworks/ets/ets/notification/notificationRequest.ets @@ -55,7 +55,8 @@ export interface NotificationCheckRequest { } class NotificationCheckRequestInner implements NotificationCheckRequest { - public contentType: notificationManager.ContentType = notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + public contentType: notificationManager.ContentType = + notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; public slotType: notificationManager.SlotType = notificationManager.SlotType.OTHER_TYPES; public extraInfoKeys: Array = {}; } -- Gitee From 3f999cc76ad55d937807c8318cabcdd1bf7c16ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Fri, 23 May 2025 09:40:54 +0800 Subject: [PATCH 31/52] some modify MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/src/sts_request.cpp | 2 +- frameworks/ets/ani/src/sts_subscribe.cpp | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index a917b3e9d..60248ca6a 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -863,7 +863,7 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Not CallSetter(env, cls, object, "notificationSlotType", slotTypeItem); } // deliveryTime?: number - SetPropertyOptionalByDouble(env, object, "id", request->GetDeliveryTime()); + SetPropertyOptionalByDouble(env, object, "deliveryTime", request->GetDeliveryTime()); // autoDeletedTime?: number SetPropertyOptionalByDouble(env, object, "autoDeletedTime", request->GetAutoDeletedTime()); // color ?: number diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 09e44f84a..066a63e85 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -620,12 +620,16 @@ 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"); - // ERR_ANS_INVALID_PARAM + 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); -- Gitee From b92ae9eac1602abc311d9a1523e69ec8525537c8 Mon Sep 17 00:00:00 2001 From: heguokai Date: Fri, 23 May 2025 16:44:30 +0800 Subject: [PATCH 32/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_request.cpp | 178 ++++++------------ .../ets/ets/@ohos.notificationManager.ets | 154 ++++++++------- 2 files changed, 144 insertions(+), 188 deletions(-) diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 60248ca6a..2d6e9c0e9 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -31,6 +31,7 @@ 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"); @@ -229,15 +230,24 @@ void GetNotificationRequestByString(ani_env *env, ani_object obj, 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) { @@ -751,53 +761,43 @@ bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notif } // isOngoing?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isOngoing", request->IsInProgress())) { - ANS_LOGE("SetNotificationRequest set 'isOngoing' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isOngoing' faild"); } // isUnremovable?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isUnremovable", request->IsUnremovable())) { - ANS_LOGE("SetNotificationRequest set 'isUnremovable' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isUnremovable' faild"); } // tapDismissed?: boolean if (!SetPropertyOptionalByBoolean(env, object, "tapDismissed", request->IsTapDismissed())) { - ANS_LOGE("SetNotificationRequest set 'tapDismissed' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'tapDismissed' faild"); } // colorEnabled?: boolean if (!SetPropertyOptionalByBoolean(env, object, "colorEnabled", request->IsColorEnabled())) { - ANS_LOGE("SetNotificationRequest set 'colorEnabled' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'colorEnabled' faild"); } // isAlertOnce?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isAlertOnce", request->IsAlertOneTime())) { - ANS_LOGE("SetNotificationRequest set 'isAlertOnce' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isAlertOnce' faild"); } // isStopwatch?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isStopwatch", request->IsShowStopwatch())) { - ANS_LOGE("SetNotificationRequest set 'isStopwatch' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isStopwatch' faild"); } // isCountDown?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isCountDown", request->IsCountdownTimer())) { - ANS_LOGE("SetNotificationRequest set 'isCountDown' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isCountDown' faild"); } // isFloatingIcon?: boolean if (!SetPropertyOptionalByBoolean(env, object, "isFloatingIcon", request->IsFloatingIcon())) { - ANS_LOGE("SetNotificationRequest set 'isFloatingIcon' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'isFloatingIcon' faild"); } // showDeliveryTime?: boolean if (!SetPropertyOptionalByBoolean(env, object, "showDeliveryTime", request->IsShowDeliveryTime())) { - ANS_LOGE("SetNotificationRequest set 'showDeliveryTime' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'showDeliveryTime' faild"); } // updateOnly?: boolean if (!SetPropertyOptionalByBoolean(env, object, "updateOnly", request->IsUpdateOnly())) { - ANS_LOGE("SetNotificationRequest set 'updateOnly' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'updateOnly' faild"); } return true; } @@ -810,40 +810,29 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Not return false; } // classification?: string - std::string value = request->GetClassification(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "classification", value)) { - ANS_LOGE("SetNotificationRequest set '' faild"); - return false; + std::string str = request->GetClassification(); + if (!SetPropertyOptionalByString(env, object, "classification", request->GetClassification())) { + ANS_LOGD("SetNotificationRequest set '' faild"); } // label?: string - value = request->GetLabel(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "label", value)) { - ANS_LOGE("SetNotificationRequest set 'label' faild"); - return false; + if (!SetPropertyOptionalByString(env, object, "label", request->GetLabel())) { + ANS_LOGD("SetNotificationRequest set 'label' faild"); } // groupName?: string - value = request->GetGroupName(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "groupName", value)) { - ANS_LOGE("SetNotificationRequest set 'groupName' faild"); - return false; + if (!SetPropertyOptionalByString(env, object, "groupName", request->GetGroupName())) { + ANS_LOGD("SetNotificationRequest set 'groupName' faild"); } // readonly creatorBundleName?: string - value = request->GetCreatorBundleName(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "creatorBundleName", value)) { - ANS_LOGE("SetNotificationRequest set 'creatorBundleName' faild"); - return false; + if (!SetPropertyOptionalByString(env, object, "creatorBundleName", request->GetCreatorBundleName())) { + ANS_LOGD("SetNotificationRequest set 'creatorBundleName' faild"); } // readonly sound?: string - value = request->GetSound(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "sound", value)) { - ANS_LOGE("SetNotificationRequest set 'sound' faild"); - return false; + if (!SetPropertyOptionalByString(env, object, "sound", request->GetSound())) { + ANS_LOGD("SetNotificationRequest set 'sound' faild"); } // readonly appInstanceKey?: string - value = request->GetAppInstanceKey(); - if (!value.empty() && !SetPropertyOptionalByString(env, object, "appInstanceKey", value)) { - ANS_LOGE("SetNotificationRequest set 'appInstanceKey' faild"); - return false; + if (!SetPropertyOptionalByString(env, object, "appInstanceKey", request->GetAppInstanceKey())) { + ANS_LOGD("SetNotificationRequest set 'appInstanceKey' faild"); } return true; } @@ -893,39 +882,24 @@ bool SetNotificationRequestByWantAgent(ani_env* env, ani_class cls, std::shared_ptr agent = request->GetWantAgent(); if (agent) { ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); - if (wantAgent == nullptr) { - ANS_LOGE("SetNotificationRequest Wrap 'wantAgent' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "wantAgent", wantAgent)) { - ANS_LOGE("SetNotificationRequest set 'wantAgent' faild"); - return false; + 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) { - ANS_LOGE("SetNotificationRequest Wrap 'removalWantAgent' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "removalWantAgent", wantAgent)) { - ANS_LOGE("SetNotificationRequest set 'removalWantAgent' faild"); - return false; + 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) { - ANS_LOGE("SetNotificationRequest Wrap 'maxScreenWantAgent' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "maxScreenWantAgent", wantAgent)) { - ANS_LOGE("SetNotificationRequest set 'maxScreenWantAgent' faild"); - return false; + if (wantAgent == nullptr || !SetPropertyByRef(env, object, "maxScreenWantAgent", wantAgent)) { + ANS_LOGD("SetNotificationRequest set 'maxScreenWantAgent' faild"); } } return true; @@ -942,39 +916,24 @@ bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const Notific std::shared_ptr littleIcon = request->GetLittleIcon(); if (littleIcon) { ani_object smallIconResult = CreateAniPixelMap(env, littleIcon); - if (smallIconResult == nullptr) { - ANS_LOGE("CreatePixelMap failed, smallIconResult is nullptr "); - return false; - } - if (!SetPropertyByRef(env, object, "smallIcon", smallIconResult)) { - ANS_LOGE("SetNotificationRequest set 'smallIcon' faild"); - return false; + 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) { - ANS_LOGE("CreatePixelMap failed, largeIconResult is nullptr"); - return false; - } - if (!SetPropertyByRef(env, object, "largeIcon", largeIconResult)) { - ANS_LOGE("SetNotificationRequest set 'largeIcon' faild"); - return false; + 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) { - ANS_LOGE("CreatePixelMap failed, overlayIconResult is nullptr"); - return false; - } - if (!SetPropertyByRef(env, object, "overlayIcon", overlayIconResult)) { - ANS_LOGE("SetNotificationRequest set 'overlayIcon' faild"); - return false; + if (overlayIconResult == nullptr || !SetPropertyByRef(env, object, "overlayIcon", overlayIconResult)) { + ANS_LOGD("SetNotificationRequest set 'overlayIcon' faild"); } } return true; @@ -990,15 +949,15 @@ bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, std::shared_ptr content = request->GetContent(); ani_object contentObj; if (!SetNotificationContent(env, content, contentObj)) { - ANS_LOGE("SetNotificationContent faild"); + ANS_LOGD("SetNotificationContent faild"); return false; } if (contentObj == nullptr) { - ANS_LOGE("contentObj is nullptr"); + ANS_LOGD("contentObj is nullptr"); return false; } if (!SetPropertyByRef(env, object, "content", contentObj)) { - ANS_LOGE("SetNotificationRequestByNotificationContent. set content faild"); + ANS_LOGD("SetNotificationRequestByNotificationContent. set content faild"); return false; } return true; @@ -1013,8 +972,7 @@ bool SetRequestExtraInfo(ani_env *env, const OHOS::Notification::NotificationReq } ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); if (extraInfo == nullptr || !SetPropertyByRef(env, object, "extraInfo", extraInfo)) { - ANS_LOGE("SetNotificationRequestByCustom: set extraInfo failed"); - return false; + ANS_LOGD("SetNotificationRequestByCustom: set extraInfo failed"); } return true; } @@ -1027,10 +985,9 @@ bool SetRequestActionButtons(ani_env *env, const OHOS::Notification::Notificatio return true; } ani_object actionButtonsArrayObj = GetAniArrayNotificationActionButton(env, actionButtons); - if (actionButtonsArrayObj != nullptr - && !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { - ANS_LOGE("SetNotificationRequest set 'actionButtons' faild"); - return false; + if (actionButtonsArrayObj == nullptr + || !SetPropertyByRef(env, object, "actionButtons", actionButtonsArrayObj)) { + ANS_LOGD("SetNotificationRequest set 'actionButtons' faild"); } return true; } @@ -1043,13 +1000,8 @@ bool SetRequestTemplate(ani_env *env, const OHOS::Notification::NotificationRequ return true; } ani_object templateObject = WrapNotificationTemplate(env, templ); - if (templateObject == nullptr) { - ANS_LOGE("SetNotificationRequest Warp 'template' faild"); - return false; - } - if (!SetPropertyByRef(env, object, "template", templateObject)) { - ANS_LOGE("SetNotificationRequest set 'template' faild"); - return false; + if (templateObject == nullptr || !SetPropertyByRef(env, object, "template", templateObject)) { + ANS_LOGD("SetNotificationRequest set 'template' faild"); } return true; } @@ -1103,12 +1055,10 @@ bool SetRequestUnifiedGroupInfo( } ani_object infoObject = nullptr; if (!WarpNotificationUnifiedGroupInfo(env, groupInfo, infoObject) || infoObject == nullptr) { - ANS_LOGE("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); - return false; + ANS_LOGD("SetNotificationRequest Warp 'unifiedGroupInfo' faild"); } if (!SetPropertyByRef(env, object, "unifiedGroupInfo", infoObject)) { - ANS_LOGE("SetNotificationRequest set 'unifiedGroupInfo' faild"); - return false; + ANS_LOGD("SetNotificationRequest set 'unifiedGroupInfo' faild"); } return true; } @@ -1128,32 +1078,26 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, // extraInfo?: {[key:string] : any} if (!SetRequestExtraInfo(env, request, object)) { ANS_LOGE("set extraInfo faild"); - return false; } // actionButtons?: Array if (!SetRequestActionButtons(env, request, object)) { - ANS_LOGE("set actionButtons faild"); - return false; + ANS_LOGD("set actionButtons faild"); } // template?: NotificationTemplate if (!SetRequestTemplate(env, request, object)) { - ANS_LOGE("set template faild"); - return false; + ANS_LOGD("set template faild"); } // readonly notificationFlags?: NotificationFlags if (!SetRequestNotificationFlags(env, request, object)) { - ANS_LOGE("set notificationFlags faild"); - return false; + ANS_LOGD("set notificationFlags faild"); } // readonly agentBundle?: agentBundle if (!SetRequestAgentBundle(env, request, object)) { - ANS_LOGE("set agentBundle faild"); - return false; + ANS_LOGD("set agentBundle faild"); } // unifiedGroupInfo?: unifiedGroupInfo if (!SetRequestUnifiedGroupInfo(env, request, object)) { - ANS_LOGE("set unifiedGroupInfo faild"); - return false; + ANS_LOGD("set unifiedGroupInfo faild"); } return true; } diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 89d07423e..999fa9b11 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -206,19 +206,19 @@ export default namespace notificationManager { } function isInvalidContent(normal?: NotificationBasicContent): boolean { - if(normal === null) { + if (normal === null) { return false; } - if(!normal?.title || normal?.title?.trim() === '') { + if (!normal?.title || normal?.title?.trim() === '') { return false; } - if(!normal?.text || normal?.text?.trim() === '') { + if (!normal?.text || normal?.text?.trim() === '') { return false; } - if(normal?.additionalText !== undefined && normal?.additionalText?.trim() === '') { + if (normal?.additionalText !== undefined && normal?.additionalText?.trim() === '') { return false; } - if(normal?.lockscreenPicture != undefined && !(normal?.lockscreenPicture instanceof image.PixelMap)) { + if (normal?.lockscreenPicture != undefined && !(normal?.lockscreenPicture instanceof image.PixelMap)) { return false; } @@ -226,32 +226,32 @@ export default namespace notificationManager { } function isInvalidLongText(longText?: NotificationLongTextContent): boolean { - if(longText === null) { + if (longText === null) { return false; } - if(!longText?.longText || longText?.longText?.trim() === '') { + if (!longText?.longText || longText?.longText?.trim() === '') { return false; } - if(!longText?.briefText || longText?.briefText?.trim() === '') { + if (!longText?.briefText || longText?.briefText?.trim() === '') { return false; } - if(!longText?.expandedTitle || longText?.expandedTitle?.trim() === '') { + if (!longText?.expandedTitle || longText?.expandedTitle?.trim() === '') { return false; } return true; } function isInvalidMultiLine(multiLine?: NotificationMultiLineContent): boolean { - if(multiLine === null) { + if (multiLine === null) { return false } - if(!multiLine?.briefText || multiLine?.briefText.trim() === '') { + if (!multiLine?.briefText || multiLine?.briefText.trim() === '') { return false; } - if(!multiLine?.longTitle || multiLine?.longTitle.trim() === '') { + if (!multiLine?.longTitle || multiLine?.longTitle.trim() === '') { return false; } - if(multiLine?.lines?.length === 0) { + if (multiLine?.lines?.length === 0) { return false; } @@ -259,57 +259,57 @@ export default namespace notificationManager { } function isInvalidPicture(picture?: NotificationPictureContent): boolean { - if(picture === null) { + if (picture === null) { return false; } - if(!picture?.briefText || picture?.briefText?.trim() === '') { + if (!picture?.briefText || picture?.briefText?.trim() === '') { return false; } - if(!picture?.expandedTitle || picture?.expandedTitle?.trim() === '') { + if (!picture?.expandedTitle || picture?.expandedTitle?.trim() === '') { return false; } - if(!(picture?.picture instanceof image.PixelMap)) { + if (!(picture?.picture instanceof image.PixelMap)) { return false; } return true; } function isInvalidSystemLiveView(systemLiveView?: NotificationSystemLiveViewContent): boolean { - if(systemLiveView === null) { + if (systemLiveView === null) { return false } - if(systemLiveView?.capsule !== undefined && systemLiveView?.capsule === null) { + if (systemLiveView?.capsule !== undefined && systemLiveView?.capsule === null) { return false } - if(systemLiveView?.capsule?.title !== undefined && systemLiveView?.capsule?.title?.trim() === '') { + if (systemLiveView?.capsule?.title !== undefined && systemLiveView?.capsule?.title?.trim() === '') { return false; } - if(systemLiveView?.capsule?.icon != undefined && !(systemLiveView?.capsule?.icon instanceof image.PixelMap)) { + if (systemLiveView?.capsule?.icon != undefined && !(systemLiveView?.capsule?.icon instanceof image.PixelMap)) { return false; } - if(systemLiveView?.capsule?.backgroundColor != undefined && systemLiveView?.capsule?.backgroundColor?.trim() === '') { + if (systemLiveView?.capsule?.backgroundColor != undefined && systemLiveView?.capsule?.backgroundColor?.trim() === '') { return false; } - if(systemLiveView?.capsule?.content != undefined && systemLiveView?.capsule?.content?.trim() === '') { + if (systemLiveView?.capsule?.content != undefined && systemLiveView?.capsule?.content?.trim() === '') { return false; } - if(systemLiveView?.capsule?.capsuleButtons != undefined && systemLiveView?.capsule?.capsuleButtons?.length === 0) { + if (systemLiveView?.capsule?.capsuleButtons != undefined && systemLiveView?.capsule?.capsuleButtons?.length === 0) { return false; } - if(systemLiveView?.button !== undefined && systemLiveView?.button === null) { + if (systemLiveView?.button !== undefined && systemLiveView?.button === null) { return false; } - if(systemLiveView?.button?.names != undefined && systemLiveView?.button?.names?.length === 0) { + if (systemLiveView?.button?.names != undefined && systemLiveView?.button?.names?.length === 0) { return false; } - if(systemLiveView?.button?.icons != undefined && systemLiveView?.button?.icons?.length === 0) { + if (systemLiveView?.button?.icons != undefined && systemLiveView?.button?.icons?.length === 0) { return false; } - if(systemLiveView?.button?.iconsResource != undefined && systemLiveView?.button?.iconsResource?.length === 0) { + if (systemLiveView?.button?.iconsResource != undefined && systemLiveView?.button?.iconsResource?.length === 0) { return false; } - if(systemLiveView?.cardButtons !== undefined && systemLiveView?.cardButtons?.length === 0) { + if (systemLiveView?.cardButtons !== undefined && systemLiveView?.cardButtons?.length === 0) { return false; } @@ -317,71 +317,71 @@ export default namespace notificationManager { } function isInvalidLiveView(liveView?: NotificationLiveViewContent): boolean { - if(liveView === null) { + if (liveView === null) { return false; } - if(liveView?.extraInfo !== undefined && liveView?.extraInfo === null) { + if (liveView?.extraInfo !== undefined && liveView?.extraInfo === null) { return false; } - if(liveView?.pictureInfo !== undefined && liveView?.pictureInfo === null) { + if (liveView?.pictureInfo !== undefined && liveView?.pictureInfo === null) { return false; } return true; } function isInvalidTemplate(template?: NotificationTemplate): boolean { - if(template === null) { + if (template === null) { return false; } - if(template?.name != undefined && template?.name?.trim() === '') { + if (template?.name != undefined && template?.name?.trim() === '') { return false; } - if(template?.data != undefined && template?.data === null) { + if (template?.data != undefined && template?.data === null) { return false; } return true; } function isInvalidDistributedOption(distributedOption?: DistributedOptions): boolean { - if(distributedOption === null) { + if (distributedOption === null) { return false } - if(distributedOption?.supportDisplayDevices != undefined && distributedOption?.supportDisplayDevices?.length === 0) { + if (distributedOption?.supportDisplayDevices != undefined && distributedOption?.supportDisplayDevices?.length === 0) { return false; } - if(distributedOption?.supportOperateDevices != undefined && distributedOption?.supportOperateDevices?.length === 0) { + if (distributedOption?.supportOperateDevices != undefined && distributedOption?.supportOperateDevices?.length === 0) { return false; } return true; } function isInvalidUnifiedGroupInfo(unifiedGroupInfo?: UnifiedGroupInfo): boolean { - if(unifiedGroupInfo === null) { + if (unifiedGroupInfo === null) { return false; } - if(unifiedGroupInfo?.key != undefined && unifiedGroupInfo?.key?.trim() === '') { + if (unifiedGroupInfo?.key != undefined && unifiedGroupInfo?.key?.trim() === '') { return false; } - if(unifiedGroupInfo?.title != undefined && unifiedGroupInfo?.title?.trim() === '') { + if (unifiedGroupInfo?.title != undefined && unifiedGroupInfo?.title?.trim() === '') { return false; } - if(unifiedGroupInfo?.content != undefined && unifiedGroupInfo?.content?.trim() === '') { + if (unifiedGroupInfo?.content != undefined && unifiedGroupInfo?.content?.trim() === '') { return false; } - if(unifiedGroupInfo?.sceneName != undefined && unifiedGroupInfo?.sceneName?.trim() === '') { + if (unifiedGroupInfo?.sceneName != undefined && unifiedGroupInfo?.sceneName?.trim() === '') { return false; } - if(unifiedGroupInfo?.extraInfo != undefined && unifiedGroupInfo?.extraInfo == null) { + if (unifiedGroupInfo?.extraInfo != undefined && unifiedGroupInfo?.extraInfo == null) { return false; } return true; } function isInvalidBundleOption(bundleOption?: BundleOption): boolean { - if(bundleOption === null) { + if (bundleOption === null) { return false; } - if(bundleOption?.bundle != undefined && bundleOption?.bundle?.trim() === '') { + if (bundleOption?.bundle != undefined && bundleOption?.bundle?.trim() === '') { return false; } return true; @@ -399,91 +399,103 @@ export default namespace notificationManager { } return error; } - if(request.content == null || request.content == undefined) { + if (request.content == null || request.content == undefined) { error = { code: 401, message: "request.content must be not Null" } return error; } - if(request.content?.normal !== undefined && !isInvalidContent(request.content.normal)) { + if (request.content?.normal !== undefined && !isInvalidContent(request.content.normal)) { return errorParamInvalid; } - if(request.content?.longText !== undefined && !isInvalidLongText(request.content.longText)) { + if (request.content?.longText !== undefined && !isInvalidLongText(request.content.longText)) { return errorParamInvalid; } - if(request.content?.multiLine !== undefined && !isInvalidMultiLine(request.content.multiLine)) { + if (request.content?.multiLine !== undefined && !isInvalidMultiLine(request.content.multiLine)) { return errorParamInvalid; } - if(request.content?.picture !== undefined && !isInvalidPicture(request.content.picture)) { + if (request.content?.picture !== undefined && !isInvalidPicture(request.content.picture)) { return errorParamInvalid; } - if(request.content?.systemLiveView !== undefined && !isInvalidSystemLiveView(request.content.systemLiveView)) { + if (request.content?.systemLiveView !== undefined && !isInvalidSystemLiveView(request.content.systemLiveView)) { return errorParamInvalid; } - if(request.content?.liveView !== undefined && !isInvalidLiveView(request.content.liveView)) { + if (request.content?.liveView !== undefined && !isInvalidLiveView(request.content.liveView)) { return errorParamInvalid; } - if(request?.appMessageId !== undefined && request?.appMessageId?.trim() === '') { + if (request?.appMessageId !== undefined && request?.appMessageId?.trim() === '') { return errorParamInvalid; } - if(request?.wantAgent !== undefined && request.wantAgent == null) { + 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) { + if (request?.actionButtons !== undefined && request?.actionButtons?.length === 0) { return errorParamInvalid; } - if(request.smallIcon !== undefined && request.smallIcon == null) { + if (request.smallIcon !== undefined && request.smallIcon == null) { return errorParamInvalid; } - if(request?.largeIcon !== undefined && request.largeIcon == null) { + if (request?.largeIcon !== undefined && request.largeIcon == null) { return errorParamInvalid; } - if(request?.overlayIcon !== undefined && request.overlayIcon == null) { + if (request?.overlayIcon !== undefined && request.overlayIcon == null) { return errorParamInvalid; } - if(request?.groupName !== undefined && request?.groupName?.trim() === '') { + if (request?.groupName !== undefined && request?.groupName?.trim() === '') { return errorParamInvalid; } - if(request?.creatorBundleName !== undefined && request?.creatorBundleName?.trim() === '') { + if (request?.creatorBundleName !== undefined && request?.creatorBundleName?.trim() === '') { return errorParamInvalid; } - if(request?.sound !== undefined && request?.sound?.trim() === '') { + if (request?.sound !== undefined && request?.sound?.trim() === '') { return errorParamInvalid; } - if(request?.classification !== undefined && request?.classification?.trim() === '') { + if (request?.classification !== undefined && request?.classification?.trim() === '') { return errorParamInvalid; } - if(request?.hashCode !== undefined && request?.hashCode?.trim() === '') { + if (request?.hashCode !== undefined && request?.hashCode?.trim() === '') { return errorParamInvalid; } - if(request?.template !== undefined && !isInvalidTemplate(request.template)) { + if (request?.template !== undefined && !isInvalidTemplate(request.template)) { return errorParamInvalid; } - if(request?.distributedOption !== undefined && !isInvalidDistributedOption(request.distributedOption)) { + if (request?.distributedOption !== undefined && !isInvalidDistributedOption(request.distributedOption)) { return errorParamInvalid; } - if(request?.deviceId !== undefined && request?.deviceId?.trim() === '') { + if (request?.deviceId !== undefined && request?.deviceId?.trim() === '') { return errorParamInvalid; } - if(request?.removalWantAgent !== undefined && request.removalWantAgent == null) { + if (request?.removalWantAgent !== undefined && request.removalWantAgent == null) { return errorParamInvalid; } - if(request?.representativeBundle !== undefined && !isInvalidBundleOption(request.representativeBundle)) { + if (request?.representativeBundle !== undefined && !isInvalidBundleOption(request.representativeBundle)) { return errorParamInvalid; } - if(request?.agentBundle !== undefined && !isInvalidBundleOption(request.agentBundle)) { + 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() === '') { + 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; } -- Gitee From c5cf7319e783cadfefc17f890be9d834527499f0 Mon Sep 17 00:00:00 2001 From: heguokai Date: Sat, 24 May 2025 15:40:14 +0800 Subject: [PATCH 33/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_common.cpp | 4 ++-- frameworks/ets/ani/src/sts_request.cpp | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 88d4b48d2..44ecf2cc0 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -135,7 +135,7 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, ani_boolean isUndefined, bool outvalue) { - ANS_LOGE("GetPropertyBool start"); + ANS_LOGD("GetPropertyBool start"); if (env == nullptr || obj == nullptr || name == nullptr) { ANS_LOGE("GetPropertyBool fail, has nullptr"); return ANI_INVALID_ARGS; @@ -153,7 +153,7 @@ ani_status GetPropertyBool(ani_env *env, ani_object obj, const char *name, return status; } if (isUndefined) { - ANS_LOGE("%{public}s is undefined", name); + ANS_LOGD("%{public}s is undefined", name); return ANI_INVALID_ARGS; } ani_boolean result = ANI_FALSE; diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index 2d6e9c0e9..e5bc82be5 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -469,19 +469,19 @@ ani_status GetNotificationContent(ani_env *env, ani_object obj, ANS_LOGE("GetNotificationContent failed, has nullptr"); return ANI_ERROR; } - ani_status status = ANI_ERROR; ani_boolean isUndefined = ANI_TRUE; ani_ref notificationContentRef = {}; if (ANI_OK != GetPropertyRef(env, obj, "content", isUndefined, notificationContentRef) || isUndefined == ANI_TRUE) { ANS_LOGE("GetNotificationContent:get contentRef failed"); - return status; + return ANI_INVALID_ARGS; } ani_ref contentTypeRef; - if (ANI_OK != GetPropertyRef(env, obj, "notificationContentType", isUndefined, contentTypeRef) + if (ANI_OK != GetPropertyRef(env, static_cast(notificationContentRef), + "notificationContentType", isUndefined, contentTypeRef) || isUndefined == ANI_TRUE || contentTypeRef == nullptr) { ANS_LOGE("GetNotificationContent:get notificationContentType failed"); - return status; + return ANI_INVALID_ARGS; } ContentType type; if (!ContentTypeEtsToC(env, static_cast(contentTypeRef), type)) { @@ -493,7 +493,7 @@ ani_status GetNotificationContent(ani_env *env, ani_object obj, return ANI_INVALID_ARGS; } ANS_LOGD("GetNotificationContent end"); - return status; + return ANI_OK; } void GetNotificationSlotType(ani_env *env, ani_object obj, std::shared_ptr &request) -- Gitee From a18e22b656336e62c1713432fd4e739f8b99db3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Mon, 26 May 2025 09:21:25 +0800 Subject: [PATCH 34/52] some modify MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- .../ets/ani/src/sts_notification_flag.cpp | 2 +- frameworks/ets/ani/src/sts_request.cpp | 15 ++++++++------- frameworks/ets/ani/src/sts_slot.cpp | 9 +++++---- frameworks/ets/ani/src/sts_sorting_map.cpp | 18 ++++++++++-------- frameworks/ets/ani/src/sts_subscribe.cpp | 12 ++++++++++++ 5 files changed, 36 insertions(+), 20 deletions(-) diff --git a/frameworks/ets/ani/src/sts_notification_flag.cpp b/frameworks/ets/ani/src/sts_notification_flag.cpp index 546561b48..ef7771fbd 100644 --- a/frameworks/ets/ani/src/sts_notification_flag.cpp +++ b/frameworks/ets/ani/src/sts_notification_flag.cpp @@ -57,7 +57,7 @@ bool WarpNotificationFlags(ani_env* env, const std::shared_ptrGetReminderFlags(); - if (SetPropertyOptionalByDouble(env, flagsObject, "reminderFlags", reminderFlags)) { + if (!SetPropertyOptionalByDouble(env, flagsObject, "reminderFlags", reminderFlags)) { ANS_LOGD("WarpNotificationFlags set 'reminderFlags' faild"); } return true; diff --git a/frameworks/ets/ani/src/sts_request.cpp b/frameworks/ets/ani/src/sts_request.cpp index e5bc82be5..7c9cc45d9 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -469,19 +469,20 @@ ani_status GetNotificationContent(ani_env *env, ani_object obj, 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 != GetPropertyRef(env, obj, "content", isUndefined, notificationContentRef) + if (ANI_OK != (status = GetPropertyRef(env, obj, "content", isUndefined, notificationContentRef)) || isUndefined == ANI_TRUE) { - ANS_LOGE("GetNotificationContent:get contentRef failed"); - return ANI_INVALID_ARGS; + ANS_LOGE("GetNotificationContent:get contentRef failed. status %{public}d", status); + return status; } ani_ref contentTypeRef; - if (ANI_OK != GetPropertyRef(env, static_cast(notificationContentRef), - "notificationContentType", isUndefined, contentTypeRef) + if (ANI_OK != (status = GetPropertyRef(env, static_cast(notificationContentRef), + "notificationContentType", isUndefined, contentTypeRef)) || isUndefined == ANI_TRUE || contentTypeRef == nullptr) { - ANS_LOGE("GetNotificationContent:get notificationContentType failed"); - return ANI_INVALID_ARGS; + ANS_LOGE("GetNotificationContent:get notificationContentType failed. status %{public}d", status); + return status; } ContentType type; if (!ContentTypeEtsToC(env, static_cast(contentTypeRef), type)) { diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 1059a851d..69bd7e210 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -157,10 +157,11 @@ bool WrapNotificationSlot(ani_env *env, sptr slo ANS_LOGE("set String params fail"); return false; } - if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { - ANS_LOGE("Set vibrationValues fail"); - return false; - } + if (slot->GetVibrationStyle().size() != 0 + && !SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { + ANS_LOGE("Set vibrationValues fail"); + return false; + } ANS_LOGD("WrapNotificationSlot end"); return true; } diff --git a/frameworks/ets/ani/src/sts_sorting_map.cpp b/frameworks/ets/ani/src/sts_sorting_map.cpp index e5a434609..67e99b341 100644 --- a/frameworks/ets/ani/src/sts_sorting_map.cpp +++ b/frameworks/ets/ani/src/sts_sorting_map.cpp @@ -83,14 +83,16 @@ bool WarpNotificationSortingMap(ani_env *env, return false; } std::vector keys = sortingMap->GetKey(); - 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; + 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; } diff --git a/frameworks/ets/ani/src/sts_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 066a63e85..11f2dd82c 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -123,6 +123,7 @@ void StsSubscriberInstance::OnCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } + ANS_LOGD("done"); } void StsSubscriberInstance::OnConsumed( const std::shared_ptr &request, @@ -151,6 +152,7 @@ void StsSubscriberInstance::OnConsumed( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } + ANS_LOGD("done"); } void StsSubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) { @@ -177,6 +179,7 @@ void StsSubscriberInstance::OnUpdate(const std::shared_ptr &date) { @@ -273,6 +279,7 @@ void StsSubscriberInstance::onDoNotDisturbChanged(const std::shared_ptr &callbackData) @@ -300,6 +307,7 @@ void StsSubscriberInstance::OnEnabledNotificationChanged( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } + ANS_LOGD("done"); } void StsSubscriberInstance::OnBadgeChanged(const std::shared_ptr &badgeData) { @@ -326,6 +334,7 @@ void StsSubscriberInstance::OnBadgeChanged(const std::shared_ptr &callbackData) { @@ -356,6 +365,7 @@ void StsSubscriberInstance::OnBadgeEnabledChanged(const sptr> &requestList, @@ -384,6 +394,7 @@ void StsSubscriberInstance::OnBatchCanceled( ANS_LOGD("DetachCurrentThread error. result: %{public}d.", aniResult); return; } + ANS_LOGD("done"); } bool StsSubscriberInstance::HasOnBatchCancelCallback() { @@ -487,6 +498,7 @@ bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::ve ANS_LOGD("FunctionalObject_Call error. result: %{public}d.", aniResult); return false; } + ANS_LOGD("done"); return true; } -- Gitee From 360f76ea290b10ea25fdf36eebeb61a137f85aa7 Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 29 May 2025 18:21:01 +0800 Subject: [PATCH 35/52] fixed for addDoNotDisturbProfile & setSlotFlagByBundle Signed-off-by: heguokai --- frameworks/ets/ani/include/manager/ani_slot.h | 2 +- frameworks/ets/ani/src/manager/ani_slot.cpp | 6 +++--- frameworks/ets/ani/src/sts_bundle_option.cpp | 2 +- frameworks/ets/ani/src/sts_disturb_mode.cpp | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h index 127dcfff8..044d5a877 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -20,7 +20,7 @@ namespace OHOS { namespace NotificationManagerSts { ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj); -void AniSetSlotFlagsByBundle(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); diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index d9ce7326b..86224ee2b 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -145,7 +145,7 @@ ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj) return slotFlags; } -void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj) +void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj, ani_double slotFlags) { ANS_LOGD("sts setSlotFlagsByBundle call"); Notification::NotificationBundleOption option; @@ -153,8 +153,8 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj) NotificationSts::ThrowStsErroWithMsg(env, "AniSetSlotFlagsByBundle : erro arguments."); return; } - uint32_t slotFlags = 0; - int returncode = Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); + int returncode = + Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, static_cast(slotFlags)); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { ANS_LOGE("AniSetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index 4da10d202..938b388b3 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -63,7 +63,7 @@ bool UnwrapArrayBundleOption(ani_env *env, for (int32_t i = 0; i < static_cast(length); i++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), - "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, i); + "$_get", "I:Lstd/core/Object;", &optionRef, i); if (status != ANI_OK) { ANS_LOGE("UnwrapArrayBundleOption: get bundleOptionRef failed, status = %{public}d", status); return false; diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp index 345d36319..a24e389b8 100644 --- a/frameworks/ets/ani/src/sts_disturb_mode.cpp +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -30,16 +30,16 @@ bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, } ani_boolean isUndefined = ANI_TRUE; ani_double idAni = 0.0; - if (ANI_OK != GetPropertyDouble(env, param, "id", isUndefined, idAni) || isUndefined == ANI_TRUE) { + 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->SetProfileId(static_cast(idAni)); profile->SetProfileName(nameStr); ani_ref trustlistRef; if (ANI_OK != GetPropertyRef(env, param, "trustlist", isUndefined, trustlistRef) || isUndefined == ANI_TRUE) { @@ -70,15 +70,15 @@ bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, ANS_LOGD("UnwrapArrayDoNotDisturbProfile: status = %{public}d", status); return false; } - sptr profile; for (int i = 0; i < static_cast(length); i++) { ani_ref optionRef; status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", - "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)i); + "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; -- Gitee From 2525e1c3fd0bb4c23193abb4cd2b0e7abc7797a9 Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 29 May 2025 18:55:42 +0800 Subject: [PATCH 36/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_subscriber.cpp | 2 +- frameworks/ets/ets/notification/notificationFlags.ets | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/ets/ani/src/sts_subscriber.cpp b/frameworks/ets/ani/src/sts_subscriber.cpp index fc0142b74..19c966c15 100644 --- a/frameworks/ets/ani/src/sts_subscriber.cpp +++ b/frameworks/ets/ani/src/sts_subscriber.cpp @@ -191,7 +191,7 @@ bool WarpSubscribeCallbackDataArray( } if (ANI_OK != (status = env->Object_CallMethodByName_Void( outObj, "$_set", "ILstd/core/Object;:V", i, obj))) { - ANS_LOGE("set object faild. index %{public}d status %{public}d", i, status); + ANS_LOGE("set object faild. status %{public}d", status); return false; } } diff --git a/frameworks/ets/ets/notification/notificationFlags.ets b/frameworks/ets/ets/notification/notificationFlags.ets index e090d8d72..7c98b19f5 100644 --- a/frameworks/ets/ets/notification/notificationFlags.ets +++ b/frameworks/ets/ets/notification/notificationFlags.ets @@ -35,7 +35,7 @@ class NotificationFlagsInner implements NotificationFlags { public soundEnabled?: NotificationFlagStatus | undefined; - public vibrationEnabled?: NotificationFlagStatus| undefined; + public vibrationEnabled?: NotificationFlagStatus | undefined; public reminderFlags?: number | undefined; } \ No newline at end of file -- Gitee From ec1c25dd5064bf8bebdddaab83bc665823936d99 Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 29 May 2025 20:12:44 +0800 Subject: [PATCH 37/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_notification_content.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/frameworks/ets/ani/src/sts_notification_content.cpp b/frameworks/ets/ani/src/sts_notification_content.cpp index 96fc4cbc6..b3aa635f9 100644 --- a/frameworks/ets/ani/src/sts_notification_content.cpp +++ b/frameworks/ets/ani/src/sts_notification_content.cpp @@ -1254,11 +1254,6 @@ bool SetNotificationMultiLineContent( if (allLinesObject == nullptr || !SetPropertyByRef(env, contentObj, "lines", allLinesObject)) { ANS_LOGD("SetNotificationMultiLineContent: set lines failed"); } - ani_object lineWantAgentsObject = GetAniWantAgentArray(env, content->GetLineWantAgents()); - if (lineWantAgentsObject == nullptr - || !SetPropertyByRef(env, contentObj, "lineWantAgents", lineWantAgentsObject)) { - ANS_LOGD("SetNotificationMultiLineContent: set lineWantAgents failed"); - } return SetPropertyByRef(env, ncObj, "multiLine", contentObj); } -- Gitee From fad59ff96f03297c4b0a7896625c763f0601f5bb Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 29 May 2025 21:34:51 +0800 Subject: [PATCH 38/52] ani fixed for getActiveNotification Signed-off-by: heguokai --- .../ets/ani/src/manager/ani_get_active.cpp | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_get_active.cpp b/frameworks/ets/ani/src/manager/ani_get_active.cpp index 8ae3e8957..74e1ccd83 100644 --- a/frameworks/ets/ani/src/manager/ani_get_active.cpp +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -19,6 +19,7 @@ #include "ans_log_wrapper.h" #include "sts_throw_erro.h" #include "sts_request.h" +#include "sts_common.h" namespace OHOS { namespace NotificationManagerSts { @@ -46,14 +47,19 @@ ani_object AniGetAllActiveNotifications(ani_env *env) 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); + ANS_LOGE("AniGetAllActiveNotifications error, errorCode: %{public}d", externalCode); return nullptr; } - ani_object arrayRequestObj = NotificationSts::GetAniNotificationRequestArrayByNotifocations(env, notifications); + 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("AniTriggerSystemLiveView buttonOption ERROR_INTERNAL_ERROR"); + ANS_LOGE("AniGetAllActiveNotifications ERROR_INTERNAL_ERROR"); } ANS_LOGD("sts AniGetAllActiveNotifications end"); return arrayRequestObj; @@ -61,22 +67,27 @@ ani_object AniGetAllActiveNotifications(ani_env *env) ani_object AniGetActiveNotifications(ani_env *env) { - ANS_LOGD("sts AniGetAllActiveNotifications call"); + 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("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); + ANS_LOGE("AniGetActiveNotifications error, errorCode: %{public}d", externalCode); return nullptr; } - ani_object arrayRequestObj = NotificationSts::GetAniNotificationRequestArray(env, requests); + 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("AniTriggerSystemLiveView buttonOption ERROR_INTERNAL_ERROR"); + ANS_LOGE("AniGetActiveNotifications ERROR_INTERNAL_ERROR"); } - ANS_LOGD("sts AniGetAllActiveNotifications end"); + ANS_LOGD("sts AniGetActiveNotifications end"); return arrayRequestObj; } } // namespace NotificationManagerSts -- Gitee From 819956dd68c98ac0e17cd88f37678329f64f90f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=89=94?= Date: Tue, 3 Jun 2025 09:51:31 +0800 Subject: [PATCH 39/52] add on/off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 一扔 --- frameworks/ets/ani/BUILD.gn | 9 ++ frameworks/ets/ani/include/manager/ani_on.h | 27 ++++ .../ani/include/manager/ani_push_callback.h | 56 +++++++ .../ani/include/sts_notification_manager.h | 3 + frameworks/ets/ani/include/sts_request.h | 2 + frameworks/ets/ani/include/sts_throw_erro.h | 12 ++ .../ets/ani/src/manager/ani_manager.cpp | 8 + frameworks/ets/ani/src/manager/ani_on.cpp | 125 +++++++++++++++ .../ets/ani/src/manager/ani_push_callback.cpp | 148 +++++++++++++++++ frameworks/ets/ani/src/sts_action_button.cpp | 2 +- frameworks/ets/ani/src/sts_bundle_option.cpp | 2 +- frameworks/ets/ani/src/sts_common.cpp | 4 +- .../ets/ani/src/sts_notification_manager.cpp | 150 ++++++++++++++++++ frameworks/ets/ani/src/sts_request.cpp | 82 ++++++++++ frameworks/ets/ani/src/sts_subscribe.cpp | 4 +- .../ets/ets/@ohos.notificationManager.ets | 96 ++++++++++- 16 files changed, 723 insertions(+), 7 deletions(-) create mode 100755 frameworks/ets/ani/include/manager/ani_on.h create mode 100755 frameworks/ets/ani/include/manager/ani_push_callback.h create mode 100755 frameworks/ets/ani/src/manager/ani_on.cpp create mode 100755 frameworks/ets/ani/src/manager/ani_push_callback.cpp diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn index fa0771b8a..34ea02605 100644 --- a/frameworks/ets/ani/BUILD.gn +++ b/frameworks/ets/ani/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("notification_manager_ani") { "./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", ] cflags = [] @@ -68,6 +70,12 @@ ohos_shared_library("notification_manager_ani") { "${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", @@ -87,6 +95,7 @@ ohos_shared_library("notification_manager_ani") { "ability_runtime:abilitykit_native", "ability_runtime:app_context", "ace_engine:ace_uicontent", + "access_token:libtokenid_sdk", ] innerapi_tags = [ "platformsdk" ] 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 000000000..911d45fd8 --- /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_push_callback.h b/frameworks/ets/ani/include/manager/ani_push_callback.h new file mode 100755 index 000000000..fcaf53782 --- /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/sts_notification_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h index 8c9a089fb..f40c52115 100644 --- a/frameworks/ets/ani/include/sts_notification_manager.h +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -22,6 +22,7 @@ #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 { @@ -138,6 +139,8 @@ ani_status UnWarpNotificationButtonOption(ani_env *env, const ani_object buttonO ani_object WarpNotificationButtonOption(ani_env *env, sptr buttonOption); 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 index 893d6ce46..02a69f21d 100644 --- a/frameworks/ets/ani/include/sts_request.h +++ b/frameworks/ets/ani/include/sts_request.h @@ -41,6 +41,8 @@ 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); } // 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 index 6bd3d6d5a..44f75ae9b 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -71,6 +71,18 @@ inline void ThrowStsErroWithMsg(ani_env *env, std::string logMsg) 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/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index 4cc8d56c2..ed6f74a8d 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -24,6 +24,7 @@ #include "ani_publish.h" #include "ani_local_live_view.h" #include "ani_request_enable.h" +#include "ani_on.h" namespace OHOS { namespace NotificationManagerSts { @@ -72,6 +73,13 @@ static std::array kitManagerFunctions = { ani_native_function {"nativeRequestEnableNotification", "Lapplication/UIAbilityContext/UIAbilityContext;:Lstd/core/Promise;", reinterpret_cast(AniRequestEnableNotification)}, + 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)}, }; void AniNotificationManagerRegistryInit(ani_env *env) 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 000000000..8d4da2c64 --- /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_push_callback.cpp b/frameworks/ets/ani/src/manager/ani_push_callback.cpp new file mode 100755 index 000000000..b20c33fbd --- /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/sts_action_button.cpp b/frameworks/ets/ani/src/sts_action_button.cpp index 7b5288f74..26968f752 100644 --- a/frameworks/ets/ani/src/sts_action_button.cpp +++ b/frameworks/ets/ani/src/sts_action_button.cpp @@ -146,7 +146,7 @@ bool SetNotificationActionButtonByRequiredParameter( } ani_string stringValue; // title: string; - if (!GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { + if (ANI_OK != GetAniStringByString(env, actionButton->GetTitle(), stringValue)) { ANS_LOGE("SetActionButtonByRequiredParameter: Get title failed"); return false; } diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index 4da10d202..c2e8937b8 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -95,7 +95,7 @@ bool WrapBundleOption(ani_env* env, } // bundle: string; ani_string stringValue = nullptr; - if (!GetAniStringByString(env, bundleOption->GetBundleName(), stringValue) + if (ANI_OK != GetAniStringByString(env, bundleOption->GetBundleName(), stringValue) || !CallSetter(env, bundleCls, bundleObject, "bundle", stringValue)) { ANS_LOGE("WrapBundleOption: set bundle failed"); return false; diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 44ecf2cc0..f8f25b2f7 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -93,8 +93,8 @@ bool GetStringArrayByAniObj(ani_env *env, const ani_object ani_obj, std::vector< return false; } std::string std_string; - if (!GetStringByAniString(env, static_cast(stringEntryRef), std_string)) { - ANS_LOGE("GetStdString faild"); + 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); diff --git a/frameworks/ets/ani/src/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index 45e711814..dfd92189c 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -15,6 +15,7 @@ #include "sts_notification_manager.h" #include "sts_common.h" #include "ani_common_util.h" +#include "ani_common_want.h" namespace OHOS { namespace NotificationSts { @@ -462,5 +463,154 @@ bool WarpNotificationDoNotDisturbDate( 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; +} } // 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 index 7c9cc45d9..ed25b307b 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -1203,5 +1203,87 @@ ani_object GetAniNotificationRequestArrayByNotifocations(ani_env *env, std::vect } 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; +} } // 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 index 11f2dd82c..441e053c1 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -481,9 +481,9 @@ bool StsSubscriberInstance::CallFunction(ani_env *env, const char *func, std::ve ANS_LOGD("enter"); if (env == nullptr) return false; ani_ref fn_ref; - ani_status aniResult = env->Object_GetFieldByName_Ref(static_cast(ref_), func, &fn_ref); + ani_status aniResult = env->Object_GetPropertyByName_Ref(static_cast(ref_), func, &fn_ref); if (ANI_OK != aniResult) { - ANS_LOGD("Object_GetFieldByName_Ref '%{public}s' error. result: %{public}d.", func, aniResult); + ANS_LOGD("Object_GetPropertyByName_Ref '%{public}s' error. result: %{public}d.", func, aniResult); return false; } ani_boolean IsUndefined = ANI_FALSE; diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 999fa9b11..7dcb4589e 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -16,7 +16,7 @@ import { BundleOption } from 'notification.NotificationCommonDef'; import { BusinessError, AsyncCallback } from '@ohos.base'; import { NotificationSlot } from 'notification.notificationSlot'; -import { NotificationRequest } from 'notification.notificationRequest'; +import { NotificationRequest, NotificationCheckRequest } from 'notification.notificationRequest'; import UIAbilityContext from 'application.UIAbilityContext'; import { NotificationBasicContent } from 'notification.notificationContent'; import { NotificationLongTextContent } from 'notification.notificationContent'; @@ -31,6 +31,8 @@ import image from '@ohos.multimedia.image'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; +type CallbackForCheckInfo = + (checkInfo: notificationManager.NotificationCheckInfo)=> notificationManager.NotificationCheckResult; const ERROR_OK = 0; const ERROR_PARAM_INVALID = 401; @@ -159,6 +161,11 @@ export default namespace notificationManager { export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; export native function nativeRequestEnableNotification(content: UIAbilityContext): Promise; + 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 = { @@ -1302,4 +1309,91 @@ export default namespace notificationManager { } ) } + + 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: Object): 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; + } } \ No newline at end of file -- Gitee From 1ec7af07e02e2fb0bcbbe241b03d4500bcec917a Mon Sep 17 00:00:00 2001 From: YOUR_NAME Date: Tue, 3 Jun 2025 15:46:04 +0800 Subject: [PATCH 40/52] =?UTF-8?q?ans=E6=A8=A1=E5=9D=97ani=E5=8C=96?= =?UTF-8?q?=E9=80=82=E9=85=8D=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: YOUR_NAME Change-Id: Ifa9add16e9d952c4eaedaa23529554f2be90963d --- frameworks/ets/ani/include/manager/ani_slot.h | 9 + frameworks/ets/ani/include/sts_common.h | 2 + frameworks/ets/ani/include/sts_slot.h | 5 + .../ani/src/manager/ani_local_live_view.cpp | 2 +- .../ets/ani/src/manager/ani_manager.cpp | 18 + frameworks/ets/ani/src/manager/ani_slot.cpp | 210 ++++++++++- frameworks/ets/ani/src/sts_common.cpp | 38 ++ frameworks/ets/ani/src/sts_slot.cpp | 115 ++++++ .../ets/ani/src/subscribe/ani_remove.cpp | 2 +- .../ets/ets/@ohos.notificationManager.ets | 338 +++++++++++++++++- 10 files changed, 715 insertions(+), 24 deletions(-) diff --git a/frameworks/ets/ani/include/manager/ani_slot.h b/frameworks/ets/ani/include/manager/ani_slot.h index 044d5a877..eecf03272 100644 --- a/frameworks/ets/ani/include/manager/ani_slot.h +++ b/frameworks/ets/ani/include/manager/ani_slot.h @@ -27,6 +27,15 @@ ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, 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/sts_common.h b/frameworks/ets/ani/include/sts_common.h index 10a56d84a..8bfe1dac6 100644 --- a/frameworks/ets/ani/include/sts_common.h +++ b/frameworks/ets/ani/include/sts_common.h @@ -47,6 +47,8 @@ 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); diff --git a/frameworks/ets/ani/include/sts_slot.h b/frameworks/ets/ani/include/sts_slot.h index f9d311058..2c4da3de6 100644 --- a/frameworks/ets/ani/include/sts_slot.h +++ b/frameworks/ets/ani/include/sts_slot.h @@ -33,6 +33,11 @@ bool SetOptionalFieldSlotLevel(ani_env *env, const ani_class cls, ani_object &ob 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/src/manager/ani_local_live_view.cpp b/frameworks/ets/ani/src/manager/ani_local_live_view.cpp index d2b76a4ed..d3c4203c8 100644 --- a/frameworks/ets/ani/src/manager/ani_local_live_view.cpp +++ b/frameworks/ets/ani/src/manager/ani_local_live_view.cpp @@ -36,7 +36,7 @@ void AniTriggerSystemLiveView( return; } NotificationSts::ButtonOption buttonOption; - if (!NotificationSts::UnWarpNotificationButtonOption(env, buttonOptionsObj, 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"); diff --git a/frameworks/ets/ani/src/manager/ani_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index ed6f74a8d..3d312623c 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -80,6 +80,24 @@ static std::array kitManagerFunctions = { ":I", reinterpret_cast(AniOn)}, ani_native_function {"nativeOff", "Lstd/core/String;Lstd/core/Function1;:I", reinterpret_cast(AniOff)}, + 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)}, }; void AniNotificationManagerRegistryInit(ani_env *env) diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index 86224ee2b..622984eea 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -27,11 +27,14 @@ 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 = 0; + int returncode = CJSystemapi::Notification::SUCCESS_CODE; std::vector> slots; BundleOption option; if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { @@ -42,7 +45,7 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + 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; @@ -56,6 +59,199 @@ ani_object AniGetSlotsByBundle(ani_env *env, ani_object bundleOption) 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)); + } + 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 "); @@ -75,7 +271,7 @@ void AniSetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enu NotificationSts::AniBooleanToBool(enable), isForceControl); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { ANS_LOGE("AniSetNotificationEnableSlot error, errorCode: %{public}d", externalCode); AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); return; @@ -100,7 +296,7 @@ void AniSetNotificationEnableSlotWithForce(ani_env *env, NotificationSts::AniBooleanToBool(enable), NotificationSts::AniBooleanToBool(isForceControl)); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { ANS_LOGE("AniSetNotificationEnableSlotSync error, errorCode: %{public}d", externalCode); AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } @@ -120,7 +316,7 @@ ani_boolean AniIsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, bool isEnable = false; int returncode = Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { ANS_LOGE("IsNotificationSlotEnabled -> error, errorCode: %{public}d", externalCode); AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } @@ -138,7 +334,7 @@ ani_int AniGetSlotFlagsByBundle(ani_env *env, ani_object obj) uint32_t slotFlags = 0; int returncode = Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { ANS_LOGE("AniGetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } @@ -156,7 +352,7 @@ void AniSetSlotFlagsByBundle(ani_env *env, ani_object obj, ani_double slotFlags) int returncode = Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, static_cast(slotFlags)); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { ANS_LOGE("AniSetSlotFlagsByBundle -> error, errorCode: %{public}d", externalCode); AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index f8f25b2f7..253a124d3 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -255,6 +255,44 @@ ani_status GetPropertyStringArray(ani_env *env, ani_object param, const char *na 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()) { diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 69bd7e210..7202f92ab 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -224,5 +224,120 @@ bool WrapNotificationSlotArray(ani_env *env, const std::vector(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/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp index 7f04ae109..be660d9fb 100644 --- a/frameworks/ets/ani/src/subscribe/ani_remove.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -104,7 +104,7 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason ANS_LOGD("StsRemoveForHashCodes enter"); std::vector hashCodesStd; int32_t reasonType; - if (ANI_OK != NotificationSts::GetStringArrayByAniObj(env, hashCodes, hashCodesStd)) { + 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); diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 7dcb4589e..88c88458f 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -160,6 +160,45 @@ export default namespace notificationManager { 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 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; + + 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; @@ -505,6 +544,287 @@ export default namespace notificationManager { } return error; } + + export function getSlotNumByBundle(bundle: BundleOption): Promise { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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: Object): 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 !== 0) { + throw error; + } + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== 0) { + 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: Object): 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 !== 0) { + throw error; + } + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== 0) { + 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); + }); + } + + export function addSlot(slot: NotificationSlot): Promise { + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== 0) { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addSlot(slot: NotificationSlot, callback: AsyncCallback): void { + let slotError: BusinessError = isInvalidParameter(slot); + if (slotError.code !== 0) { + 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: Object): 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: Object): 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { @@ -590,11 +910,7 @@ export default namespace notificationManager { export function isNotificationEnabled(userId: number, callback: AsyncCallback): void { if (callback == null) { - let error: BusinessError = { - code: 410, - message : "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithId(userId); }); p.then((data: NullishType): void => { @@ -625,11 +941,7 @@ export default namespace notificationManager { export function isNotificationEnabled(callback: AsyncCallback): void { if (callback == null) { - let error: BusinessError = { - code: 410, - message : "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(); }); p.then((data: NullishType): void => { @@ -1192,11 +1504,7 @@ export default namespace notificationManager { throw error; } if (callback == null) { - let error: BusinessError = { - code: 410, - message : "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { -- Gitee From 71716191cccf2019e53084f0fc197678f4b2f2e9 Mon Sep 17 00:00:00 2001 From: YOUR_NAME Date: Wed, 4 Jun 2025 16:12:46 +0800 Subject: [PATCH 41/52] =?UTF-8?q?ans=E6=A8=A1=E5=9D=97ani=E5=8C=96?= =?UTF-8?q?=E9=80=82=E9=85=8D=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: YOUR_NAME Change-Id: I2265ab1e658aa5d56d2f91c303238af3d5167251 --- frameworks/ets/ani/BUILD.gn | 2 + .../include/manager/ani_distributed_enable.h | 28 ++ .../include/manager/ani_notification_enable.h | 2 + .../include/manager/ani_support_template.h | 27 ++ .../ani/include/sts_notification_manager.h | 16 ++ .../src/manager/ani_distributed_enable.cpp | 100 +++++++ .../ets/ani/src/manager/ani_manager.cpp | 14 + .../src/manager/ani_notification_enable.cpp | 30 ++ .../ani/src/manager/ani_support_template.cpp | 72 +++++ .../ets/ani/src/sts_notification_manager.cpp | 64 +++++ .../ets/ets/@ohos.notificationManager.ets | 257 ++++++++++++++++++ 11 files changed, 612 insertions(+) create mode 100755 frameworks/ets/ani/include/manager/ani_distributed_enable.h create mode 100755 frameworks/ets/ani/include/manager/ani_support_template.h create mode 100755 frameworks/ets/ani/src/manager/ani_distributed_enable.cpp create mode 100755 frameworks/ets/ani/src/manager/ani_support_template.cpp diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn index 34ea02605..627f97101 100644 --- a/frameworks/ets/ani/BUILD.gn +++ b/frameworks/ets/ani/BUILD.gn @@ -58,6 +58,8 @@ ohos_shared_library("notification_manager_ani") { "./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", ] cflags = [] 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 000000000..4a712316f --- /dev/null +++ b/frameworks/ets/ani/include/manager/ani_distributed_enable.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_DISTRIBUTED_ENBLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ETS_ANI_INCLUDE_ANI_DISTRIBUTED_ENBLE_H +#include "ani.h" + +namespace OHOS { +namespace NotificationManagerSts { +void AniSetDistributedEnable(ani_env* env, ani_boolean enabled); +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); + +} // namespace NotificationManagerSts +} // namespace OHOS +#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 index 3fdb7013d..93dee4348 100644 --- a/frameworks/ets/ani/include/manager/ani_notification_enable.h +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.h @@ -23,6 +23,8 @@ 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 AniGetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId); } // 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 000000000..5be565d99 --- /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/sts_notification_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h index f40c52115..bf9cba112 100644 --- a/frameworks/ets/ani/include/sts_notification_manager.h +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -32,6 +32,7 @@ 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; enum STSSlotType { UNKNOWN_TYPE = 0, SOCIAL_COMMUNICATION = 1, @@ -61,6 +62,13 @@ enum STSContentType { NOTIFICATION_CONTENT_LIVE_VIEW, }; +enum class STSRemindType { + IDLE_DONOT_REMIND, + IDLE_REMIND, + ACTIVE_DONOT_REMIND, + ACTIVE_REMIND +}; + class StsSlotTypeUtils { public: static bool StsToC(const STSSlotType inType, SlotType &outType); @@ -79,6 +87,12 @@ 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(); @@ -133,6 +147,8 @@ 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); 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 000000000..fa63aae21 --- /dev/null +++ b/frameworks/ets/ani/src/manager/ani_distributed_enable.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 "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); +} +} +} \ 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 index 3d312623c..d5679284e 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -25,6 +25,8 @@ #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" namespace OHOS { namespace NotificationManagerSts { @@ -98,6 +100,18 @@ static std::array kitManagerFunctions = { reinterpret_cast(AniSetSlotByBundle)}, ani_native_function {"nativeGetSlotNumByBundle", nullptr, reinterpret_cast(AniGetSlotNumByBundle)}, + 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) diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index 9c987eedc..daaa2baef 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -92,5 +92,35 @@ void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean } ANS_LOGD("AniSetNotificationEnable end"); } + +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 != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniGetSyncNotificationEnabledWithoutApp -> error, errorCode: %{public}d", 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 != CJSystemapi::Notification::SUCCESS_CODE) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + ANS_LOGE("AniSetSyncNotificationEnabledWithoutApp -> error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("AniSetSyncNotificationEnabledWithoutApp end"); +} } // namespace NotificationManagerSts } // namespace OHOS \ 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 000000000..461787a31 --- /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/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index dfd92189c..afc5f6c1b 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -218,6 +218,51 @@ bool StsSlotLevelUtils::StsToC(const STSSlotLevel inLevel, SlotLevel &outLevel) 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() {} @@ -383,6 +428,25 @@ bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enu 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) { diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index 88c88458f..ee2307572 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -122,6 +122,13 @@ export default namespace notificationManager { 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; @@ -170,6 +177,14 @@ export default namespace notificationManager { 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; function isInvalidParameter(slot: NotificationSlot): BusinessError { @@ -1704,4 +1719,246 @@ export default namespace notificationManager { public slotType: SlotType = SlotType.UNKNOWN_TYPE; public extraInfos?: Record; } + + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + 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 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: Object): 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: Object): 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: Object): 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 !== 0) { + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback): void + { + + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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: Object): 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 !== 0) { + 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); + }) + } } \ No newline at end of file -- Gitee From 878f395e22e41ec3c31aa4b126b22d75b7a7031f Mon Sep 17 00:00:00 2001 From: heguokai Date: Thu, 5 Jun 2025 23:54:50 +0800 Subject: [PATCH 42/52] =?UTF-8?q?ans=E6=A8=A1=E5=9D=97=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3ani=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: heguokai --- frameworks/ets/ani/BUILD.gn | 9 + .../ets/ani/include/manager/ani_cance.h | 3 + .../ani/include/manager/ani_display_badge.h | 2 + .../include/manager/ani_distributed_enable.h | 12 +- .../include/manager/ani_do_not_disturb_date.h | 29 + .../manager/ani_do_not_disturb_profile.h | 1 + .../ets/ani/include/manager/ani_get_active.h | 1 + .../include/manager/ani_notification_enable.h | 3 + .../ani/include/manager/ani_open_settings.h | 73 ++ .../ets/ani/include/manager/ani_publish.h | 2 + .../ani/include/manager/ani_remove_group.h | 25 + .../ets/ani/include/manager/ani_sync_config.h | 24 + .../ets/ani/include/sts_bundle_option.h | 1 + frameworks/ets/ani/include/sts_disturb_mode.h | 1 + .../ani/include/sts_notification_manager.h | 20 + frameworks/ets/ani/include/sts_request.h | 1 + frameworks/ets/ani/include/sts_subscribe.h | 1 + frameworks/ets/ani/include/sts_throw_erro.h | 3 +- .../ets/ani/include/subscribe/ani_remove.h | 2 + frameworks/ets/ani/src/manager/ani_cance.cpp | 71 ++ .../ets/ani/src/manager/ani_display_badge.cpp | 34 + .../src/manager/ani_distributed_enable.cpp | 192 ++++ .../src/manager/ani_do_not_disturb_date.cpp | 138 +++ .../manager/ani_do_not_disturb_profile.cpp | 37 + .../ets/ani/src/manager/ani_get_active.cpp | 29 + .../ets/ani/src/manager/ani_manager.cpp | 53 + .../src/manager/ani_notification_enable.cpp | 79 +- .../ets/ani/src/manager/ani_open_settings.cpp | 352 +++++++ .../ets/ani/src/manager/ani_publish.cpp | 64 +- .../ets/ani/src/manager/ani_remove_group.cpp | 53 + .../ets/ani/src/manager/ani_sync_config.cpp | 61 ++ frameworks/ets/ani/src/sts_bundle_option.cpp | 31 + frameworks/ets/ani/src/sts_disturb_mode.cpp | 69 ++ .../ets/ani/src/sts_notification_manager.cpp | 91 ++ frameworks/ets/ani/src/sts_request.cpp | 49 +- frameworks/ets/ani/src/sts_subscribe.cpp | 43 +- .../ets/ani/src/subscribe/ani_remove.cpp | 41 + .../ets/ani/src/subscribe/ani_subscribe.cpp | 17 +- .../ets/ets/@ohos.notificationManager.ets | 959 +++++++++++++++--- .../ets/ets/@ohos.notificationSubscribe.ets | 131 +++ 40 files changed, 2629 insertions(+), 178 deletions(-) create mode 100644 frameworks/ets/ani/include/manager/ani_do_not_disturb_date.h create mode 100644 frameworks/ets/ani/include/manager/ani_open_settings.h create mode 100644 frameworks/ets/ani/include/manager/ani_remove_group.h create mode 100644 frameworks/ets/ani/include/manager/ani_sync_config.h create mode 100644 frameworks/ets/ani/src/manager/ani_do_not_disturb_date.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_open_settings.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_remove_group.cpp create mode 100644 frameworks/ets/ani/src/manager/ani_sync_config.cpp diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn index 627f97101..46336e3a1 100644 --- a/frameworks/ets/ani/BUILD.gn +++ b/frameworks/ets/ani/BUILD.gn @@ -45,6 +45,11 @@ ohos_shared_library("notification_manager_ani") { "./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", @@ -52,6 +57,7 @@ ohos_shared_library("notification_manager_ani") { "./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", @@ -60,6 +66,9 @@ ohos_shared_library("notification_manager_ani") { "./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 = [] diff --git a/frameworks/ets/ani/include/manager/ani_cance.h b/frameworks/ets/ani/include/manager/ani_cance.h index 5e3f19fd6..485c27fa7 100644 --- a/frameworks/ets/ani/include/manager/ani_cance.h +++ b/frameworks/ets/ani/include/manager/ani_cance.h @@ -24,6 +24,9 @@ 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 index a9489f60b..a292920bf 100644 --- a/frameworks/ets/ani/include/manager/ani_display_badge.h +++ b/frameworks/ets/ani/include/manager/ani_display_badge.h @@ -21,6 +21,8 @@ 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 index 4a712316f..385c801ac 100755 --- a/frameworks/ets/ani/include/manager/ani_distributed_enable.h +++ b/frameworks/ets/ani/include/manager/ani_distributed_enable.h @@ -18,11 +18,19 @@ namespace OHOS { namespace NotificationManagerSts { -void AniSetDistributedEnable(ani_env* env, ani_boolean enabled); +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 000000000..721ba1d52 --- /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 index b4a0ac997..c5e9b03c1 100644 --- a/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h +++ b/frameworks/ets/ani/include/manager/ani_do_not_disturb_profile.h @@ -21,6 +21,7 @@ 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 index b2d18712d..3d8861090 100644 --- a/frameworks/ets/ani/include/manager/ani_get_active.h +++ b/frameworks/ets/ani/include/manager/ani_get_active.h @@ -22,6 +22,7 @@ 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_notification_enable.h b/frameworks/ets/ani/include/manager/ani_notification_enable.h index 93dee4348..bb657a6e2 100644 --- a/frameworks/ets/ani/include/manager/ani_notification_enable.h +++ b/frameworks/ets/ani/include/manager/ani_notification_enable.h @@ -24,7 +24,10 @@ 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_open_settings.h b/frameworks/ets/ani/include/manager/ani_open_settings.h new file mode 100644 index 000000000..1617ec391 --- /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 index fd18fc59c..33a018c6a 100644 --- a/frameworks/ets/ani/include/manager/ani_publish.h +++ b/frameworks/ets/ani/include/manager/ani_publish.h @@ -21,6 +21,8 @@ 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_remove_group.h b/frameworks/ets/ani/include/manager/ani_remove_group.h new file mode 100644 index 000000000..1ec3dbe08 --- /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_sync_config.h b/frameworks/ets/ani/include/manager/ani_sync_config.h new file mode 100644 index 000000000..a337aed87 --- /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_bundle_option.h b/frameworks/ets/ani/include/sts_bundle_option.h index a1bc56061..5bda338dd 100644 --- a/frameworks/ets/ani/include/sts_bundle_option.h +++ b/frameworks/ets/ani/include/sts_bundle_option.h @@ -26,6 +26,7 @@ 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); } } diff --git a/frameworks/ets/ani/include/sts_disturb_mode.h b/frameworks/ets/ani/include/sts_disturb_mode.h index eb208a289..491450d9f 100644 --- a/frameworks/ets/ani/include/sts_disturb_mode.h +++ b/frameworks/ets/ani/include/sts_disturb_mode.h @@ -25,6 +25,7 @@ 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_manager.h b/frameworks/ets/ani/include/sts_notification_manager.h index bf9cba112..f2d72b257 100644 --- a/frameworks/ets/ani/include/sts_notification_manager.h +++ b/frameworks/ets/ani/include/sts_notification_manager.h @@ -18,6 +18,7 @@ #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" @@ -33,6 +34,15 @@ 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, @@ -69,6 +79,12 @@ enum class STSRemindType { 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); @@ -153,8 +169,12 @@ bool DeviceRemindTypeEtsToC(ani_env *env, ani_enum_item enumItem, RemindType &re 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 diff --git a/frameworks/ets/ani/include/sts_request.h b/frameworks/ets/ani/include/sts_request.h index 02a69f21d..c35fee773 100644 --- a/frameworks/ets/ani/include/sts_request.h +++ b/frameworks/ets/ani/include/sts_request.h @@ -43,6 +43,7 @@ ani_object GetAniNotificationRequestArray(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_subscribe.h b/frameworks/ets/ani/include/sts_subscribe.h index 9f948df7e..bfa5abf07 100644 --- a/frameworks/ets/ani/include/sts_subscribe.h +++ b/frameworks/ets/ani/include/sts_subscribe.h @@ -112,6 +112,7 @@ public: 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() {} diff --git a/frameworks/ets/ani/include/sts_throw_erro.h b/frameworks/ets/ani/include/sts_throw_erro.h index 44f75ae9b..642ed3b42 100644 --- a/frameworks/ets/ani/include/sts_throw_erro.h +++ b/frameworks/ets/ani/include/sts_throw_erro.h @@ -60,7 +60,7 @@ inline std::string FindAnsErrMsg(const int32_t errCode) { auto findMsg = ERROR_CODE_TO_MESSAGE.find(errCode); if (findMsg == ERROR_CODE_TO_MESSAGE.end()) { - ANSR_LOGE("FindAnsErrMsg Inner error."); + ANS_LOGE("FindAnsErrMsg Inner error."); return "Inner error."; } return findMsg->second; @@ -68,6 +68,7 @@ inline std::string FindAnsErrMsg(const int32_t errCode) 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)); } diff --git a/frameworks/ets/ani/include/subscribe/ani_remove.h b/frameworks/ets/ani/include/subscribe/ani_remove.h index a60aa5ab8..c10e15dc4 100644 --- a/frameworks/ets/ani/include/subscribe/ani_remove.h +++ b/frameworks/ets/ani/include/subscribe/ani_remove.h @@ -22,6 +22,8 @@ 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); } } #endif \ 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 index 180bedaac..600558eff 100644 --- a/frameworks/ets/ani/src/manager/ani_cance.cpp +++ b/frameworks/ets/ani/src/manager/ani_cance.cpp @@ -114,5 +114,76 @@ void AniCancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string label) } 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 index 7cba58762..ed01c043a 100644 --- a/frameworks/ets/ani/src/manager/ani_display_badge.cpp +++ b/frameworks/ets/ani/src/manager/ani_display_badge.cpp @@ -78,5 +78,39 @@ ani_boolean AniIsBadgeDisplayed(ani_env *env, ani_object obj) 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 index fa63aae21..4beb262fd 100755 --- a/frameworks/ets/ani/src/manager/ani_distributed_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_distributed_enable.cpp @@ -96,5 +96,197 @@ ani_boolean AniIsDistributedEnabledByBundleType(ani_env* env, ani_object obj, an 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 000000000..7d09b4241 --- /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 index 0d7158d5f..0bd98152f 100644 --- a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -20,6 +20,7 @@ #include "sts_common.h" #include "sts_throw_erro.h" #include "sts_disturb_mode.h" +#include "sts_bundle_option.h" namespace OHOS { namespace NotificationManagerSts { @@ -64,5 +65,41 @@ void AniRemoveDoNotDisturbProfile(ani_env *env, ani_object obj) } 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)); + } + + ANS_LOGD("doNotDisturbProfile ProfileId: %{public}lld, ProfileName %{public}s", + doNotDisturbProfile->GetProfileId(), doNotDisturbProfile->GetProfileName().c_str()); + 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 index 74e1ccd83..93c02e572 100644 --- a/frameworks/ets/ani/src/manager/ani_get_active.cpp +++ b/frameworks/ets/ani/src/manager/ani_get_active.cpp @@ -90,5 +90,34 @@ ani_object AniGetActiveNotifications(ani_env *env) 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_manager.cpp b/frameworks/ets/ani/src/manager/ani_manager.cpp index d5679284e..7cecd7021 100644 --- a/frameworks/ets/ani/src/manager/ani_manager.cpp +++ b/frameworks/ets/ani/src/manager/ani_manager.cpp @@ -19,6 +19,7 @@ #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" @@ -27,6 +28,9 @@ #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 { @@ -75,6 +79,22 @@ static std::array kitManagerFunctions = { 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;" @@ -82,6 +102,18 @@ static std::array kitManagerFunctions = { ":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, @@ -100,6 +132,27 @@ static std::array kitManagerFunctions = { 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)}, diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index daaa2baef..c2b2529bd 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -27,9 +27,9 @@ ani_boolean AniIsNotificationEnabled(ani_env *env) { ANS_LOGD("AniIsNotificationEnabled call"); bool allowed = false; - int returncode = Notification::NotificationHelper::IsAllowedNotify(allowed); + int returncode = Notification::NotificationHelper::IsAllowedNotifySelf(allowed); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniIsNotificationEnabled -> error, errorCode: %{public}d", externalCode); } @@ -43,7 +43,7 @@ ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_double userId) bool allowed = false; int returncode = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniIsNotificationEnabledWithId -> error, errorCode: %{public}d", externalCode); } @@ -54,7 +54,7 @@ ani_boolean AniIsNotificationEnabledWithId(ani_env *env, ani_double userId) ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bundleOption) { ANS_LOGD("AniIsNotificationEnabledWithBundleOption call"); - int returncode = 0; + int returncode = ERR_OK; bool allowed = false; BundleOption option; if (NotificationSts::UnwrapBundleOption(env, bundleOption, option)) { @@ -65,7 +65,7 @@ ani_boolean AniIsNotificationEnabledWithBundleOption(ani_env *env, ani_object bu } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); ANS_LOGE("AniIsNotificationEnabledWithBundleOption -> error, errorCode: %{public}d", externalCode); return ANI_FALSE; @@ -86,13 +86,47 @@ void AniSetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean int returncode = Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(option, deviceId, NotificationSts::AniBooleanToBool(enable)); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { + 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"); @@ -100,12 +134,12 @@ ani_boolean AniGetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double use int returncode = Notification::NotificationHelper::GetSyncNotificationEnabledWithoutApp( static_cast(userId), enabled); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { - OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + 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); + ANS_LOGD("End success, enabled: %{public}d, returncode: %{public}d", enabled, externalCode); return NotificationSts::BoolToAniBoolean(enabled); } @@ -115,12 +149,35 @@ void AniSetSyncNotificationEnabledWithoutApp(ani_env* env, ani_double userId, an int returncode = Notification::NotificationHelper::SetSyncNotificationEnabledWithoutApp( static_cast(userId), NotificationSts::AniBooleanToBool(enabled)); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != CJSystemapi::Notification::SUCCESS_CODE) { - OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); + 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) != ANI_OK) { + 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_open_settings.cpp b/frameworks/ets/ani/src/manager/ani_open_settings.cpp new file mode 100644 index 000000000..962e28e77 --- /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 index 225be2cd1..ba7f1f4f8 100644 --- a/frameworks/ets/ani/src/manager/ani_publish.cpp +++ b/frameworks/ets/ani/src/manager/ani_publish.cpp @@ -17,6 +17,7 @@ #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" @@ -37,8 +38,7 @@ void AniPublish(ani_env *env, ani_object obj) } int returncode = NotificationHelper::PublishNotification(*notificationRequest); int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) { - ANS_LOGE("AniPublish error, errorCode: %{public}d", externalCode); + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } ANS_LOGD("AniPublish end"); @@ -50,18 +50,74 @@ void AniPublishWithId(ani_env *env, ani_object obj, ani_double userId) //NotificationRequest request; std::shared_ptr notificationRequest = std::make_shared(); if (NotificationSts::UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { - ANS_LOGE("UnWarpNotificationRequest failed"); 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 != 0) { + 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_remove_group.cpp b/frameworks/ets/ani/src/manager/ani_remove_group.cpp new file mode 100644 index 000000000..b916af197 --- /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_sync_config.cpp b/frameworks/ets/ani/src/manager/ani_sync_config.cpp new file mode 100644 index 000000000..5a05c28f7 --- /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_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index ecc112188..5f89307c8 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -44,6 +44,37 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification 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; + } + ani_size 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) { diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp index a24e389b8..1aca78724 100644 --- a/frameworks/ets/ani/src/sts_disturb_mode.cpp +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -88,5 +88,74 @@ bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, 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; + } + + size_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 ddd 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_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index afc5f6c1b..acde5ca6a 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -218,6 +218,29 @@ bool StsSlotLevelUtils::StsToC(const STSSlotLevel inLevel, SlotLevel &outLevel) 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) { @@ -428,6 +451,19 @@ bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enu 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; @@ -676,5 +712,60 @@ bool WarpNotificationCheckInfo( 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: begin(%{public}lld) >= end(%{public}lld)", + doNotDisturbDate.GetBeginDate(), doNotDisturbDate.GetEndDate()); + 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 index ed25b307b..ed3de90e9 100644 --- a/frameworks/ets/ani/src/sts_request.cpp +++ b/frameworks/ets/ani/src/sts_request.cpp @@ -25,6 +25,8 @@ #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 { @@ -1146,10 +1148,6 @@ bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::Notificatio ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests) { - if (requests.empty()) { - ANS_LOGE("actionButtons is empty"); - return nullptr; - } ani_object arrayObj = newArrayClass(env, requests.size()); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is nullptr"); @@ -1175,10 +1173,6 @@ ani_object GetAniNotificationRequestArray(ani_env *env, std::vector> requests) { - if (requests.empty()) { - ANS_LOGE("actionButtons is empty"); - return nullptr; - } ani_object arrayObj = newArrayClass(env, requests.size()); if (arrayObj == nullptr) { ANS_LOGE("arrayObj is nullptr"); @@ -1285,5 +1279,44 @@ bool UnWarpNotificationCheckRequest(ani_env *env, ani_object obj, sptr(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_subscribe.cpp b/frameworks/ets/ani/src/sts_subscribe.cpp index 441e053c1..1fd46299f 100644 --- a/frameworks/ets/ani/src/sts_subscribe.cpp +++ b/frameworks/ets/ani/src/sts_subscribe.cpp @@ -609,13 +609,13 @@ bool SubscriberInstanceManager::Subscribe(ani_env *env, ani_object subscriber, a return false; } } - ErrCode status = 0; + ErrCode status = ERR_OK; if (!isInfoUndefine) { status = NotificationHelper::SubscribeNotification(stsSubscriber, SubscribeInfo); } else { status = NotificationHelper::SubscribeNotification(stsSubscriber); } - if (status != 0) { + if (status != ERR_OK) { int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(status); externalErrorCode = (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? status : externalErrorCode; @@ -647,7 +647,7 @@ bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) bool ret = AddDeletingSubscriber(stsSubscriber); if (ret) { int32_t status = NotificationHelper::UnSubscribeNotification(stsSubscriber); - if (status != 0) { + if (status != ERR_OK) { int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(status); externalErrorCode = (externalErrorCode == CJSystemapi::Notification::SUCCESS_CODE) ? status : externalErrorCode; @@ -665,6 +665,43 @@ bool SubscriberInstanceManager::UnSubscribe(ani_env *env, ani_object subscriber) 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) { diff --git a/frameworks/ets/ani/src/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp index be660d9fb..8db7371bd 100644 --- a/frameworks/ets/ani/src/subscribe/ani_remove.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -130,5 +130,46 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); } } + +void AniRemoveAllForBundle(ani_env *env, ani_object bundle) +{ + ANS_LOGD("removeAll enter"); + int retcode = ERR_OK; + bool isForBundleUndefine = NotificationSts::IsUndefine(env, bundle); + if (isForBundleUndefine) { + retcode = NotificationHelper::RemoveNotifications(); + std::string msg = "IsUndefine falid"; + ANS_LOGE("IsUndefine is falid"); + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + BundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { + ANS_LOGE("bundle is valid"); + std::string msg = "UnwrapBundleOption faild"; + OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); + return; + } + int ret = NotificationHelper::RemoveAllNotifications(option); + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + if (ret != ERR_OK) { + std::string msg = OHOS::NotificationSts::FindAnsErrMsg(externalErrorCode); + OHOS::AbilityRuntime::ThrowStsError(env, externalErrorCode, msg); + } +} + +void AniRemoveAllForUserId(ani_env *env, ani_double userId) +{ + ANS_LOGD("removeAll enter"); + ANS_LOGD("sts RemoveAll call, userId:%{public}lf", userId); + int ret = NotificationHelper::RemoveNotifications(userId); + int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); + ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); + if (ret != ERR_OK) { + 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 index 03f5caef5..0bc5efab4 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -39,6 +39,9 @@ static const char *SUBSCRIBE_SIGNATURE = "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"; ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo) { @@ -90,6 +93,12 @@ void AniUnSubscribe(ani_env *env, ani_object obj) 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"); @@ -101,7 +110,8 @@ void AniSubScribeRegistryInit(ani_env *env) } std::array methods = { - ani_native_function {"nativeRemove", REMOVE_FOR_BUNDLE_SIGNATURE, reinterpret_cast(AniRemoveForBundle)}, + 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", @@ -110,6 +120,11 @@ void AniSubScribeRegistryInit(ani_env *env) 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)}, }; ANS_LOGD("Start bind native methods to '%{public}s'", npName); diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index ee2307572..f621dcb2f 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -27,6 +27,7 @@ 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; @@ -137,10 +138,13 @@ export default namespace notificationManager { 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; @@ -167,6 +171,10 @@ export default namespace notificationManager { 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; @@ -186,6 +194,40 @@ export default namespace notificationManager { 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) { @@ -222,22 +264,13 @@ export default namespace notificationManager { function isInvalidParameter(bundle: BundleOption): BusinessError { - let error: BusinessError = { - code: 0, - message: "" - } + let error: BusinessError = successCallbackError if (bundle == null) { - error = { - code: 401, - message: "BundleOption must be not Null" - } + error = errorParamInvalid return error; } if (bundle.bundle == null || bundle.bundle?.length === 0) { - error = { - code: 401, - message: "Incorrect parameter types. The type of bundle must be string." - } + error = errorParamInvalid return error; } return error; @@ -245,24 +278,33 @@ export default namespace notificationManager { function isInvalidParameter(option: ButtonOptions): BusinessError { - let error: BusinessError = { - code: 0, - message: "" - } + let error: BusinessError = successCallbackError if (option == null) { - error = { - code: 401, - message: "ButtonOptions must be not Null" - } + error = errorParamInvalid return error; } if (option.buttonName == null || option.buttonName?.length === 0) { - error = { - code: 401, - message: "Incorrect parameter types. The type of buttonName must be string." - } + 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 @@ -449,22 +491,13 @@ export default namespace notificationManager { } function isInvalidParameter(request: NotificationRequest): BusinessError { - let error: BusinessError = { - code: 0, - message: "" - } + let error: BusinessError = successCallbackError if (request == null) { - error = { - code: 401, - message: "request must be not Null" - } + error = errorParamInvalid return error; } if (request.content == null || request.content == undefined) { - error = { - code: 401, - message: "request.content must be not Null" - } + error = errorParamInvalid return error; } if (request.content?.normal !== undefined && !isInvalidContent(request.content.normal)) { @@ -562,7 +595,7 @@ export default namespace notificationManager { export function getSlotNumByBundle(bundle: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -579,7 +612,7 @@ export default namespace notificationManager { export function getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { @@ -599,11 +632,11 @@ export default namespace notificationManager { export function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let slotError: BusinessError = isInvalidParameter(slot); - if (slotError.code !== 0) { + if (slotError.code !== ERROR_OK) { throw slotError; } if (callback == null) { @@ -621,11 +654,11 @@ export default namespace notificationManager { export function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let slotError: BusinessError = isInvalidParameter(slot); - if (slotError.code !== 0) { + if (slotError.code !== ERROR_OK) { throw slotError; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -783,7 +816,7 @@ export default namespace notificationManager { export function addSlot(slot: NotificationSlot): Promise { let slotError: BusinessError = isInvalidParameter(slot); - if (slotError.code !== 0) { + if (slotError.code !== ERROR_OK) { throw slotError; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -799,7 +832,7 @@ export default namespace notificationManager { export function addSlot(slot: NotificationSlot, callback: AsyncCallback): void { let slotError: BusinessError = isInvalidParameter(slot); - if (slotError.code !== 0) { + if (slotError.code !== ERROR_OK) { throw slotError; } if (callback == null) { @@ -844,7 +877,7 @@ export default namespace notificationManager { export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -861,13 +894,11 @@ export default namespace notificationManager { export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { @@ -882,13 +913,11 @@ export default namespace notificationManager { export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundleOption); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabledWithBundleOption(bundleOption); }); p.then((data: NullishType): void => { @@ -905,7 +934,7 @@ export default namespace notificationManager { export function isNotificationEnabled(bundleOption: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundleOption); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -992,13 +1021,11 @@ export default namespace notificationManager { callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute( (): void => { return nativeSetNotificationEnableSlotWithForce(bundle, type, enable, isForceControl); @@ -1016,7 +1043,7 @@ export default namespace notificationManager { bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let forceControl: boolean = false; @@ -1040,13 +1067,11 @@ export default namespace notificationManager { bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable); }); p.then((data: NullishType): void => { @@ -1061,7 +1086,7 @@ export default namespace notificationManager { export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1079,13 +1104,11 @@ export default namespace notificationManager { export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { @@ -1102,13 +1125,11 @@ export default namespace notificationManager { export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); p.then((data: NullishType): void => { @@ -1125,7 +1146,7 @@ export default namespace notificationManager { export function getSlotsByBundle(bundle: BundleOption): Promise> { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise>( @@ -1143,7 +1164,7 @@ export default namespace notificationManager { export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1159,7 +1180,7 @@ export default namespace notificationManager { export function getSlotFlagsByBundle(bundle: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1176,13 +1197,11 @@ export default namespace notificationManager { export function publish(request: NotificationRequest, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(request); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativePublish(request); }); p.then((data: NullishType): void => { @@ -1196,7 +1215,7 @@ export default namespace notificationManager { export function publish(request: NotificationRequest): Promise { let error: BusinessError = isInvalidParameter(request); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1212,13 +1231,11 @@ export default namespace notificationManager { export function publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(request); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); p.then((data: NullishType): void => { @@ -1232,7 +1249,7 @@ export default namespace notificationManager { export function publish(request: NotificationRequest, userId: number): Promise { let error: BusinessError = isInvalidParameter(request); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1250,11 +1267,11 @@ export default namespace notificationManager { bundle: BundleOption, notificationId: number, buttonOptions: ButtonOptions): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } error = isInvalidParameter(buttonOptions); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1288,11 +1305,7 @@ export default namespace notificationManager { export function removeDoNotDisturbProfile(templates: Array): Promise { if (!templates || templates.length === 0) { - let error: BusinessError = { - code: 401, - message: "templates must be not null" - } - throw error; + throw errorParamInvalid; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); @@ -1307,11 +1320,7 @@ export default namespace notificationManager { export function addDoNotDisturbProfile(templates: Array): Promise { if (!templates || templates.length === 0) { - let error: BusinessError = { - code: 401, - message: "templates must be not null" - } - throw error; + throw errorParamInvalid; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); @@ -1326,11 +1335,7 @@ export default namespace notificationManager { export function getAllActiveNotifications(callback: AsyncCallback>): void { if (!callback) { - let error: BusinessError = { - code: 401, - message: "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): Array => { return nativeGetAllActiveNotifications(); }); p.then((data: NullishType): void => { @@ -1374,11 +1379,7 @@ export default namespace notificationManager { export function getActiveNotifications(callback: AsyncCallback>): void { if (!callback) { - let error: BusinessError = { - code: 401, - message: "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): Array => { return nativeGetActiveNotifications(); }); p.then((data: NullishType): void => { @@ -1392,6 +1393,22 @@ export default namespace notificationManager { }) } + 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(); }); @@ -1407,13 +1424,11 @@ export default namespace notificationManager { export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { - error.code = 401; - error.message = "callback must be not null"; - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); p.then((e: NullishType): void => { @@ -1427,7 +1442,7 @@ export default namespace notificationManager { export function displayBadge(bundle: BundleOption, enable: boolean): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1443,7 +1458,7 @@ export default namespace notificationManager { export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); @@ -1460,7 +1475,7 @@ export default namespace notificationManager { export function isBadgeDisplayed(bundle: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1477,7 +1492,7 @@ export default namespace notificationManager { export function cancel(bundle: BundleOption, id: number): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1493,11 +1508,7 @@ export default namespace notificationManager { export function cancel(id: number, label?: string): Promise { if (label == null || label?.length === 0) { - let error: BusinessError = { - code: 401, - message: "Incorrect parameter types. The type of label must be string." - } - throw error; + throw errorParamInvalid; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeCancelWithIdOptionalLabel(id, label); }); @@ -1512,11 +1523,7 @@ export default namespace notificationManager { export function cancel(id: number, label: string, callback: AsyncCallback): void { if (label == null || label?.length === 0) { - let error: BusinessError = { - code: 401, - message: "Incorrect parameter types. The type of label must be string." - } - throw error; + throw errorParamInvalid; } if (callback == null) { throw errorParamInvalid; @@ -1533,11 +1540,7 @@ export default namespace notificationManager { export function cancel(id: number, callback: AsyncCallback): void { if (callback == null) { - let error: BusinessError = { - code: 410, - message : "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); p.then((data: NullishType): void => { @@ -1563,11 +1566,7 @@ export default namespace notificationManager { export function cancelAll(callback: AsyncCallback): void { if (callback == null) { - let error: BusinessError = { - code: 410, - message : "callback must be not null" - } - throw error; + throw errorParamInvalid; } let p = taskpool.execute((): void => { return nativeCancelAll(); }); p.then((data: NullishType): void => { @@ -1719,6 +1718,122 @@ export default namespace notificationManager { 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: Object): 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: Object): 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: Object): 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } export function isSupportTemplate(templateName: string): Promise { @@ -1734,36 +1849,584 @@ export default namespace notificationManager { return pPromise; } - export function isSupportTemplate(templateName: string, callback: AsyncCallback): void + export function removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback): void { - if (callback == null) { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== ERROR_OK) { + throw error; + } + if (groupName === '') { throw errorParamInvalid; } - let p = taskpool.execute((): boolean => { return nativeIsSupportTemplate(templateName); }); + if (!callback) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { return nativeRemoveGroupByBundle(bundle, groupName); }); p.then((data: NullishType): void => { - let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; - callback(err, ret); + callback(err, undefined); }, (error: Object): void => { - let ret : boolean = false; let err: BusinessError = error as BusinessError; - callback(err, ret); + callback(err, undefined); }) } - export function setDistributedEnable(enable: boolean, callback: AsyncCallback): void + 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: Object): 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: Object): 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback): void { if (callback == null) { throw errorParamInvalid; } - let p = taskpool.execute((): void => { return nativeSetDistributedEnable(enable); }); + 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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: Object): 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 @@ -1813,7 +2476,7 @@ export default namespace notificationManager { export function isDistributedEnabledByBundle(bundle: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { @@ -1832,7 +2495,7 @@ export default namespace notificationManager { { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == null) { @@ -1853,7 +2516,7 @@ export default namespace notificationManager { export function isDistributedEnabledByBundle(bundle: BundleOption, deviceType: string): Promise { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index b6f139162..21a9c6bc1 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -31,6 +31,27 @@ 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 { @@ -58,6 +79,9 @@ export default namespace notificationSubscribe { 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 function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void { if (subscriber == undefined || callback == undefined) { @@ -303,4 +327,111 @@ export default namespace notificationSubscribe { 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: Object): void => { + reject(error); + } + ) + }); + return pPromise; + } + + export function removeAll(bundle: BundleOption, callback: AsyncCallback): void { + let error: BusinessError = isInvalidParameter(bundle); + if (error.code !== 0) { + 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.nativeRemoveAllForBundle(); + } else { + return notificationSubscribe.nativeRemoveAllForBundle(bundle); + } + }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeAll(callback: AsyncCallback): void { + if (callback == undefined) { + throw errorParamInvalid; + } + let p = taskpool.execute((): void => { + return notificationSubscribe.nativeRemoveAllForBundle(); + }); + 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: Object): void => { + reject(error); + }); + }); + return pPromise; + } } \ No newline at end of file -- Gitee From cda580bcb5f59cc893e77c4aeb5deac5786c034b Mon Sep 17 00:00:00 2001 From: heguokai Date: Fri, 6 Jun 2025 00:55:22 +0800 Subject: [PATCH 43/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/sts_disturb_mode.cpp | 2 +- frameworks/ets/ani/src/subscribe/ani_subscribe.cpp | 2 +- frameworks/ets/ets/@ohos.notificationSubscribe.ets | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp index 1aca78724..0b9924ebd 100644 --- a/frameworks/ets/ani/src/sts_disturb_mode.cpp +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -144,7 +144,7 @@ bool WrapDoNotDisturbProfile(ani_env* env, sptr } ani_double id = static_cast(profile->GetProfileId()); if (ANI_OK != (status = env->Object_SetPropertyByName_Double(outObj, "id", id))) { - ANS_LOGE("WrapDoNotDisturbProfile ddd set reason faild. status %{public}d", status); + ANS_LOGE("WrapDoNotDisturbProfile : set reason faild. status %{public}d", status); return false; } if (!SetPropertyOptionalByString(env, outObj, "name", profile->GetProfileName())) { diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp index 0bc5efab4..b951b75f1 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -124,7 +124,7 @@ void AniSubScribeRegistryInit(ani_env *env) ani_native_function {"nativeRemoveAllForBundle", REMOVEALL_FOR_BUNDLEOPTION_SIGNATURE, reinterpret_cast(AniRemoveAllForBundle)}, ani_native_function {"nativeRemoveAllForUserId", - REMOVEALL_FOR_USERID_STGNATURE,reinterpret_cast(AniRemoveAllForUserId)}, + REMOVEALL_FOR_USERID_STGNATURE, reinterpret_cast(AniRemoveAllForUserId)}, }; ANS_LOGD("Start bind native methods to '%{public}s'", npName); diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index 21a9c6bc1..9bad8d255 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -347,7 +347,7 @@ export default namespace notificationSubscribe { export function removeAll(bundle: BundleOption, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); - if (error.code !== 0) { + if (error.code !== ERROR_OK) { throw error; } if (callback == undefined) { -- Gitee From 9f91a640893115c999d3c3bea1cbac9d9a3b728c Mon Sep 17 00:00:00 2001 From: heguokai Date: Fri, 6 Jun 2025 11:02:58 +0800 Subject: [PATCH 44/52] modify Signed-off-by: heguokai --- frameworks/ets/ani/src/manager/ani_notification_enable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp index c2b2529bd..ba521c2dc 100644 --- a/frameworks/ets/ani/src/manager/ani_notification_enable.cpp +++ b/frameworks/ets/ani/src/manager/ani_notification_enable.cpp @@ -161,7 +161,7 @@ void AniDisableNotificationFeature(ani_env *env, ani_boolean disabled, ani_objec { ANS_LOGD("AniDisableNotificationFeature enter"); std::vector bundleListStd; - if (NotificationSts::GetStringArrayByAniObj(env, bundleList, bundleListStd) != ANI_OK) { + 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); -- Gitee From 73872d09c84dee753fa758c1649a6089317611ea Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 9 Jun 2025 20:44:45 +0800 Subject: [PATCH 45/52] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: heguokai --- .../ets/ets/@ohos.notificationManager.ets | 327 ++++++++++-------- .../ets/notification/notificationRequest.ets | 2 - 2 files changed, 192 insertions(+), 137 deletions(-) diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index f621dcb2f..ab484c2cb 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -246,11 +246,11 @@ export default namespace notificationManager { } } if (slot.desc !== undefined && slot.desc?.trim() === '') { - return errorParamInvalid; - } + return errorParamInvalid; + } if (slot.sound !== undefined && slot.sound?.trim() === '') { - return errorParamInvalid; - } + return errorParamInvalid; + } if (slot.vibrationValues !== undefined && slot.vibrationValues?.length === 0) { return errorParamInvalid; } @@ -310,183 +310,240 @@ export default namespace notificationManager { 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 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?.longText || longText?.longText?.trim() === '') { - return false; - } - if (!longText?.briefText || longText?.briefText?.trim() === '') { - return false; - } - if (!longText?.expandedTitle || longText?.expandedTitle?.trim() === '') { - return false; - } + 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?.briefText || multiLine?.briefText.trim() === '') { - return false; - } - if (!multiLine?.longTitle || multiLine?.longTitle.trim() === '') { - return false; - } - if (multiLine?.lines?.length === 0) { - return false; - } - + 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?.briefText || picture?.briefText?.trim() === '') { - return false; - } - if (!picture?.expandedTitle || picture?.expandedTitle?.trim() === '') { - return false; - } - if (!(picture?.picture instanceof image.PixelMap)) { - return false; - } + 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?.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 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?.extraInfo !== undefined && liveView?.extraInfo === null) { - return false; - } - if (liveView?.pictureInfo !== undefined && liveView?.pictureInfo === null) { - return false; - } + 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 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 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 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 false; + } + if (bundleOption?.bundle != undefined && bundleOption?.bundle?.trim() === '') { + return false; + } return true; } function isInvalidParameter(request: NotificationRequest): BusinessError diff --git a/frameworks/ets/ets/notification/notificationRequest.ets b/frameworks/ets/ets/notification/notificationRequest.ets index 5b1993bd1..b990da8d5 100644 --- a/frameworks/ets/ets/notification/notificationRequest.ets +++ b/frameworks/ets/ets/notification/notificationRequest.ets @@ -108,7 +108,6 @@ export interface NotificationRequest { readonly creatorUid?: number; readonly creatorPid?: number; readonly creatorUserId?: number; - readonly creatorInstanceKey?: number; sound?: string; classification?: string; readonly hashCode?: string; @@ -160,7 +159,6 @@ class NotificationRequestInner implements NotificationRequest { public readonly creatorUid?: number | undefined; public readonly creatorPid?: number | undefined; public readonly creatorUserId?: number | undefined; - public readonly creatorInstanceKey?: number | undefined; public sound?: string | undefined; public classification?: string | undefined; public readonly hashCode?: string | undefined; -- Gitee From 2d967d993350a773fcc1d73a52e9495c8e244255 Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 9 Jun 2025 20:53:18 +0800 Subject: [PATCH 46/52] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: heguokai --- frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp | 2 -- frameworks/ets/ani/src/sts_bundle_option.cpp | 2 +- frameworks/ets/ani/src/sts_disturb_mode.cpp | 2 +- frameworks/ets/ani/src/sts_notification_manager.cpp | 3 +-- 4 files changed, 3 insertions(+), 6 deletions(-) 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 index 0bd98152f..71f94dd19 100644 --- a/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp +++ b/frameworks/ets/ani/src/manager/ani_do_not_disturb_profile.cpp @@ -89,8 +89,6 @@ ani_object AniGetDoNotDisturbProfile(ani_env *env, ani_double id) OHOS::AbilityRuntime::ThrowStsError(env, externalCode, NotificationSts::FindAnsErrMsg(externalCode)); } - ANS_LOGD("doNotDisturbProfile ProfileId: %{public}lld, ProfileName %{public}s", - doNotDisturbProfile->GetProfileId(), doNotDisturbProfile->GetProfileName().c_str()); if (!NotificationSts::WrapDoNotDisturbProfile(env, doNotDisturbProfile, profile)) { ANS_LOGE("AniGetDoNotDisturbProfile WrapDoNotDisturbProfile failed"); OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, diff --git a/frameworks/ets/ani/src/sts_bundle_option.cpp b/frameworks/ets/ani/src/sts_bundle_option.cpp index 5f89307c8..2cf67a9bf 100644 --- a/frameworks/ets/ani/src/sts_bundle_option.cpp +++ b/frameworks/ets/ani/src/sts_bundle_option.cpp @@ -57,7 +57,7 @@ ani_object GetAniArrayBundleOption(ani_env* env, ANS_LOGE("GetAniArrayActionButton: arrayObj is nullptr"); return nullptr; } - ani_size index = 0; + int32_t index = 0; for (auto &option : bundleOptions) { std::shared_ptr optSp = std::make_shared(option); ani_object item; diff --git a/frameworks/ets/ani/src/sts_disturb_mode.cpp b/frameworks/ets/ani/src/sts_disturb_mode.cpp index 0b9924ebd..1cc2f7c28 100644 --- a/frameworks/ets/ani/src/sts_disturb_mode.cpp +++ b/frameworks/ets/ani/src/sts_disturb_mode.cpp @@ -104,7 +104,7 @@ bool WrapProfileTrustList(ani_env* env, sptr pr return false; } - size_t index = 0; + int32_t index = 0; for (const auto& bundle : trustList) { auto bundlePtr = std::make_shared(bundle); ani_object bundleObj = nullptr; diff --git a/frameworks/ets/ani/src/sts_notification_manager.cpp b/frameworks/ets/ani/src/sts_notification_manager.cpp index acde5ca6a..eb0116381 100644 --- a/frameworks/ets/ani/src/sts_notification_manager.cpp +++ b/frameworks/ets/ani/src/sts_notification_manager.cpp @@ -760,8 +760,7 @@ bool UnWarpNotificationDoNotDisturbDate( doNotDisturbDate.SetEndDate(static_cast(mDouble)); } if (doNotDisturbDate.GetBeginDate() >= doNotDisturbDate.GetEndDate()) { - ANS_LOGE("Invalid time range: begin(%{public}lld) >= end(%{public}lld)", - doNotDisturbDate.GetBeginDate(), doNotDisturbDate.GetEndDate()); + ANS_LOGE("Invalid time range"); return false; } ANS_LOGD("Successfully parsed DoNotDisturbDate"); -- Gitee From 31749be97aa1e902119f0387155bcd7d48207f8f Mon Sep 17 00:00:00 2001 From: Martin Sajti Date: Wed, 28 May 2025 10:59:13 +0200 Subject: [PATCH 47/52] Fix invlid code after primitive type refactor Change-Id: I0615ceabceb8503b09b036dbbb595fe63eda1bc7 Signed-off-by: Martin Sajti --- .../ets/ets/@ohos.notificationManager.ets | 224 +++++++++--------- .../ets/ets/@ohos.notificationSubscribe.ets | 34 +-- 2 files changed, 129 insertions(+), 129 deletions(-) diff --git a/frameworks/ets/ets/@ohos.notificationManager.ets b/frameworks/ets/ets/@ohos.notificationManager.ets index ab484c2cb..1bd0e6d84 100644 --- a/frameworks/ets/ets/@ohos.notificationManager.ets +++ b/frameworks/ets/ets/@ohos.notificationManager.ets @@ -31,7 +31,7 @@ import { NotificationFilter } from 'notification.notificationRequest'; import image from '@ohos.multimedia.image'; type ResolveCallback = (data: T) => void; -type RejectCallback = (err: Object) => void; +type RejectCallback = (err: Error) => void; type CallbackForCheckInfo = (checkInfo: notificationManager.NotificationCheckInfo)=> notificationManager.NotificationCheckResult; @@ -649,7 +649,7 @@ export default namespace notificationManager { } return error; } - + export function getSlotNumByBundle(bundle: BundleOption): Promise { let error: BusinessError = isInvalidParameter(bundle); if (error.code !== ERROR_OK) { @@ -660,7 +660,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : number = data as number; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -680,7 +680,7 @@ export default namespace notificationManager { let ret : number = data as number; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret: number = -1; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -703,7 +703,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -722,7 +722,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetSlotByBundle(bundle, slot); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -737,7 +737,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -748,7 +748,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeRemoveAllSlots(); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -763,7 +763,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -774,7 +774,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeRemoveSlot(slotType); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -787,7 +787,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : Array = data as Array; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -803,7 +803,7 @@ export default namespace notificationManager { let ret : Array = data as Array; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : Array = []; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -816,7 +816,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : NotificationSlot = data as NotificationSlot; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -832,7 +832,7 @@ export default namespace notificationManager { let ret : NotificationSlot = data as NotificationSlot; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : NotificationSlot = { enabled: false, reminderMode: 0, authorizedStatus: 0 } as NotificationSlot; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -847,7 +847,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeAddSlots(slots); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -865,7 +865,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -880,7 +880,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeAddSlotByNotificationSlot(slot); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -899,7 +899,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -913,7 +913,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -924,7 +924,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeAddSlotBySlotType(type); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -941,13 +941,13 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); return pPromise; } - + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let error: BusinessError = isInvalidParameter(bundle); @@ -961,7 +961,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -981,7 +981,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -1001,7 +1001,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1018,7 +1018,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -1032,7 +1032,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1049,7 +1049,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -1063,7 +1063,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1090,7 +1090,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -1113,7 +1113,7 @@ export default namespace notificationManager { }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1134,7 +1134,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -1151,7 +1151,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1172,7 +1172,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -1193,13 +1193,13 @@ export default namespace notificationManager { let slots : Array = data as Array; let err: BusinessError = {code: 0, data: undefined}; callback(err, slots); - }, (error: Object): void => { + }, (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); @@ -1212,7 +1212,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let slots : Array = data as Array; resolve(slots); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1228,7 +1228,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetSlotFlagsByBundle(bundle, slotFlags); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1245,7 +1245,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : Double = data as Double; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1264,7 +1264,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -1279,7 +1279,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativePublish(request); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1298,12 +1298,12 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (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) { @@ -1313,7 +1313,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativePublishWithUserId(request, userId); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1333,11 +1333,11 @@ export default namespace notificationManager { } let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { - return nativeTriggerSystemLiveView(bundle, notificationId, buttonOptions); + return nativeTriggerSystemLiveView(bundle, notificationId, buttonOptions); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1353,7 +1353,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSubscribeSystemLiveView(subscriber); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1368,7 +1368,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeRemoveDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1383,7 +1383,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeAddDoNotDisturbProfile(templates); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1399,7 +1399,7 @@ export default namespace notificationManager { let ret : Array = data as Array; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let retData : Array = []; let err: BusinessError = error as BusinessError; callback(err, retData); @@ -1414,7 +1414,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : Array = data as Array; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1427,7 +1427,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : Array = data as Array; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1443,7 +1443,7 @@ export default namespace notificationManager { let ret : Array = data as Array; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let retData : Array = []; let err: BusinessError = error as BusinessError; callback(err, retData); @@ -1472,7 +1472,7 @@ export default namespace notificationManager { p.then((data :NullishType): void => { let ret : number = data as number; resolve(ret); - }, (err:Object): void => { + }, (err:Error): void => { reject(err); }); }); @@ -1491,12 +1491,12 @@ export default namespace notificationManager { p.then((e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (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) { @@ -1506,7 +1506,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1523,13 +1523,13 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (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) { @@ -1540,7 +1540,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1556,7 +1556,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelWithBundle(bundle, id); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1571,7 +1571,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelWithIdOptionalLabel(id, label); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1589,7 +1589,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -1603,7 +1603,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -1614,7 +1614,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelAll(); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1629,7 +1629,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -1655,7 +1655,7 @@ export default namespace notificationManager { } } }, - (error: Object): void => { + (error: Error): void => { reject(error); } ) @@ -1682,7 +1682,7 @@ export default namespace notificationManager { } } }, - (error: Object): void => { + (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -1722,7 +1722,7 @@ export default namespace notificationManager { await p.then( (e: NullishType): void => { result = e as notificationManager.NotificationCheckResult; - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; result = { code: err.code, @@ -1784,7 +1784,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let options : Array = data as Array; resolve(options); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1816,7 +1816,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetBadgeNumber(badgeNumber); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1833,7 +1833,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetBadgeNumberByBundle(bundle, badgeNumber); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1885,7 +1885,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : NotificationRequest = data as NotificationRequest; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1899,7 +1899,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1922,7 +1922,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -1941,7 +1941,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeRemoveGroupByBundle(bundle, groupName); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -1984,7 +1984,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativePublishAsBundle(request, representativeBundle, userId); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2005,7 +2005,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativePublishAsBundleWithBundleOption(representativeBundle, request); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2024,7 +2024,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }); @@ -2039,7 +2039,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelAsBundle(id, representativeBundle, userId); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2057,7 +2057,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelAsBundleWithBundleOption(representativeBundle, id); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2091,7 +2091,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeCancelGroup(groupName); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2127,7 +2127,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDate(date); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2163,7 +2163,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetDoNotDisturbDateWithId(date, userId); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2194,7 +2194,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; resolve(doNotDisturbDate); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2225,7 +2225,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let doNotDisturbDate : DoNotDisturbDate = data as DoNotDisturbDate; resolve(doNotDisturbDate); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2273,7 +2273,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2287,7 +2287,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : DoNotDisturbProfile = data as DoNotDisturbProfile; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2314,7 +2314,7 @@ export default namespace notificationManager { } } }, - (error: Object): void => { + (error: Error): void => { reject(error); } ) @@ -2327,7 +2327,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativesetTargetDeviceStatus(deviceType,status); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2344,7 +2344,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativesetDistributedEnabledByBundle(bundle, deviceType, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2362,7 +2362,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativesetDistributedEnableByBundle(bundle, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2375,7 +2375,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativesetSmartReminderEnabled(deviceType, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2389,7 +2389,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2404,7 +2404,7 @@ export default namespace notificationManager { }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2418,7 +2418,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2431,7 +2431,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : Double = data as Double; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2445,7 +2445,7 @@ export default namespace notificationManager { }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2492,7 +2492,7 @@ export default namespace notificationManager { let p = taskpool.execute((): void => { return nativeSetDistributedEnable(enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2506,7 +2506,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2523,7 +2523,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -2541,7 +2541,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2563,7 +2563,7 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); @@ -2581,7 +2581,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2596,7 +2596,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : DeviceRemindType = data as DeviceRemindType; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2613,7 +2613,7 @@ export default namespace notificationManager { let ret : DeviceRemindType = data as DeviceRemindType; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { const defaultRemindType: DeviceRemindType = DeviceRemindType.IDLE_DONOT_REMIND; let err: BusinessError = error as BusinessError; callback(err, defaultRemindType); @@ -2631,7 +2631,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); }) @@ -2644,7 +2644,7 @@ export default namespace notificationManager { { return nativeSetSyncNotificationEnabledWithoutApp(userId, enable); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2658,7 +2658,7 @@ export default namespace notificationManager { p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -2675,10 +2675,10 @@ export default namespace notificationManager { let ret : boolean = data as boolean; let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); - }, (error: Object): void => { + }, (error: Error): void => { let ret : boolean = false; let err: BusinessError = error as BusinessError; callback(err, ret); }) } -} \ No newline at end of file +} diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index 9bad8d255..81e911475 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -19,7 +19,7 @@ import { NotificationSubscribeInfo } from 'notification.notificationSubscribeInf import { NotificationSubscriber } from 'notification.notificationSubscriber'; type ResolveCallback = (data: T) => void; -type RejectCallback = (err: Object) => void; +type RejectCallback = (err: Error) => void; const ERROR_OK = 0; const ERROR_PARAM_INVALID = 401; @@ -92,7 +92,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -111,7 +111,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -126,7 +126,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -143,7 +143,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -159,7 +159,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -183,7 +183,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -205,7 +205,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -224,7 +224,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -242,7 +242,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -261,7 +261,7 @@ export default namespace notificationSubscribe { (e: NullishType): void => { let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); - }, (error: Object): void => { + }, (error: Error): void => { let err: BusinessError = error as BusinessError; callback(err, undefined); } @@ -279,7 +279,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -310,7 +310,7 @@ export default namespace notificationSubscribe { } else { resolve(undefined); } - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -337,7 +337,7 @@ export default namespace notificationSubscribe { p.then( (e: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); } ) @@ -380,7 +380,7 @@ export default namespace notificationSubscribe { }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); @@ -428,10 +428,10 @@ export default namespace notificationSubscribe { let p = taskpool.execute((): void => { return notificationSubscribe.nativeRemoveAllForUserId(userId); }); p.then((data: NullishType): void => { resolve(undefined); - }, (error: Object): void => { + }, (error: Error): void => { reject(error); }); }); return pPromise; } -} \ No newline at end of file +} -- Gitee From 16116503e0b7e3774cbf153502d93938b730aa77 Mon Sep 17 00:00:00 2001 From: heguokai Date: Mon, 16 Jun 2025 00:12:28 +0800 Subject: [PATCH 48/52] fixed for getSlot & getSlots Signed-off-by: heguokai --- frameworks/ets/ani/src/manager/ani_slot.cpp | 5 ++ frameworks/ets/ani/src/sts_common.cpp | 4 +- frameworks/ets/ani/src/sts_slot.cpp | 82 ++++++++----------- .../ets/ani/src/subscribe/ani_subscribe.cpp | 2 +- 4 files changed, 43 insertions(+), 50 deletions(-) diff --git a/frameworks/ets/ani/src/manager/ani_slot.cpp b/frameworks/ets/ani/src/manager/ani_slot.cpp index 622984eea..8790b0a3b 100644 --- a/frameworks/ets/ani/src/manager/ani_slot.cpp +++ b/frameworks/ets/ani/src/manager/ani_slot.cpp @@ -132,6 +132,11 @@ ani_object AniGetSlot(ani_env *env, ani_enum_item enumObj) 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"); diff --git a/frameworks/ets/ani/src/sts_common.cpp b/frameworks/ets/ani/src/sts_common.cpp index 253a124d3..31f5b6b53 100644 --- a/frameworks/ets/ani/src/sts_common.cpp +++ b/frameworks/ets/ani/src/sts_common.cpp @@ -515,8 +515,8 @@ ani_object newRecordClass(ani_env *env) ani_object ConvertArrayDoubleToAniObj(ani_env *env, const std::vector values) { - if (env == nullptr || values.empty()) { - ANS_LOGE("ConvertArrayDoubleToAniObj fail, env is nullptr or values is empty"); + if (env == nullptr) { + ANS_LOGE("ConvertArrayDoubleToAniObj fail, env is nullptr"); return nullptr; } ani_object arrayObj = newArrayClass(env, values.size()); diff --git a/frameworks/ets/ani/src/sts_slot.cpp b/frameworks/ets/ani/src/sts_slot.cpp index 7202f92ab..844c3fc89 100644 --- a/frameworks/ets/ani/src/sts_slot.cpp +++ b/frameworks/ets/ani/src/sts_slot.cpp @@ -21,18 +21,31 @@ namespace OHOS { namespace NotificationSts { -bool CheckOptionalFieldSlotTypeParam(const ani_env *env, const ani_class cls, const ani_object &object) +bool SetOptionalFieldSlotLevel( + ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotLevel value) { - if (env == nullptr) { - ANS_LOGE("env is null"); + ANS_LOGD("SetOptionalFieldSlotLevel call"); + if (env == nullptr || cls == nullptr || object == nullptr) { + ANS_LOGE("SetOptionalFieldSlotLevel failed, has nullptr"); return false; } - if (cls == nullptr) { - ANS_LOGE("cls is null"); + 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; } - if (object == nullptr) { - ANS_LOGE("object is null"); + 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; @@ -41,9 +54,9 @@ bool CheckOptionalFieldSlotTypeParam(const ani_env *env, const ani_class cls, co bool SetOptionalFieldSlotType( ani_env *env, const ani_class cls, ani_object &object, const std::string fieldName, const SlotType value) { - ANS_LOGD("WrapNotificationSlot call"); - if (!CheckOptionalFieldSlotTypeParam(env, cls, object)) { - ANS_LOGE("WrapNotificationSlot failed, has nullptr"); + ANS_LOGD("SetOptionalFieldSlotType call"); + if (env == nullptr || cls == nullptr || object == nullptr) { + ANS_LOGE("SetOptionalFieldSlotType failed, has nullptr"); return false; } ani_field field = nullptr; @@ -141,10 +154,19 @@ bool WrapNotificationSlot(ani_env *env, sptr slo 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; @@ -157,41 +179,11 @@ bool WrapNotificationSlot(ani_env *env, sptr slo ANS_LOGE("set String params fail"); return false; } - if (slot->GetVibrationStyle().size() != 0 - && !SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { - ANS_LOGE("Set vibrationValues fail"); - return false; - } - ANS_LOGD("WrapNotificationSlot end"); - return true; -} - -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) { - ANS_LOGE("SetOptionalFieldSlotLevel failed, env is 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; - if (!NotificationSts::SlotLevelCToEts(env, value, enumItem) || enumItem == nullptr) { - ANS_LOGE("get enumItem failed"); - 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()); + if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) { + ANS_LOGE("Set vibrationValues fail"); return false; } + ANS_LOGD("WrapNotificationSlot end"); return true; } @@ -199,10 +191,6 @@ bool WrapNotificationSlotArray(ani_env *env, const std::vectorPromise_New(&aniResolver, &aniPromise)) { - ANS_LOGD("Promise_New faild"); + ANS_LOGE("Promise_New faild"); return nullptr; } bool noWithOperationInfo = false; -- Gitee From 4a1e93eb14b9a398c44784e505b66f1adeb8b254 Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 17 Jun 2025 19:18:57 +0800 Subject: [PATCH 49/52] fixed function for RemoveAll Signed-off-by: heguokai --- .../ets/ani/include/subscribe/ani_remove.h | 1 + .../ets/ani/src/subscribe/ani_remove.cpp | 56 ++++++++++--------- .../ets/ani/src/subscribe/ani_subscribe.cpp | 2 + 3 files changed, 32 insertions(+), 27 deletions(-) diff --git a/frameworks/ets/ani/include/subscribe/ani_remove.h b/frameworks/ets/ani/include/subscribe/ani_remove.h index c10e15dc4..5b7680a87 100644 --- a/frameworks/ets/ani/include/subscribe/ani_remove.h +++ b/frameworks/ets/ani/include/subscribe/ani_remove.h @@ -24,6 +24,7 @@ void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEn 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/src/subscribe/ani_remove.cpp b/frameworks/ets/ani/src/subscribe/ani_remove.cpp index 8db7371bd..64e59665d 100644 --- a/frameworks/ets/ani/src/subscribe/ani_remove.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_remove.cpp @@ -35,19 +35,19 @@ void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notification int32_t reasonType = 0; if (!NotificationSts::UnwrapBundleOption(env, bundle, option)) { ANS_LOGE("bundle is valid"); - std::string msg = "UnwrapBundleOption faild"; + 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 faild"; + 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 faild"; + std::string msg = "UnWarpReasonEnum failed"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } @@ -58,9 +58,9 @@ void AniRemoveForBundle(ani_env *env, ani_object bundle, ani_object notification return; } int ret = NotificationHelper::RemoveNotification(option, key.id, key.label, reasonType); - int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); - ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); 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); } @@ -79,7 +79,7 @@ void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEn } if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { ANS_LOGE("enum convert failed"); - std::string msg = "UnWarpReasonEnum faild"; + std::string msg = "UnWarpReasonEnum failed"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } @@ -91,9 +91,9 @@ void AniRemoveForHashCode(ani_env *env, ani_string hashCode, ani_object reasonEn } ANS_LOGD("hashCode: %{public}s, reasonType: %{public}d", hashCodeStd.c_str(), reasonType); int ret = NotificationHelper::RemoveNotification(hashCodeStd, reasonType); - int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); - ANS_LOGD("StsRemoveForHashCode ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); 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); } @@ -112,7 +112,7 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason } if (!NotificationSts::UnWarpReasonEnum(env, reasonEnum, reasonType)) { ANS_LOGE("enum convert failed"); - std::string msg = "UnWarpReasonEnum faild"; + std::string msg = "UnWarpReasonEnum failed"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } @@ -123,37 +123,40 @@ void AniRemoveForHashCodes(ani_env *env, ani_object hashCodes, ani_object reason return; } int ret = NotificationHelper::RemoveNotifications(hashCodesStd, reasonType); - int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); - ANS_LOGD("StsRemoveForHashCodes ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); 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 AniRemoveAllForBundle(ani_env *env, ani_object bundle) +void AniRemoveAll(ani_env *env) { ANS_LOGD("removeAll enter"); - int retcode = ERR_OK; - bool isForBundleUndefine = NotificationSts::IsUndefine(env, bundle); - if (isForBundleUndefine) { - retcode = NotificationHelper::RemoveNotifications(); - std::string msg = "IsUndefine falid"; - ANS_LOGE("IsUndefine is falid"); - OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); - return; + 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 faild"; + std::string msg = "UnwrapBundleOption failed"; OHOS::AbilityRuntime::ThrowStsError(env, ERROR_PARAM_INVALID, msg); return; } int ret = NotificationHelper::RemoveAllNotifications(option); - int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); - ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); 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); } @@ -161,12 +164,11 @@ void AniRemoveAllForBundle(ani_env *env, ani_object bundle) void AniRemoveAllForUserId(ani_env *env, ani_double userId) { - ANS_LOGD("removeAll enter"); - ANS_LOGD("sts RemoveAll call, userId:%{public}lf", userId); + ANS_LOGD("AniRemoveAllForUserId enter"); int ret = NotificationHelper::RemoveNotifications(userId); - int32_t externalErrorCode = CJSystemapi::Notification::ErrorToExternal(ret); - ANS_LOGD("StsRemoveForBundle ret %{public}d. ErrorToExternal %{public}d", ret, externalErrorCode); 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 index 26bfbad84..00bea6b3e 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -42,6 +42,7 @@ static const char *UNSUBSCRIBE_SIGNATURE = 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) { @@ -125,6 +126,7 @@ void AniSubScribeRegistryInit(ani_env *env) 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); -- Gitee From 1eb28f92930f101d913096287c8d43535b3e2e8d Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 17 Jun 2025 19:29:34 +0800 Subject: [PATCH 50/52] add ets Signed-off-by: heguokai --- frameworks/ets/ets/@ohos.notificationSubscribe.ets | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frameworks/ets/ets/@ohos.notificationSubscribe.ets b/frameworks/ets/ets/@ohos.notificationSubscribe.ets index 9bad8d255..00a67dd0e 100644 --- a/frameworks/ets/ets/@ohos.notificationSubscribe.ets +++ b/frameworks/ets/ets/@ohos.notificationSubscribe.ets @@ -82,6 +82,7 @@ export default namespace notificationSubscribe { 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) { @@ -369,11 +370,10 @@ export default namespace notificationSubscribe { 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.nativeRemoveAllForBundle(); + return notificationSubscribe.nativeRemoveAll(); } else { return notificationSubscribe.nativeRemoveAllForBundle(bundle); } @@ -392,7 +392,7 @@ export default namespace notificationSubscribe { throw errorParamInvalid; } let p = taskpool.execute((): void => { - return notificationSubscribe.nativeRemoveAllForBundle(); + return notificationSubscribe.nativeRemoveAll(); }); p.then( (e: NullishType): void => { -- Gitee From b665e6c04427d7433745823aa20737f58c8cf266 Mon Sep 17 00:00:00 2001 From: heguokai Date: Tue, 17 Jun 2025 11:44:49 +0000 Subject: [PATCH 51/52] update frameworks/ets/ani/src/subscribe/ani_subscribe.cpp. Signed-off-by: heguokai --- frameworks/ets/ani/src/subscribe/ani_subscribe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp index 00bea6b3e..f73b6c60b 100644 --- a/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp +++ b/frameworks/ets/ani/src/subscribe/ani_subscribe.cpp @@ -42,7 +42,7 @@ static const char *UNSUBSCRIBE_SIGNATURE = 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"; +static const char *REMOVEALL_SIGNATURE = ":V"; ani_object AniDistributeOperation(ani_env *env, ani_string hashcode, ani_object operationInfo) { -- Gitee From 951e4de8781da9e25f6f219f37e8be1fbd0511c2 Mon Sep 17 00:00:00 2001 From: cheerful_ricky Date: Thu, 27 Mar 2025 11:43:01 +0800 Subject: [PATCH 52/52] add notificationExtensionWrapper unit test --- services/ans/test/unittest/BUILD.gn | 47 +++ .../notification_extension_wrapper_test.cpp | 385 ++++++++++++++++++ 2 files changed, 432 insertions(+) create mode 100644 services/ans/test/unittest/notification_extension_wrapper_test.cpp diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 19aad802a..098cd250c 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/notification_extension_wrapper_test.cpp b/services/ans/test/unittest/notification_extension_wrapper_test.cpp new file mode 100644 index 000000000..9c6fe14e5 --- /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 -- Gitee