From c042c044d223c9eee697e55418069f0762b04fa1 Mon Sep 17 00:00:00 2001 From: chensi10 Date: Thu, 15 Jul 2021 11:12:35 +0800 Subject: [PATCH] Update framework struct and add new function Signed-off-by: chensi10 --- BUILD.gn | 14 + LICENSE | 177 + OAT.xml | 70 + README.en.md | 36 - README.md | 39 - README_zh.md | 48 + figures/ans_logical_architecture_diagram.png | Bin 0 -> 61925 bytes innerkits/BUILD.gn | 89 + innerkits/base/include/ans_const_define.h | 32 + innerkits/base/include/ans_inner_errors.h | 76 + innerkits/base/include/ans_log_wrapper.h | 78 + innerkits/base/src/ans_log_wrapper.cpp | 43 + .../include/ans_manager_death_recipient.h | 34 + .../core/include/ans_manager_interface.h | 146 + innerkits/core/include/ans_manager_proxy.h | 95 + innerkits/core/include/ans_manager_stub.h | 149 + innerkits/core/include/ans_notification.h | 532 +++ .../core/include/ans_subscriber_interface.h | 63 + innerkits/core/include/ans_subscriber_proxy.h | 50 + innerkits/core/include/ans_subscriber_stub.h | 60 + .../core/src/ans_manager_death_recipient.cpp | 29 + innerkits/core/src/ans_manager_proxy.cpp | 1678 ++++++++++ innerkits/core/src/ans_manager_stub.cpp | 1376 ++++++++ innerkits/core/src/ans_notification.cpp | 656 ++++ innerkits/core/src/ans_subscriber_proxy.cpp | 289 ++ innerkits/core/src/ans_subscriber_stub.cpp | 224 ++ kits/BUILD.gn | 21 + kits/napi/BUILD.gn | 79 + kits/napi/include/cancel.h | 58 + kits/napi/include/common.h | 193 ++ kits/napi/include/constant.h | 37 + kits/napi/include/create_subscriber.h | 160 + kits/napi/include/get_active.h | 52 + kits/napi/include/init.h | 52 + kits/napi/include/publish.h | 75 + kits/napi/include/remove.h | 53 + kits/napi/include/slot.h | 120 + kits/napi/include/subscribe.h | 48 + kits/napi/include/unsubscribe.h | 49 + kits/napi/src/cancel.cpp | 220 ++ kits/napi/src/common.cpp | 2918 +++++++++++++++++ kits/napi/src/constant.cpp | 203 ++ kits/napi/src/create_subscriber.cpp | 988 ++++++ kits/napi/src/get_active.cpp | 332 ++ kits/napi/src/init.cpp | 86 + kits/napi/src/publish.cpp | 162 + kits/napi/src/remove.cpp | 254 ++ kits/napi/src/slot.cpp | 552 ++++ kits/napi/src/subscribe.cpp | 155 + kits/napi/src/unsubscribe.cpp | 137 + kits/native/BUILD.gn | 96 + kits/native/include/message_user.h | 169 + kits/native/include/notification.h | 215 ++ .../include/notification_action_button.h | 212 ++ .../include/notification_basic_content.h | 102 + kits/native/include/notification_constant.h | 155 + kits/native/include/notification_content.h | 182 + .../notification_conversational_content.h | 144 + .../notification_conversational_message.h | 120 + kits/native/include/notification_helper.h | 503 +++ .../include/notification_long_text_content.h | 124 + .../include/notification_media_content.h | 108 + .../include/notification_multiline_content.h | 121 + .../include/notification_normal_content.h | 58 + .../include/notification_picture_content.h | 115 + kits/native/include/notification_request.h | 996 ++++++ kits/native/include/notification_slot.h | 372 +++ kits/native/include/notification_slot_group.h | 142 + kits/native/include/notification_sorting.h | 185 ++ .../native/include/notification_sorting_map.h | 103 + .../include/notification_subscribe_info.h | 102 + kits/native/include/notification_subscriber.h | 165 + kits/native/include/notification_user_input.h | 281 ++ kits/native/src/message_user.cpp | 163 + kits/native/src/notification.cpp | 287 ++ .../native/src/notification_action_button.cpp | 302 ++ .../native/src/notification_basic_content.cpp | 99 + kits/native/src/notification_constant.cpp | 23 + kits/native/src/notification_content.cpp | 218 ++ .../notification_conversational_content.cpp | 185 ++ .../notification_conversational_message.cpp | 146 + kits/native/src/notification_helper.cpp | 256 ++ .../src/notification_long_text_content.cpp | 133 + .../native/src/notification_media_content.cpp | 116 + .../src/notification_multiline_content.cpp | 131 + .../src/notification_normal_content.cpp | 41 + .../src/notification_picture_content.cpp | 130 + kits/native/src/notification_request.cpp | 1398 ++++++++ kits/native/src/notification_slot.cpp | 341 ++ kits/native/src/notification_slot_group.cpp | 164 + kits/native/src/notification_sorting.cpp | 180 + kits/native/src/notification_sorting_map.cpp | 114 + .../src/notification_subscribe_info.cpp | 82 + kits/native/src/notification_subscriber.cpp | 126 + kits/native/src/notification_user_input.cpp | 320 ++ kits/native/wantagent/BUILD.gn | 90 + .../wantagent/include/cancel_listener.h | 31 + .../wantagent/include/completed_callback.h | 41 + .../wantagent/include/completed_dispatcher.h | 52 + kits/native/wantagent/include/pending_want.h | 275 ++ kits/native/wantagent/include/trigger_info.h | 163 + kits/native/wantagent/include/want_agent.h | 71 + .../wantagent/include/want_agent_constant.h | 132 + .../wantagent/include/want_agent_helper.h | 159 + .../wantagent/include/want_agent_info.h | 124 + .../include/want_agent_log_wrapper.h | 68 + .../wantagent/src/completed_dispatcher.cpp | 45 + kits/native/wantagent/src/pending_want.cpp | 413 +++ kits/native/wantagent/src/trigger_info.cpp | 100 + kits/native/wantagent/src/want_agent.cpp | 58 + .../wantagent/src/want_agent_helper.cpp | 338 ++ kits/native/wantagent/src/want_agent_info.cpp | 108 + .../wantagent/src/want_agent_log_wrapper.cpp | 44 + kits/native/wantagent/test/BUILD.gn | 25 + .../completed_dispatcher_test/BUILD.gn | 71 + .../completed_dispatcher_test.cpp | 208 ++ .../test/unittest/pending_want_test/BUILD.gn | 75 + .../pending_want_test/pending_want_test.cpp | 723 ++++ .../test/unittest/trigger_Info_test/BUILD.gn | 71 + .../trigger_Info_test/trigger_Info_test.cpp | 224 ++ .../unittest/want_agent_helper_test/BUILD.gn | 71 + .../want_agent_helper_test.cpp | 712 ++++ .../unittest/want_agent_info_test/BUILD.gn | 71 + .../want_agent_info_test.cpp | 322 ++ .../test/unittest/want_agent_test/BUILD.gn | 71 + .../want_agent_test/want_agent_test.cpp | 101 + kits/wantAgent/BUILD.gn | 66 + kits/wantAgent/napi_want_agent.cpp | 1742 ++++++++++ kits/wantAgent/napi_want_agent.h | 185 ++ kits/wantAgent/native_module.cpp | 62 + notification.gni | 37 + ohos.build | 21 + sa_profile/3203.xml | 24 + sa_profile/BUILD.gn | 19 + services/BUILD.gn | 16 + services/ans/BUILD.gn | 83 + .../include/advanced_notification_service.h | 121 + .../advanced_notification_service_ability.h | 45 + services/ans/include/bundle_manager_helper.h | 55 + services/ans/include/disturb_filter.h | 38 + services/ans/include/notification_filter.h | 41 + .../ans/include/notification_preferences.h | 165 + .../ans/include/notification_slot_filter.h | 38 + .../include/notification_subscriber_manager.h | 86 + services/ans/include/permission_filter.h | 38 + services/ans/include/remote_death_recipient.h | 53 + .../ans/src/advanced_notification_service.cpp | 886 +++++ .../advanced_notification_service_ability.cpp | 50 + services/ans/src/bundle_manager_helper.cpp | 105 + services/ans/src/disturb_filter.cpp | 33 + services/ans/src/notification_preferences.cpp | 1204 +++++++ services/ans/src/notification_slot_filter.cpp | 52 + .../src/notification_subscriber_manager.cpp | 311 ++ services/ans/src/permission_filter.cpp | 51 + services/ans/test/unittest/BUILD.gn | 113 + ...nced_notification_service_ability_test.cpp | 57 + .../advanced_notification_service_test.cpp | 872 +++++ .../unittest/bundle_manager_helper_test.cpp | 72 + .../ans/test/unittest/disturb_filter_test.cpp | 79 + .../mock/include/mock_bundle_manager.h | 412 +++ .../unittest/mock/mock_bundle_manager.cpp | 45 + .../mock/mock_bundle_manager_helper.cpp | 51 + .../unittest/mock/mock_bundle_mgr_proxy.cpp | 280 ++ .../test/unittest/mock/mock_event_handler.cpp | 110 + services/ans/test/unittest/mock/mock_ipc.cpp | 33 + .../notification_preferences_test.cpp | 830 +++++ .../notification_slot_filter_test.cpp | 79 + .../notification_subscriber_manager_test.cpp | 149 + .../test/unittest/permission_filter_test.cpp | 146 + services/test/moduletest/BUILD.gn | 112 + services/test/moduletest/ans_module_test.cpp | 132 + .../mock/include/mock_bundle_manager.h | 413 +++ .../moduletest/mock/mock_bundle_manager.cpp | 45 + .../mock/mock_bundle_manager_helper.cpp | 56 + .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 282 ++ .../moduletest/mock/mock_event_handler.cpp | 124 + services/test/moduletest/mock/mock_ipc.cpp | 27 + test/BUILD.gn | 0 tools/BUILD.gn | 16 + 179 files changed, 37956 insertions(+), 75 deletions(-) create mode 100644 BUILD.gn create mode 100644 LICENSE create mode 100644 OAT.xml delete mode 100644 README.en.md delete mode 100644 README.md create mode 100644 README_zh.md create mode 100644 figures/ans_logical_architecture_diagram.png create mode 100644 innerkits/BUILD.gn create mode 100644 innerkits/base/include/ans_const_define.h create mode 100644 innerkits/base/include/ans_inner_errors.h create mode 100644 innerkits/base/include/ans_log_wrapper.h create mode 100644 innerkits/base/src/ans_log_wrapper.cpp create mode 100644 innerkits/core/include/ans_manager_death_recipient.h create mode 100644 innerkits/core/include/ans_manager_interface.h create mode 100644 innerkits/core/include/ans_manager_proxy.h create mode 100644 innerkits/core/include/ans_manager_stub.h create mode 100644 innerkits/core/include/ans_notification.h create mode 100644 innerkits/core/include/ans_subscriber_interface.h create mode 100644 innerkits/core/include/ans_subscriber_proxy.h create mode 100644 innerkits/core/include/ans_subscriber_stub.h create mode 100644 innerkits/core/src/ans_manager_death_recipient.cpp create mode 100644 innerkits/core/src/ans_manager_proxy.cpp create mode 100644 innerkits/core/src/ans_manager_stub.cpp create mode 100644 innerkits/core/src/ans_notification.cpp create mode 100644 innerkits/core/src/ans_subscriber_proxy.cpp create mode 100644 innerkits/core/src/ans_subscriber_stub.cpp create mode 100644 kits/BUILD.gn create mode 100644 kits/napi/BUILD.gn create mode 100644 kits/napi/include/cancel.h create mode 100644 kits/napi/include/common.h create mode 100644 kits/napi/include/constant.h create mode 100644 kits/napi/include/create_subscriber.h create mode 100644 kits/napi/include/get_active.h create mode 100644 kits/napi/include/init.h create mode 100644 kits/napi/include/publish.h create mode 100644 kits/napi/include/remove.h create mode 100644 kits/napi/include/slot.h create mode 100644 kits/napi/include/subscribe.h create mode 100644 kits/napi/include/unsubscribe.h create mode 100644 kits/napi/src/cancel.cpp create mode 100644 kits/napi/src/common.cpp create mode 100644 kits/napi/src/constant.cpp create mode 100644 kits/napi/src/create_subscriber.cpp create mode 100644 kits/napi/src/get_active.cpp create mode 100644 kits/napi/src/init.cpp create mode 100644 kits/napi/src/publish.cpp create mode 100644 kits/napi/src/remove.cpp create mode 100644 kits/napi/src/slot.cpp create mode 100644 kits/napi/src/subscribe.cpp create mode 100644 kits/napi/src/unsubscribe.cpp create mode 100644 kits/native/BUILD.gn create mode 100644 kits/native/include/message_user.h create mode 100644 kits/native/include/notification.h create mode 100644 kits/native/include/notification_action_button.h create mode 100644 kits/native/include/notification_basic_content.h create mode 100644 kits/native/include/notification_constant.h create mode 100644 kits/native/include/notification_content.h create mode 100644 kits/native/include/notification_conversational_content.h create mode 100644 kits/native/include/notification_conversational_message.h create mode 100644 kits/native/include/notification_helper.h create mode 100644 kits/native/include/notification_long_text_content.h create mode 100644 kits/native/include/notification_media_content.h create mode 100644 kits/native/include/notification_multiline_content.h create mode 100644 kits/native/include/notification_normal_content.h create mode 100644 kits/native/include/notification_picture_content.h create mode 100644 kits/native/include/notification_request.h create mode 100644 kits/native/include/notification_slot.h create mode 100644 kits/native/include/notification_slot_group.h create mode 100644 kits/native/include/notification_sorting.h create mode 100644 kits/native/include/notification_sorting_map.h create mode 100644 kits/native/include/notification_subscribe_info.h create mode 100644 kits/native/include/notification_subscriber.h create mode 100644 kits/native/include/notification_user_input.h create mode 100644 kits/native/src/message_user.cpp create mode 100644 kits/native/src/notification.cpp create mode 100644 kits/native/src/notification_action_button.cpp create mode 100644 kits/native/src/notification_basic_content.cpp create mode 100644 kits/native/src/notification_constant.cpp create mode 100644 kits/native/src/notification_content.cpp create mode 100644 kits/native/src/notification_conversational_content.cpp create mode 100644 kits/native/src/notification_conversational_message.cpp create mode 100644 kits/native/src/notification_helper.cpp create mode 100644 kits/native/src/notification_long_text_content.cpp create mode 100644 kits/native/src/notification_media_content.cpp create mode 100644 kits/native/src/notification_multiline_content.cpp create mode 100644 kits/native/src/notification_normal_content.cpp create mode 100644 kits/native/src/notification_picture_content.cpp create mode 100644 kits/native/src/notification_request.cpp create mode 100644 kits/native/src/notification_slot.cpp create mode 100644 kits/native/src/notification_slot_group.cpp create mode 100644 kits/native/src/notification_sorting.cpp create mode 100644 kits/native/src/notification_sorting_map.cpp create mode 100644 kits/native/src/notification_subscribe_info.cpp create mode 100644 kits/native/src/notification_subscriber.cpp create mode 100644 kits/native/src/notification_user_input.cpp create mode 100644 kits/native/wantagent/BUILD.gn create mode 100644 kits/native/wantagent/include/cancel_listener.h create mode 100644 kits/native/wantagent/include/completed_callback.h create mode 100644 kits/native/wantagent/include/completed_dispatcher.h create mode 100644 kits/native/wantagent/include/pending_want.h create mode 100644 kits/native/wantagent/include/trigger_info.h create mode 100644 kits/native/wantagent/include/want_agent.h create mode 100644 kits/native/wantagent/include/want_agent_constant.h create mode 100644 kits/native/wantagent/include/want_agent_helper.h create mode 100644 kits/native/wantagent/include/want_agent_info.h create mode 100644 kits/native/wantagent/include/want_agent_log_wrapper.h create mode 100644 kits/native/wantagent/src/completed_dispatcher.cpp create mode 100644 kits/native/wantagent/src/pending_want.cpp create mode 100644 kits/native/wantagent/src/trigger_info.cpp create mode 100644 kits/native/wantagent/src/want_agent.cpp create mode 100644 kits/native/wantagent/src/want_agent_helper.cpp create mode 100644 kits/native/wantagent/src/want_agent_info.cpp create mode 100644 kits/native/wantagent/src/want_agent_log_wrapper.cpp create mode 100644 kits/native/wantagent/test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp create mode 100644 kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp create mode 100644 kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp create mode 100644 kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp create mode 100644 kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp create mode 100644 kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn create mode 100644 kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp create mode 100644 kits/wantAgent/BUILD.gn create mode 100644 kits/wantAgent/napi_want_agent.cpp create mode 100644 kits/wantAgent/napi_want_agent.h create mode 100644 kits/wantAgent/native_module.cpp create mode 100644 notification.gni create mode 100644 ohos.build create mode 100755 sa_profile/3203.xml create mode 100644 sa_profile/BUILD.gn create mode 100644 services/BUILD.gn create mode 100644 services/ans/BUILD.gn create mode 100644 services/ans/include/advanced_notification_service.h create mode 100644 services/ans/include/advanced_notification_service_ability.h create mode 100644 services/ans/include/bundle_manager_helper.h create mode 100644 services/ans/include/disturb_filter.h create mode 100644 services/ans/include/notification_filter.h create mode 100644 services/ans/include/notification_preferences.h create mode 100644 services/ans/include/notification_slot_filter.h create mode 100644 services/ans/include/notification_subscriber_manager.h create mode 100644 services/ans/include/permission_filter.h create mode 100644 services/ans/include/remote_death_recipient.h create mode 100644 services/ans/src/advanced_notification_service.cpp create mode 100644 services/ans/src/advanced_notification_service_ability.cpp create mode 100644 services/ans/src/bundle_manager_helper.cpp create mode 100644 services/ans/src/disturb_filter.cpp create mode 100644 services/ans/src/notification_preferences.cpp create mode 100644 services/ans/src/notification_slot_filter.cpp create mode 100644 services/ans/src/notification_subscriber_manager.cpp create mode 100644 services/ans/src/permission_filter.cpp create mode 100644 services/ans/test/unittest/BUILD.gn create mode 100644 services/ans/test/unittest/advanced_notification_service_ability_test.cpp create mode 100644 services/ans/test/unittest/advanced_notification_service_test.cpp create mode 100644 services/ans/test/unittest/bundle_manager_helper_test.cpp create mode 100644 services/ans/test/unittest/disturb_filter_test.cpp create mode 100644 services/ans/test/unittest/mock/include/mock_bundle_manager.h create mode 100644 services/ans/test/unittest/mock/mock_bundle_manager.cpp create mode 100644 services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp create mode 100644 services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp create mode 100644 services/ans/test/unittest/mock/mock_event_handler.cpp create mode 100644 services/ans/test/unittest/mock/mock_ipc.cpp create mode 100644 services/ans/test/unittest/notification_preferences_test.cpp create mode 100644 services/ans/test/unittest/notification_slot_filter_test.cpp create mode 100644 services/ans/test/unittest/notification_subscriber_manager_test.cpp create mode 100644 services/ans/test/unittest/permission_filter_test.cpp create mode 100644 services/test/moduletest/BUILD.gn create mode 100644 services/test/moduletest/ans_module_test.cpp create mode 100644 services/test/moduletest/mock/include/mock_bundle_manager.h create mode 100644 services/test/moduletest/mock/mock_bundle_manager.cpp create mode 100644 services/test/moduletest/mock/mock_bundle_manager_helper.cpp create mode 100644 services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp create mode 100644 services/test/moduletest/mock/mock_event_handler.cpp create mode 100644 services/test/moduletest/mock/mock_ipc.cpp create mode 100644 test/BUILD.gn create mode 100644 tools/BUILD.gn diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 000000000..11f42d3ff --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,14 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..4947287f7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 000000000..aa01ceabe --- /dev/null +++ b/OAT.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + diff --git a/README.en.md b/README.en.md deleted file mode 100644 index 3c3ffbaf0..000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# notification_ans_standard - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md deleted file mode 100644 index 64250220e..000000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# notification_ans_standard - -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. xxxx -2. xxxx -3. xxxx - -#### 使用说明 - -1. xxxx -2. xxxx -3. xxxx - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 特技 - -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 000000000..740832be1 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,48 @@ +# 事件通知子系统 + +## 简介 + +OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对通知类型的消息进行管理,支持多种通知类型,包括文本,长文本,多文本,图片,社交,媒体等。所有系统服务以及应用都可以通过通知接口发送通知消息,用户可以通过SystemUI系统APP查看所有通知消息。 为应用程序提供订阅、发布、取消订阅的能力。 + +通知常见的使用场景: + +- 显示接收到短消息、即时消息等。 +- 显示应用的推送消息,如广告、版本更新等。 +- 显示当前正在进行的事件,如播放音乐、导航、下载等。 + +### 架构图 + +![](figures\ans_logical_architecture_diagram.png "通知服务架构图") + +## 目录 + +``` +/base/notification/ans_standard/ +├── innerkits # 对内接口目录 +├── kits # 对外接口目录 +├── sa_profile # 组件服务配置 +├── services # 组件服务实现 +├── tools # 组件工具实现 +│── ohos.build # 组件编译脚本 + +``` + +## 使用说明 + +以下模块的JS接口为非正式API,仅供SystemUI等系统应用使用,不排除对这些接口进行变更的可能性,后续版本将提供正式API。 + +- notificationSlot.d.ts +- notificationRequest.d.ts +- notificationContent.d.ts +- notificationActionButton.ts +- triggerInfo.d.ts +- wantAgentInfo.d.ts +- @ohos.notification.d.ts +- @ohos.wantAgent.d.ts + +## 相关仓 + +事件通知子系统 + +**notification_ans_standard** + diff --git a/figures/ans_logical_architecture_diagram.png b/figures/ans_logical_architecture_diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..6f2161e3203602b66578e78d67d8731098ee4d45 GIT binary patch literal 61925 zcmaI7WmKF?uqX;42@b&>f&>U|3Be(_GcdSoa2ebkg1fuB1b2eF4DRj(cfUjS-e z2$3u-EJ(;GIWvwihy*Qtla!v} z$-Ry8`KX2cBP<-e$dtUEmHnK4S6^RW$jrpz#`H~OEg#-cQBf6Ew?LNHbdDxWs6!}eX={RPDu32p zL_}nM{|vItFPyxwMOf1fg`4*_Bhasr^H7eUah*vZQ%Kpme|oE}x* zi7jo1KY(AlUP{-GGOHi!B&UDq@Fw~^WghNm z_gHK7c=o6xG`8>I0ke;2`{1Z~cj>VDm}M)9TB zRMg_u$(WDEK(o*6^=*2Wb>2+n$oW|AWb?~v&%F8W?+34ptJ2D1nPT{S^RBfT4aL``=pa&^0_@JPU4#b57fKFO}o+47zRb6%iqmCU! zd*rMqzDR^|#+iabJ-6{$clfFY&&snyV-zhxOqbj zrN}@1K#F)X+qj#0({kdvV#~mA%wy{^mu96hWV4pESv{6l+3t#yVR`f03SoU6UWdNV z`$u?0*XpOK#iQfqr{$++%UKRFispAw{TzgV5R?x$CQE|3iPs3a$8dHk6YKa#-_%7cB-w0Pfhhr2Q$iPrR8P&>F^xRN{)XxlR5i} zax!**cik~9e{`|_9+a&?akJDFL$q}O)kYsKpN){v(V@cbDvoN@p+7=htPdUmBu0mC z)S1<9ek&Ip6+WUi6_O4VR$-hsXUncLYiuZXjrJ|iN&x`{gqvZ1fq&*GH51k1zeI;{ zf#{<8*DH=VsR6TcG>P%yk!D;X>9{&|T=LElJK>)W)#CBRglkkMeT`xJRV>(wzfIAJ zmaTo14?!SBTaZ8*YTFXx@M`6saVy^u-Wu!Oan8ziJ+wZZ?iP zHoG+8XF1;}ap*LmA8Gpl3$rS6CrcJ&7~D<{i5&&YJ@f-D2ezM-d6e(^_z&S!w!QWx z*vJwZQ=!Vpb>ixmuUFEwV>B&YA7-vst_63A2k)=jDaEI~IiizU-+uyGnz^3%XeVf* zUe^)pompF;Tw*1aXMIHn6E2jE3XFAa`oh6e4X?zp21k+nwTohqJnAP7E9_~~F7sqg zkx<6oZXpHwS#l3ln}#J)rf4JYPhxuB`nAGYK+z@nj2(q##+^&PkRgMBL*oDzkY~^y zU4v*k$9-36q6IdhZi|ehgIU7PDD_Tke-Vb$^iMd{2LY}C- zG7Q%?Le7UiEj^xt!_ryf!(_5x((?E0bEY|ByCL|K+_b59HT>I;_u6fVK-qKx&7=K4D| z(unkTcWA8mnU!-%5^QXp!9oabhx;(9;AN27M}S~k_0-1!#?P+7aaK6Le!4pm#lkVG z$m|xi?t<2)94)OupAPJNFI3R;_KtajvhfW}*%olW-X2w|AX#o14}I!tA`arDVeI`b zp64=Zu}(N^$);fAO3}%IEAl1EmFZqSNTS|0&>oYV-w{;|XcY@EWx?GqQfwt(^=IcC zS~{KtOh@QWD7cPZahgtDsT*d=l5t4qo-cyRX94@yNhHR?uvxg!P0bLl`RKv!#~FKd z=J22+`v}sY>Bhl0=|tYe85^IZ36g;cK^qi_I9FAJ?6)o9MHx4l zPYzB=Au%uK$rwFRdkaS6@}H1xY5t?RxU$H519G)G6r)Jygy`31(yW~8*-OG=hNZT? z>{^7u2Z`?fL;+m21~VvPrGI}u5R)8;azHHCByJH|JrPmNmo0pScfO+{pQ1@%ktAY6 zSF8z(76??fb%jxSex)a8mT;HqC{$C|FQ7diPV@5k_7&uk-?@u|gpuPcGo|hjs6tY%F!soC$;52m^%PRu^z>%SkNV9xL3%*xR>IX#~p=4Nj;7fbm$3E)jT?)sTYXsi3E zDxvEb(|d?|u-UO`O9_hF_EMmaFqUqAI~{iRuO);{=cuTRFCeJvd38lFW86psXS5L<`g`iAV}Y>v&z7stmE= zk(0N%u^j4BWN4y9w!JozcJB6*%i66kNg9jEquXVh@y7OwJq=Y&E*?)Sz;bJ%cA?2$ z3W-D?p~pJo55!~s1Mk5(7!uv^HrUZz%CMg~3$ZruKYmkkOF5hRBypmgu++#YHr8<& z9kI)VKA@nHPYDL89$$qdY$38P|y2u)B;kCJz_z6 zpOOWovi)K{gF{bmj-}uKb!S?-uYtj6Q|7o)Zm$0UUhG2uQ^=OHz)birouV5>>k=)UEy#tn4^CEU}9595qhe6?z+Yn{fQY{Svm;NkDgCk22_*6F*9j&$%_E!hkGl zamC~IG)j9`bJU`_Ox@LLFCCc8r{-sqR#7#$Wwk6}zePwQ0Y^W+)Qg3jB0tusy*=Q>8Gkx{|-j0 zd`mzNFfy5_?uQPxZ7);Md8SZHBF9go(JSc7HL36o>j)wJNU?4+Y#8H44HACT(XG98 zifHYa<@7e8)(9iu4)MNJ6dL445nLHfl>QQ_feVG(x>l zIA934W4w8~B8)SuL2eWYQCI{i>s1J0xi{1q9Wr8&sAaQ~9Ngk^-0Z=D?)rMXYBY*I zUk`O^f0jYHR~xw6+Uf=JU=vT9)qK-bmmuMoq>b7tExwxf@d%nDdVBi&qbj<;-!@7n z><`cs1wy8ftyrB9BS)#aT+n4->vtOPn%EZ|XbPGdP6ima2@F!ed8MR3I+zsJD-h-I zD!89EsDX9QDX5c^^YDLWhty8Z}2zuUY3n3 zgcR{UbeGk+W$Z`!4uBVe{aoue2)jJS0Pw903qK!5r9YjYY#R5R>mz-Nq~1mIr4d5) z@T?HxZ5JVTzm=el3NfUfG|r8P*)L+vEgQV0Hl^AOJ2h^e9Jl4rfpTG^XOGXe`9|bv z|LH!zVh;+F{P)R8oLHN*7JQ#Q54tcw)HE&>5rrje+X3*h*yYhvoMjftZg85l8eo>%&GkWh z1G7{+o-~P~Vj zVjP2N^uFgH()$qKQa0(`ts6M-dqfPM&U|t-nsJl89@Z%(k+iEqG91h#{trPK8rRC% zk-2m!Rim3e=Gm5Q`J-i-QJ3osttMLt>EkFFCq91?Ga;|9;zfb_>Q$ zH4oZBjG-17OVR!tyI&yuXXpx`ZP`%X5!lpKmXiC`hoF8$m1}Hn9#ZdpD%;+Am$3Hn z(3?3ul=}zr-zhnpboh^>I#>7kcvVl< z@Y15P((Lh2Mcs;qrhD7h*4TTd3oq=&k0$avY|9DwBoH*$B6>TJ#fyKFNM_+wcys6iF*QkPW&NEwCY+&H>SB zpDQhZg9+CfxfzZ3a0_$*mW?1xMFM(hl^Mpulp}|NVBju=g%IyKi`E$f22Xa&3 zwzCg|>9q3_)wZ)HmiW$jmj>NdSzDwEyMx-04e%(JPcxm7F&K6yBtNb$9Uh08;5%^8SBLq;QyZ23_f(GwIvh@qNiJ?2&f z$MR*1XtvPPnLJ#dxp%J2F1xT=Tc94}@0&U+v;{R^*hXygbIm8v- zG{z<*?Y56EeG}o`K|gSQ8m@2D9mcqyn_{SMWZMa-h?DT_pH_g{T**G;VTi!{y5V#R zYuUq8_PZ(^%3aNQhG_oY+WPLqIg7FD(k{cA;i2il^%NCD86-c9^i>aGu|ASRDQd;h zJ&yfq(4q~*)w*O>LDQ6a02R2kV?lSbO?=W<1*5L)Xr)IgYnMPz*vBm0?s^gDHaMd{ z-@z3U@%A4ecZy(D3t=blw&sll0jBh^^YJlcA;6BqSoyt1G%Z>?78xCL6O1f7GNf;FXxUp1yp~<$~tjlpwOefx1 zcmAFcEEl^(R}zPnsXBXBVvw1`^+rW0KR7pz*4RoVzI}w?!Sut&?hMM@f~MZ^CA$(v z2DRh8r~2${747X6v2^VCg6w4Om=G&IFWxLNj$at*a8Buw@rNhzWlH+)_qZqVJp&9h z?D)?`ItXJJF5Oq`ZDSfoODBaU}K~+GSjRNlte`FhBWwL z%q_-NR_a=W7uK#1XxN&Gc6KUC*<|{da|WIZtno2XM75cxs-26ABm-RVO`%6-bR$5v z_dz&MwmdZVgr4TwJsi%^0j1_wS|VStM$*Lt5j8&h;UT;pDT;a301(qHuHe%0g~s+R zb-|_n=MkLI!fz}de&mE8>)cTHV~U*E%q78ah5Sunxgf4US;dif^Pv_IR12#Y(Y#}K zW5}XK`Q({7AR7{ojP%j}hpn zT8F7D>u!nhTPLzTo_Yov)BTg%p7dPn*h5b&>2t*``k^jEGXCJyShNr$=OLD%Dit;| z&_r&RKeMiCQ1I>0BKWKT+A;!KHuZzi*Z16j^>Q${`d@1sJ{uAW(222MRiuc0R?8-n zvK$?_QfO=hR^;gQiGn24I=6DVI>VKP{|NPZQ4ymC;aquqdcLd3)w+Z`aM}k7bAG|v zHV5dFm+bL8>ehT?q|u`zPTEuigS*MV;W7;>Gml065$D^jqIkoBIBEGRY=zklrL(v| zSvmRhpLuT;z<|k;Y!DDDtcF(lHd^MKeS-Zt+WBbD=*{as-rs4lVW`9x857PKWRo@W z-=r}!PWAEu5PkJM%BGu*ooKX|>$Ys)MAnBu*ex)|;5gE7rtcahrB zR#q=ukM3q(vAq+!(0C>l<(3<^PlNaOJNFCtGtTD3iFR7uanQUA8we1qIh4$bmFBsj zl+iFUGV(A!87E!O!DrQrHfPXE6D=w#zS$%@KXHJ*Tu!SC6wa?Ky*t<=tf64+IXhue zYrYY}zJO^JyU!To^E@nLY=7JcxmkU=eaK^M4cg3Ik`VVt!1TuRB5jm+AFlqXZR-O8eel@`)0jksC8rN0(t zC;hHEZxJgl#qF#{HUqQ3T%(5?ZC2|uO z-UamA5i(pzYr>?v>yI$0Wf`G%mks`XaeoH8sJNBmA8ZgUxRjzw>y!sOM)6lFle$r!Nr+RM8%Ux%5fn6V+ar7#BKBjNh5SWt>UqbC?b^%cvy_pQ9kB&!R@W(f;}@ zG=CeDqWnu=)q@MK<)`oN6?xzwV9EG4_xwAdaIs&zNDf`nH0iuZw#_RKQ&1W45kp>` z7;@pydYe$#u_Iqt(ZJoSuAH1#?tmee8U`{z1560JO|kF-yihl;jlt`dpga<1 zttMWy_VT;Wqg$9$Z4Wq91TcmK+OqX20D%> zrk5pEqPk%3Md0V1Z&^UH#o4!8KQze# z{aV>G(F*%drZI0Bx#CJ59+XcsrhMhVV6#1gVzGtWv*{9Jt<|#i)t=>)@!2#X=;Iz_ z=MF!osAgO1kK*wTHo)h*m#WDh4v?E20H~?3mGp*~^#7Y0{QokA|GEy_uC#XtgVy|F#UyyyGuv@d8wZQ0qkZ}!B_*S5u!2HL*tXM_+JGp$y6!&Y;zo(jwq#7$(9*&J znf3x&9jOxS2jWn2M)+}?gPpRQXaeUbteMpi!Qu|gSG>POeBq;MBEwfx#%gtUpLXBT zkGizGN!pmx{TJ)kJ>vh!HS|4Z{*Rda?Eh)bfW!X7!)b(dm$KOBwJQz9icgddJE!+o zR_|ug!a6w5OlLC<}sFZ)GW5Gi9--Z5{oSyJeU@Ynwj5+gPc9o2U zxTLS~g{B4^J3sI{#KZiki@|}uByX>sez)$t%&Pw~IZWu&WKdLCU;KO%=byo|Z5lRs>ZZ}s-ni6i-e6Zu(wr(Ij`6Kl1KuxTmoW`_%`(_+rOmfV?#A55n@iug8xA#hH<&^X#ju&e{JX%Sf zGnMfHC@Rg96TrhA^*`H~o&-;;Kl=ZAJaxw_6Kd420W{{d+pP-p^Iy_OhY&qV9Ni)SwJV#~C;@ z+`?I+vDa(OCR1J85=jrvRaTvmuT7(sHd%?sRIqstT#n1#U3WG~l75P6V;p*UyF`%m zn?<}LIG2(pfub|NB%<{r&H0ytU?JM7=)!)!(cd?$#bif?7eI<@+OS}e zXxl}C=+ctxe3iOf0`6+UikcilwgjWlh%}m2)_{)4G%56A;( z;Crll%KaM~=C7VZayHEW5iN+frshVi9Dw>;uGl=@>-FE2mZSV%La%5L`sQE#(-Zv> z`sRP6Jq-HaW>vT)(!VM)LL8AA!Z#+SR*|7*^LFV!k%eE zVL4eP*%QirZu$i_Y<^l46%zI3mdAUxsf!x;7rs{(7cxb5$#&h)&pv>AQsr<+HVHB0 zhyj|KOd@_^iNEW&u~@GWZ&YT`GG!T#co#T?(@kAwD&Eu+a8qzP&3#s?0M$l(avr8{ z?A``+h)C%?V6*noxU@7kdphpx+yor#XBSI8hXik#j5XtsoHRZ8!hpLcj>Aftf1si` zkZ3QtyWKHdx9GXdcQSJvopl^TSDo!UGD`BQG}94?z9V4vK2jfkEbhOnlS=O^Bf;6u z8ap6t!l3EoyY(X$RTx6&%|>WJz;dj=wCR%S4@5l)e$jQFv?7Ez?|xfn#e7kc-F$C- z^r^oM`%esMIcu>`Rt?11&p z-B-AJ*De9wHs5F?KK`3LnkFRVmI*s!_hK=pb)fJ!2l&2BwgEBFq*MzRZ`;Pd9lY$q$@YC;)!b?Px*tMr%_=gowFPLvw=y- zddT0Ev$jJPCyht2>WlRazPCWs^8F1kfvfA{F0n;(L^)5(hvGfd=2_X?%!!Dz4uZ(g zb+HuZxu5Xn+UNV%#0zdEi^u5{aTuSPA`Fm+j_3i#$u(@hZy>2E{}WWPh;xauu<@TC zt_zoo*~JXJ(>X^8ixD*>Zk1(-g?pX;usD|=(VvVeaNOT{Uf7l7sM}j=rmH+?kf=Ae z)$ME*dE5Hd;N9j-949%h+}&6$wtX!;Kvl{PdQ<5jCCV%CU&1 zy8TTSjdSECfxzS7dx;f7?C9E)3!ktJH#iTgGMR6A90;sZ-YHv4MX0f8) z%5c2(HKVH_oqIjX*^9oe`GMyjhDOOV3;O$y#Nm_;_2G|GAzBSy=MyJlyc+z(-`Dgz zLWOXd+LL=Z5dB`(svyQ(TTfzeIMl1(rL1%h(OrOql_6IT+4=$hdf!hp z=k3}gFrLZ3iC#UEV<@yNX2TCVr}W=EIXORm{Z;h(pkJlAIh$SZB9xH{t|F8`G{-Qh zx#6WREHSBv84(@WFwa^;v!jn~R>SkZtI!$sq(ypxeqSGV%&qYBAwfHM9Fmdn1A+G) zp~o$c*GIEssdwNclFHH|M?08^@7vYAO`*lvEF=o}EFji|JEI_4};{JV@-GlQ?X?IQnrR3$nPc*(X8y8U9SqZn1qD{2|K&!s# zZ{_TlfCPwB8>G(rbVMEzZ#z;r6SQcv)Eo4??kyp}s+^Z!7~tt(M!4x#B$41_+Z+MV z3}Uy|(q!3ShU9P9Fm3c5bODH~3~^I@s!B$pRBEbGpPt99vp+i{X^RB}XZniNkd5hf z2NB$Ji+x1i%?Katd$&{g)5X~FlDQFnj%euOEk;#}YWng5P1m;tFw5YK=-9!0Wr(HZ zZt>3ufa0U`9EuF)CEZuNQwt9AZh^pJF^Y0AqUI~4BQ%3TI3Hnf0Qa?g>D5&%K1uxO-&&06nfJ!yXAPsTD$`sxgoTrf_Mi#4@73v<6B8o%0^u4cyz?k-V9 z@Mw!x(@51hXA{lBCyV5UvaxC;JRle$xz|hppW24ZM@dq>RZiH@&Ya#ZQru?Wwuon* zX5vS^3l=;u$}48l67(}z%_W$RvDdkEIpCEi3$dC`Pno#+kP1WGzVJwRjU;{Ww)d!t zzrb`%`cI@{F=C@8aPbuFDFqwa)PX<(KoDnDY>`G?m>P;Gx!W9BPYz8+D1GEO=wo%# z)qL3qvNJY~+8kfAqHA%o!=zMP1=$O(;uKE7o^x9I1tw3(tBk?}zcWj5K?)r2mvgfI z3M8|)1a*LkXrSTzwEwGUL1L{${!f@)H91|7vefIO9w>;-{CAS7C_BCj_N(K;D11A% z@~-vbht)%ls0Zv{T?h&eMSBhH^xnipZV+1zJ%zL~9qm;@#GO?HqJQcK0Koo}7FMIW z3o7|D-x@J$OazJ~D3rb9}RR4Va6hYehu-YbS|)Mjj%j39a_n2K=MIAH<4CXd!N`ENC1p#ypZEksrNvdw<1vu(O?7U}lI7Ye?S8v2 z@|yEtX7GYm&yj>``---V)wi?DlD)+r5;yqsn|`Nb^i`znQyD$_D}U`TN~*`yC_VI26cszF;>D#d6jbVXxI=QwdYvs2Orb4lmV^>gVUs_^H?5-J3Kp917Yix2y9 zW6Z|zvzD>~s1>ddN9?0OW77)kn8LjxFbZS4=cd@m&h}~dhjY}*(brzq@FG9GL?s>7 zd75bTT)jpj(UaQm7U~P0@Ae>~7>OYB{Sw+*NO3LN!It8#XVL@=qcz!nNuy=5;FofUw zkn5aWrh15QBRGb6r}n%?gl}KZ2V!m@*%9u$zd9rb{|^9{C}xDenv)3;n^(8?Z)OJ3 zk~>GK%7N$H6U(WZ z91Qk1=Tf5nTHW-NB)zWBPb|0kHhm>zGMplTyF?fe>UN|~ImObIn|HN%LC2l+w-dEz z`e;DAojQ+^j;iqb9R02clrb(!h?A=~LWq+?nnZ!2naH>t6Bq3ZAo&NC*H>Mfzf1^l zigFt*3VvjVx((ePIzn<Q4E;v#fa7XoDO(o{}H>Edw#fF3(e|VaSpxE8){pOXV|FVX0p7;Mw zgH((m%}jm$Va+zJd&))I_myYa+zJ5~9A=!WI9i z*K7*VV|L~u46#72Vqc?aDfYM)BSu(A09vYv6w_I+w~%ce^=gG5uqUOrg(T~*p=L;$ zEN<8o@mYZ?@yIy6UVnX&`Kq1|kVMmZ;AZ>2dA3~JU%z{Kc|x|94ciJybP-a;ehsqV z6*}y2`XIBgNQ>q@X7r;PD~jrK{d!dua7xgQWFEl7xz8VIl>fUCcQ;P_kUVEXik? zG9F?+&ckV5)wXyHz3BL`07H}~0Jz^Jwmifzmz5D^zp4D|c8?avzA*5-dhC+bkltss z!r!(J>)@yXo4u|l2Kz|CpEC&<|9E3Rt@M0y6Vz83W5L2=jtaj2tH)17X+_lCz^TBZ zLY!B_xj&h70GMBeWjt|@y8hUe z8cRw;c27a&3{sL$l4(}55aZ>&Aib+ezM5;lmaqF5ziGu3iN~g7;mG-GslGH&R1s_r zF{ean)VXx^tvOew2Rs9lSkrJNXCjisM%auGi_XrLd@fSsiyl{a_PjVFx$o&WjhqS8u$lO^BtN8@1ADV8+e=n~31lMp`?PATEHD}|a`8san< z%`O;8VX>&GjhgN1_qXtAtv@{e$b=Ci35?7SvWik^x2i1$HCIsR8!R2xgeF6X^4MfwKd@s~(&H%vZ&vG&7Tcdb$Ls13pHagT%Nf6Dj zX!Vd5ZqP{I6c} z?~{rD3Zegx?wyZ4YbbdjWy7r;ao0DHu}=u+SV{3t&A@HsovaM@rD)kA zVXf8!LXZdPkL5UbYt{@b8e6YngF{MOn=q$r;P$ZW;Mw8=3Kg=wh8C^+_N+%_*fc`E8Y4p zV>yuj3}FUxD{acm2Od&9xI{QzJ5%>V_fyJBoa=Ye-3PyYsxI`2k)>ek=m|W>?Tz}o z(+FKcj{p0>+f!x20A^`pP13*L-^v+xC6aZ75X=9?wy(z*GNNlsL~^e3{6!VbPL}cf z*291CJu?;OQE6F4S=n;)^ZWtN?otycn!^WkyH%&C(ve9nrX84MWjJZ;vn+0C%mp#) z+xj9K(eDxJnh*ZXRZaIv_X9u9Iipc|BNeacZPU5`LvHs=jP3WG_D{#(zU8G_HW|)V z-UQ3dvKcn`QO5%Z8m;$w>6PnC`@Ll=2~L~4Le}X9GM7oVEb)>b0$m`_Pf0v?w|i7Y z`u9O(1fzykb?^JebyFO(rSAu@oE4M?ZG+@G?b{(QH2>FDzoxQ=!ZTB`goP*#k_zB9!Oa zTHp8U(c@p()k51ISxl$0)f7w@<|4_iezxGTiIK=@a%n9o z_4Fq=@n6jqH?Wj3qz@Mz3=>-Buqo;2%gT`O**pmsjTMVGqLSIN<}xwfAyg>_MgK|W zI%k;)*vW{`Q^NU@^UX2@YXb@;=&0wJ=$C<5Qkp~_Ws-em`8)EMFeO?C8&#?NpzoXb z7Mc?w{ZYO=0~vq3#>jn%S%ynigSN^V)uas;X4pq0DECUoZ|4FXaJ*Bb_W?j?=B?6Z ztbSE(G_YZY5_ML^`16~0?qCKP)33^Mb*Y+B?1}n{v3q%FiB=nCNAWd#m2Y_1Dn9(x z;y2VaAL`gIeP!@oG?xTmmrQC>#&vUGZcJ;=v?nq@&u7zG3NL;M_?2~nt~k}hX7HnB z{YV2NlJq??8>%O9DCSipdLAow%J&Ea7@V#fgh1cJkm@gf{hwE4dO_JDSYMZprxq-5 zOYLwC!-~HsuR;nl>>CbCk;(;6Kpmy?Lo7 zz6#pO5PKX?8P(3>BZo0B=pkMBnQ1gG z7Z>ZDL85Yd>S+(MwqLMP-7 zD%P}~Fel8hr7Lckmkdnr1>@_OCaHZevRQkomeZqiW~kuajNUXTHzkmxrNe7dzRN%-EBu zu@x|51!eH!<|BQ^co#nu{f^V!{9BTxt|rJoj$QXCtiiwCL8AiXK^A0~S9}3qgm6H= zS?z~(aqwAT>^r^TzJpTk0drNPUJeS%{u{ZRQGP@Mgi{)bnItq|)Z~pP z8ehAVcpsZ_sCjSe?NI=Q2tc@=b0b@oti#V=1oRsVl#g`_1(cr(jRg_U-XAE^vkg`? zW6?jrcoYU!>C=Ck&{H3G9&#ncQ`=!uD;?fLvL#b75>AsbMHIMXy(Sl)BH~fbtMz?5 zF-UM^kcr!e%gT;lMznm64@Yg6ts1#4^pz@^2ZP{}^jiQ+AO~0~5s|8Ded!O!dtb;0 zEIj#S3?k@0o$(!^YBIsWN$ylGP8B_z zw68Dm!!gg;GoGqS&x0p?^y6=l_3c&|ZTxjE7OP6^9;EgK+lQD!$#_RW*^4LfS~qP5 zxV=m)Y1Eouko2ifwz$AavyyqUk|#D@Orhq_;~QbRQk^gNX{$8uk7rgkkfmpLuzB+P z8P?0+#80DJZQeeXTfcl}LL0$?_C3)*=55RHP z*Z~=F@0{m;#~Ahv;NsX33jDn+p1PqEMBBrZWV=BlGmBN;}(`t80PcS?nKyfit?m> z+Z*;1jW+7tmSpLjLjugd&h3?Dw=E*&KrW?$OZZiv7bmp$GnqfLd8GcO2h~o zX;W8IL)Y(a^24onJ;VAlwYgZ(>+`&^Q-Q{DY5T1#*g*q8)7LhL{GhC-$pK1!+Hc#C{rz5`SN6dClECaJGH2q z{(SgC!NVevMqTv#)9vR}xLs1X0a9x;^4}>x%{yeS@WdlPYf)k!6?t{X-(F;{%Y<`) z2Yk!*|8|T{b!2%-4tB4vR|N0oHk97;a9EHQ4#5kanxsCTbS6ViHZ*5_dO{uq?#hJU z5$GEEePpq2dy<6T;QP=ZYe*l#R8VGies_xO_D6HhBiQz4iTLqk9os>3uDS9Gv&1^n zjp|;pOanFc$4#@w0(o_468{B6Pau$px;5o0<`?fTx390u0?~c7nhLlR1*~L}r`&6v zE;VKqZf`z>@N9jyOxhRHesIl;UV^$qxy5ZkZM)qF$#6$>yJ=pHBT;(pMHOa4u)v)Z zTF%Egp=}(uhHc27RqYO{%g}7DqoQPNSUS`2ltJ%Hy$MIO!#JTi5c>9WJQwY7zl@ja z{^F!d`WfYL*8lv^#u~|9uyFReTkrP40qps&{1Oqgr-<~2>X(Mt6QR6`)d#h5jG*Pi zg2V@oNAV?Vbw=0H)Tz(GPte`XyYEbR;M@vNqwEqndF^9f z#C8ls*%XF96AWVVXN3{7p}RYHUL8%-&T*bN4q6Hjil!R7KMmYtEbCuJT~X*J>kzXo z4RE+X?4Smv$2Z5PmWJ^I_p{_$`}x+QekaSLk=oi?S2HvG>`>m}pwKZUFLnFG_nMA} zC=8eRw)kO}-=l0@OmxEtsw^)B|2@~V)Eq}haEe#$HG}o9_G1TyVswxO*oMGt@9W7J z40}y(3-NR{W{9#+}ixYoRxZ2I2)EU_AYq69Hczn-%^1Sni_kY3|e zEJ(Ns3QnVDL@&b7y*rvnn#H-EkBcpkl=V%)kdE7A+1aFV1X4A*Kk$5;$nO3)b+HJS zwh9iL{lMj!ac;M7V*Lt0qt{JiJK)`9%l9cVyr70AxI&D9^BC4Vl0D*ABym1Qmi3G0 zvzAsmIcjHIJWIg>9HxCuQC-wBKoQdOz&GBL?mp!fZ1y~vlbxdKyt!{Io(}S}MCE&J z$dtiu{O=Cih}EJBNu$fe(C3Q>11TooXy#Al5L|?p+`8c>yVerY&tCE8p-ra%Sd09z z%Se{94NDTv(h4y|d0DrxjS>~LynXsWWc#bD>RudZX?rozH=p>On=aX$1X!C3!`i=@ zRtR0Gy*tA1T56&vp0o^Pv(0yTkO<3?Gr*A~oi?h58AA(+b5ox)W^|P7sUlMRI#^5H z=~*O1P#m5>Wu4s*d8GU1nbYv@vZo^`xlqiIJXkrN-Js|pHC82KI0)ZZau!NH8u&3F zGC1U`T3qpcMM&~qPVS`2j0cSCMgw-pntP~*WdiPqmLsk4gUqM18HYx^FKS%00M({& zJpj+LkL>s~2Paws4;EGQ^M{>D{)qX5Z}q+&3NF-@OVssTM3?d7MJElc13;^I3{u*C zmm&LIC8g9ubDbX)MwErY@0d^XS7%L)ML*}qx!8TL0~jKNsN_q277&{8XDr_zYyz6W zPJHyqm7^umvD4SGp;d!3Z}c|*;`v#_p_hQywY2`q>#J8kjcb*f>m^7WaV6yYHecPi zf=P$CaP)bw(3Kq`ZMK9soUyi61i<;whi8nAm51|RimxdM2aLIxyhj3+Lr?glEyu)Og87P6aoNhT^ zTqlk~(RnuUY@-p~74Bj1iuKB73bQ1^G|p~S$3IB)xuP(SQ6tU!g;*_ZtJi!53P)8`XMc zj90yplTC_RajgR-8mJ&#a3#z5WCd4DF zr2-b>1NMQftQJ9cI?`c2OvS-nIQh))wh`m`D*%$Wx}2?OxS>JPYv-)=`Hl=Q_xO&E zEWfT+P`jYl??*%T8Vl&D3i}>xu#vHNq#W#KVO#1;fOg9|)JLpkAACYgKR0~8n(X4S zx)>&Mz4RLpD0Gn;!uEL^uMT=V_X{eQjMjt27$yk&#yu9NPDWL4Osj;m`!If*uFyhd zM(7!i$lK|T1O_VW2$%QVUfSMcbfh_Ny^%UdRdGspjPT-*u;)y5b2=Y-W1!`##r0Vb zIlw1z;M~GjA&bf=lZZ|}e2QIq+d?_KyitsQN9Fmqp`@3uF>$cxBeYv0-RHk0w4}Sw zr2+fsbMwG<XfycsOZ2!t-2w_qw%5-t-MY@-zrdPq(Z-d zzU|X$R~MM`o85Mpi&P=~7816yJif?|rZVvk%A(i6&^!G3FhBVN%P|SjgoQZyD;DMh zrO@b9rK9leoNph+&S4R9B_X-eTAkzYfYA7u-7wW=afkEWZT`4kZz-pAe@}(j$#uw( zcbM_l;5xKr^B$a_Buuhe4OBmwQr_bTqw<6KPc@x^-|b}9Gv1k_Ap58x7;vCeaFFe$ zpO*mwd4=YE6B?H~T66mPgGqsI+S$fZ!FNjcfY}pnN}|qycA;)J-ft~$;1!i7&hn>iMr*Z#y0@3Mx}LEl}R%6L^m(1$UL&AK(c462{Dz6K5;3DC4U#(3CtfaV*!1do8rW zSx6`v?@Ugs<#rSg300w!Fm|MAqxTA&B%|mKOw~b9e{l^E%BRzLV~K^Z*)Wb+>rI#y z5shH9-hagqWXAPvej|ObYEeg7U57lw?1OVb;fwK$t&*pb=`wkXO!qYrnJUTYqGZ{q zAFFbIV46I5R(85i4@juhm2CCK?bQRtH>BP^o+Zq9%UKoi(!5#X;39zezFxCsUfq_T zqy@nPuyd?385>((v}i?LYK}!}q+_}nACai(U}T5g#=HU@o1g3NXrPOV#k#*XSUXeT zdd7(ZVRdU(CXq*CKPnVQuP$Q`I4~w+KZ_@nCw-Srg>-Lh84%|`@VbZSt?l2XuSaU{ zt-noQtT!=kSNhCq9Gt?+AaGYp4TS9U$i@cFBz*DpZ+6n{-(vt{8I&|LpJXf-*p+Ny zcNuadg(d7#W@ED|vLfSU%;%saEUP7=9bCB0A$y0QhQ1!izF{b9LBvGp}n`f6Q#?alX6@-)|$mSwoKK znZVEv!GrU&ClPjpH%jR`(i{_=SJ5-i1XdKjp_|xr%VL*@^Gr3^C=4$@WaCb`i@qW* z(i0|ruq63{^f4RT9F$T50%eE<-?I^Zz~J60JTgCpb}C0mkTPB7x+`40dexgS=INVR z#3TVY2-$e=(i6lsv6WGK5v-5(_CUp?V3fCyMUrIAA**NBmlW}{(b7q4kursa|~FO&8L)=Hq?d8|c1I5|48`VMa^S;Gem#>+7q02Amk5Gnehl zS-v&9Ox~r|o3pgb$#qG657GzMb6FtrpU3Iw@u1sMa%W3C>G-#I2~C&&B2wlvR<`^U zNB;b2RGmXLb?5GzB@AvGNKjJ}Be{+y<~BR%A8?^X*Zl%qeCPDR?wiU<^{c?ry$(xz zA{(PwYR^~?0Y3iLYFtJ|z_3J_4t6ecZ@en5K8~qp_+PK7nJDXes!qi6&h_lNo6(ZL zOEP?nH2-x$tcH2%e~GFQ?k zJd!~7TP7zv`2MQ7Kff~DE%5?aS0Wit(x$|gVxv=a0qC>fq0ag#ppOepT#lY6_7606 z{*5$!_y#*e;?uIi2j3c(@_JlkU&}n-2m3+TIeH7h-9yW2Rul2WZms+?;;NCg{3DNF z--R2!iq{v3&JN~};6TMrmVTzZvzA1BY!}Gx_g9fW0V*V|z`&fR%eu%b4J=F0`GFfa|29@~OURIE@2|oqL6u7* z`L?@HuTQR+!)JfF&w+$Y6Yq@X0}tB9%JQ)E!^+<-oVK>`Ti8+s>E5YQWueV{ zM%;75V%z!v_RPJQ0%zmqcr>8We>}>rE=wy#IGV2l9nP+J-$l~e&C|FAps6MVck2!X z!Jb$947-gt*NRA2zVUoHZuX+G;ZmPp>w=8_IRn$2$KF@iW3W|?C6Rpq4o=y0S6Ao8 zqbzYwo%dgZU)x$;()LEwDEOkTo*=Khk<5sSzp@)A(^#m2#go*tbPYcpKUB}&{Nz#H z(6CXcXIQ`R+0#D+R9Ix!O$~eK)0;qee{obQ{;9q2T(6>5rNOO5Stq?O*%%#`8V=;q zEYj14m+YJaKDK^X0^zdgU!HASmDQ%stXb)BLnS)HjgMR(Si97NQSpu+k9)NX8W`_} zXS$wwLtKm?@j=j>_~xeKXv!K@Mwpkh+TK*P%6d_kw|@_HtRXSgTC9-2?fc!tS+=pE z8rk2t3VZ-SlaB5>FCRJ7${DhT7)C8m2vqPAll2wUS65Ux+u3Ya({Ws^*{3(AmF`hr z;oaA~nooNlTNNpQkTWf&3A6crBh|OWd3-`1R#DjppNRTtqQC`)t?U#)3|)Zi?&(iE zrH2oH6%^P65xN}>wmjlJx|ab;Bt0i|eQ8T~QFp{#k~;t7`o(Hf(v5P-&dJG1Vf~ad zrZ8ywWHj4>OE`->=>F=*D3k(Va0S>o-eZi_&w=l%;yl78oj15EKik+<#~l#O3$Om9 z?^q&N<7evqMA)UTB!!AYasTsks8+wlUJ?KwC4E+VAH~LYu@wCjhAkS8W|k4H@Cq_2 z#=Sc3y^gaom1CaQes1zJ_qoe4e&~-t|7IkR2PlJRKmLKYL7U=#UIb}8#cioOem~oj zEQopo(Tjl)vlit=+4TC`dm5YyHeoFmVO0x#yLYQfXxp|fIiJV1QA&VJ5+~O4dde3k(_Jevsh+RU?JX21@ z=gy!r87F>gc&@#gt)#r0SYz}i7|e=M_FW5SNMH}EYdUcqYLwwz&|8xltM`OxEbvc% zV`b<6<6B@S%ZItCrH2Yd>rkcQ=ZS&baeopqTu95QYB1YsYhKyH+6w^4 zTrwd^YZ*MqJIC5!jZ%>yBuxJDtjh3d$@-j01Jg`kBHsvDA--7P;OsqHZZOZpwgQmo z&M}R-!q^c{=fFt8tiru3eu4R$3Qrr%n2X=ReHF&T6#2D?pe8O$jb0_jn4J57+k_yM zJEwwK#cEbGkT5OHtdY}(L5Bj_3w}Of2f1Yx+P$$c-i{+kW_gbhflAKGlxO>;e0+hg zjADf2v&Bf}OUS9|)p`2C!@56~EixAq zbFlMSa)Q{kowP7!1!{Koih=~rHkvxh${oLXmMN1CXWNN8{kq6m&p_YK z8PCa>JyZ`$v|x0b-9wpL z!d`CDWHF98Rxo`+kKY-e$VmJBUGySSvkI&shuB?mE-^I&V-?) z!hx?VU$_rFTbzkFbNS&L0p)URP>d+q^B6H>v2+(TG+oXa-F79S&wATNDw=`%c_UiJ z>RB7&P7jSTzEb+b+H@PQ6u7Wg#8Kl3oj4dCp#hV;1=67hLj3oX)~tI2 zC7Y8h9sqdZ@0dG#R>1vLTobY0KwJ}*e@w%wvD?9fKw`$;pM2lAokI&>>?O(f`=ITaDhzRAyp*D?h z@M$e{2l_v$+EYp*43RB(F9derJysp_>nPrm?L>KRiciBDv(Eez#z>kt*8;Uy;4Ipy z>d~VdLL}WQE(C24mDIjh;dFL$01>@{lu0WkMSXmqPg^8=pqBmHr?dp4l>?(=!i6{a z{YR8X70xc-Jcy}Qi>3o#M>UJRLR$cf7uMJ6Z9tAJC7Vkge}?%@@{EBVbh5hYE@j zkp?FMr!oZ692lD1H=4gLWl9^r<0`OoH3KzHGBx^W`3+Mt0ICIddVNX&>1#>l&~~W# zH7)#}_hoJ&>eLR7YtmMfs^J?7g4Jd!7Cgrh*?zK#Jyrg2IyX=V^!2%R8$R_DkzXwpe!^%d#c-g*Y?t&k4ox!{`7 z@WM#|J;QxS?KO-zF-yms9`Q%+6PD zuu^IqifhB(sE;9RbE7&1RNqqDhOa~4L;=$4;1q zGGFjI8l-4v#xcGu*gn{)CRp>^7m)Gw-OYxj!iMnUPts4a*YII;hq*&2lV&at&iV^$ zeM(`HwYD$)Oe11P9r+m(LLo*3Q=NpL`ISRZ=*Ic#oOCcuvFDVev%KS5$bq;=nAEH##k`q)fy zdp8u$58NN0nm|nR3k9wU3f@V))Ku9iBD5vPT7hQAJDro|=XXlgq+3JA{H~QWny6~} z35AUuIluzTRehtQqf?14q{nGaTaWYd^uxxtbRS{;=Qa^{;;K8ASK!)JeU3Nh%)gqz z5MJW^^Ozq$4ofC6Q=O0!7^)z`7YQN0hIQw`eV;v3A-*@7Jet#lSVF5KQNt;8?B|NX zB5wawE45d$+fAIO= zpHkQ^70%8M@A~`xke7?yv9YzCdCstbKyp)hu8azI%y`^g3p1XJ{Kf~@9Ap)?#9f`{ ze+E_Q9cwm*u>PmXjO7S#2Ufr^P@>1#vjTr0a7{RS|L5lavhjrrl9h+j{n?%?3gd6Bhv*IWrDavwfk?al0cK#)0Dch|xjX*ig=MkkUICDy?R z^LC?zjzy>t*Yk@WE^s0z5yN9^l*6>A&p{4}AbGMN!Uq)}&ikViF!;kd5dV3kHkd_s zJP7UYcS{TuF@X>PLH65r(C9^E^{yXNe*!tZu}={7>#@cT3pLV3Lp#NPmk_CcWR&n* zLg4y%aD@}+<+OB<-P>`qs-$OX6?#*VCWD6Nie6@{evjg?oblRZGOO|R%ZIa z{NZ*a`%sM5vLg8|Ca;Wn%t8>+ZY@>l{R}0Rn9HJv`&FaJM(X(|B~X|cs+JXwSE&EE zMm^c~_W``}sg1MD{(cop4vRN7T%M%mx%eB5;sXjQ0 zzT|!Mb+*zmgx;Xsc1}7O>M;R@R_H`{A+=aw8P!&>sa-2K+)IAIY%Q2fEL|;8^Uj~1 zX^eApp)?p!9D%{t(vMB(y+tD81Kf!e;Z-+Qr<7)hd9V$UF6t{)$9W5-|r)cNxHZYzmNYyn?k z8}U=^pb^iRo%a<+I97-b;|8L(HH7>Qk~=Z z-0L{tjA-PT(68Oa1vmT3r?ijlm4v5qzcUl0rfbMEF}?0K>^4fM9~}v_>>P-h_g(n# z4V1Pod0(Fs&*~ec;q#}UdT8lRH?T&PWXD%KwMz`M)+N2b2l5$NJPABpG>z!`&z|j3 zlXBbV1lgjtw13N!sTwp7f1K6Ea1=MroGEpWK%}2SjYEk?dNI7?@&O)G18dE@D$oE@ zvxn?4sl75OAc;cC(~EF%a=!2@M2&>g;9Lny$153b@w;nUQ(bv25`quisA+{`IeROV zymrp+lhIp_%&3%%!kG`&2VTW33S3K(FI>9II3xmnJ(1wY+wS(Dc+7)5Nn)}>>Ma=v zXQBSd&KD9oQBi#%vW$vv^WQsB{ky7%h$j8`-cI462S(N}t;czRw#&>OjOU~+Gb;-l zwBJMeb+aw+}h7HGKO&7G1F*S@n4y+;o?L$ zNtUb~YFfj*AUO29{~m<@JdXZR<&f7v^MUSKD=OHs^8poe2}FUy+vyFJLy(#nOsOO? z)Sz^7fL>3=A@&&EI&G#&T#{?L1wpZg(Zvq-o=zo7264w4r}OEGQRZtt(Q+cA?H1t> z#8*EY6&s%1w9Q=T)>`{QZ=91f@tc-ZoMxCm1Zs2k&B}4Y!u?s9icL(W&x_!e*ApQE z*QEp|?bNe$2UsHEhy9yrF)m+dKY-|i4*4(m?txXRxWJD-a5C3JmTU~N9yMzzkX$#` zsPypi&Nrrp1%YdTpN&0%{uPMyABD4Q=0Gm|>)mXfemYNP5vY>a4- zt2!R*Mtq^<{?x;{zMqL^kJ%jVpGTAaY_TfyQT%rVY$))RW94`1-co^IYlqbGFVH@& zKzYD-2W=Zd23&<9Ut~IVI-B2`cA>wn6?@th=pZW3D*RC-){0BKbcEzdpUOSiufdrY z^5s({xnsLNpb=ABnrTeL*JF2M37Vy&cSwmPTorAv!EJ~+p>%4TXwoBg0$-a`pS z%dn(OVRov1L245{Z_Ihr>K>QoaN$f;8R75+ZiZO-wFo7cz&9liIE)XhusRES^b*8V z0pd7#DVg(J^1H=))=H{Lb&bDdek!#JSmvtkV_?yF{~cgtI#U|TlN^pFL(EYtHCSYX zByj6!Cz3_^JjTm>XZ?~}gQ5j1Ii@CFMJ160`0w1z>Na=IbGm%#9mo|5L;1Ag3~a~7Bd!qf?lit*Jq%ABwkEmIAAZoIU>C6(iNNHn^|J~bJRW<&x>fVHKdg856W zf`ISF6hS6ig&LMUD^OJ5XZ<#|zL91L%iZxgjdH0R~r9x{X58E?!GzG>BIk!CjoYc)o>IH9y^#+>;C}-^ln9=?#l=hnFlTllauX z=uUGOjV)hs*KQekR6J;2pc5m$i6%+m5<-0MyCe&qPMaE*&3ZrGFKZ2Yfk0?B zFet4;X(C6<@m)+$=*L3p7Bkjk)mZ|bqFUV347n7@4Qq2+nn=AFZGth#i ztMSUujVal*IAyzWYM%=WqDqra2cOv8g z?|sh~@*j^)nWYsp4A8MVz=FM=7?$nhWCjEsZ+WT;VmFVOiK7~$jUo3ggi=%b-%6Uq zCs|0Is|3k!V>moS?acNd_FW9&5nvi0&`6_ZxLer0Zr2&X7FUx@$as=QW&{yWh)Lje zX;A_vqR^i84+8+{2OIZ*@wc!|FrVtSaS{Tx)`M6~eJCus$$>c4Q$_n8rd%WOqd z0YFOtL~kKs2N2ic<7}V+fCP2EaPv*DrandeF&Xr6UmT4 zv`psBb~qh_O9aX-u4&&oXFgL3+(b{sVih9lh!G`y4mp0|mH7U*K?N(<9FKp~TWz zzg6b*%*oq-qGuL@q~L2nF20PRrY0w@$wO_38q@rt+&bZ{!m|X{S=7K93dlPj$fUe$ zBRuN|RGk;Zt?byHr)kf3V`XMp#`8PbgVqnz3?S7u?`T>dimj(Ow6TAL8vAg!#{0U= zJdJ@|$CLXTfBbPHzr*xf*7l)42V?>2iP&uK@~TWDmuhm6%`{xhMY)9@9HHJS>+kiR z|G|sx%6prhz5lcq!Sx5(zuJyHlmdtbOb)%Wqr^cU#%^suG~Hc$mwT&v zm$CeiY%-wrMBsVVcE{*=1~ih#nGSS#XslfBM6&AJv9<|0f7nE6 zfH08$i8642AEn5?R$U|?z=oIjd@8|(Sp?2A(8kq$Jl$Q3sD0hBPmTESuEj)w1dxST zR7IIUxFEc2{FLVPRj%XPRML7)TH8kJ#4J}MCfal1EL3dk4;7-YFl2dm2N650T@&MZ z7_~(wU@)Jy(XP5Z(+|wr6Q_GQSl^sox&)gWK#U3w)sFi#&QCgy>ZW^04cFY*VwKu_ zI$X+m0-;%g^lc&JVP^J^(ew;}aMFLD!S-}STbn{i(#Xw;aK-iA*tVf_(Ht>G+|;yw zKEy!mS2arpeTv+NX%mV3SxUVI%u`@3XaOa#cddR)_>N^{#98=f7A%+P@!y(|F!=H3 z-=zoDM`x0!@glq5YSRq-v5opyV|Riuc4neq5bZ?QCE<}MH>u|fnV&FV|I=`vd<0*8 zs8M>32(i@i)&@6K8jbM|&45E&Oz&U;1^Y;Ab|XWV=``lqNg!1y`yfw;NF_Xe%CqJj z`%e8>E(hG3A(LOLww+rTX`rX`zg{}>zuh}BT2+@@8%D5h^eW&S9_B~g`%6Cy3JIw# zE%P2cfL}@0G;@Y4RStJX2qvBRf2m&VJL+)#Y#{uA zH>xZR1O&wu7}hhh0(2d=#Q#<)OKcd>qjPO>xF%6p}OZmdAMbbvb++|RW$e=-wm>#p_9gE7>eORu4dZnpN( zUF1u*MIZa@Mu-S$Wi|)`bvaWRE9^9%@LXdE;nvfcae^=Si~XKuHLf9$FOV0t626nb z0wIv~bQ6WGc~f;}bs&yZB|Xnv-`Z@pv|3e~Zcfm;j?SEvN@>;mZ^OVBVj@t+pSJ64 zRV9~)>aFnt$Vmn%Wfh&{0)1~!)~WIE*sxtslWR#bka;{oQdxb1t8g};x(nSI3VYjB zU$@uEf3q*xIeCI?M#vL?MY`OYz<|UY@Mc^E`Q^E{S&sG3@kX43y^ujZ?@>j_JFesJGxP$>{c%yC=cIEox_D6D zed-_fvd#xGElfvKbPVm0x)$^NGgiwv{+FbDY zs-Jy)XV;zkae;{M!L=?$H)1sAppW=GyrD7{P+|MBJp}J!V*;NOPmp?OjnkW&Y$!sP+UBBV+r>LL#wI`-!$sLTTcbx$dna z&Xpi!yqAAu{67aS!+#)3v>F@m!0wmb$E$gLW9-a2y1ImY&E8fs5xrgq>|lXoBUZXY z>eW`I4KAxsRO59w!GNH9kCET}$OPiJ;YO}d(%@m(NTnlulK{&Fbp_=w1mpu%X@#u~ zFOE)6ZjPk@S&CMlb|4kWu)>2xZ}-?O!mUC-mcOKgRZ;Jb0Oa{MP`k}#fC1XVTk7H60Ck~io8!vW~O$w1bF)TMk;$oYIUBsVmyH zItL5S`^)$Xy?q=Im;EjPFp-LN27vSrdt!=c-6iO3-S3e>-g@R|G)Q974tW*5ETLTh zk^NrdAt~Anb(7MoS7WL_bs9gr*vuT{eX8){*9?HRm#gI5sE{~1{Yk>d<)2CCrX1}K z8_-HSPpLw>291l~&tEs(vgDi&v~krGpZ4K7E%fV?_v|ksdZOVLz63FWa&AgW#%1Z* ztI&*~4YD4@Pa`1=$nf#G1RPUVZr1jFQ8u#HPc4?rYwNv4K7?qD>>j<%Bk*B#sEO!c zgwUB;yi^&MY~8(A!XFQpkd2#G@ru2X58J|i*ot_>&4wAU!98jM1-&U`-*%9XrG%A* z=SFI$bJjeq)T1?r9GgYoNrN~EdA z_Bq7W`dlG&&@bmV9*p~GNCnL7fG`r>Goyvz>Q|5tQokgu(Lq&nG3BPV?1Fd-r6|KN zFOI64-gMhSOPmPKCSDp#r%R65_E_qLEn4aYFW%@tSvbU=U2d}bgCve~F$cc}vuu># zku`K6C;nO$V-{aTM4s`TgaRV9VJ}C<)6FfVdfd)*pvHAsh0kq8Zm;Lu!)!lAWL%!i z8ALUUcod$-TDV1Tb9vCC{#0g}k|vjd(WUG?+_vuqjvWY!F%VQe;D`d;qix|~1k>7@ zL=X3oB4v5;7m4cO3UEP;Y6+aN(Av7mkEUG5F(lEB*!YFRZmbUQ35;l%1U+WZ|0c8XE{sN;dKmlQouT|yWuv&6scNB`)!O!ajT2WX-a_Qn zgBWqkad9UlQ~3o}DBIL8GZJBkX8i?Besz4Sa5jf%x#Z~VkUWVwT0=lKzGDF?yORU* z0=sG6MVjI+4Onc|m&(9>^+{RXmY(dXAQs_coAEDQrCozNA3)98dc)Dw!4K_zoPSHV zWpAgWZwmchDb%pl1;gZ!jypSh$SQ6}By z(;TV_Hen%=u8U6x1?~fNjCqle5-Mq|v z$~ie!AciXs<38TI*7#)XPHNd&R0y5Dw2YYYkI+f{=aK0X%aTwj=V<~XsS;?DfMbZe z99L{!zxW!o1SNxHS0ZkU^r09%eGuwmDsQo9JNvSNREI;1#_)^PlnW&mRkr-K8loID zUiK0K#S`LQM)!~2!uLBTZHM;_Et}=26GQvR*M3Yu#gFeTe-;P3|6sfAj;%0hTwGyV z^ZJSKXX9U`VuJE}IxGs3BG;j2;?#2M9Ej1WxlC?^GI6PbOn9c@m?EsoIs3`b7pf8) zCS4s*pgGkA*lE7e@-u?p1ghW5^CE~DkS9YOJ-UnHAXR&DwQPssBdeV*Fevg?{-lj^ zy#lbh`nh{#ucR9+Udy4^qb~NvEupoWH{^Uy)zi@ocr@37fA*l=F-6Y7W-@HKUuvOo ztOEVaL7*&x_Sj)qnu6t11Pn8wtI<7AP$f7cS*CWXkcL2pPg*9NUX|`sSt%9XE|fAs zMwU(Q_!7kx{(Mofke$w?dTBv>!zABE1aXk2Q0sq_BTkr5^0vZr z0eYV9{^WrA`p$bG{U90>zSir)&T)ZqOE8Pl_Vm`^YYHTNlJ=2dD4+VW@eRt>+3n@+ zPt}E>!!usWk_k?9FjIeL-TL`Kk}1^+=-jLXZ*U#IlCb?S?Y`sH5w-P8n=h^+HN#1$ z=Wl^jZNTPPtwwe3`pXwvj0dvN<1$Cqt1)bW`^DWPz}<+4h;VytHoDG~=maIk+*P`Z z{>Oif8~GWI>-mndY>fG-UU`8!#@5_rMIM?&zqCX$E|r#!?#38IMp_vs+GOew$EAzD zk6KZ`KTvhjpOzf)4JIv{3hEMSP(Fq%g>_@J3*0>^l=kh7aiLJP)gZT5w+bcMQsQ}9 zFu2yq5(c3o-Bscw;2DW8hoFAkg^my(QzIl17$cK|Ih}%|2?++QEF>d@(Sp~o04k(R z$6P7tLvcOMBeMJ0;9Q=G5o~Mj&~6SkE|(4mi1t*DF<%@ofdCmgo67oGo5UC4DrfK0jrh1IIb!&JIMCn$ z!j&?!V60v_{!DGJ&9r+hOHV4e<@A$nHc||d&_i1P$XoYSwLt797l+DdB*$Ug%cnua zx|)5P#z)>S%h#7SSw#g4O1PLbj%17Z3~X@;fjU@0xH=uCayl#F%6a1tMqX`TO{=RN zdq2`td((2~aMG0yOdu7oL{5G5QQclD=l-&7S;k7}grlM1n(T_0I-Vmf{bbfb=CN~^ zm)s9(bcXXy2Ie_Z7WU1Z>;ZZ0pdn6OeD?rOIub_hJLI2mNVX}3O^>{>u>FQC(}?fi z&JHCGQ!>t9X!i#?DfzvmJ>lgKC)~BF~3iXOni)Sf0D`m zZt^?b`2aTsOyai+V^pMW829gK{S{;w74SjakqIjaqR7DWD+rgmLMdqc_BO!HCMYzU zMXOh!&uL|ASD-^HRoHml$>|{B>B;v2ZLPwMU&-I=PIZ5{y(W+ypK>Mug+ zhp8C2G}ImS-|A0sLw&ieZH0$W`Tu^z+X!qNc;&KR_u?h!p*VaE#ounHg-7fGPd)E) zTJ?_y*Z}gp#aRT`TOzE>mr7rcP8&3qpg`)umJR&E0r;#V)c)(chyBYfdauy|O)wCP zmv>)*id<)?yo9Y$?s2$+VJHpv0I71UP~jY#XABiPX41-Cn7N%5`FzJ4tqG4kP7$Jk z;n(PX*u_YcCI-HkTmW!%b|dnMl2+0P!S2r6kDfpw_ogQXCD75RZRFOt;7Yl705%T& z=zE&TnZ9dRqdXzSJ&YR|Abe1STTD`4^dmkefXEm=HCRo~UX~B?T6p_JLt+&twjXnX zy>|mZ$*o`*@cq+i2au~PaHU1@7n>UguV*uWB+**RKn#$`f)2XWE)?ngVExe_ZaV{v z(MQ6+)QErm*G#l~Ocs}M3dDHHo;M*8XX`&3pFh^)EXa?%koJ7h3m`NNz|MaFCy?m^ z?4!@`16z_##Faj1yx1JBlmyrrMGu>x;$+{;Fj<4Qz7jx!;vY?WHZODBrLM5zKp&%4 zDWs0ea39BylNky0xGwvrdJ#_!(%1%hA@^M0$YeHdYQFfj0Q^Q@Yjl`q4J6=1Ekj8Q zZMqc0iz{4=FV|ZUx;3YdNNg|f^Oya8yLq2(vUX1z&-MC;%GXYWOs2?j-U_so_D|s| zWZ_E41tyBrE4+$ITVePbWa7FLelbvPD(?j4tFs{v#W)K z7XZWKXaIFf;qC=6JH?S_{oKFTeXsaPCeP&Xy85D3u4Nsgc0I4pS8w(TDrYWYfCcam zPLT>-&!eG~>m#;?1LAZ3j!H)Dzp64fG>>G#AD!X9U{k6CO*^peQJ;%OUNdP_{Dz#v zC5k}67bJ@2p7e5jmpwd{y-73t7nAqj3%hgiAss>|@{4={S_8O;eq%%)(`-aQd#8sS z%ky13@zJu=gA?nNl++46Ly8+56f3SaU6j7mIWQ_XgUnum2Q^W=V(VT>i%1$XL86J^ zzp}EB%yHPA8sNH)HddD?8U_YKXmE>7lB6fcY1s~4X|o7Uq`*P@sig_S?%-W{x5Yxw zb4s~97CX26PT9hxHk)VD!e<*_qdDL?&nmXw0igQhaZm%1MsS3t41Mh(pD&1-_sVd; zsB}s9nHd`0?(bF|eFNy&spPlteYiB|;cl5akMos^%Nn8%+7rjBJ5Di!P>c8+>Pftn z_Q}2Mynnmsomovk8d1UiiEJhP&!wsILXeH&J6pDW>MtM2DF+ci4h~PAmH~TJomY8H zgB_o(IB{hOZe}+#hAw-~!%&h-lD;Rh^?rV_+`Lz92ZQ?B5jQFZ+=XrSXns7)zhf3j zu(7)fc#qM_2FZ9Qw{_GFX~$V>WuDn`YsPXvD1W+<50iE(5+8|Cps=%^%ji9wsqA3W zU}V%WxGc=1HqmE7*lkdNTYjxo$PIgbI94>Jw<_l1a71d+f!^?;xb1LK>yg@Qel4xP zk7t1Nv45SFmip&98+`eO{4R%16}t%e<^X!+qs5L;UN!qLM>JIF2)=pdSPijFOHG}6 zGP{9YOfRu!JDpaf)Lx7Y`C`r^0S=m{KIqoO@HC4M`#YOd%qQLz_tR*l(Ca8#HpT~J z2J2G!Djy0lf#;(E3%pxt9USX})jR6SJD>w8BL3sYz(5bQorOuD(4cEg&N@@gmz}0| z@aIAhH~9~28vGI`W)`%^6Pd;RZ!RCKtyFpyFIEo14Tp&F*>kKgHhM~5?)N6W&}0_29MdQi&Au{e_!&v|>Yt;n}6Yn6vioeq6*OK@13 zDm7wW1S@6Vuh%Q6y1zBjAJ@&i`y}OBO93uDr3ud={;x77YO9YtL z?h>|cUEI32Pmj_{#GMkJ^5IUWb~(#?H;!fUFhlfeQCkP~69DM4!5c{%B8frK;A@*! z{+Czj=Ss=Xm^9re+tq*NZb+ue zS3AVe)kB_%snQ&oVLx2z{K@3N@E%LJbH{UYmwz z&UlM)`Q+QUp&=MnvSd>80JBjQ1(tgY0qyI8cxhbCHEgp zjYFNRRjE@lV+d2GScA{&-8ilOIdxT$(9pV6=|*dvvgb_UZ_l!*cA&34l$hX$TyPQJ z_WZN=dWpGOA%}P6C)r>?V!j=ayqNQgX-dsncE?*Xp*aS6O)R^|tRMx>a#$g~gQUZpSx7%bqVhsD6>)De4 zJ|sJO+UsPllywJ5V}E%KIg+|in|pN~NtFs?ilQ*SY&k(I?Dko98rX%Vt|p?&!_Ad) z?jQl#sCbN55(Qj{p)qr7dPeG;A@=*(CFFshtIqduw1 zVNdh-`h|`wy_NL--6p`-cbRvU)9(PGa{F93z}79;aFV*;87P7k3dg7)r%A<=+t_tY zt>TC3|B8Im&kqha)xv5S)Wi z0Nw&cz~m+bm} zdO<<8!b?Alux-?JpROeUtc?epNW22Acg5-TyY-D^asc}3hN%@F_zl2}EwCI?JFn{7 z&LEF5FD;UTM@hM3-ouv?!TSRufmb`cwcF> z63|R9Iplh7TdTz>!k_2Y9j0wB(PN@fIo&o6kEBV)z}Ll$d3bzfh?<+2@naUEz2*i9i-ytEoCJ zT9)Mic>s_r2xu3YU=|OK(8q}+J*9q3y5JH|yR#g&L=nILsE)J4(yg$81=vU)R#cP3a<0GOdcUAF zD@g*p@V|AgieL!{7qK;D7|3Bns(1gghd)09;tuBjKA=WC2*}dRseBu2a1&}jj)~d(6{wt{k^vN+V zBHPA@WFB?{exf8kbm2jj4WJM~!v*vUnMD`N!)X|Dc!x*;h8!M&)=Wo#c-CK=ImXVB z*xbf{JE#LwC7^cx_~y13;R1GuC^C8F_=#NA7uhX}fC=U=?-_94N)dk_qtP_BxlNx; z#rjG0*LD76evIEv3qaLwSNV*`0Gv$8pKsR4bpU7YujCNqLJCn4L(ubPjxkmD*%t|D zR-^wtpVNWB?xkTe!*146@UeeWA`+syXM0r?x0R9n{xg9ogo3cfsDyuc)RdRI824@K zR~1*njdzQysK2X*FOcE2@OQy??Kc**UAc*kNQ%1_3ub_3^tJ9z7!oRPW@y;kFXIs0*`HGYld8#G^pTp)wKN?Hn@kPHUjRL2y$Tbyx>A4a~N`VirCa>9a zLE$=MQ$gY9o3@J!Vg&S0fKfsI)zNc9$k8CbeUdQ45Y5N+ib}g`gg!VD6%1VH+$_>h+zexkV%XdS)cG*hyglj=A=~4NiKvkgUXdz9h*PD9nJTOoIOUwY z=YB>XqN4I9!!zv&Z*$ZKTlFG{RcHmOZ4sdT&dSPGACh8y_lyADp>Li`lMXF?aK&xw zgyCWRU%@X2hSdlB^g{T@v5Z@QQFor}c-oVxnjj_AXOwT=T*r4q^BdD^n&xsblVh%dvG9`8G zkLn)Ts8J9se3<42eImL?Q%!6fX4~$P#ImJy#R-D!)_ZRfC!=Joz{dNI?>8r^rKFuV%{IgVa)t-oy>NcMdYbZh zur9=j;qbA3VPRJ}nkQxR^o^fDEJ$7wEDWHI1Doy#*OAW5kfRqKv2$?gM$(vXQ$z25 zIfpKw0-=Xvjg)#n9{P?-G@Nz-u|Fi!CDZ7qI8gxZLAeN- z(tiOEXts8CeZtak=_n*AMx>+J4f1?8i|}|U@}@EkRPTG)i4E`U3aczio^%FN3mM;J zI}n24Yxk=`&Hq=Z)m9bkzCv-elJw55A3=52MC-$!-MHwnJ|}rZUGLQaB-bQin!}3} z{|{$x9adG>wT~(wAh8KSY7<+!y9LB8EnR}7goFZ{ZUm7{cXy|NbeD8WcSv`GG@OO{ zKJW8=zZ2JW{()=3S~JERbIdXBd(1hv*gy9rV0Hg+4nd0MC4T-M@LX{grGVtTAmkr$ z+)T^~8kd8GaIDqN9H&2Mqz~7l1qp8R4ldkeZqANVNHP!S+E=H@<>NGT7Z-x+_(#88 zOCZq`*wL~GPQk+T{Og)V0xRqNHr+oO_#eOe(}e=^8nhK~)YJO-W3hs~fK=W;w(OrZ zR$&d?2N!Q~HTk5>O`iVGTlTULYF$!h7C76x(hRn6v=~Y&JYgkk-VP;pO4XNM3CGXrFBr4vIa zI=@3EA^n>%8mEj1b9GnB)Ym62)-Qa4@PP_@1;?=1vQ|HMaZ z`B>bf@rgkN%b|`MX8|{bT$C~A3St6phfg6Vzd*z-DU49%l6ZwsYXCpUtH{NY8W22h zwWr+ZuM_reET6V0ww+E2j#a4@F?>lr45AG$LM%kE(H371s(tju)(sWHZ%V|zA}(P+ zk+T9F;t+@m4lsZb;E~IqOU);h24iH3FF{575y*#q7-af+6v`?s^W%Q+#Y3R80SS!{ zy#h9ZW<=*weN+hC82nyXoza=ju+tKeFJ6w<@+uW?I=n4SJQ9RXbCM=bX#v577^v${ zJs_oh22lrY5>5Bl#|w5^#tHb&C-%!Bt_zO+*;b0&3nCC0gY5z)7S)fCB)i(|O zo%a`4`jKsiwUMFk;DT%_{|M9}1=9H|Q@u<_{MzZU}4OGx4O8id5MsX6=QVOaqAP_&T&OI)KO3tz61A zK37RJ9&I{HCpcbJJvkdV2LC*Sj;<*3JaklwwN1}2|0`0Ano7t6xMmdQ=-2s|O;y7! zk|VB?fX51r_resYW@~GS?=L@K}Mvf!8m7R<0lj_!_yac*CHl>X^5#$vn|3=x- z>m6wL9EbCfZ>tlG`cPZ!YrFcRymFeL-07`XMuZ_$J9++Ws^nYE&To~11HJH73fHzN zDW5|aCSb$JW*9`s`J7=`q9*hxQ_&H8NJFQ@P>yJ*Uwx==Yr4dz7O!HB(H33O_i1I3 zA8`BNO5&#w(~00#D&-TLwzOA^(;nT(!9)IU`;Aqi*}gPsw!f{FR}FZjZ0-Ac3yP2D z?M`OZ1KIv2S%?-`qhl&@Dp0F-y@*ZoDiOGqjbbfPQk3Qwq$XC3Je=b?5FNcC^3!*F zwu(@WAtVwQRZK{h$jcyg+hL;MmtUk@C3~WV6YSK}uvEotMe`{j>@{HcE-^v{7bYIf z#EhaSt@Fz#6BXpRkAVCZ`ix6#6IMaH$FH5k-AT1+E0+a)-p>o>@@U%|z8d?gGTpDK zlIP$1HCMP^G4I_IV4i?Vv&c_6Aagk~mSnI(zuO8-`F#Ehdl^^Bow1Yzjyx}zq2vwl4WrxqX@RcZXvT*4FHwR!GKVz(e+Dv(w!cW?H8Zw3`VO)H(uD=#qTDj-qy zyE<=0BGt<+RU9b+PwT?5wsgM{nZj)I85M!k=Ly^WXg7Jq0`Uz2x`=Xul%|1$Da}B- zWl2yeOs?Lm5kE}y>x09=j}+&Uyq_LVi*pi{dIJN(981^X_s&_>Bge;w7_>Mlyz1Y< z(b13#%h41QKarT>(s9|pa?Vv=O=T5 zUdiRkydY0}6^TZD^LK+Q4(-fso&IWK+jv%8YdEmwH%Jn+8G?hanRR$DHaj2+<0q1I z%G#t86>8Ih2lgMSKAHfY?H7*qP$SYZJtZKKU-=*{kK=uR2Hr$>(Z`&>D=)C70$U~V z`rycHQ8vdVD{Qu8A`2XL#^#AYQ5H&#kzych6tc+MEVj!2QiP6d?hq-eb$nR;! zj?v1;{q2f#4Jp5!4P$wX@=(;MfpIpXiW z-NCUph?07VsFOEDHV9+yn0R6m1$)O>26k;eqU{KFa<}lu{ObPF&Qz07TD>?scXMNC zPDn|Em)lqn_8)Z-&PLG#{+v{SC;94eit`4T%mYcy@ zE3rEg$YfI<2h}2=UGnO(+di(RvyPr+<<&Qz3-)$AwYo>lHBeCA&xLDIzb^i;OS!44 zy+6J&))JoieV$8$SHdIe5PxN>W}L7CLiOpVwQ)*hh%VFS-c5mwx^h}*nNHb98+L(&!iNv_l`&bHt5^6s7J zT!nuPd+lP^RLztn+~{4lCpnSS2HC9};R7xp>vfpzSC1iE2t7>|pW|yY)DKqb)A*47 zY>~T;4a8q%`)iMJv_`%s0VRYrjlHP0E+k7aGYq8Q*&BkDDLeV0IFZ$;8^W~ssr(VH zOrU_3gN06m=VZp%%T?~QlEMFUL~n4SXY!7v>Df_34l<4HaPjqgz}!@L=2;4H6?R%E zQ}tH|%FWHJ1mpQ>#qHsYbuHn7iJ@y}B?g4}wu+Tn@H%!q%X*asvfbf1@#428mUY4F zMsS2>=AJjf{z)C==l0?E{gV@Ezb;C2-7tds>}pm)-P{%4{rXVg%)l@Lsmw!Buwpl_ zr^oBxlCL?NTygRR zsSC1`XAsd1V@9?MG5-ARxmNc=3ef2a-Z(1!Gv8>6fl_O7alDtA!$eu;>y^Q0(JR#` zbr#Pi>zfy3k+KAFD{84XG^dfK+3cnEUj0WUVKvJ|doCx^#LhY*@6Mhi&CQkVbr^`y zFR6S#>o*lC?jG)z7~Drg>7M;59DrfcUCzji50M|B3x;k+rss(B?I6C;bzA(HJMUCwdK(0!C`rGI4N9it|JObJn z6UDU&941ZP8lLujA#?rI3t3m&Ce{xEGU2~&cq_|~-2yLO3{ULIm@IWLia1D0Ufp$a zoQ0kuIw(8n({F~QthLBJ4}_kdh+=KJn0X@#Z%}tTTfg=P6T>;OUVHgghz`l3yi;E8n0UovsrHVEi#Lfntx2@oo@a9WHoj4R6b_4hIvl zdpDe-3;n!Wo9FWm9O!8&3y=HJtUVTJch|3OYE8Xy7dBo@E-7g(Q*U)DT{$dQPYcSD zDtS8IWvOrZTP}USMo`2-#qfeNF{Qu)+yu)MfdD)pIpN~^dzcE|% zwU4v?sYj{phex9sp-&0ww+Ui|KXO1z^TKRpTLar`LjSZt2BPu}XhdSGoH^53=gS3o2w! zK1r3}nX}RM`S7bf>GosmM(fhx%a;{+`mip#wTt&hPIKCi*H{xcR-If(wIndM60qjh zxukwj3LR6HZo2x)@L9sT2oYQgA%84E7B<5qTWO8;Eg3?9OF}{-R-p_Nf;{%~@mV1U z?W*RRoL4)spM!Zs4NvD`X?sux|Q9(xKlHLfiW9v_o`rDdm2WY606g>EP6IyoDw`mm!4 z{*U%pUo>AhrbD_sD6VIl*5~cdzRgHPV-4tP%(;5yjl{c0ooHdrosH1NaZ_jN;(wGz zXeA`QayNmbY5ITLhXo@gA?mnOnNg?UQ&hSq zpK;8}t6@+Q{I`(M^@KUy+w&Q;mCDNX0d4vBY^LDL2NL^*S(_p*Br^#&Fv%JZ-5jxm z`jEZ*v(0(yswRlUd3Gv%{@AVPm$`btQqK=h8pr;t!>ITlfbDSW-$wqI29x|(Kp3rW zF#b`;|JMiXN%Mb?u|A;<=zoq>pxDYf?ZX}pynoLRE0OY$h(|_@Ui1VcJxULru<%4? zVbf>>mx1$$+&PtR1cKo^S7~3o&FG)~K$81pcg7iBk%C(+%$+pRO)$DN_~7rn0{#m$ zlPROi6lMY=e3sju_V8~fUnM_&1J-;a9yYQxxWx8KApnZ_SDk&IKl#R2{w?rXPJ3Fr zzHe#{J!r}e?S4j~;?IV(r+sN(Qux%K_NaMju-nHBn7VtNOM~Cv!RUZLAn3t1451Zx zFCU#5z)bYx#KHc(wYgSKE9LKsRt#WWoW;0m)nL!Cv&CTlFM)z#smfmCCMI7S`?mVoaP(Ps;3WcG1(M`hJ9^l zE_kcy=@aoi9#aEra?`O!BC7)8uBo^cq=_ z#sLZhEPitwvS13*uTAN43q^%(8G?2&Q9?lOj1?>j*?PgMri8viqz2ve5!|Q@yCxh$D2?YyL!K{tc;e zI)@4$v*a)@=B2r{b?gOeS%WLwxL`Rw5ie>H%--mF8h_@)Q?=K^Tra66D~;lZfu{$> zcLq)JwW9U)Nlnk?Q2b>ix92@q(`#XcNled1<(EUZB`xBuJMFY^eMeml#c&|0jOXOEF^j zAdbv}wy8?N60&Urjceo9Pe&3{b??!QvQx)N9OwPqF-?K9~ z?ky7*b+LhdL!WS3DnhXVuYm%lcNXVfZyRTDU61|E*p)&_Wlt)k2u8$tnXarV$K`QZ zGgzNg(6zWC>i6*)6T&ZZYvNOGpR#GLtB%Ti&fH0LZ}e=BBqFZ0DI--3H^Gsp-sng} z7H7bX)1Svjdf?IWz&2Ap=C+1K;4~WD;63VV8M0WFEDW6TH{UHrvTfe7+Grr&1ta$r zvFBNT8ZGk>rm`(FM?$XNk?;>4a-l=As12f;p)&GG?l#FsdJ2Dvo1X>D^R9A>4%EP@ zUN%m?As@zqJ1Wp7!5kmeN$@u#5+VKu7J!-^sI4wZ+<9E5nS^X|fFQL{4VZ=8$FE&$ z%-1;mp^ebfvIIPj+(OYzMvkEpqpg8F6K>n7sNkYspq_|i^vBRw&sX-#M7;P`%nFG! zo=ul)*$56hU4|+V;0S1bsSJ58*!Ys&Jfb6i%rD zS}=}f7GPE~>JDbx)^wlBp(?7gx6|NDu6ANZ*{+nNeM}~Y+q2=%9*k&mQGVsd|K#M% zb``P7oM31VlUx^_GnprW>sb&^^v&_&gG3a? z41EWrPF^2a00DpHs=LgBo2I0f=5-B%{6Gj);LTHWyyIi>4IvW4cHp$}>Lk7-&5cv; z&GwQF@f-kbi)%%zmC%`6^5d*!$?0M%PKlOtQGzJ(Ri32huc$sQXPiE5SKXX%9gxt> z&FyymRTct8ePue|h&G)BT$U2oXG@1nj70H4MN5`P-BrS;ZCdG;s;Ra3MMLdZ+jVFx z{W*S`s)I$&+R6;)$x62?TY%KEf=Zq~@wPz-k3~&}>M3&&mmTxSReFG!R+ zO0JLwGyPRiC9 zchDSUaEZu;A&*c!h06)50KS@)NIOiD1t*N*I%qte!n8gqzy=evr)(w3c{=xCr%_SV zTBir6oCKG1ue&XwqG{_9LsBsLw~@Z%+70@)w5R4j58E>dzCYRc(mjbwikTab=`1#I zW}nL=VB^u(Dok0>?M0?P4x`(vwinBPxq3MX5~4DTknV}uAy!tzyoh&3VV78z3y4{N zMZj!3!@-m5UviM}B$zbPh(W~u_UaMELh||c%U_=?hvT3<@&oAjn7vc z67Bk6vkNj*S|oxeNbJkDcyR)lN52*xO|Zi?EhJMqsmcPN*4%zE8Ei)rAlwKzRs3*8 zjU@7IZcYeCsZK$9h`i6ld2bN3vE({uC(7dORV!sI7R1sgLK^##>qpmq&7$4?vv3?% zMsFmJ7}@c#575T+Xh-jPqIcVmZ)JEe5m4D{r}M-sGG$MUbpwS@0tg`u`yWCdFAs{> zQ7?SE@=~u|WDkVmcSX-m`jorxQK5OJ*`yh>die^cQu+{tlt=M=VdyPjsxVx0(1PWD zHVsT^qT-f``kWE2V&>hVpYyr=_Qjh{Pd+OBSzZ1Z)(>BTQ!M1zK~rbHy=}ms!0SwF z%QSi`9IzZ3n0MnqK}viC@<|_VM}p;gq;BG%M~D1m5tz@6nNL%*tM0G#DAIqdM(R>vnISjJU*S-RMuAYqMLqhf2N;A*N9a^WvjD05bcF*WAT zt0lW;qYy1kK&kcZWo?8q3M)E70Smj7wQA+lPLQ*@k7Z@N*2?k1Dk2hf|F>rg3WZ;P zdK=nuG@B%;hY9Py{K|eg{YtI}xb;m{ey`~TeuY#$jm^>^nlOV2Ax^^dnJk2Nq=n@s z=f`^@7K$%Fo`a$U-I<0+;F$=qC(>!VmAu)n_+LaU>6vFto9LHzDSA>_Dn$V~gsFS+ zg2P|`%p4pinoxteLQ*8S<_|mMDeW&3Ez<(S^t^1o47Brs8QnkKsf)@TJvAB+KGw=* zy%%1|OU<#do354Un>_3D$Kvd_=zPckqudmv{&&_~bAm#XRov=a;@paRvJ6j1ka>Ad5EYl54{!yo9NGkLpZBmDYi7{hq0 zD=v2r#kcFNAGHU*{;Jyh-Ib{Z-7RY|-?^2iEy|@l!rW&=#m*0g`t^a(N79GV0<-qY z+eChCU9!iXlefGAFA`p?`t&SC>l`ClhhSpl1xC0%Y()R@&NsCkh6;UA`*Ug#=W8H6;XG1NxNH?6V24B36jJ`I8$aUuR^3|zX_6U9FI-Y8SI7a?@ zb@Vxv;WBYg9={Hj`?XXOO#Tmjwsx{giTHkqOSr z%1}K#eslrW3)6QMl(6=IPx{Y|9{7eb-aaVbID{rYT;b%1P7 z>HB4fq~C`kVMlaitf%A_DNA$Aq5!fWfDbqdQH;5+Lh#0?imeh-8)9gzoLf@9EzQuq z8R+vb6jEYu(--XPmI!KlJ0WA8K4!Y@>YrOADiCKP*K*sKYre>0*6cBpxp|z`iA;sH zV~e7z_-!VdJ! zIT+pVxP?)_dK!HwK(s8V#7dh(ly{=HDN^TD`e){|mi5tI$?;@HhYYf`8ShwPLW*)* ziu$F+?d`g!Sq?v0^%Mwahh|n}p9VrPSfc7_(6e>R0Kn|3#~9l+ddAeC)4~WYWJl#7 zgP>wUltwE?_9-lvt%%w$L%P>vXyFlz4uk9V>W)!#@%D3J&qo1QY)S$AB0M2-m(C;qfzr zm_bma3O=p}e~=mfF3yKQA-#0gnm|K*P|aW_5B{J*_p=EoCt7i(oUfb@1LuUR{a@bE z#f6l2DSk_20HzWBr^ojZDry7}p;D7%YkZ*VRrsH%#{U`dVi+`*?Ei5=hjQ8g464%) zXde*EeqRdJCk*iXe|kXwUziJq!GL}aH`3o0zkCFoXVb^OQ~vM3{td-#juvqa+J7VW z!1m=P-Ai(-em+?s{=F9*6Nm`C^X@CKpF5<+A`y7}jWTVPC0*Mjf9S3Bu9?3~p~L`g ztkJeOB`afI^|k(wZAN(W7nNp{dkWxV2>(I-XagXyjbdpJ>VT#!UWdCYkJH|} z+CBW+Q{B5WyLFG_y8+UU$KG=(035gD*rak9UZ7F0?kxXwfhEe~^M1V!LqoxpE@PDY z$(3$r&+h*93kLvHB<#>9=_Xfreoxq((dKBwj0B@Yrvz>LXCX>*mEJ z;M5569!o!O^4T@AR-hWf6bP*AzB*&{Y%VR%`(iUX?{&-v_PV}U_rTHpyW4#;VTRY- z$PjeseHA4KG8j-@s~G?i@+n?s3w+Y9&V_NqT5Uww@Lv%(1+ksbYVigN|0CzXh1f@uKEC%B=@UThOXNuId(f4C+=svWa+)BtElnAOG4pSbGEpjq6B zY*BfOD^b`LN^x~`JL%cWr!o6{>!9#L$n(Zc3oAR+5G>H1wQ94mqBhO)a7%ku07{1H zj!)f1Y(WRY_r3klZv{z|fG$gX*I2jES#$o5u{`K09%U$05L@^D%+6`~h2Tn=93oQH zk)&L$OOj$Nc7fT(t1qHlrm~bm6pTogep`BaMd88%ue8&k#dJg!AQT#mB1aI|)k;!XV8bWq^_ zntUyqqGX+=Scn=XxhDBDJ8@N=`X$pM)R@_80U^d!Xr(??++9|Q&Fl-mG))ZKLW?n5 z)^|D9*l#O3B`l3Sd%=DAmjmc;^(M%zOpuvb@n&jB9K5FRL0=#olt%JUnFge6;2i6V z(%7z8^Zz!|;Ma3|klT)tt?%scElv_s?NIM^(IZZpDcXWJG4t3B_3l+m>)0rB+s<7t zModfRXK~A$Ja#BQ?O#RMc7fOxy}b6Th@2*at_rg#3ciVNO2yZ*O4#la7;UrEIf`An zboFnMePiiU$*{R|(sxpK%lsa`YS%7~@7%Ol1M!Lwnf>RmtETgJ+!TYjx)XTl_xB6OQi%F~=uvxko$qs)j(pH?gzMHk*kwuTW$BXe_5AgyhB`7KX`#5?y~ z^__2cpX&FRm_^lY#OY~)qYgE4%jeMXJ|XGE612>@bzJ|;FmyJr-niYlT|bC9QBnf6 zh*4(B*mV6U4C(CpRPa-2NTVx4%Ef%tLCG>Ws^<}MPRb=l%Y(NhjW9eYPe8;V$a+8<`j)3NFKN5W6Z zYu>JF4V&)Q*zAEPs;YoTV)#G}bJH?q6XEAX1|i2y9pS5!#SwE>a%*{H0}4he+=J(FwGW)c*S0;yh5=~$Z+GTiwuCzuy;dQ7kB9fJqUAi2d(3bn$Rtxd%&&W` zYZkEFY~|j~AZmNGO0=NF#!1B<3W{=&zlT<_1%OZc^^Z47xL~J4ED@6kC9$ z^tj)bV2x0rTbnbspcbmCzGfu9ce{_SbdQad?V1z(LuBVElKsfM0#@o+Lzqp$Q8tn}SsNI@u zXRTX#>MU*7h@%OeEH313gY?GP8KC(meK8IXISYRZ3qAHGw!SV}NlyzWh0j~DI`M}* zTkU|_F6^;J-W=a(BX8{{FcZ829#2{?=-T?}VvFNOaOVq;~F1dEH}jd3lh#fxS6NW({l* zs+`5#K<0>^BJAqAMJS2w^6OV}!zj8PmQL+k7o`+)$*QWejjUIxJAB?~=E3JDQA~kQ zuh|?cU%r!VkCrGFz)XgTmTTyGEE(2hYdLH?|NLlI;>|r*)y)j&>>`fYPLRj;Oy20s zrr`<1q4R}$EQb)v(5$lF#q5}`!)FK2n{|z4LW?t>6L{T7wwZ#Iu&yl7Xle2S^ga>c z2{oORG#3jt-mRvPuesM~aK4MGZOTmI$6%v; zNs13R^c@Q0b8FMnLgetGuC}#Z#!c#)EBV7-jmrF)YU9!YeG|p4{5|F<|4MqDZu(oN7n@Amc5DZ?fTi(Jh>QP!Yj0r zUhNPALu2~|dsM)&TEc6CT)B4<#@Uez0EseT35&_w)ckw9-;2G*XN{$G!Ac((3a=@0WArs2>exduIVDO)$*-41rpGa!!qdY%N<`J0dZ*I)Qs8p-3IOsY`cGxZBtL_Q^iU@0(1Hs)`pzm@GN;yo=77q$DaEKuN>eZ3*|QvOIuuZRmn6z(rI-C{@PI2%OQ9!RF%$Js#W!b*>`9~PLC;smu z2-?yt=NsLw<|d@GCYo4g$laej+$cbmCU3lor(rWjyC+ni--qVkmlPh-94v*=A5<@3 zWx+Ot=AIw-4{x7e+vlBJxzF(70%KymI|JZc>~bPTb4N@12L&G+2 zP=+T!1y3{r5kB7XiSjrzD;doT{N6A$MW_bOdFIa8xy_%08!5^LqV>cJB zcYC{s2=M=16_$V`+xc!H?Ro>?kG}$$9A5iKqIY)ut20^Q^M!h^5i6OAqf7!m?^}@! zrQ9>XWcL`HJ}mda6UW0?ZLq*`#_)EE)mUt#1$ek$UWfHYGTQfLah5~3@^8Vto{Nmp z{%nr;p_*m_*`zMkeAx!Th==pks;Ap4YH-JfD_objoOZUfNK!P~(>hWeUp7QH=$c|| zd=1-b3@hG(#fnt{*Au-x4@5LfIQ>|QuRT6JIVDq2)>lEsFxJMyFcz%K|6BqG-ZPbN zx*BIR!8>D-sz_tx1Ctc!o@gqxc~)oXqI3zwi!)inAE&OI&#E*#vEhS@T*OH{(G``Q zyXTZ2-5%Q_)ag*EnOVTizwN}Daw*P4xeY_v3i-Ux2TjUJqe;rQ{PIr8$=nm zj@iT#h0sVXu)mLnN61{YUv`7ac6 zWd#^VO35~^sg7lSDw@l;mc`p@`H6_2Y%3)cnBfa8f&M)4VQl75{g%Yl<#^GI%+r&n zqL{z%%TN=u8_#k0YE?EV#Z8n_nRyg*zf?$!r4?M|uNO5Bt zl*hGQXo()H+YiDoR41*lV3w8%u^fDTj^>67q{MIv465z%qAi!X{I_yq8hOqaKeLLa zEhwE?u283!BGYx%=A!q&7GQ}&=dv;{eglq^6C=pER5x8?u@N$1P71Mn#jcqEu4HYb z_1jmgquJv)7aU92?}Djb;N?p&$C0$1uF9d$5$}Ey|Gp?*D}+0;AN{r{;}q?4f#p$< zS)WvR!G#enyk}TZy^WBVkddlFT@~2X@Db5Gs)M6;*V>F$N2Pe6XagG8*sNh|J36uR zBHk>@KA`1Q-4@q56-}UX>#u|%f7HR*$=q%`&o*hAK{Lth=H(8E!J6%|!h!N47lYI9 zdFO%#lXTO_hEC5&UvIV<1)|moZH4k7g-DPWruY$rw01QL%7KS*3T+#<{KDE&g2t`K z#)jwP-Ad1t5<3UOiQt;VhQKw!jr$W^YnRcev|&QboXvbUqxvrNDxD7WD#|qs4?ECh z;_wySv-Si&;K*SfqCl#%*ULK54yHnynQB+nv_Ggu6`l}g^dSf&9(H|rk-Kr-qF=Tc zO^;@{yQLVVb8aLZOc# z+6S1)-bM!`PN(rqb$37r1h zB>)e0YFL-18&i5!PA zkGYHgnoEPBCTAX}$@M$%sE$f3%jY!WZj0sj^!S`KUiNc^JJn1(cl#T5KnAbc~mRv=L0|_CDM5t;1!p;Sql@U*xlf7%IjI_U6G}3+eEBktan8 znhkwff(b{3(A>lLTZTH%@GHo%!29ipciMiY(n!&Q`Zxpx(^Kb0NZm_oavmIa|+8X!pE!ENpSb%8#UQ- zL%%ue)t7KE#-H8WSPuQs9n$OEs>35e2sg~m9)YYyYaeLZ@QYZx#g`=dGERvyAK$1ekc|)vq;ppnq#pMvFk*%~& zM=~E3@AnGVnH?2nOd|%h-7zs^bgPTgj0w_#$UZi`C&|Mmth@1Qp+41*o{S3w(DJO#C*JanqGP)Ko_elS3s@z` zDU@$YzI^$!ei-%K(pm;WH*)fel3bw(#jl;I2`h_=B)3N09?h8;==p^i)|ZW>eY8Q~ zU;!)&wua#FDitgjlol@7^2~NFYFWAk@*bu~)7-!oX zW!$-|Qa;U0sIM%`TcoB<}*&^R!+_fyUU5g>A(HqDge(5%cv*GEK6sX zqMi$UX};Msh_BArYbC_kT`_5e+Uxm z-75tcT?q6`m>2{FU`0J!H{?4)l z@RxrS6$6} z;8K!ceU^VpjjZOa^GTdbo}$@R%OmYTM8?W*zk>t-2l<=uNs<&&qcV9B@^E>uGG%+G zrqFyZes6NVaqZXjP@(O_`Ja0J$vy2^g^K`Z=RuYf@>DKSJa)}z_0~m@iA~9#yKM?b zF}J00aqL1a&reZUBew0ATm6}tROJ5TRl6#m-~0v~R-$;}fzabk3#-NaP(;Tx8QVsr{|N zVA4$&CK@rE?Z&D4W^fKI7!8YzU&NFc-F_V%-A)C-_9rGk0JBYWAe{b!_P-qeYrp%b*(^mt1q<(;o%v}uw3bWLQEj?r^dg>6$9H- z4{B%6ZdXFM<6RA|x2;o_%XKf9Exu)tB9fc3?C_sq$cPgoQ8%~+OOWqw#z3)jf4#~Y z;#0{o4zw&7O7-&p#s}Px;nl3eNKhlchz;AQ&|UIx4z|Ytq(gZ(C(p6$)Wc{c3~GSM zjLaS_nmh-o<`FH=m~rJM{*RPkAOtP9X?w2LQ#EGtzlIcm=S|jqoxVoiS9ov9@AKRf z_}z+re2wdrzNjR|%+LBOQy@T^{dr&bZ@v+TUEhG?NnGCsA^$6SwfX$JoPQdApB)c+ zEI7^oj*M~j_qRa9mdl%~>X-x~JNQ(8Cny8D7;GOL`=9FW>0#%qmrzBY<~D$yCHnH@ zplF~(N51E&CZP2j2lar~BmL_`y8O}k`SX2FG{+6_L`U0y`gp_SZprNoUV0n=5X}g3 z3GPC)%4PtG`l+>kfm<(}@1#K2#03*>rYOB|gI;tR`hE$Rg1#k}^g!g;`R4NU4OoEd zUN-5{q{`q+d5@#wC~4{iJ!qOHo*U9n@|%;++1Fj1FyQUByQT&kmoTcjW0&PU(&+T= zM_D`Zq#YkaM7O6Tm|H7#BX9Jkz0}@u;p1Y8nRB4@2jFVuPwNqVSVm@K5as+hTOLzV zSMU@o>zy)FCKzjrY#Lo+vH(0J?r3g`#e{d&dG2u0!OR+l6K3a^d+ipR$4AQ&x1PAb z-?U#NW=}6-BrwV+J*Cc0nve1PV^EijiZooOn{~2A`POdijqb^1BZ+0V*ezuI{SUJ3 zkh$Gnw-9-LCV3&j!IYi=VK3JHTc&N@+mrFc_t zi{t~{Tkn>L!g2Du%N#a>vRwZJ5Vx1tLFhDnQvur5`?yr5;L~$=N#( z^?Av-IYvg?-F>ceyVqH!rpo{h$n0#PX(l0;lf*qP&5?ClJwHaeu-y*ReuQvxvW`+qP3ZV7IrA)B1-q(Q93vk8S zVoRgeQ+h`R6pd91b0Nm#bfa!|beylKtglMK=ql};pG&|US5|^MY3nw-c^fPPQi#b@ zj=Hl1R0w0KL&Q{F@k!AXI1p4-@(UY1R$Tcx5I>I3k?p}m$seLEZNP)~Fy<&48>qxc zEZY-7Nu9e~RuQ3xU2mnzWrOX1PR`XnyfH0sA*N6tSa?OzZMtDjQ)881v#R8t|IS?^ zzPzj3-gyZ=;vbH!;Ep2Nb%BNO1N~Cyu^s>CCky1#@5S6)Mr=*mPGdGDqNdL1IZ3fJ z9A;oyK!!*8yv@LkpISsXpkJk>AWUtNG%gL%#sf`lIk@mBrnXDzv!PlWH~9fH%SP69 zi|ZBA#9YCH+Y2!Gs9x(84-c?_b-vQr_`cMM8(Q?TnaPPMe<^B<{UZLM;F5*N7Wh&t zA?rwvMv6N6LEfOA%SxCaI`VF}$rat6(ze^|t=M=rgNLF&&wLNFnm}NJWI|?i#5AR1 zd??m4);6@UWeg0hVwqd|Nis~I2w7s;Ha7{=G{(9=-KNZmf2c;25djBQxFFL4wj>XR3)K(FAImj@En9m^|)A+bl~o5$ni4ThQ_7#U6OpE-WT!=%pC%zPbS zrWCI9OEq7EpQv`8}TOQJKjZX?Z?Puu@~TXJ=fk;-kPMgo!6FtRPW*Tq89C8*-A;Szxsy;HwhM>V4=e9 zk3_S|GrLw|!Eeiuhl9~g928k)s*9E(PrI$^mZ^KGD6RA7Kn@{~a+DP@&<|cChdPx{ z@fru%_!YU#zgTXYu92*O!7l0iq*a|g!AGBLM?LgGITjcP-t`R3>cm>V1L*7KoAyhZ#%bAuz#84jIa*lWsYZrh7ci9Gdz z>T-5}v9V{ihcIp^{0v_DvehV;Vec}aeB6w(7@DOJKbP%gm((->_)i-uQMG{Yk2ep z9D(Wdu#KrUrtQmw8DAlF^NrCNeYqy@{7No{KQYQbT7-Zoubf2|k~`d90h7EjKsmDlUA^gJNo_ zfc%-mmbFx<<__yX`v!KU5NVj5PyH+ALH#gLw?6R&#<^vd|HmKNaMaW0cpST&zVfOp znW2Z{)F*fu0#rWjuM6$p_P{m;sOqSUC~-*YXd`T#$@pnl($$J9g)?Wv6ctB4ofTtA zszdampFdSS%rE54f)0?Ho@Vd}Y`6%JEydbr5uLtbH)-_TwgmBH-HvO*#kY)}TZTJ3 zJ+s!8u3r+I^Xo7rKz8fbpR>yq^!vqmWQf0JecesmB z7q*OViz>6L^qxq%dVP_jo|y+p+@X!aGHtsY1#=ie+^1am3SO;gUoNnnd=vZ?8}@${ z_LTuqbzR$1(nCl{42^Vy$j}VZEhs1*D_(%>K=;n1DZ(%l`>g2a&062f~1 zy?yTI`F?!!Z|3aTXYIB3TI*WZ-e;YjaJV?NN#1}0eC~Pqoc$ao*Jobqg-lSh>_dr`NO`Q zq+)%eq!E(uhESYLa*do>buz+L!H@Wtv$#Duk1A*TFf!sbrocMexGlX1ws_!4%x~8| zq-{GA%vLUfcUj$Wl+E~<`@f15eS&(Xr+2hB<;F$kd@iRiYjNU2L5MaE{H zeveBEMLT0D=&lNv#&9j$dm{O;`!N)wv&JW@e*hLGH! z1Q5kKmD#(Bkxayk-75X+6*RggphIH9@kEN84+*n$bjP37bb#UXp;nF}CvuIfxuBb$ zW_=Oq{f#f3ND%!;sMq-IpI+O9 zM*_&HjDBYRMP%&aLiMx2FX?_04>4!V?k=3$Vv~;>qJbCsp~wWRta9wChTy+KR5vyP z39T5emMy-6FQxx}(cf_ana_Gy0f`tnFbslw13;@-Ka>uuztNr`SePh{W>g6da?lW3 zr2yV6DQ6H_+>TlH-5m1drjkgNHyCoqr7}fY5_T5U@uKcgV%z05xA3jg{S^sm6Hdjw845 z-LAJEV=8W5De~_ac;G1)H36XVxl@zZcy}%(q+~R&OP}emJ?*KJw@iA1fI5kgRQmxh zBo05R+G!_uJ15(hZ>A;Gcuz~m;VmnlHDEV9CmSEO zw&fPHt75N5AZF)6>7=FdrqoxPUx%>`4Jz=8nQ`+ER`!YAaY3J-TBb~nwOm|S z>T%6L>FF(6Thd*uH?>d#+CyZuz-h_#zK?_&2zUXoPdY?Ig&Gw1B?248G+Z`SI;||b zLotXgehM6dVOa)BXjlOv-Un?DnEEX#w=5`gq*gF)yv~r=%*vhN5E0Q zsmVSjE2)FD9UsPrdsfS<%dgl;OfQ|^HJ%78AUXtzT9;e57(%UFR3_moo3#hcWC{az zl149s$Kh*g!alKgqsJaUPLy6ex`slc)kOO0?fMn^+OG_|hGGJQ~qKL&J(T{ta!uFA*h4S?n^_H zQAy^e=9q}_LeN|e*w{Gn89L}re#rUiBi0fuq9Ec_i z2Uz%v_&ivvvOVA4O0w_Xp>KdlNvYb~tHajDE-o&p2#LA|+J$C=K5EUhznn3^V9O6@ zgRl*uagMgC_rrn|YhypO8whi0f^}N+UcrYvyu?eQN42MWgH8Lp?&miBM-@*L>_AH+ z?wkg+KnEHdgI=P7HAlr`rz&X#z0tt(%O}i)D&4C-pFgaoh%AN(XF#N}uaq3%cUM>PY!a;JOvWoZCRI^sGsU2b|B?Atk&S}KfJ>s`_?>nI)0 z*kz_<_rpXIZ;H)8{y!9xxqf^6P0R!wCWU=B9;)IgifhC!3>LoM zI1Z=9|D%Ik&=9Gz?pB;$q#&3$QTAXYRK*LET(GIqLn4h9@Z8wXx>^zrYIJqsN_N5` zz0B;pPow#Xq)C){88WD&6x}F7;hyG`&NpgiVV#`*znx_9tvWmXQDmC6nX%acNArU^ zRHqsl8H%J`hA9sk5Dw2Zk8#xmLI)e*&BxOx!fYU-FdyQd{Uoqse<`DDPEmC!T{QTiU9yAwlCSrs6XVt{Otg%t}QkB(pvs=|^?$y>KmhTo1k@frM zYp}IqQ8o=h8=JDdwaCtPsFKIR=MUG8twyoYsC?3pnj1BEOS=}wTxtfTCrEE+KMcI> zBG8AR9ybX;>5B-qXDW1V$U!kWb6C^?c|CO^TJ16LlE%j8d>GpU+4zF${DQ?L{QAa> zEaBI8nSySXtA<;Ub#2D7mhL;D45_CmqAq#^;y?vl)TKZbL$N=@T!-k>0mI<>k5+-0 zAqvDrC3N`sv(CHY*9Tkb>ZGy5oPkJ)Rz12A)m7Z?yWn|QK(c%QWE#wK!*rqO7U(&~ z0oGK>m2mbe6Q5G%tbO{G^^hC!zEx9q9$bY#OB29`XbBV1>B_T9gMhmGwh;q!)(HgP z;FRk?vO@GnEgJC9Og&d0>xb~d%7-K;^VYUAHKbQqFBr(l&@%qqGPvd;G#;`J`3#)g zV#pZ`bJNQmW%>;$fNn@^hu@lu2ChRCXR7uy6Vv0)L&h{Q=Ne>~OxpbZiJ$opfvlOq zvj6>^xzQF-uzeJ$&Nm}Lj%-@9XC0gptC(q91-zTqnn)O5pTXMg?~QP|(x z1CuLAl(urE41ts^FE6h!BaVP8a4iIAV)55K8*4@0XF|;uL5BIagxm|f7cL4(e_R}5 zpt!I1S^%{^ZUgv;`JeuP5=xdY{myC?8qX$h)AMc$qU()JT|0h2<~~KME2=rrad!4- zsUwJQrCPEs?6HB)ePEEl$^7x_XrM7N9;EOb0<&}TcK_L4((>+gOIXSE3aw=a!B^}Z zlyXLtSkHiRO@?#}7u=ZIk5~yZx~f<4`UG7EnZ@&TDdo}EyRfEp`fVgb+DJ>{+VDb{ zosvSgim>lG>rdT;R-;w2w`5yMj$z`c^ zOI?%^VE~L@iUoS5!+&+5KH^LsW1>-2=TwX9J>%kS;VDJ2F(}kA7diQoqf&S< zhm>FWV>Z8jHe6yx@d^TkQk3edBaaQg+1M(^iw;%2#crz>2T{&RyH!9AVlPip_KR2y zMwwR_z4y4Z*czJwTZsM^0fCl1cNb(ena5d@t_cm5uQ~i1b4tO zm;NA9_LK+v8Q>#=n;{1nTp+ONPSB>eCdbT57+gO|xENC&ZnwR;IfIY|Lbc;UIp9kl zkX21Z&oEdfUD8*Pf)!Z%czOA*KmFrL1V1?K&~0B}9XIuTBw?8SzT01*EU^4#Ju(!& zxZBs8K*lpjIGmkS>t;6X-kFX4&#L-}X&+GIW3-&2{bh`F0)N{j)jAh~Zz0Dp48TG#Al>YcJ`9zJ({#I$#uhg^@+->T{ODS@>TW>T}mMxNIp)jTYT5@D~n zYgr%!eix5lFE+^hh*3CrU#tTwsp!c_lkKYA-1{0R6xqEwO*g}gAwse#&S(OB~Ej_hgtuUQ}v7{3~ zH0^rZK0i9QBCpNXxy{#oaoc#~e7qxFecbA^gwv&AgD6vhGtBzRL$h%`*N0f8wd$5^ zZW8)WB(y}-Q`ecF{2RQFWCpD)zs{ed4|PkL{^Y26A8yS=A>Wd=MvFNV(Gb>gP?8A^ zK${M=_>N_(^UktQQnXjyeuDmTTLFituqR9HjUZ}T_b7%Psjp3wU4pq-Mdg0~4eBu= zY?gGtVr;%i;FduUyhL5}iCV2)_EdxO1qVk!AO_+wQA@Uj!$S%0)2@zX7fvjxm%*W+ zx<$q=35i)!)o+Xg5)x1GyVi8pS7#aan+KW-C8cTXt9|O8_f#+Kx^E!FIP##d<8k+A z_W(2qI84p#j-69_dWLoZ^4W2-&!*w$rTymTN<-%BBEqc=jqjUbz*Avqw??7xZmcd3 z?*s-zO5ER>a$Y{kxB2xtH72XoYxSRon0Qt(>XBcW1b}Y~!G0PsSvin{n_g5}D-r%5 z{v_>VFzYiL$NFS!vth%2Blr)#zBU_ep>ZAfeeBm<9 zwCHLRIta#lIK*||X%Rm-JAkLGv9nX%;hPLF&IO(9hgc0h(s{ui!jXROg@2*?`lp>L z2I|#R+kpU<`2IQGmbvrLa*nCn(+uUGc+>Q&1<%I}@&E$E=y#&;2!ec;Cdk35#ZU}- z4BlHaj&1g_zlr^^e>%OmhQJPD+ym{{ZPZj?9}Z832GV&>X<>h%p<>nK`DBGj0IK3U zN}S>RVTDr&*9JiaT=>2TyI3!@W}K?92{TsRju~lmQ5D;78i@*mAC6rf zJ^7wy#Aza>kGhT8C7ZbM?9O++oj0&Sub`(szX*$@p>B%4%2?vh-!~|aUw`trt1VLU zsYdknZJtO)sCei{IeqRMMUsl+ShP9`79st z9a628{?|ti<@>Rz7Ef zwv2M+Q%`S}9Uv?i8^+}6&$@Kpu|=EO0ypmqdg#D(xDqQwbTzk2On3~jL<>PGl}JPO zekI#FYxei{94<=`rTa-ylH_93igtbNZ?&yWrh|zm?Q=3be)U!sdkLAN<(SYj!faO} zB{mvzb`I{2IoH+u3XU3~oYgEOPc^F7SZY(eJL4AUu;|g`I^amA98RSb82IkN!`@|7 z~p8d4f?@M`Q6;LV;fyvh8;pzQtwrE~gN*;D>psHgVnG__+%IUFaNJY(hFMw_L$ z=GJG>(Bp`UQ=f(%_qCg`ANzZB$39Ifanj1Kr)uGLD88TN(a)jmMk$QLL(8rMITKZ3 zv+?{8_>P-m!Q7iQ10iquhxn2Ryw3@&N%y~9dvKmTW^Kzd-wc0}`*A4G85Wd4HL!)l z_Bu(ff{W<82x?nZAaVU`*9mWI7SxeYOKvxviZckGlX5mND%j^KOdM?n)49@-ztI^Amj?M%E9=kJwP(!LD`E+MxJg-cKJo7J5=oXi`^Q z%DZ-#O=Iijw{w==IghA@t~Yj$^^Y)f$Kb?wdiu5Evi0n2zEu2iH>PU?GzuQ`lxj`S zYeIn928{|t*+bwq1PaDFqH!Gs-(QsUnai{HI;cWgk(=(>1)4T$aD^m^jiW@ypRZ&~ zswk+6@@~BpX`AtoNcD^n20s)BGLe2`czU5$3$cO=C(8Ia4~-Jv%<;4^nP8cj7U(Cv zy!J-EJY2G@RV5XAsRB1&R8z8J5g{XzRqP9ty&s#E+Ll8EfTpC3%^wW>?1{9;D5G64 zO(nOfIYp->7OyZ4Jy_TA4nKkwwMvq$|GA;aOd`sM9?4NADr{q@NDRX}V;6ypGB4wm z%LR~Orz!4YOKG;Xjl4(hzYbQ;LwI*~p46;m+cJBaW5lLI69vmnM{)M0R)+?G*o-w= zG}Jhcu!u{D9hnx+WhH^Rs5x_n)EiGxm=vhRg9_+?d>?RqpSBKXq9!J~d9p!mc}m6A`n*jt(}#fTE3=t-Zkb@rqVQ*PdwQxe1LbRH40Tv=c|ochuO)oaPI5TQ$?bGn@pFI0 z2|aa#VVJq+Hio7gbe-XhVd`9{JTkJhKGZI$-3U3QXy=BE9?rB>#vm%YNNvU0^4&qOm_^l9%3Q6mvcrN;Tt|0bk~M6Qc|DuMKBDA@AOgd* z(cEfs86`nWZ+n;Pk(BZQ%6Ks?nT}|e0VE6DWXu4bZFg@SQ-~%^FWX6_RI>De4z)Ln zx0=`Jd|G}@af1YRCbV>$cDLeE0Z!#T%<=wlWYDNM#*AfQ8~?C~uoV~We=^g7aV@f*O4H#=u3F)gC^60l#|NMW6<2u9B_?<~ci6)_M(L_l~TbUiXY5_XB4IRB(Ens{wW+(O}njXi6kD zru)Skr_#eKHVc#R0TKw^+_v9UxgGAhto0U8-6Q(zrYs@)m{)MlNeB!aqq*WD{|7d1 zT>oDvnTNP>#l(gtpjlxEqFG9nArpFHxWxq=#`z;=6D%A13O)iTGyUIeode}7uS2>1 zehhE8vj@I4QDVe%NBrLDp*BQQM{~el7JA#qdFwkZP;r*#4_OCb?9gYA zA!tkru>M3X)_DIRBd@j-h%rpj+ek{9SB&_7xRNVze^XapF literal 0 HcmV?d00001 diff --git a/innerkits/BUILD.gn b/innerkits/BUILD.gn new file mode 100644 index 000000000..72b56403e --- /dev/null +++ b/innerkits/BUILD.gn @@ -0,0 +1,89 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") + +ANS_STANDARD_INNERKITS_CORE_PATH = "${innerkits_path}/core" +ANS_STANDARD_INNERKITS_BASE_PATH = "${innerkits_path}/base" + +group("innerkits_target") { + deps = [ ":ans_innerkits" ] +} + +config("private_config") { + include_dirs = [ "//utils/system/safwk/native/include" ] +} + +config("public_ans_innerkits_config") { + include_dirs = [ + "${ANS_STANDARD_INNERKITS_CORE_PATH}/include", + "${ANS_STANDARD_INNERKITS_BASE_PATH}/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "${kits_path}/native/include", + "//utils/native/base/include", + ] +} + +ohos_shared_library("ans_innerkits") { + sources = [ + "${ANS_STANDARD_INNERKITS_BASE_PATH}/src/ans_log_wrapper.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_death_recipient.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_proxy.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_manager_stub.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_notification.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_subscriber_proxy.cpp", + "${ANS_STANDARD_INNERKITS_CORE_PATH}/src/ans_subscriber_stub.cpp", + "${kits_path}/native/src/message_user.cpp", + "${kits_path}/native/src/notification.cpp", + "${kits_path}/native/src/notification_action_button.cpp", + "${kits_path}/native/src/notification_basic_content.cpp", + "${kits_path}/native/src/notification_constant.cpp", + "${kits_path}/native/src/notification_content.cpp", + "${kits_path}/native/src/notification_conversational_content.cpp", + "${kits_path}/native/src/notification_conversational_message.cpp", + "${kits_path}/native/src/notification_helper.cpp", + "${kits_path}/native/src/notification_long_text_content.cpp", + "${kits_path}/native/src/notification_media_content.cpp", + "${kits_path}/native/src/notification_multiline_content.cpp", + "${kits_path}/native/src/notification_normal_content.cpp", + "${kits_path}/native/src/notification_picture_content.cpp", + "${kits_path}/native/src/notification_request.cpp", + "${kits_path}/native/src/notification_slot.cpp", + "${kits_path}/native/src/notification_slot_group.cpp", + "${kits_path}/native/src/notification_sorting.cpp", + "${kits_path}/native/src/notification_sorting_map.cpp", + "${kits_path}/native/src/notification_subscribe_info.cpp", + "${kits_path}/native/src/notification_subscriber.cpp", + "${kits_path}/native/src/notification_user_input.cpp", + ] + + configs = [ ":private_config" ] + + public_configs = [ ":public_ans_innerkits_config" ] + + deps = [ + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_L2:samgr_proxy", + ] + + part_name = "ans_standard" + subsystem_name = "notification" +} diff --git a/innerkits/base/include/ans_const_define.h b/innerkits/base/include/ans_const_define.h new file mode 100644 index 000000000..016adbf38 --- /dev/null +++ b/innerkits/base/include/ans_const_define.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H + +namespace OHOS { +namespace Notification { + +// Max active notification number +constexpr uint32_t MAX_ACTIVE_NUM = 1024 * 1024; +constexpr uint32_t MAX_SLOT_NUM = 5; +constexpr uint32_t MAX_SLOT_GROUP_NUM = 4; +constexpr int32_t ANS_UID = 1000; +constexpr int32_t ANS_GID = 1000; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H \ No newline at end of file diff --git a/innerkits/base/include/ans_inner_errors.h b/innerkits/base/include/ans_inner_errors.h new file mode 100644 index 000000000..1a43e7103 --- /dev/null +++ b/innerkits/base/include/ans_inner_errors.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_INNER_ERRORS_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_INNER_ERRORS_H + +#include "errors.h" + +namespace OHOS { +namespace Notification { +/** + * ErrCode layout + * + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * | Bit |31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|09|08|07|06|05|04|03|02|01|00| + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * |Field|Reserved| Subsystem | Module | Code | + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + +constexpr uint32_t EVENT_SUB_MODULE_OFFSET = 8; // sub-module offset value + +// ANS's module const defined. +enum AnsModule : uint32_t { + ANS_MODULE_COMMON = 0x00, +}; + +// Offset of common event sub-system's errcode base. +constexpr ErrCode ANS_COMMON_ERR_OFFSET = ErrCodeOffset(SUBSYS_NOTIFICATION, ANS_MODULE_COMMON); + +// Error code defined. +enum ErrorCode : uint32_t { + ERR_ANS_SERVICE_NOT_READY = ANS_COMMON_ERR_OFFSET + 1, + ERR_ANS_SERVICE_NOT_CONNECTED, + ERR_ANS_INVALID_PARAM, + ERR_ANS_INVALID_UID, + ERR_ANS_INVALID_PID, + ERR_ANS_NOT_ALLOWED, + ERR_ANS_PARCELABLE_FAILED, + ERR_ANS_TRANSACT_FAILED, + ERR_ANS_REMOTE_DEAD, + ERR_ANS_NO_MEMORY, + ERR_ANS_TASK_ERR, + ERR_ANS_NON_SYSTEM_APP, + ERR_ANS_NOTIFICATION_NOT_EXISTS, + ERR_ANS_NOTIFICATION_IS_UNREMOVABLE, + + ERR_ANS_PREFERENCES_FILE_IS_NULL, + ERR_ANS_PREFERENCES_FILE_DOES_NOT_OPEN, + ERR_ANS_PREFERENCES_FILE_EXCEPTION, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST, + ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_EXCEED_MAX_NUM, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_HAS_EXISTED, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID, + ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM, +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_INNER_ERRORS_H \ No newline at end of file diff --git a/innerkits/base/include/ans_log_wrapper.h b/innerkits/base/include/ans_log_wrapper.h new file mode 100644 index 000000000..3f03294f4 --- /dev/null +++ b/innerkits/base/include/ans_log_wrapper.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_LOG_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_LOG_HELPER_H + +#include + +#include "hilog/log.h" + +namespace OHOS { +namespace Notification { + +#ifndef LOG_DOMAIN +#define LOG_DOMAIN 0xD001800 +#endif + +#ifndef ANS_LOG_TAG +#define ANS_LOG_TAG NULL +#endif + +enum class AnsLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; + +static constexpr OHOS::HiviewDFX::HiLogLabel ANS_LABEL = {LOG_CORE, LOG_DOMAIN, "ANS_STANDARD"}; + +class AnsLogWrapper { +public: + AnsLogWrapper() = delete; + ~AnsLogWrapper() = delete; + + static bool JudgeLevel(const AnsLogLevel &level); + + static void SetLogLevel(const AnsLogLevel &level) + { + level_ = level; + } + + static const AnsLogLevel &GetLogLevel() + { + return level_; + } + + static std::string GetBriefFileName(const char *str); + +private: + static AnsLogLevel level_; +}; + +#define PRINT_LOG(LEVEL, Level, fmt, ...) \ + if (AnsLogWrapper::JudgeLevel(AnsLogLevel::LEVEL)) \ + OHOS::HiviewDFX::HiLog::Level(ANS_LABEL, \ + "[%{public}s(%{public}s):%{public}d] " fmt, \ + AnsLogWrapper::GetBriefFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + __LINE__, \ + ##__VA_ARGS__) + +#define ANS_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define ANS_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define ANS_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define ANS_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define ANS_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_LOG_HELPER_H \ No newline at end of file diff --git a/innerkits/base/src/ans_log_wrapper.cpp b/innerkits/base/src/ans_log_wrapper.cpp new file mode 100644 index 000000000..dc568d400 --- /dev/null +++ b/innerkits/base/src/ans_log_wrapper.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 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 "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +AnsLogLevel AnsLogWrapper::level_ = {AnsLogLevel::DEBUG}; +bool AnsLogWrapper::JudgeLevel(const AnsLogLevel &level) +{ + const AnsLogLevel &curLevel = AnsLogWrapper::GetLogLevel(); + if (level < curLevel) { + return false; + } + return true; +} + +std::string AnsLogWrapper::GetBriefFileName(const char *str) +{ + if (!str) { + return std::string(); + } + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + if (pos == std::string::npos) { + return std::string(); + } + return fullPath.substr(pos + 1); +} +} // namespace Notification +} // namespace OHOS diff --git a/innerkits/core/include/ans_manager_death_recipient.h b/innerkits/core/include/ans_manager_death_recipient.h new file mode 100644 index 000000000..acf6b9372 --- /dev/null +++ b/innerkits/core/include/ans_manager_death_recipient.h @@ -0,0 +1,34 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Notification { +class AnsManagerDeathRecipient : public IRemoteObject::DeathRecipient { +public: + AnsManagerDeathRecipient() = default; + + virtual ~AnsManagerDeathRecipient() = default; + + virtual void OnRemoteDied(const wptr &object) override; +}; + +} // namespace Notification +} // namespace OHOS + +#endif diff --git a/innerkits/core/include/ans_manager_interface.h b/innerkits/core/include/ans_manager_interface.h new file mode 100644 index 000000000..ad843cdd1 --- /dev/null +++ b/innerkits/core/include/ans_manager_interface.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H + +#include +#include + +#include "ans_subscriber_interface.h" +#include "iremote_broker.h" +#include "notification_constant.h" +#include "notification_request.h" +#include "notification_slot.h" +#include "notification_slot_group.h" +#include "notification_sorting.h" +#include "notification_subscribe_info.h" + +namespace OHOS { +namespace Notification { +class IAnsManager : public IRemoteBroker { +public: + IAnsManager() = default; + virtual ~IAnsManager() override = default; + DISALLOW_COPY_AND_MOVE(IAnsManager); + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Notification.IAnsManager"); + + virtual ErrCode Publish(const std::string &label, const sptr ¬ification) = 0; + virtual ErrCode PublishToDevice(const sptr ¬ification, const std::string &deviceId) = 0; + virtual ErrCode Cancel(int notificationId, const std::string &label) = 0; + virtual ErrCode CancelAll() = 0; + virtual ErrCode AddSlots(const std::vector> &slots) = 0; + virtual ErrCode RemoveSlots(const std::vector &slotIds) = 0; + virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) = 0; + virtual ErrCode AddSlotGroups(std::vector> groups) = 0; + virtual ErrCode GetSlot(const std::string &slotId, sptr &slot) = 0; + virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) = 0; + virtual ErrCode GetSlots(std::vector> &slots) = 0; + virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) = 0; + virtual ErrCode GetSlotGroups(std::vector> &groups) = 0; + virtual ErrCode RemoveSlotGroups(const std::vector &groupIds) = 0; + virtual ErrCode GetActiveNotifications(std::vector> ¬ifications) = 0; + virtual ErrCode GetActiveNotificationNums(int &num) = 0; + virtual ErrCode GetAllActiveNotifications(std::vector> ¬ifications) = 0; + virtual ErrCode GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) = 0; + virtual ErrCode SetNotificationAgent(const std::string &agent) = 0; + virtual ErrCode GetNotificationAgent(std::string &agent) = 0; + virtual ErrCode CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) = 0; + virtual ErrCode PublishAsBundle( + const sptr notification, const std::string &representativeBundle) = 0; + virtual ErrCode SetNotificationBadgeNum(int num) = 0; + virtual ErrCode GetBundleImportance(int &importance) = 0; + virtual ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) = 0; + virtual ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) = 0; + virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) = 0; + virtual ErrCode SetPrivateNotificationsAllowed(bool allow) = 0; + virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) = 0; + virtual ErrCode Delete(const std::string &key) = 0; + virtual ErrCode DeleteByBundle(const std::string &bundle) = 0; + virtual ErrCode DeleteAll() = 0; + virtual ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) = 0; + virtual ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) = 0; + virtual ErrCode UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) = 0; + virtual ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) = 0; + virtual ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) = 0; + virtual ErrCode SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) = 0; + virtual ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) = 0; + virtual ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) = 0; + virtual ErrCode Subscribe(const sptr &subscriber, const sptr &info) = 0; + virtual ErrCode Unsubscribe( + const sptr &subscriber, const sptr &info) = 0; + virtual ErrCode AreNotificationsSuspended(bool &suspended) = 0; + virtual ErrCode GetCurrentAppSorting(sptr &sortingMap) = 0; + virtual ErrCode IsAllowedNotify(bool &allowed) = 0; + virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) = 0; + +protected: + enum TransactId : uint32_t { + PUBLISH_NOTIFICATION = FIRST_CALL_TRANSACTION, + PUBLISH_NOTIFICATION_TO_DEVICE, + CANCEL_NOTIFICATION, + CANCEL_ALL_NOTIFICATIONS, + ADD_SLOTS, + REMOVE_SLOTS, + REMOVE_SLOT_BY_TYPE, + ADD_SLOT_GROUPS, + GET_SLOT, + GET_SLOT_BY_TYPE, + GET_SLOTS, + GET_SLOT_GROUP, + GET_SLOT_GROUPS, + REMOVE_SLOT_GROUPS, + GET_ACTIVE_NOTIFICATIONS, + GET_ACTIVE_NOTIFICATION_NUMS, + GET_ALL_ACTIVE_NOTIFICATIONS, + GET_SPECIAL_ACTIVE_NOTIFICATIONS, + SET_NOTIFICATION_AGENT, + GET_NOTIFICATION_AGENT, + CAN_PUBLISH_AS_BUNDLE, + PUBLISH_AS_BUNDLE, + SET_NOTIFICATION_BADGE_NUM, + GET_BUNDLE_IMPORTANCE, + SET_DISTURB_MODE, + GET_DISTURB_MODE, + IS_NOTIFICATION_POLICY_ACCESS_GRANTED, + SET_PRIVATIVE_NOTIFICATIONS_ALLOWED, + GET_PRIVATIVE_NOTIFICATIONS_ALLOWED, + DELETE_NOTIFICATION, + DELETE_NOTIFICATION_BY_BUNDLE, + DELETE_ALL_NOTIFICATIONS, + GET_SLOTS_BY_BUNDLE, + UPDATE_SLOTS, + UPDATE_SLOT_GROUPS, + SET_NOTIFICATION_ENABLED_FOR_BUNDLE, + SET_NOTIFICATION_ENABLED_FOR_ALL_BUNDLE, + SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, + SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, + GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, + SUBSCRIBE_NOTIFICATION, + UNSUBSCRIBE_NOTIFICATION, + ARE_NOTIFICATION_SUSPENDED, + GET_CURRENT_APP_SORTING, + IS_ALLOWED_NOTIFY, + IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, + }; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_INTERFACE_H diff --git a/innerkits/core/include/ans_manager_proxy.h b/innerkits/core/include/ans_manager_proxy.h new file mode 100644 index 000000000..c9e9e8e17 --- /dev/null +++ b/innerkits/core/include/ans_manager_proxy.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H + +#include "ans_manager_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Notification { +class AnsManagerProxy : public IRemoteProxy { +public: + AnsManagerProxy() = delete; + explicit AnsManagerProxy(const sptr &impl); + ~AnsManagerProxy() override; + DISALLOW_COPY_AND_MOVE(AnsManagerProxy); + + ErrCode Publish(const std::string &label, const sptr ¬ification) override; + ErrCode PublishToDevice(const sptr ¬ification, const std::string &deviceId) override; + ErrCode Cancel(int notificationId, const std::string &label) override; + ErrCode CancelAll() override; + ErrCode AddSlots(const std::vector> &slots) override; + ErrCode RemoveSlots(const std::vector &slotIds) override; + ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + ErrCode AddSlotGroups(std::vector> groups) override; + ErrCode GetSlot(const std::string &slotId, sptr &slot) override; + ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; + ErrCode GetSlots(std::vector> &slots) override; + ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; + ErrCode GetSlotGroups(std::vector> &groups) override; + ErrCode RemoveSlotGroups(const std::vector &groupIds) override; + ErrCode GetActiveNotifications(std::vector> ¬ifications) override; + ErrCode GetActiveNotificationNums(int &num) override; + ErrCode GetAllActiveNotifications(std::vector> ¬ifications) override; + ErrCode GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) override; + ErrCode SetNotificationAgent(const std::string &agent) override; + ErrCode GetNotificationAgent(std::string &agent) override; + ErrCode CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) override; + ErrCode PublishAsBundle( + const sptr notification, const std::string &representativeBundle) override; + ErrCode SetNotificationBadgeNum(int num) override; + ErrCode GetBundleImportance(int &importance) override; + ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; + ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; + ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; + ErrCode SetPrivateNotificationsAllowed(bool allow) override; + ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + ErrCode Delete(const std::string &key) override; + ErrCode DeleteByBundle(const std::string &bundle) override; + ErrCode DeleteAll() override; + ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; + ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; + ErrCode UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) override; + ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) override; + ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; + ErrCode SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) override; + ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; + ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + ErrCode Subscribe(const sptr &subscriber, const sptr &info) override; + ErrCode Unsubscribe(const sptr &subscriber, const sptr &info) override; + ErrCode AreNotificationsSuspended(bool &suspended) override; + ErrCode GetCurrentAppSorting(sptr &sortingMap) override; + ErrCode IsAllowedNotify(bool &allowed) override; + ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + +private: + ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); + + template + bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &data); + + template + bool ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &reply, ErrCode &result); + static inline BrokerDelegator delegator_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_PROXY_H diff --git a/innerkits/core/include/ans_manager_stub.h b/innerkits/core/include/ans_manager_stub.h new file mode 100644 index 000000000..ec967f40f --- /dev/null +++ b/innerkits/core/include/ans_manager_stub.h @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H + +#include +#include + +#include "ans_manager_interface.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace Notification { +class AnsManagerStub : public IRemoteStub { +public: + AnsManagerStub(); + ~AnsManagerStub() override; + DISALLOW_COPY_AND_MOVE(AnsManagerStub); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + virtual ErrCode Publish(const std::string &label, const sptr ¬ification) override; + virtual ErrCode PublishToDevice( + const sptr ¬ification, const std::string &deviceId) override; + virtual ErrCode Cancel(int notificationId, const std::string &label) override; + virtual ErrCode CancelAll() override; + virtual ErrCode AddSlots(const std::vector> &slots) override; + virtual ErrCode RemoveSlots(const std::vector &slotIds) override; + virtual ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + virtual ErrCode AddSlotGroups(std::vector> groups) override; + virtual ErrCode GetSlot(const std::string &slotId, sptr &slot) override; + virtual ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; + virtual ErrCode GetSlots(std::vector> &slots) override; + virtual ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; + virtual ErrCode GetSlotGroups(std::vector> &groups) override; + virtual ErrCode RemoveSlotGroups(const std::vector &groupIds) override; + virtual ErrCode GetActiveNotifications(std::vector> ¬ifications) override; + virtual ErrCode GetActiveNotificationNums(int &num) override; + virtual ErrCode GetAllActiveNotifications(std::vector> ¬ifications) override; + virtual ErrCode GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) override; + virtual ErrCode SetNotificationAgent(const std::string &agent) override; + virtual ErrCode GetNotificationAgent(std::string &agent) override; + virtual ErrCode CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) override; + virtual ErrCode PublishAsBundle( + const sptr notification, const std::string &representativeBundle) override; + virtual ErrCode SetNotificationBadgeNum(int num) override; + virtual ErrCode GetBundleImportance(int &importance) override; + virtual ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; + virtual ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; + virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; + virtual ErrCode SetPrivateNotificationsAllowed(bool allow) override; + virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + virtual ErrCode Delete(const std::string &key) override; + virtual ErrCode DeleteByBundle(const std::string &bundle) override; + virtual ErrCode DeleteAll() override; + virtual ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; + virtual ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; + virtual ErrCode UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) override; + virtual ErrCode SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) override; + virtual ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; + virtual ErrCode SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) override; + virtual ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; + virtual ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + virtual ErrCode Subscribe( + const sptr &subscriber, const sptr &info) override; + virtual ErrCode Unsubscribe( + const sptr &subscriber, const sptr &info) override; + virtual ErrCode AreNotificationsSuspended(bool &suspended) override; + virtual ErrCode GetCurrentAppSorting(sptr &sortingMap) override; + virtual ErrCode IsAllowedNotify(bool &allowed) override; + virtual ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + +private: + static const std::map> interfaces_; + + ErrCode HandlePublish(MessageParcel &data, MessageParcel &reply); + ErrCode HandlePublishToDevice(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCancel(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCancelAll(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAddSlots(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveSlots(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveSlotByType(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAddSlotGroups(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlot(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlots(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlotByType(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlotGroup(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlotGroups(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveSlotGroups(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetActiveNotifications(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetActiveNotificationNums(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetAllActiveNotifications(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSpecialActiveNotifications(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationAgent(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetNotificationAgent(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCanPublishAsBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandlePublishAsBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationBadgeNum(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetBundleImportance(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetDisturbMode(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetDisturbMode(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsNotificationPolicyAccessGranted(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); + ErrCode HandleDelete(MessageParcel &data, MessageParcel &reply); + ErrCode HandleDeleteByBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleDeleteAll(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetSlotsByBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleUpdateSlots(MessageParcel &data, MessageParcel &reply); + ErrCode HandleUpdateSlotGroups(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationsEnabledForBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationsEnabledForAllBundles(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetNotificationsEnabledForSpecialBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSubscribe(MessageParcel &data, MessageParcel &reply); + ErrCode HandleUnsubscribe(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAreNotificationsSuspended(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetCurrentAppSorting(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); + + template + bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result); + + template + bool ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &data); +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_MANAGER_STUB_H diff --git a/innerkits/core/include/ans_notification.h b/innerkits/core/include/ans_notification.h new file mode 100644 index 000000000..c75fbda1c --- /dev/null +++ b/innerkits/core/include/ans_notification.h @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H + +#include + +#include "ans_manager_death_recipient.h" +#include "ans_manager_interface.h" +#include "notification_request.h" +#include "notification_slot.h" +#include "notification_slot_group.h" +#include "notification_sorting_map.h" +#include "notification_subscriber.h" + +namespace OHOS { +namespace Notification { +class AnsNotification { +public: + /** + * Creates a notification slot. + * @note You can call the NotificationRequest::SetSlotType(NotificationConstant::SlotType) method to bind the slot + * for publishing. A NotificationSlot instance cannot be used directly after being initialized. Instead, you have to + * call this method to create a notification slot and bind the slot ID to a NotificationRequest object so that the + * notification published can have all the characteristics set in the NotificationSlot. After a notification slot is + * created by using this method, only the name and description of the notification slot can be changed. Changes to + * the other attributes, such as the vibration status and notification tone, will no longer take effect. + * + * @param slot Indicates the notification slot to be created, which is set by NotificationSlot. + * This parameter must be specified. + * @return Returns add notification slot result. + */ + ErrCode AddNotificationSlot(const NotificationSlot &slot); + + /** + * Creates multiple notification slots. + * + * @param slots Indicates the notification slots to create. + * @return Returns add notification slots result. + */ + ErrCode AddNotificationSlots(const std::vector &slots); + + /** + * Deletes a created notification slot based on the slot ID. + * + * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot + * This parameter must be specified. + * @return Returns remove notification slot result. + */ + ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + + /** + * Queries a created notification slot. + * + * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot(NotificationSlot). This + * parameter must be specified. + * @param slot Indicates the created NotificationSlot. + * @return Returns the get notification slot result. + */ + ErrCode GetNotificationSlot(const NotificationConstant::SlotType &slotType, sptr &slot); + + /** + * Obtains all notification slots of this application. + * @param slots Indicates the created NotificationSlot. + * @return Returns all notification slots of this application. + */ + ErrCode GetNotificationSlots(std::vector> &slots); + + /** + * Creates a notification slot group to which a NotificationSlot object can be bound by + * calling NotificationSlot::SetSlotGroup(string). + * @note A NotificationSlotGroup instance cannot be used directly after being initialized. + * Instead, you have to call this method to create a notification slot group so that you can bind + * NotificationSlot objects to it. + * + * @param slotGroup Indicates the notification slot group to be created, which is set by NotificationSlotGroup. + * This parameter must be specified. the notification slot to be created, which is set by + * NotificationSlot. + * @return Returns add notification slot group result. + */ + ErrCode AddNotificationSlotGroup(const NotificationSlotGroup &slotGroup); + + /** + * Creates multiple notification slot groups. + * @note The precautions for using this method are similar to those for + * AddNotificationSlotGroup(NotificationSlotGroup). + * + * @param slotGroups Indicates a list of NotificationSlotGroup objects to create. This parameter cannot be null. + * @return Returns add notification slot groups result. + */ + ErrCode AddNotificationSlotGroups(const std::vector &slotGroups); + + /** + * Deletes a created notification slot group based on the slot group ID. + * + * @param slotGroupId Indicates the ID of the notification slot group, which is created by + * AddNotificationSlotGroup(NotificationSlotGroup) This parameter must be specified. + * @return Returns remove notification slot group result. + */ + ErrCode RemoveNotificationSlotGroup(const std::string &slotGroupId); + + /** + * Queries a created notification slot group. + * + * @param groupId Indicates the ID of the slot group. + * @param group Indicates the created NotificationSlotGroup. + * @return Returns get notification slot group result. + */ + ErrCode GetNotificationSlotGroup(const std::string &groupId, sptr &group); + + /** + * Obtains a list of created notification slot groups. + * + * @param groups Indicates a list of created notification slot groups. + * @return Returns get notification slot groups result. + */ + ErrCode GetNotificationSlotGroups(std::vector> &groups); + + /** + * Publishes a notification. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return returns publish notification result. + */ + ErrCode PublishNotification(const NotificationRequest &request); + + /** + * Publishes a notification with a specified label. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param label Indicates the label of the notification to publish. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return returns publish notification result. + */ + ErrCode PublishNotification(const std::string &label, const NotificationRequest &request); + + /** + * Publishes a notification on a specified remote device. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @param deviceId Indicates the ID of the remote device. If this parameter is null or an empty string, + * the notification will be published on the local device. + * @return returns publish notification result. + */ + ErrCode PublishNotification(const NotificationRequest &request, const std::string &deviceId); + + /** + * Cancels a published notification. + * + * @param notificationId Indicates the unique notification ID in the application. + * The value must be the ID of a published notification. + * Otherwise, this method does not take effect. + * @return returns cancel notification result. + */ + ErrCode CancelNotification(int32_t notificationId); + + /** + * Cancels a published notification matching the specified label and notificationId. + * + * @param label Indicates the label of the notification to cancel. + * @param notificationId Indicates the ID of the notification to cancel. + * @return returns cancel notification result. + */ + ErrCode CancelNotification(const std::string &label, int32_t notificationId); + + /** + * Cancels all the published notifications. + * @note To cancel a specified notification, see CancelNotification(int_32). + * @return returns cancel all notifications result. + */ + ErrCode CancelAllNotifications(); + + /** + * Obtains the number of active notifications of the current application in the system. + * + * @param num Indicates the number of active notifications of the current application. + * @return Returns get active notification nums result. + */ + ErrCode GetActiveNotificationNums(int32_t &num); + + /** + * Obtains active notifications of the current application in the system. + * @param request Indicates active NotificationRequest objects of the current application. + * @return Returns get active notifications result. + */ + ErrCode GetActiveNotifications(std::vector> &request); + + /** + * Obtains the map for sorting notifications of the current application. + * + * @param sortingMap Indicates the NotificationSortingMap object for the current application. + * @return Returns get current app sorting result. + */ + ErrCode GetCurrentAppSorting(sptr &sortingMap); + + /** + * Allows another application to act as an agent to publish notifications in the name of your application bundle. + * You can revoke this authorization by passing null to this method. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application. + * @return Returns set notification agent result. + */ + ErrCode SetNotificationAgent(const std::string &agent); + + /** + * Obtains the name of the application bundle that can publish notifications in the name of your application. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application if + * any; returns null otherwise. + * @return Returns get notification agent result. + */ + ErrCode GetNotificationAgent(std::string &agent); + + /** + * Checks whether your application has permission to publish notifications by calling + * PublishNotificationAsBundle(string, NotificationRequest) in the name of another application indicated by the + * given representativeBundle. + * + * @param representativeBundle Indicates the name of application bundle your application is representing. + * @param canPublish Indicates whether your application has permission to publish notifications. + * @return Returns can publish notification as bundle result. + */ + ErrCode CanPublishNotificationAsBundle(const std::string &representativeBundle, bool &canPublish); + + /** + * Publishes a notification in the name of a specified application bundle. + * @note If the notification to be published has the same ID as a published notification that has not been canceled, + * the existing notification will be replaced by the new one. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @param representativeBundle Indicates the name of the application bundle that allows your application to publish + * notifications for it by calling setNotificationAgent. + * @return Returns publish notification as bundle result. + */ + ErrCode PublishNotificationAsBundle(const std::string &representativeBundle, const NotificationRequest &request); + + /** + * Sets the number of active notifications of the current application as the number to be displayed on the + * notification badge. + * @return Returns set notification badge num result. + */ + ErrCode SetNotificationBadgeNum(); + + /** + * Sets the number to be displayed on the notification badge of the application. + * + * @param num Indicates the number to display. A negative number indicates that the badge setting remains unchanged. + * The value 0 indicates that no badge is displayed on the application icon. + * If the value is greater than 99, 99+ will be displayed. + * @return Returns set notification badge num result. + */ + ErrCode SetNotificationBadgeNum(int32_t num); + + /** + * Checks whether this application has permission to publish notifications. + * + * @param allowed True if this application has the permission; returns false otherwise + * @return Returns is allowed notify result. + */ + ErrCode IsAllowedNotify(bool &allowed); + + /** + * Checks whether this application is in the suspended state.Applications in this state cannot publish + * notifications. + * + * @param suspended True if this application is suspended; returns false otherwise. + * @return Returns are notifications suspended. + */ + ErrCode AreNotificationsSuspended(bool &suspended); + + /** + * Checks whether this application has permission to modify the Do Not Disturb (DND) notification policy. + * + * @param hasPermission True if this application is suspended; returns false otherwise. + * @return Returns has notification policy access permission. + */ + ErrCode HasNotificationPolicyAccessPermission(bool &hasPermission); + + /** + * Obtains the importance level of this application. + * + * @param importance the importance level of this application, which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Returns get bundle importance result + */ + ErrCode GetBundleImportance(NotificationSlot::NotificationLevel &importance); + + /** + * Subscribes to notifications from all applications. This method can be called only by applications + * with required system permissions. + * @note To subscribe to a notification, inherit the {NotificationSubscriber} class, override its + * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to notifications published only by specified sources, for example, notifications from + * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} + * method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + + /** + * Subscribes to all notifications based on the filtering criteria. This method can be called only + * by applications with required system permissions. + * @note After {subscribeInfo} is specified, a subscriber receives only the notifications that + * meet the filter criteria specified by {subscribeInfo}. + * To subscribe to a notification, inherit the {NotificationSubscriber} class, override its + * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to and receive all notifications, call the + * {SubscribeNotification(NotificationSubscriber)} method. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + + /** + * Unsubscribes from all notifications. This method can be called only by applications with required + * system permissions. + * @note Generally, you subscribe to a notification by calling the + * {SubscribeNotification(NotificationSubscriber)} method. If you do not want your application + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + + /** + * Unsubscribes from all notifications based on the filtering criteria. This method can be called + * only by applications with required system permissions. + * @note A subscriber will no longer receive the notifications from specified notification sources. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param key Indicates the key of the notification to remove. + * @return Returns remove notification result. + */ + ErrCode RemoveNotification(const std::string &key); + + /** + * Removes all removable notifications of a specified bundle. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @return Returns remove notifications result. + */ + ErrCode RemoveNotifications(const std::string &bundleName); + + /** + * Removes all removable notifications in the system. + * @note Your application must have platform signature to use this method. + * @return Returns remove notifications result. + */ + ErrCode RemoveNotifications(); + + /** + * Returns all notification slots belonging to the specified bundle. + * + * @param bundleName Indicates the application name. + * @param slots Indicates a list of notification slots. + * @return Returns get notification slots for bundle result. + */ + ErrCode GetNotificationSlotsForBundle(const std::string &bundleName, std::vector> &slots); + + /** + * Obtains all active notifications in the current system. The caller must have system permissions to + * call this method. + * + * @param notification Indicates all active notifications of this application. + * @return Returns get all active notifications + */ + ErrCode GetAllActiveNotifications(std::vector> ¬ification); + + /** + * Obtains the active notifications corresponding to the specified key in the system. To call this method + * to obtain particular active notifications, you must have received the notifications and obtained the key + * via {Notification::GetKey()}. + * + * @param key Indicates the key array for querying corresponding active notifications. + * If this parameter is null, this method returns all active notifications in the system. + * @param notification Indicates the set of active notifications corresponding to the specified key. + * @return Returns get all active notifications result. + */ + ErrCode GetAllActiveNotifications( + const std::vector key, std::vector> ¬ification); + + /** + * Checks whether a specified application has the permission to publish notifications. If bundle specifies + * the current application, no permission is required for calling this method. If bundle specifies another + * application, the caller must have system permissions. + * + * @param bundle Indicates the bundle name of the application to check. + * @param allowed True if the application has permissions; returns false otherwise. + * @return Returns is allowed notify result. + */ + ErrCode IsAllowedNotify(const std::string &bundle, bool &allowed); + + /** + * Sets whether to allow all applications to publish notifications on a specified device. The caller must have + * system permissions to call this method. + * + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only + * be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow all applications to publish notifications. The value true + * indicates that notifications are allowed, and the value false indicates that notifications are not + * allowed. + * @return Returns set notifications enabled for all bundles result. + */ + ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled); + + /** + * Sets whether to allow the current application to publish notifications on a specified device. The caller + * must have system permissions to call this method. + * + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can + * only be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow the current application to publish notifications. The value + * true indicates that notifications are allowed, and the value false indicates that + * notifications are not allowed. + * @return Returns set notifications enabled for default bundle result. + */ + ErrCode SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled); + + /** + * Sets whether to allow a specified application to publish notifications on a specified device. The caller + * must have system permissions to call this method. + * + * @param bundle Indicates the bundle name of the application. + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only + * be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow the given application to publish notifications. The value + * true indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. + * @return Returns set notifications enabled for specified bundle result. + */ + ErrCode SetNotificationsEnabledForSpecifiedBundle( + const std::string &bundle, const std::string &deviceId, bool enabled); + + /** + * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications + * that are allowed to interrupt users. + * @note Your application must have system signature to call this method. + * + * @param mode Indicates the Do Not Disturb mode to set. The value must be + * {NotificationConstant.DisturbMode.ALLOW_ALL}, {NotificationConstant.DisturbMode.ALLOW_PRIORITY}, + * {NotificationConstant.DisturbMode.ALLOW_NONE}, or {NotificationConstant.DisturbMode.ALLOW_ALARMS}. + * @return Returns set disturb mode result. + */ + ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); + + /** + * Obtains the Disturb Mode. + * @param disturbMode The current type of the Do Not Disturb mode. + * @return Returns get disturb mode result. + */ + ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); + + /** + * Reset ans manager proxy when OnRemoteDied called. + */ + void ResetAnsManagerProxy(); + +private: + /** + * Get Ans Manager proxy. + * + * @return Get Ans Manager proxy success or not + */ + bool GetAnsManagerProxy(); + + /** + * Can Publish Media Content + * + * @return Can publish return true otherwise return false + */ + bool CanPublishMediaContent(const NotificationRequest &request) const; + +private: + std::mutex mutex_; + sptr ansManagerProxy_; + sptr recipient_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_NOTIFICATION_H \ No newline at end of file diff --git a/innerkits/core/include/ans_subscriber_interface.h b/innerkits/core/include/ans_subscriber_interface.h new file mode 100644 index 000000000..9270ab9ff --- /dev/null +++ b/innerkits/core/include/ans_subscriber_interface.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H + +#include "iremote_broker.h" + +#include "notification.h" +#include "notification_constant.h" +#include "notification_request.h" +#include "notification_sorting.h" +#include "notification_sorting_map.h" + +namespace OHOS { +namespace Notification { +class IAnsSubscriber : public IRemoteBroker { +public: + IAnsSubscriber() = default; + virtual ~IAnsSubscriber() override = default; + DISALLOW_COPY_AND_MOVE(IAnsSubscriber); + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Notification.IAnsSubscriber"); + + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) = 0; + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) = 0; + virtual void OnConsumed(const sptr ¬ification) = 0; + virtual void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) = 0; + virtual void OnCanceled(const sptr ¬ification) = 0; + virtual void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int deleteReason) = 0; + virtual void OnUpdated(const sptr ¬ificationMap) = 0; + virtual void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) = 0; + +protected: + enum TransactId : uint32_t { + ON_SUBSCRIBE = FIRST_CALL_TRANSACTION, + ON_UNSUBSCRIBE, + ON_CONSUMED, + ON_CONSUMED_MAP, + ON_CANCELED, + ON_CANCELED_MAP, + ON_UPDATED, + ON_DISTURB_MODE_CHANGED, + }; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_INTERFACE_H diff --git a/innerkits/core/include/ans_subscriber_proxy.h b/innerkits/core/include/ans_subscriber_proxy.h new file mode 100644 index 000000000..514f4c473 --- /dev/null +++ b/innerkits/core/include/ans_subscriber_proxy.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H + +#include "ans_subscriber_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Notification { + +class AnsSubscriberProxy : public IRemoteProxy { +public: + AnsSubscriberProxy() = delete; + explicit AnsSubscriberProxy(const sptr &impl); + ~AnsSubscriberProxy() override; + DISALLOW_COPY_AND_MOVE(AnsSubscriberProxy); + + void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnConsumed(const sptr ¬ification) override; + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override; + void OnCanceled(const sptr ¬ification) override; + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int deleteReason) override; + void OnUpdated(const sptr ¬ificationMap) override; + void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + +private: + ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); + static inline BrokerDelegator delegator_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_PROXY_H diff --git a/innerkits/core/include/ans_subscriber_stub.h b/innerkits/core/include/ans_subscriber_stub.h new file mode 100644 index 000000000..8690140ff --- /dev/null +++ b/innerkits/core/include/ans_subscriber_stub.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H + +#include "ans_subscriber_interface.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace Notification { + +class AnsSubscriberStub : public IRemoteStub { +public: + AnsSubscriberStub(); + ~AnsSubscriberStub() override; + DISALLOW_COPY_AND_MOVE(AnsSubscriberStub); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnConsumed(const sptr ¬ification) override; + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override; + void OnCanceled(const sptr ¬ification) override; + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int deleteReason) override; + void OnUpdated(const sptr ¬ificationMap) override; + void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + +private: + std::map> interfaces_; + + ErrCode HandleOnSubscribe(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnUnsubscribe(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnConsumed(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnConsumedMap(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnCanceled(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnCanceledMap(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnUpdated(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnDisturbModeChanged(MessageParcel &data, MessageParcel &reply); +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_CORE_INCLUDE_ANS_SUBSCRIBER_STUB_H diff --git a/innerkits/core/src/ans_manager_death_recipient.cpp b/innerkits/core/src/ans_manager_death_recipient.cpp new file mode 100644 index 000000000..07d648bff --- /dev/null +++ b/innerkits/core/src/ans_manager_death_recipient.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 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 "ans_manager_death_recipient.h" +#include "ans_log_wrapper.h" +#include "ans_notification.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +void AnsManagerDeathRecipient::OnRemoteDied(const wptr &remote) +{ + ANS_LOGE("Ans service died"); + DelayedSingleton::GetInstance()->ResetAnsManagerProxy(); +} +} // namespace Notification +} // namespace OHOS diff --git a/innerkits/core/src/ans_manager_proxy.cpp b/innerkits/core/src/ans_manager_proxy.cpp new file mode 100644 index 000000000..6a479f34b --- /dev/null +++ b/innerkits/core/src/ans_manager_proxy.cpp @@ -0,0 +1,1678 @@ +/* + * Copyright (c) 2021 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 "ans_manager_proxy.h" + +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "message_option.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { + +AnsManagerProxy::AnsManagerProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +AnsManagerProxy::~AnsManagerProxy() +{} + +ErrCode AnsManagerProxy::Publish(const std::string &label, const sptr ¬ification) +{ + if (notification == nullptr) { + ANS_LOGW("[Publish] fail: notification is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[Publish] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(label)) { + ANS_LOGW("[Publish] fail: write label failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[Publish] fail: write notification parcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(PUBLISH_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[Publish] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[Publish] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::PublishToDevice(const sptr ¬ification, const std::string &deviceId) +{ + if (notification == nullptr) { + ANS_LOGW("[PublishToDevice] fail: notification is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[PublishToDevice] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[PublishToDevice] fail: write notification parcelable failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGW("[PublishToDevice] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(PUBLISH_NOTIFICATION_TO_DEVICE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[PublishToDevice] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[PublishToDevice] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::Cancel(int notificationId, const std::string &label) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[Cancel] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(notificationId)) { + ANS_LOGW("[Cancel] fail: write notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(label)) { + ANS_LOGW("[Cancel] fail: write label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(CANCEL_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[Cancel] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[Cancel] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::CancelAll() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[CancelAll] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(CANCEL_ALL_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[CancelAll] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[CancelAll] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::AddSlots(const std::vector> &slots) +{ + if (slots.empty()) { + ANS_LOGW("[AddSlots] fail: slots is empty."); + return ERR_ANS_INVALID_PARAM; + } + + uint32_t slotsSize = slots.size(); + if (slotsSize > MAX_SLOT_NUM) { + ANS_LOGW("[AddSlots] fail: slotsSize over max size."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[AddSlots] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!WriteParcelableVector(slots, data)) { + ANS_LOGW("[AddSlots] fail: write slots failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ADD_SLOTS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[AddSlots] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[AddSlots] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveSlots(const std::vector &slotIds) +{ + if (slotIds.empty()) { + ANS_LOGW("[RemoveSlots] fail: slotIds is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveSlots] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteStringVector(slotIds)) { + ANS_LOGW("[RemoveSlots] fail:: write slotIds failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_SLOTS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveSlots] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveSlots] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveSlotByType(const NotificationConstant::SlotType slotType) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveSlotByType] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(slotType)) { + ANS_LOGW("[RemoveSlotByType] fail:: write slotIds failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_SLOT_BY_TYPE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveSlotByType] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveSlotByType] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::AddSlotGroups(std::vector> groups) +{ + if (groups.empty()) { + ANS_LOGW("[AddSlotGroups] fail: groups is empty."); + return ERR_ANS_INVALID_PARAM; + } + + uint32_t groupsSize = groups.size(); + if (groupsSize > MAX_SLOT_GROUP_NUM) { + ANS_LOGW("[AddSlotGroups] fail: groupsSize over max size."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[AddSlotGroups] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!WriteParcelableVector(groups, data)) { + ANS_LOGW("[AddSlotGroups] fail: write groups failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ADD_SLOT_GROUPS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[AddSlotGroups] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[AddSlotGroups] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlot(const std::string &slotId, sptr &slot) +{ + if (slotId.empty()) { + ANS_LOGW("[GetSlot] fail: slotId is null."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlot] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(slotId)) { + ANS_LOGW("[GetSlot] fail:: write slotId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOT, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlot] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetSlot] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + slot = reply.ReadParcelable(); + if (slot == nullptr) { + ANS_LOGW("[GetSlot] fail: read slot failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlotByType] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(slotType)) { + ANS_LOGW("[GetSlotByType] fail:: write slotId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOT_BY_TYPE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlotByType] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetSlotByType] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + slot = reply.ReadParcelable(); + if (slot == nullptr) { + ANS_LOGW("[GetSlotByType] fail: read slot failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlots(std::vector> &slots) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlots] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOTS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlots] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(slots, reply, result)) { + ANS_LOGW("[GetSlots] fail: read slots failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlotGroup(const std::string &groupId, sptr &group) +{ + if (groupId.empty()) { + ANS_LOGW("[GetSlotGroup] fail: groupId is null."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlotGroup] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(groupId)) { + ANS_LOGW("[GetSlotGroup] fail:: write groupId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOT_GROUP, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlotGroup] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetSlotGroup] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + group = reply.ReadParcelable(); + if (group == nullptr) { + ANS_LOGW("[GetSlotGroup] fail: read group failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlotGroups(std::vector> &groups) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlotGroups] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOT_GROUPS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlotGroups] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(groups, reply, result)) { + ANS_LOGW("[GetSlotGroups] fail: read groups failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveSlotGroups(const std::vector &groupIds) +{ + if (groupIds.empty()) { + ANS_LOGW("[RemoveSlotGroups] fail: groupIds is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveSlotGroups] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteStringVector(groupIds)) { + ANS_LOGW("[RemoveSlotGroups] fail:: write groupIds failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_SLOT_GROUPS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveSlotGroups] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveSlotGroups] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetActiveNotifications(std::vector> ¬ifications) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetActiveNotifications] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_ACTIVE_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetActiveNotifications] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(notifications, reply, result)) { + ANS_LOGW("[GetActiveNotifications] fail: read notifications failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetActiveNotificationNums(int &num) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetActiveNotificationNums] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_ACTIVE_NOTIFICATION_NUMS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetActiveNotificationNums] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!data.ReadInt32(num)) { + ANS_LOGW("[GetActiveNotificationNums] fail: read notification num failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetAllActiveNotifications(std::vector> ¬ifications) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetAllActiveNotifications] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_ALL_ACTIVE_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetAllActiveNotifications] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(notifications, reply, result)) { + ANS_LOGW("[GetAllActiveNotifications] fail: read notifications failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) +{ + if (key.empty()) { + ANS_LOGW("[GetSpecialActiveNotifications] fail: key is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSpecialActiveNotifications] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteStringVector(key)) { + ANS_LOGW("[GetSpecialActiveNotifications] fail:: write key failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SPECIAL_ACTIVE_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSpecialActiveNotifications] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(notifications, reply, result)) { + ANS_LOGW("[GetSpecialActiveNotifications] fail: read notifications failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationAgent(const std::string &agent) +{ + if (agent.empty()) { + ANS_LOGW("[SetNotificationAgent] fail: agent is null."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetNotificationAgent] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(agent)) { + ANS_LOGW("[SetNotificationAgent] fail:: write agent failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_AGENT, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationAgent] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationAgent] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetNotificationAgent(std::string &agent) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetNotificationAgent] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_NOTIFICATION_AGENT, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetNotificationAgent] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetNotificationAgent] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadString(agent)) { + ANS_LOGW("[GetNotificationAgent] fail: read agent failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) +{ + if (representativeBundle.empty()) { + ANS_LOGW("[CanPublishAsBundle] fail: representativeBundle is null."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[CanPublishAsBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(representativeBundle)) { + ANS_LOGW("[CanPublishAsBundle] fail: write representativeBundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(CAN_PUBLISH_AS_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[CanPublishAsBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[CanPublishAsBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(canPublish)) { + ANS_LOGW("[CanPublishAsBundle] fail: read canPublish failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::PublishAsBundle( + const sptr notification, const std::string &representativeBundle) +{ + if (notification == nullptr) { + ANS_LOGW("[PublishAsBundle] fail: notification is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + if (representativeBundle.empty()) { + ANS_LOGW("[PublishAsBundle] fail: representativeBundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[PublishAsBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[PublishAsBundle] fail: write notification failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(representativeBundle)) { + ANS_LOGW("[PublishAsBundle] fail: write representativeBundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(PUBLISH_AS_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[PublishAsBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[PublishAsBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationBadgeNum(int num) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetNotificationBadgeNum] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(num)) { + ANS_LOGW("[SetNotificationBadgeNum] fail: write num failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_BADGE_NUM, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationBadgeNum] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationBadgeNum] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetBundleImportance(int &importance) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetBundleImportance] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_BUNDLE_IMPORTANCE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetBundleImportance] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetBundleImportance] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(importance)) { + ANS_LOGW("[GetBundleImportance] fail: read importance failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetDisturbMode(NotificationConstant::DisturbMode mode) +{ + if ((mode < NotificationConstant::DisturbMode::ALLOW_ALARMS) || + (mode > NotificationConstant::DisturbMode::ALLOW_UNKNOWN)) { + ANS_LOGW("[SetDisturbMode] fail: input mode is not in DisturbMode."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetDisturbMode] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(mode)) { + ANS_LOGW("[SetDisturbMode] fail: write mode failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_DISTURB_MODE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetDisturbMode] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetDisturbMode] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetDisturbMode(NotificationConstant::DisturbMode &mode) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetDisturbMode] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_DISTURB_MODE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetDisturbMode] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetDisturbMode] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + mode = static_cast(reply.ReadInt32()); + + return result; +} + +ErrCode AnsManagerProxy::HasNotificationPolicyAccessPermission(bool &granted) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[HasNotificationPolicyAccessPermission] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_NOTIFICATION_POLICY_ACCESS_GRANTED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[HasNotificationPolicyAccessPermission] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[HasNotificationPolicyAccessPermission] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(granted)) { + ANS_LOGW("[HasNotificationPolicyAccessPermission] fail: read granted failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetPrivateNotificationsAllowed(bool allow) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetPrivateNotificationsAllowed] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(allow)) { + ANS_LOGW("[SetPrivateNotificationsAllowed] fail: write allow failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_PRIVATIVE_NOTIFICATIONS_ALLOWED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetPrivateNotificationsAllowed] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetPrivateNotificationsAllowed] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetPrivateNotificationsAllowed(bool &allow) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetPrivateNotificationsAllowed] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_PRIVATIVE_NOTIFICATIONS_ALLOWED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetPrivateNotificationsAllowed] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetPrivateNotificationsAllowed] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allow)) { + ANS_LOGW("[GetPrivateNotificationsAllowed] fail: read allow failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::Delete(const std::string &key) +{ + if (key.empty()) { + ANS_LOGW("[Delete] fail: key is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[Delete] fail:, write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(key)) { + ANS_LOGW("[Delete] fail:: write key failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(DELETE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[Delete] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[Delete] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::DeleteByBundle(const std::string &bundle) +{ + if (bundle.empty()) { + ANS_LOGW("[DeleteByBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[DeleteByBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[DeleteByBundle] fail: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(DELETE_NOTIFICATION_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[DeleteByBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[DeleteByBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::DeleteAll() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[DeleteAll] fail:, write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(DELETE_ALL_NOTIFICATIONS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[DeleteAll] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[DeleteAll] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSlotsByBundle(const std::string &bundle, std::vector> &slots) +{ + if (bundle.empty()) { + ANS_LOGW("[GetSlotsByBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetSlotsByBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[GetSlotsByBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SLOTS_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetSlotsByBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!ReadParcelableVector(slots, reply, result)) { + ANS_LOGW("[GetSlotsByBundle] fail: read slots failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::UpdateSlots(const std::string &bundle, const std::vector> &slots) +{ + if (bundle.empty()) { + ANS_LOGW("[UpdateSlots] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + if (slots.empty()) { + ANS_LOGW("[UpdateSlots] fail: slots is empty."); + return ERR_ANS_INVALID_PARAM; + } + + uint32_t slotSize = slots.size(); + if (slotSize > MAX_SLOT_NUM) { + ANS_LOGW("[UpdateSlots] fail: slotSize over max size."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[UpdateSlots] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[UpdateSlots] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!WriteParcelableVector(slots, data)) { + ANS_LOGW("[UpdateSlots] fail: write slots failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(UPDATE_SLOTS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[UpdateSlots] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[UpdateSlots] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) +{ + if (bundle.empty()) { + ANS_LOGW("[UpdateSlotGroups] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + if (groups.empty()) { + ANS_LOGW("[UpdateSlotGroups] fail: groups is empty."); + return ERR_ANS_INVALID_PARAM; + } + + uint32_t groupSize = groups.size(); + if (groupSize > MAX_SLOT_GROUP_NUM) { + ANS_LOGW("[UpdateSlotGroups] fail: groupSize over max size."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[UpdateSlotGroups] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[UpdateSlotGroups] fail:: write bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!WriteParcelableVector(groups, data)) { + ANS_LOGW("[UpdateSlotGroups] fail: write groups failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(UPDATE_SLOT_GROUPS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[UpdateSlotGroups] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[UpdateSlotGroups] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetNotificationsEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGW("[SetNotificationsEnabledForBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[SetNotificationsEnabledForBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationsEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationsEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetNotificationsEnabledForAllBundles] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGW("[SetNotificationsEnabledForAllBundles] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[SetNotificationsEnabledForAllBundles] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_FOR_ALL_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationsEnabledForAllBundles] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationsEnabledForAllBundles] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) +{ + if (bundleName.empty()) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: bundleName is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundleName)) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write bundleName failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_NOTIFICATION_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetNotificationsEnabledForSpecialBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +{ + if (bundle.empty()) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail:: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +{ + if (bundle.empty()) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGW("[GetShowBadgeEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::Subscribe(const sptr &subscriber, const sptr &info) +{ + if (subscriber == nullptr) { + ANS_LOGW("[Subscribe] fail: subscriber is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[Subscribe] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool ret = data.WriteRemoteObject(subscriber->AsObject()); + if (!ret) { + ANS_LOGW("[Subscribe] fail: write subscriber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(info != nullptr)) { + ANS_LOGW("[Subscribe] fail: write isSubcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (info != nullptr) { + if (!data.WriteParcelable(info)) { + ANS_LOGW("[Subscribe] fail: write subcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SUBSCRIBE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[Subscribe] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[Subscribe] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::Unsubscribe( + const sptr &subscriber, const sptr &info) +{ + if (subscriber == nullptr) { + ANS_LOGW("[Unsubscribe] fail: subscriber is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[Unsubscribe] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool ret = data.WriteRemoteObject(subscriber->AsObject()); + if (!ret) { + ANS_LOGW("[Unsubscribe] fail: write subscriber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(info != nullptr)) { + ANS_LOGW("[Unsubscribe] fail: write isSubcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (info != nullptr) { + if (!data.WriteParcelable(info)) { + ANS_LOGW("[Unsubscribe] fail: write subcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(UNSUBSCRIBE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[Unsubscribe] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[Unsubscribe] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::AreNotificationsSuspended(bool &suspended) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[AreNotificationsSuspended] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ARE_NOTIFICATION_SUSPENDED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[AreNotificationsSuspended] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[AreNotificationsSuspended] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(suspended)) { + ANS_LOGW("[AreNotificationsSuspended] fail: read suspended failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetCurrentAppSorting(sptr &sortingMap) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetCurrentAppSorting] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_CURRENT_APP_SORTING, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetCurrentAppSorting] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetCurrentAppSorting] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + sortingMap = reply.ReadParcelable(); + if (sortingMap == nullptr) { + ANS_LOGW("[GetCurrentAppSorting] fail: read sortingMap failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsAllowedNotify(bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGW("[IsAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +{ + if (bundle.empty()) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundle)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) +{ + auto remote = Remote(); + if (remote == nullptr) { + ANS_LOGW("[InnerTransact] fail: get Remote fail code %{public}d", code); + return ERR_DEAD_OBJECT; + } + int err = remote->SendRequest(code, data, reply, flags); + switch (err) { + case NO_ERROR: { + return ERR_OK; + } + case DEAD_OBJECT: { + ANS_LOGW("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + return ERR_DEAD_OBJECT; + } + default: { + ANS_LOGW("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + return ERR_ANS_TRANSACT_FAILED; + } + } +} + +template +bool AnsManagerProxy::WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &data) +{ + if (!data.WriteInt32(parcelableVector.size())) { + ANS_LOGW("write ParcelableVector size failed"); + return false; + } + + for (auto &parcelable : parcelableVector) { + if (!data.WriteStrongParcelable(parcelable)) { + ANS_LOGW("write ParcelableVector failed"); + return false; + } + } + return true; +} + +template +bool AnsManagerProxy::ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &reply, ErrCode &result) +{ + if (!reply.ReadInt32(result)) { + ANS_LOGW("read result failed."); + return false; + } + + int32_t infoSize = 0; + if (!reply.ReadInt32(infoSize)) { + ANS_LOGW("read Parcelable size failed."); + return false; + } + + parcelableInfos.clear(); + for (int32_t index = 0; index < infoSize; index++) { + sptr info = reply.ReadStrongParcelable(); + if (info == nullptr) { + ANS_LOGW("read Parcelable infos failed."); + return false; + } + parcelableInfos.emplace_back(info); + } + + return true; +} + +} // namespace Notification +} // namespace OHOS diff --git a/innerkits/core/src/ans_manager_stub.cpp b/innerkits/core/src/ans_manager_stub.cpp new file mode 100644 index 000000000..9774f7de3 --- /dev/null +++ b/innerkits/core/src/ans_manager_stub.cpp @@ -0,0 +1,1376 @@ +/* + * Copyright (c) 2021 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 "ans_manager_stub.h" + +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "message_option.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { + +const std::map> + AnsManagerStub::interfaces_ = { + {AnsManagerStub::PUBLISH_NOTIFICATION, + std::bind( + &AnsManagerStub::HandlePublish, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::PUBLISH_NOTIFICATION_TO_DEVICE, + std::bind(&AnsManagerStub::HandlePublishToDevice, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::CANCEL_NOTIFICATION, + std::bind( + &AnsManagerStub::HandleCancel, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::CANCEL_ALL_NOTIFICATIONS, + std::bind( + &AnsManagerStub::HandleCancelAll, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::ADD_SLOTS, + std::bind( + &AnsManagerStub::HandleAddSlots, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::REMOVE_SLOTS, + std::bind(&AnsManagerStub::HandleRemoveSlots, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::REMOVE_SLOT_BY_TYPE, + std::bind(&AnsManagerStub::HandleRemoveSlotByType, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::ADD_SLOT_GROUPS, + std::bind(&AnsManagerStub::HandleAddSlotGroups, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_SLOT, + std::bind( + &AnsManagerStub::HandleGetSlot, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::GET_SLOT_BY_TYPE, + std::bind(&AnsManagerStub::HandleGetSlotByType, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_SLOTS, + std::bind( + &AnsManagerStub::HandleGetSlots, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::GET_SLOT_GROUP, + std::bind(&AnsManagerStub::HandleGetSlotGroup, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_SLOT_GROUPS, + std::bind(&AnsManagerStub::HandleGetSlotGroups, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::REMOVE_SLOT_GROUPS, + std::bind(&AnsManagerStub::HandleRemoveSlotGroups, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_ACTIVE_NOTIFICATIONS, + std::bind(&AnsManagerStub::HandleGetActiveNotifications, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_ACTIVE_NOTIFICATION_NUMS, + std::bind(&AnsManagerStub::HandleGetActiveNotificationNums, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_ALL_ACTIVE_NOTIFICATIONS, + std::bind(&AnsManagerStub::HandleGetAllActiveNotifications, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_SPECIAL_ACTIVE_NOTIFICATIONS, + std::bind(&AnsManagerStub::HandleGetSpecialActiveNotifications, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::SET_NOTIFICATION_AGENT, + std::bind(&AnsManagerStub::HandleSetNotificationAgent, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_NOTIFICATION_AGENT, + std::bind(&AnsManagerStub::HandleGetNotificationAgent, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::CAN_PUBLISH_AS_BUNDLE, + std::bind(&AnsManagerStub::HandleCanPublishAsBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::PUBLISH_AS_BUNDLE, + std::bind(&AnsManagerStub::HandlePublishAsBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::SET_NOTIFICATION_BADGE_NUM, + std::bind(&AnsManagerStub::HandleSetNotificationBadgeNum, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_BUNDLE_IMPORTANCE, + std::bind(&AnsManagerStub::HandleGetBundleImportance, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::SET_DISTURB_MODE, + std::bind(&AnsManagerStub::HandleSetDisturbMode, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_DISTURB_MODE, + std::bind(&AnsManagerStub::HandleGetDisturbMode, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::IS_NOTIFICATION_POLICY_ACCESS_GRANTED, + std::bind(&AnsManagerStub::HandleIsNotificationPolicyAccessGranted, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::SET_PRIVATIVE_NOTIFICATIONS_ALLOWED, + std::bind(&AnsManagerStub::HandleSetPrivateNotificationsAllowed, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::GET_PRIVATIVE_NOTIFICATIONS_ALLOWED, + std::bind(&AnsManagerStub::HandleGetPrivateNotificationsAllowed, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::DELETE_NOTIFICATION, + std::bind( + &AnsManagerStub::HandleDelete, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::DELETE_NOTIFICATION_BY_BUNDLE, + std::bind(&AnsManagerStub::HandleDeleteByBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::DELETE_ALL_NOTIFICATIONS, + std::bind( + &AnsManagerStub::HandleDeleteAll, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::GET_SLOTS_BY_BUNDLE, + std::bind(&AnsManagerStub::HandleGetSlotsByBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::UPDATE_SLOTS, + std::bind(&AnsManagerStub::HandleUpdateSlots, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::UPDATE_SLOT_GROUPS, + std::bind(&AnsManagerStub::HandleUpdateSlotGroups, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::SET_NOTIFICATION_ENABLED_FOR_BUNDLE, + std::bind(&AnsManagerStub::HandleSetNotificationsEnabledForBundle, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, + std::bind(&AnsManagerStub::HandleSetNotificationsEnabledForSpecialBundle, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, + std::bind(&AnsManagerStub::HandleSetShowBadgeEnabledForBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, + std::bind(&AnsManagerStub::HandleGetShowBadgeEnabledForBundle, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::SUBSCRIBE_NOTIFICATION, + std::bind( + &AnsManagerStub::HandleSubscribe, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, + {AnsManagerStub::UNSUBSCRIBE_NOTIFICATION, + std::bind(&AnsManagerStub::HandleUnsubscribe, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::ARE_NOTIFICATION_SUSPENDED, + std::bind(&AnsManagerStub::HandleAreNotificationsSuspended, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, + {AnsManagerStub::GET_CURRENT_APP_SORTING, + std::bind(&AnsManagerStub::HandleGetCurrentAppSorting, std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)}, +}; + +AnsManagerStub::AnsManagerStub() +{} + +AnsManagerStub::~AnsManagerStub() +{} + +int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &flags) +{ + std::u16string descriptor = AnsManagerStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + ANS_LOGW("[OnRemoteRequest] fail: invalid interface token!"); + return OBJECT_NULL; + } + + auto it = interfaces_.find(code); + if (it == interfaces_.end()) { + ANS_LOGW("[OnRemoteRequest] fail: unknown code!"); + return IRemoteStub::OnRemoteRequest(code, data, reply, flags); + } + + auto fun = it->second; + if (fun == nullptr) { + ANS_LOGW("[OnRemoteRequest] fail: not find function!"); + return IRemoteStub::OnRemoteRequest(code, data, reply, flags); + } + + ErrCode result = fun(this, data, reply); + if (SUCCEEDED(result)) { + return NO_ERROR; + } + + ANS_LOGW("[OnRemoteRequest] fail: Failed to call interface %{public}u, err:%{public}d", code, result); + return result; +} + +ErrCode AnsManagerStub::HandlePublish(MessageParcel &data, MessageParcel &reply) +{ + std::string label; + if (!data.ReadString(label)) { + ANS_LOGW("[HandlePublish] fail: read label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandlePublish] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = Publish(label, notification); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandlePublish] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandlePublishToDevice(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandlePublishToDevice] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string deviceId; + if (!data.ReadString(deviceId)) { + ANS_LOGW("[HandlePublishToDevice] fail: read deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = PublishToDevice(notification, deviceId); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandlePublishToDevice] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleCancel(MessageParcel &data, MessageParcel &reply) +{ + int notificationId = 0; + if (!data.ReadInt32(notificationId)) { + ANS_LOGW("[HandleCancel] fail: read notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string label; + if (!data.ReadString(label)) { + ANS_LOGW("[HandleCancel] fail: read label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = Cancel(notificationId, label); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleCancel] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleCancelAll(MessageParcel &data, MessageParcel &reply) +{ + ErrCode result = CancelAll(); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleCancelAll] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleAddSlots(MessageParcel &data, MessageParcel &reply) +{ + std::vector> slots; + if (!ReadParcelableVector(slots, data)) { + ANS_LOGW("[HandleAddSlots] fail: read slotsSize failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = AddSlots(slots); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleAddSlots] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleRemoveSlots(MessageParcel &data, MessageParcel &reply) +{ + std::vector slotIds; + if (!data.ReadStringVector(&slotIds)) { + ANS_LOGW("[HandleRemoveSlots] fail: read slotIds failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveSlots(slotIds); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveSlots] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleRemoveSlotByType(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::SlotType slotType = static_cast(data.ReadInt32()); + + ErrCode result = RemoveSlotByType(slotType); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveSlotByType] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleAddSlotGroups(MessageParcel &data, MessageParcel &reply) +{ + std::vector> groups; + if (!ReadParcelableVector(groups, data)) { + ANS_LOGW("[HandleAddSlotGroups] fail: read slotsSize failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = AddSlotGroups(groups); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleAddSlotGroups] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlot(MessageParcel &data, MessageParcel &reply) +{ + std::string slotId; + if (!data.ReadString(slotId)) { + ANS_LOGW("[HandleGetSlot] fail: read slotId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr slot; + ErrCode result = GetSlot(slotId, slot); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetSlot] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteParcelable(slot)) { + ANS_LOGW("[HandleGetSlot] fail: write slot failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlots(MessageParcel &data, MessageParcel &reply) +{ + std::vector> slots; + ErrCode result = GetSlots(slots); + + if (!WriteParcelableVector(slots, reply, result)) { + ANS_LOGW("[HandleGetSlots] fail: write slots failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlotByType(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::SlotType slotType = static_cast(data.ReadInt32()); + + sptr slot; + ErrCode result = GetSlotByType(slotType, slot); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetSlotByType] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteParcelable(slot)) { + ANS_LOGW("[HandleGetSlotByType] fail: write slot failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlotGroup(MessageParcel &data, MessageParcel &reply) +{ + std::string groupId; + if (!data.ReadString(groupId)) { + ANS_LOGW("[HandleGetSlotGroup] fail: read groupId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr group; + ErrCode result = GetSlotGroup(groupId, group); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetSlotGroup] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteParcelable(group)) { + ANS_LOGW("[HandleGetSlotGroup] fail: write group failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlotGroups(MessageParcel &data, MessageParcel &reply) +{ + std::vector> groups; + ErrCode result = GetSlotGroups(groups); + + if (!WriteParcelableVector(groups, reply, result)) { + ANS_LOGW("[HandleGetSlotGroups] fail: write groups failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleRemoveSlotGroups(MessageParcel &data, MessageParcel &reply) +{ + std::vector groupIds; + if (!data.ReadStringVector(&groupIds)) { + ANS_LOGW("[HandleRemoveSlotGroups] fail: read groupIds failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveSlotGroups(groupIds); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveSlotGroups] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetActiveNotifications(MessageParcel &data, MessageParcel &reply) +{ + std::vector> notifications; + ErrCode result = GetActiveNotifications(notifications); + + if (!WriteParcelableVector(notifications, reply, result)) { + ANS_LOGW("[HandleGetActiveNotifications] fail: write notifications failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetActiveNotificationNums(MessageParcel &data, MessageParcel &reply) +{ + int num = 0; + ErrCode result = GetActiveNotificationNums(num); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetActiveNotificationNums] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteInt32(num)) { + ANS_LOGW("[HandleGetActiveNotificationNums] fail: write num failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetAllActiveNotifications(MessageParcel &data, MessageParcel &reply) +{ + std::vector> notifications; + ErrCode result = GetAllActiveNotifications(notifications); + + if (!WriteParcelableVector(notifications, reply, result)) { + ANS_LOGW("[HandleGetAllActiveNotifications] fail: write notifications failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSpecialActiveNotifications(MessageParcel &data, MessageParcel &reply) +{ + std::vector key; + if (!data.ReadStringVector(&key)) { + ANS_LOGW("[HandleGetSpecialActiveNotifications] fail: read key failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::vector> notifications; + ErrCode result = GetAllActiveNotifications(notifications); + + if (!WriteParcelableVector(notifications, reply, result)) { + ANS_LOGW("[HandleGetSpecialActiveNotifications] fail: write notifications failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetNotificationAgent(MessageParcel &data, MessageParcel &reply) +{ + std::string agent; + if (!data.ReadString(agent)) { + ANS_LOGW("[HandleSetNotificationAgent] fail: read agent failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetNotificationAgent(agent); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetNotificationAgent] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetNotificationAgent(MessageParcel &data, MessageParcel &reply) +{ + std::string agent; + ErrCode result = GetNotificationAgent(agent); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetNotificationAgent] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteString(agent)) { + ANS_LOGW("[HandleGetNotificationAgent] fail: write agent failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleCanPublishAsBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string representativeBundle; + if (!data.ReadString(representativeBundle)) { + ANS_LOGW("[HandleCanPublishAsBundle] fail: read representativeBundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool canPublish = false; + ErrCode result = CanPublishAsBundle(representativeBundle, canPublish); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleCanPublishAsBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(canPublish)) { + ANS_LOGW("[HandleCanPublishAsBundle] fail: write canPublish failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandlePublishAsBundle(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandlePublishAsBundle] fail: read notification failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string representativeBundle; + if (!data.ReadString(representativeBundle)) { + ANS_LOGW("[HandlePublishAsBundle] fail: read representativeBundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = PublishAsBundle(notification, representativeBundle); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandlePublishAsBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetNotificationBadgeNum(MessageParcel &data, MessageParcel &reply) +{ + int num = 0; + if (!data.ReadInt32(num)) { + ANS_LOGW("[HandleSetNotificationBadgeNum] fail: read notification failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetNotificationBadgeNum(num); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetNotificationBadgeNum] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetBundleImportance(MessageParcel &data, MessageParcel &reply) +{ + int importance = 0; + ErrCode result = GetBundleImportance(importance); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetBundleImportance] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteInt32(importance)) { + ANS_LOGW("[HandleGetBundleImportance] fail: write importance failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetDisturbMode(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::DisturbMode mode = static_cast(data.ReadInt32()); + ErrCode result = SetDisturbMode(mode); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetDisturbMode(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::DisturbMode mode; + ErrCode result = GetDisturbMode(mode); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteInt32(mode)) { + ANS_LOGW("[HandleGetDisturbMode] fail: write mode failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleIsNotificationPolicyAccessGranted(MessageParcel &data, MessageParcel &reply) +{ + bool granted = false; + ErrCode result = HasNotificationPolicyAccessPermission(granted); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleIsNotificationPolicyAccessGranted] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(granted)) { + ANS_LOGW("[HandleIsNotificationPolicyAccessGranted] fail: write granted failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply) +{ + bool allow = false; + if (!reply.ReadBool(allow)) { + ANS_LOGW("[HandleSetPrivateNotificationsAllowed] fail: read allow failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetPrivateNotificationsAllowed(allow); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetPrivateNotificationsAllowed] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply) +{ + bool allow = false; + ErrCode result = GetPrivateNotificationsAllowed(allow); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetPrivateNotificationsAllowed] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleDelete(MessageParcel &data, MessageParcel &reply) +{ + std::string key; + if (!data.ReadString(key)) { + ANS_LOGW("[HandleDelete] fail: read key failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = Delete(key); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleDelete] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleDeleteByBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleDeleteByBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = DeleteByBundle(bundle); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleDeleteByBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleDeleteAll(MessageParcel &data, MessageParcel &reply) +{ + ErrCode result = DeleteAll(); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleDeleteAll] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetSlotsByBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleGetSlotsByBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::vector> slots; + ErrCode result = GetSlotsByBundle(bundle, slots); + if (!WriteParcelableVector(slots, reply, result)) { + ANS_LOGW("[HandleGetSlotsByBundle] fail: write slots failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleUpdateSlots(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleUpdateSlots] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::vector> slots; + if (!ReadParcelableVector(slots, data)) { + ANS_LOGW("[HandleUpdateSlots] fail: read slots failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = UpdateSlots(bundle, slots); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleUpdateSlots] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleUpdateSlotGroups(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleUpdateSlotGroups] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::vector> groups; + if (!ReadParcelableVector(groups, data)) { + ANS_LOGW("[HandleUpdateSlotGroups] fail: read groups failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = UpdateSlotGroups(bundle, groups); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleUpdateSlotGroups] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetNotificationsEnabledForBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceId; + if (!data.ReadString(deviceId)) { + ANS_LOGW("[HandleSetNotificationsEnabledForBundle] fail: read deviceId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleSetNotificationsEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetNotificationsEnabledForBundle(deviceId, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetNotificationsEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetNotificationsEnabledForAllBundles(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceId; + if (!data.ReadString(deviceId)) { + ANS_LOGW("[HandleSetNotificationsEnabledForAllBundles] fail: read deviceId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleSetNotificationsEnabledForAllBundles] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetNotificationsEnabledForAllBundles(deviceId, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetNotificationsEnabledForAllBundles] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetNotificationsEnabledForSpecialBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string deviceId; + if (!data.ReadString(deviceId)) { + ANS_LOGW("[HandleSetNotificationsEnabledForSpecialBundle] fail: read deviceId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleSetNotificationsEnabledForSpecialBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleSetNotificationsEnabledForSpecialBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW( + "[HandleSetNotificationsEnabledForSpecialBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleSetShowBadgeEnabledForBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleSetShowBadgeEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetShowBadgeEnabledForBundle(bundle, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSetShowBadgeEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetShowBadgeEnabledForBundle(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + ErrCode result = GetShowBadgeEnabledForBundle(bundle, enabled); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(enabled)) { + ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: write enabled failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleSubscribe(MessageParcel &data, MessageParcel &reply) +{ + sptr subscriber = data.ReadRemoteObject(); + if (subscriber == nullptr) { + ANS_LOGW("[HandleSubscribe] fail: read subscriber failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool subcribeInfo; + if (!data.ReadBool(subcribeInfo)) { + ANS_LOGW("[HandleSubscribe] fail: read isSubcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr info = nullptr; + if (subcribeInfo) { + info = data.ReadParcelable(); + if (info == nullptr) { + ANS_LOGW("[HandleSubscribe] fail: read info failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + ErrCode result = Subscribe(iface_cast(subscriber), info); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleSubscribe] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleUnsubscribe(MessageParcel &data, MessageParcel &reply) +{ + sptr subscriber = data.ReadRemoteObject(); + if (subscriber == nullptr) { + ANS_LOGW("[HandleUnsubscribe] fail: read subscriber failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool subcribeInfo; + if (!data.ReadBool(subcribeInfo)) { + ANS_LOGW("[HandleUnsubscribe] fail: read isSubcribeInfo failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr info = nullptr; + if (subcribeInfo) { + info = data.ReadParcelable(); + if (info == nullptr) { + ANS_LOGW("[HandleUnsubscribe] fail: read info failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + ErrCode result = Unsubscribe(iface_cast(subscriber), info); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleUnsubscribe] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleAreNotificationsSuspended(MessageParcel &data, MessageParcel &reply) +{ + bool suspended = false; + ErrCode result = AreNotificationsSuspended(suspended); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleAreNotificationsSuspended] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(suspended)) { + ANS_LOGW("[HandleAreNotificationsSuspended] fail: write suspended failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetCurrentAppSorting(MessageParcel &data, MessageParcel &reply) +{ + sptr sortingMap; + ErrCode result = GetCurrentAppSorting(sortingMap); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetCurrentAppSorting] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteParcelable(sortingMap)) { + ANS_LOGW("[HandleGetCurrentAppSorting] fail: write sortingMap failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply) +{ + bool allowed = false; + ErrCode result = IsAllowedNotify(allowed); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleIsAllowedNotify] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(allowed)) { + ANS_LOGW("[HandleIsAllowedNotify] fail: write allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) +{ + std::string bundle; + if (!data.ReadString(bundle)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool allowed = false; + ErrCode result = IsSpecialBundleAllowedNotify(bundle, allowed); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(allowed)) { + ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +template +bool AnsManagerStub::WriteParcelableVector( + const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) +{ + if (!reply.WriteInt32(result)) { + ANS_LOGW("write result failed, ErrCode=%{public}d", result); + return false; + } + + if (!reply.WriteInt32(parcelableVector.size())) { + ANS_LOGW("write ParcelableVector size failed"); + return false; + } + + for (auto &parcelable : parcelableVector) { + if (!reply.WriteStrongParcelable(parcelable)) { + ANS_LOGW("write ParcelableVector failed"); + return false; + } + } + return true; +} + +template +bool AnsManagerStub::ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &data) +{ + int32_t infoSize = 0; + if (!data.ReadInt32(infoSize)) { + ANS_LOGW("read Parcelable size failed."); + return false; + } + + parcelableInfos.clear(); + for (int32_t index = 0; index < infoSize; index++) { + sptr info = data.ReadStrongParcelable(); + if (info == nullptr) { + ANS_LOGW("read Parcelable infos failed."); + return false; + } + parcelableInfos.emplace_back(info); + } + + return true; +} + +ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) +{ + ANS_LOGW("AnsManagerStub::Publish called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::PublishToDevice(const sptr ¬ification, const std::string &deviceId) +{ + ANS_LOGW("AnsManagerStub::PublishToDevice called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::Cancel(int notificationId, const std::string &label) +{ + ANS_LOGW("AnsManagerStub::Cancel called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::CancelAll() +{ + ANS_LOGW("AnsManagerStub::CancelAll called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::AddSlots(const std::vector> &slots) +{ + ANS_LOGW("AnsManagerStub::AddSlots called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::RemoveSlots(const std::vector &slotIds) +{ + ANS_LOGW("AnsManagerStub::RemoveSlots called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::RemoveSlotByType(const NotificationConstant::SlotType slotType) +{ + ANS_LOGW("AnsManagerStub::RemoveSlotByType called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::AddSlotGroups(std::vector> groups) +{ + ANS_LOGW("AnsManagerStub::AddSlotGroups called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlot(const std::string &slotId, sptr &slot) +{ + ANS_LOGW("AnsManagerStub::GetSlot called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) +{ + ANS_LOGW("AnsManagerStub::GetSlotByType called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlots(std::vector> &slots) +{ + ANS_LOGW("AnsManagerStub::GetSlots called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlotGroup(const std::string &groupId, sptr &group) +{ + ANS_LOGW("AnsManagerStub::GetSlotGroup called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlotGroups(std::vector> &groups) +{ + ANS_LOGW("AnsManagerStub::GetSlotGroups called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::RemoveSlotGroups(const std::vector &groupIds) +{ + ANS_LOGW("AnsManagerStub::RemoveSlotGroups called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetActiveNotifications(std::vector> ¬ifications) +{ + ANS_LOGW("AnsManagerStub::GetActiveNotifications called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetActiveNotificationNums(int &num) +{ + ANS_LOGW("AnsManagerStub::GetActiveNotificationNums called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetAllActiveNotifications(std::vector> ¬ifications) +{ + ANS_LOGW("AnsManagerStub::GetAllActiveNotifications called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) +{ + ANS_LOGW("AnsManagerStub::GetSpecialActiveNotifications called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetNotificationAgent(const std::string &agent) +{ + ANS_LOGW("AnsManagerStub::SetNotificationAgent called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetNotificationAgent(std::string &agent) +{ + ANS_LOGW("AnsManagerStub::GetNotificationAgent called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) +{ + ANS_LOGW("AnsManagerStub::CanPublishAsBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::PublishAsBundle( + const sptr notification, const std::string &representativeBundle) +{ + ANS_LOGW("AnsManagerStub::PublishAsBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetNotificationBadgeNum(int num) +{ + ANS_LOGW("AnsManagerStub::SetNotificationBadgeNum called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetBundleImportance(int &importance) +{ + ANS_LOGW("AnsManagerStub::GetBundleImportance called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetDisturbMode(NotificationConstant::DisturbMode mode) +{ + ANS_LOGW("AnsManagerStub::SetDisturbMode called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetDisturbMode(NotificationConstant::DisturbMode &mode) +{ + ANS_LOGW("AnsManagerStub::GetDisturbMode called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::HasNotificationPolicyAccessPermission(bool &granted) +{ + ANS_LOGW("AnsManagerStub::HasNotificationPolicyAccessPermission called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetPrivateNotificationsAllowed(bool allow) +{ + ANS_LOGW("AnsManagerStub::SetPrivateNotificationsAllowed called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetPrivateNotificationsAllowed(bool &allow) +{ + ANS_LOGW("AnsManagerStub::GetPrivateNotificationsAllowed called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::Delete(const std::string &key) +{ + ANS_LOGW("AnsManagerStub::Delete called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::DeleteByBundle(const std::string &bundle) +{ + ANS_LOGW("AnsManagerStub::DeleteByBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::DeleteAll() +{ + ANS_LOGW("AnsManagerStub::DeleteAll called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetSlotsByBundle(const std::string &bundle, std::vector> &slots) +{ + ANS_LOGW("AnsManagerStub::GetSlotsByBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::UpdateSlots(const std::string &bundle, const std::vector> &slots) +{ + ANS_LOGW("AnsManagerStub::UpdateSlots called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) +{ + ANS_LOGW("AnsManagerStub::UpdateSlotGroups called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) +{ + ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForAllBundles called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) +{ + ANS_LOGW("AnsManagerStub::SetNotificationsEnabledForSpecialBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +{ + ANS_LOGW("AnsManagerStub::SetShowBadgeEnabledForBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +{ + ANS_LOGW("AnsManagerStub::GetShowBadgeEnabledForBundle called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::Subscribe(const sptr &subscriber, const sptr &info) +{ + ANS_LOGW("AnsManagerStub::Subscribe called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::Unsubscribe(const sptr &subscriber, const sptr &info) +{ + ANS_LOGW("AnsManagerStub::Unsubscribe called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::AreNotificationsSuspended(bool &suspended) +{ + ANS_LOGW("AnsManagerStub::AreNotificationsSuspended called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::GetCurrentAppSorting(sptr &sortingMap) +{ + ANS_LOGW("AnsManagerStub::GetCurrentAppSorting called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::IsAllowedNotify(bool &allowed) +{ + ANS_LOGW("AnsManagerStub::IsAllowedNotify called!"); + return ERR_OK; +} + +ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +{ + ANS_LOGW("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); + return ERR_OK; +} + +} // namespace Notification +} // namespace OHOS diff --git a/innerkits/core/src/ans_notification.cpp b/innerkits/core/src/ans_notification.cpp new file mode 100644 index 000000000..fc521dbf1 --- /dev/null +++ b/innerkits/core/src/ans_notification.cpp @@ -0,0 +1,656 @@ +/* + * Copyright (c) 2021 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 "ans_notification.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "notification_request.h" +#include "notification_sorting.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +ErrCode AnsNotification::AddNotificationSlot(const NotificationSlot &slot) +{ + std::vector slots; + slots.push_back(slot); + return AddNotificationSlots(slots); +} + +ErrCode AnsNotification::AddNotificationSlots(const std::vector &slots) +{ + if (slots.size() == 0) { + ANS_LOGE("Failed to add notification slots because input slots size is 0."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + std::vector> slotsSptr; + for (auto it = slots.begin(); it != slots.end(); ++it) { + sptr slot = new NotificationSlot(*it); + if (slot == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr."); + return ERR_ANS_NO_MEMORY; + } + slotsSptr.emplace_back(slot); + } + + return ansManagerProxy_->AddSlots(slotsSptr); +} + +ErrCode AnsNotification::RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->RemoveSlotByType(slotType); +} + +ErrCode AnsNotification::GetNotificationSlot( + const NotificationConstant::SlotType &slotType, sptr &slot) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSlotByType(slotType, slot); +} + +ErrCode AnsNotification::GetNotificationSlots(std::vector> &slots) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSlots(slots); +} + +ErrCode AnsNotification::AddNotificationSlotGroup(const NotificationSlotGroup &slotGroup) +{ + std::vector slotGroups; + slotGroups.emplace_back(slotGroup); + return AddNotificationSlotGroups(slotGroups); +} + +ErrCode AnsNotification::AddNotificationSlotGroups(const std::vector &slotGroups) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + std::vector> slotGroupsSptr; + for (auto it = slotGroups.begin(); it != slotGroups.end(); ++it) { + sptr slotGroup = new NotificationSlotGroup((*it).GetId(), (*it).GetName()); + if (slotGroup == nullptr) { + ANS_LOGE("Failed to add notification slot groups with NotificationSlotGroup nullptr"); + return ERR_ANS_NO_MEMORY; + } + slotGroupsSptr.emplace_back(slotGroup); + } + + return ansManagerProxy_->AddSlotGroups(slotGroupsSptr); +} + +ErrCode AnsNotification::RemoveNotificationSlotGroup(const std::string &slotGroupId) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + std::vector slotGroupIds; + slotGroupIds.emplace_back(slotGroupId); + return ansManagerProxy_->RemoveSlotGroups(slotGroupIds); +} + +ErrCode AnsNotification::GetNotificationSlotGroup(const std::string &groupId, sptr &group) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSlotGroup(groupId, group); +} + +ErrCode AnsNotification::GetNotificationSlotGroups(std::vector> &groups) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSlotGroups(groups); +} + +ErrCode AnsNotification::PublishNotification(const NotificationRequest &request) +{ + ANS_LOGI("enter"); + return PublishNotification(std::string(), request); +} + +ErrCode AnsNotification::PublishNotification(const std::string &label, const NotificationRequest &request) +{ + ANS_LOGI("enter"); + + if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { + ANS_LOGE("Refuse to publish the notification without valid content"); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the sequence numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr reqPtr = new (std::nothrow) NotificationRequest(request); + if (reqPtr == nullptr) { + ANS_LOGE("Failed to create NotificationRequest ptr"); + return ERR_ANS_NO_MEMORY; + } + return ansManagerProxy_->Publish(label, reqPtr); +} + +ErrCode AnsNotification::PublishNotification(const NotificationRequest &request, const std::string &deviceId) +{ + if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { + ANS_LOGE("Refuse to publish the notification without valid content"); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the sequence numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr reqPtr = new (std::nothrow) NotificationRequest(request); + if (reqPtr == nullptr) { + ANS_LOGE("Failed to create NotificationRequest ptr"); + return ERR_ANS_NO_MEMORY; + } + return ansManagerProxy_->PublishToDevice(reqPtr, deviceId); +} + +ErrCode AnsNotification::CancelNotification(int32_t notificationId) +{ + return CancelNotification("", notificationId); +} + +ErrCode AnsNotification::CancelNotification(const std::string &label, int32_t notificationId) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->Cancel(notificationId, label); +} + +ErrCode AnsNotification::CancelAllNotifications() +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->CancelAll(); +} + +ErrCode AnsNotification::GetActiveNotificationNums(int32_t &num) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetActiveNotificationNums(num); +} + +ErrCode AnsNotification::GetActiveNotifications(std::vector> &request) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetActiveNotifications(request); +} + +ErrCode AnsNotification::GetCurrentAppSorting(sptr &sortingMap) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetCurrentAppSorting(sortingMap); +} + +ErrCode AnsNotification::SetNotificationAgent(const std::string &agent) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationAgent(agent); +} + +ErrCode AnsNotification::GetNotificationAgent(std::string &agent) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetNotificationAgent(agent); +} + +ErrCode AnsNotification::CanPublishNotificationAsBundle(const std::string &representativeBundle, bool &canPublish) +{ + if (representativeBundle.empty()) { + ANS_LOGW("Input representativeBundle is empty"); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->CanPublishAsBundle(representativeBundle, canPublish); +} + +ErrCode AnsNotification::PublishNotificationAsBundle( + const std::string &representativeBundle, const NotificationRequest &request) +{ + if (representativeBundle.empty()) { + ANS_LOGE("Refuse to publish the notification whit invalid representativeBundle"); + return ERR_ANS_INVALID_PARAM; + } + + if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { + ANS_LOGE("Refuse to publish the notification without valid content"); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the sequence numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr reqPtr = new (std::nothrow) NotificationRequest(request); + if (reqPtr == nullptr) { + ANS_LOGE("Failed to create NotificationRequest ptr"); + return ERR_ANS_NO_MEMORY; + } + return ansManagerProxy_->PublishAsBundle(reqPtr, representativeBundle); +} + +ErrCode AnsNotification::SetNotificationBadgeNum() +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + int32_t num = -1; + return ansManagerProxy_->SetNotificationBadgeNum(num); +} + +ErrCode AnsNotification::SetNotificationBadgeNum(int32_t num) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationBadgeNum(num); +} + +ErrCode AnsNotification::IsAllowedNotify(bool &allowed) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->IsAllowedNotify(allowed); +} + +ErrCode AnsNotification::AreNotificationsSuspended(bool &suspended) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->AreNotificationsSuspended(suspended); +} + +ErrCode AnsNotification::HasNotificationPolicyAccessPermission(bool &hasPermission) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->HasNotificationPolicyAccessPermission(hasPermission); +} + +ErrCode AnsNotification::GetBundleImportance(NotificationSlot::NotificationLevel &importance) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + int importanceTemp; + ErrCode ret = ansManagerProxy_->GetBundleImportance(importanceTemp); + if ((NotificationSlot::LEVEL_NONE <= importanceTemp) && (importanceTemp <= NotificationSlot::LEVEL_HIGH)) { + importance = static_cast(importanceTemp); + } else { + importance = NotificationSlot::LEVEL_UNDEFINED; + } + return ret; +} + +ErrCode AnsNotification::SubscribeNotification(const NotificationSubscriber &subscriber) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr subscriberSptr = subscriber.GetImpl(); + if (subscriberSptr == nullptr) { + ANS_LOGE("Failed to subscribe with SubscriberImpl null ptr."); + return ERR_ANS_INVALID_PARAM; + } + return ansManagerProxy_->Subscribe(subscriberSptr, nullptr); +} + +ErrCode AnsNotification::SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr sptrInfo = new (std::nothrow) NotificationSubscribeInfo(subscribeInfo); + if (sptrInfo == nullptr) { + ANS_LOGE("Failed to create NotificationSubscribeInfo ptr."); + return ERR_ANS_NO_MEMORY; + } + + sptr subscriberSptr = subscriber.GetImpl(); + if (subscriberSptr == nullptr) { + ANS_LOGE("Failed to subscribe with SubscriberImpl null ptr."); + return ERR_ANS_INVALID_PARAM; + } + return ansManagerProxy_->Subscribe(subscriberSptr, sptrInfo); +} + +ErrCode AnsNotification::UnSubscribeNotification(NotificationSubscriber &subscriber) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr subscriberSptr = subscriber.GetImpl(); + if (subscriberSptr == nullptr) { + ANS_LOGE("Failed to unsubscribe with SubscriberImpl null ptr."); + return ERR_ANS_INVALID_PARAM; + } + return ansManagerProxy_->Unsubscribe(subscriberSptr, nullptr); +} + +ErrCode AnsNotification::UnSubscribeNotification( + NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr sptrInfo = new (std::nothrow) NotificationSubscribeInfo(subscribeInfo); + if (sptrInfo == nullptr) { + ANS_LOGE("Failed to create NotificationSubscribeInfo ptr."); + return ERR_ANS_NO_MEMORY; + } + + sptr subscriberSptr = subscriber.GetImpl(); + if (subscriberSptr == nullptr) { + ANS_LOGE("Failed to unsubscribe with SubscriberImpl null ptr."); + return ERR_ANS_INVALID_PARAM; + } + return ansManagerProxy_->Unsubscribe(subscriberSptr, sptrInfo); +} + +ErrCode AnsNotification::RemoveNotification(const std::string &key) +{ + if (key.empty()) { + ANS_LOGW("Input key is empty."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->Delete(key); +} + +ErrCode AnsNotification::RemoveNotifications(const std::string &bundleName) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->DeleteByBundle(bundleName); +} + +ErrCode AnsNotification::RemoveNotifications() +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->DeleteAll(); +} + +ErrCode AnsNotification::GetNotificationSlotsForBundle( + const std::string &bundleName, std::vector> &slots) +{ + if (bundleName.empty()) { + ANS_LOGE("Input bundleName is empty."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSlotsByBundle(bundleName, slots); +} + +ErrCode AnsNotification::GetAllActiveNotifications(std::vector> ¬ification) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetAllActiveNotifications(notification); +} + +ErrCode AnsNotification::GetAllActiveNotifications( + const std::vector key, std::vector> ¬ification) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetSpecialActiveNotifications(key, notification); +} + +ErrCode AnsNotification::IsAllowedNotify(const std::string &bundle, bool &allowed) +{ + if (bundle.empty()) { + ANS_LOGE("Input bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->IsSpecialBundleAllowedNotify(bundle, allowed); +} + +ErrCode AnsNotification::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationsEnabledForAllBundles(deviceId, enabled); +} + +ErrCode AnsNotification::SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationsEnabledForBundle(deviceId, enabled); +} + +ErrCode AnsNotification::SetNotificationsEnabledForSpecifiedBundle( + const std::string &bundle, const std::string &deviceId, bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); +} + +ErrCode AnsNotification::SetDisturbMode(NotificationConstant::DisturbMode mode) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->SetDisturbMode(mode); +} + +ErrCode AnsNotification::GetDisturbMode(NotificationConstant::DisturbMode &disturbMode) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetDisturbMode(disturbMode); +} + +void AnsNotification::ResetAnsManagerProxy() +{ + ANS_LOGI("enter"); + std::lock_guard lock(mutex_); + if ((ansManagerProxy_ != nullptr) && (ansManagerProxy_->AsObject() != nullptr)) { + ansManagerProxy_->AsObject()->RemoveDeathRecipient(recipient_); + } + ansManagerProxy_ = nullptr; +} + +bool AnsNotification::GetAnsManagerProxy() +{ + if (!ansManagerProxy_) { + std::lock_guard lock(mutex_); + if (!ansManagerProxy_) { + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + ANS_LOGE("Failed to get system ability mgr."); + return false; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (!remoteObject) { + ANS_LOGE("Failed to get notification Manager."); + return false; + } + + ansManagerProxy_ = iface_cast(remoteObject); + if ((!ansManagerProxy_) || (!ansManagerProxy_->AsObject())) { + ANS_LOGE("Failed to get notification Manager's proxy"); + return false; + } + + recipient_ = new AnsManagerDeathRecipient(); + if (!recipient_) { + ANS_LOGE("Failed to create death recipient"); + return false; + } + ansManagerProxy_->AsObject()->AddDeathRecipient(recipient_); + } + } + + return true; +} + +bool AnsNotification::CanPublishMediaContent(const NotificationRequest &request) const +{ + if (NotificationContent::Type::MEDIA != request.GetNotificationType()) { + return true; + } + + if (request.GetContent() == nullptr) { + ANS_LOGE("Failed to publish notification with null content."); + return false; + } + + auto media = std::static_pointer_cast(request.GetContent()->GetNotificationContent()); + if (media == nullptr) { + ANS_LOGE("Failed to get media content."); + return false; + } + + auto showActions = media->GetShownActions(); + uint32_t size = request.GetActionButtons().size(); + for (auto it = showActions.begin(); it != showActions.end(); ++it) { + if (*it > size) { + ANS_LOGE("The sequence numbers actions is: %{public}d, the assigned to added action buttons size is: " + "%{public}d.", + *it, + size); + return false; + } + } + + return true; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/innerkits/core/src/ans_subscriber_proxy.cpp b/innerkits/core/src/ans_subscriber_proxy.cpp new file mode 100644 index 000000000..f42f9a8c3 --- /dev/null +++ b/innerkits/core/src/ans_subscriber_proxy.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2021 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 "ans_subscriber_proxy.h" + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "message_option.h" +#include "message_parcel.h" + +namespace OHOS { +namespace Notification { +AnsSubscriberProxy::AnsSubscriberProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +AnsSubscriberProxy::~AnsSubscriberProxy() +{} + +ErrCode AnsSubscriberProxy::InnerTransact( + uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) +{ + auto remote = Remote(); + if (remote == nullptr) { + ANS_LOGW("[InnerTransact] fail: get Remote fail code %{public}d", code); + return ERR_DEAD_OBJECT; + } + + int err = remote->SendRequest(code, data, reply, flags); + switch (err) { + case NO_ERROR: { + return ERR_OK; + } + case DEAD_OBJECT: { + ANS_LOGW("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + return ERR_DEAD_OBJECT; + } + default: { + ANS_LOGW("[InnerTransact] fail: ipcErr=%{public}d code %{public}d", err, code); + return ERR_ANS_TRANSACT_FAILED; + } + } +} + +void AnsSubscriberProxy::OnSubscribeResult(NotificationConstant::SubscribeResult result) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnSubscribeResult] fail: write interface token failed."); + return; + } + + if (!data.WriteUint32(result)) { + ANS_LOGW("[OnSubscribeResult] fail: write result failed"); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode transactResult = InnerTransact(ON_SUBSCRIBE, option, data, reply); + if (transactResult != ERR_OK) { + ANS_LOGW("[OnSubscribeResult] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnUnsubscribeResult] fail: write interface token failed."); + return; + } + + if (!data.WriteUint32(result)) { + ANS_LOGW("[OnUnsubscribeResult] fail: write result failed"); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode transactResult = InnerTransact(ON_UNSUBSCRIBE, option, data, reply); + if (transactResult != ERR_OK) { + ANS_LOGW("[OnUnsubscribeResult] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnConsumed(const sptr ¬ification) +{ + if (notification == nullptr) { + ANS_LOGW("[OnConsumed] fail: notification is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnConsumed] fail: write interface token failed."); + return; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[OnConsumed] fail: write notification failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_CONSUMED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnConsumed] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{ + if (notification == nullptr) { + ANS_LOGW("[OnConsumed] fail: notification is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnConsumed] fail: write interface token failed."); + return; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[OnConsumed] fail: write notification failed."); + return; + } + + if (!data.WriteBool(notificationMap != nullptr)) { + ANS_LOGW("[OnConsumed] fail: write existMap failed"); + return; + } + + if (notificationMap != nullptr) { + if (!data.WriteParcelable(notificationMap)) { + ANS_LOGW("[OnConsumed] fail: write notificationMap failed"); + return; + } + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_CONSUMED_MAP, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnConsumed] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnCanceled(const sptr ¬ification) +{ + if (notification == nullptr) { + ANS_LOGW("[OnCanceled] fail: notification is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnCanceled] fail: write interface token failed."); + return; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[OnCanceled] fail: write notification failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_CANCELED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnCanceled] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) +{ + if (notification == nullptr) { + ANS_LOGW("[OnCanceled] fail: notification is nullptr."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnCanceled] fail: write interface token failed."); + return; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGW("[OnCanceled] fail: write notification failed."); + return; + } + + if (!data.WriteBool(notificationMap != nullptr)) { + ANS_LOGW("[OnCanceled] fail: write existMap failed"); + return; + } + + if (notificationMap != nullptr) { + if (!data.WriteParcelable(notificationMap)) { + ANS_LOGW("[OnCanceled] fail: write notificationMap failed"); + return; + } + } + + if (!data.WriteInt32(deleteReason)) { + ANS_LOGW("[OnCanceled] fail: write deleteReason failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_CANCELED_MAP, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnCanceled] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnUpdated(const sptr ¬ificationMap) +{ + if (notificationMap == nullptr) { + ANS_LOGW("[OnUpdated] fail: notificationMap is empty."); + return; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnUpdated] fail: write interface token failed."); + return; + } + + if (!data.WriteParcelable(notificationMap)) { + ANS_LOGW("[OnUpdated] fail: write notificationMap failed."); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_UPDATED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnUpdated] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +void AnsSubscriberProxy::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { + ANS_LOGW("[OnDisturbModeChanged] fail: write interface token failed."); + return; + } + + if (!data.WriteUint32(mode)) { + ANS_LOGW("[OnDisturbModeChanged] fail: write mode failed"); + return; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + ErrCode result = InnerTransact(ON_DISTURB_MODE_CHANGED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnDisturbModeChanged] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + return; + } +} + +} // namespace Notification +} // namespace OHOS diff --git a/innerkits/core/src/ans_subscriber_stub.cpp b/innerkits/core/src/ans_subscriber_stub.cpp new file mode 100644 index 000000000..31850df90 --- /dev/null +++ b/innerkits/core/src/ans_subscriber_stub.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 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 + +#include "ans_subscriber_stub.h" + +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "message_option.h" +#include "message_parcel.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +AnsSubscriberStub::AnsSubscriberStub() +{ + interfaces_.emplace(ON_SUBSCRIBE, + std::bind(&AnsSubscriberStub::HandleOnSubscribe, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_UNSUBSCRIBE, + std::bind(&AnsSubscriberStub::HandleOnUnsubscribe, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_CONSUMED, + std::bind(&AnsSubscriberStub::HandleOnConsumed, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_CONSUMED_MAP, + std::bind(&AnsSubscriberStub::HandleOnConsumedMap, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_CANCELED, + std::bind(&AnsSubscriberStub::HandleOnCanceled, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_CANCELED_MAP, + std::bind(&AnsSubscriberStub::HandleOnCanceledMap, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace( + ON_UPDATED, std::bind(&AnsSubscriberStub::HandleOnUpdated, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_DISTURB_MODE_CHANGED, + std::bind(&AnsSubscriberStub::HandleOnDisturbModeChanged, this, std::placeholders::_1, std::placeholders::_2)); +} + +AnsSubscriberStub::~AnsSubscriberStub() +{} + +int32_t AnsSubscriberStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &flags) +{ + std::u16string descriptor = AnsSubscriberStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + ANS_LOGW("[OnRemoteRequest] fail: invalid interface token!"); + return OBJECT_NULL; + } + + auto it = interfaces_.find(code); + if (it == interfaces_.end()) { + ANS_LOGW("[OnRemoteRequest] fail: unknown code!"); + return IRemoteStub::OnRemoteRequest(code, data, reply, flags); + } + + auto fun = it->second; + if (fun == nullptr) { + ANS_LOGW("[OnRemoteRequest] fail: not find function!"); + return IRemoteStub::OnRemoteRequest(code, data, reply, flags); + } + + fun(data, reply); + return NO_ERROR; +} + +ErrCode AnsSubscriberStub::HandleOnSubscribe(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::SubscribeResult result = + static_cast(data.ReadUint32()); + OnSubscribeResult(result); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnUnsubscribe(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::SubscribeResult result = + static_cast(data.ReadUint32()); + OnUnsubscribeResult(result); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnConsumed(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandleOnConsumed] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + OnConsumed(notification); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnConsumedMap(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandleOnConsumedMap] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool existMap; + if (!data.ReadBool(existMap)) { + ANS_LOGW("[HandleOnConsumedMap] fail: read existMap failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr notificationMap = nullptr; + if (existMap) { + notificationMap = data.ReadParcelable(); + if (notificationMap == nullptr) { + ANS_LOGW("[HandleOnConsumedMap] fail: read NotificationSortingMap failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + OnConsumed(notification, notificationMap); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnCanceled(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandleOnCanceled] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + OnCanceled(notification); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnCanceledMap(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGW("[HandleOnCanceledMap] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool existMap; + if (!data.ReadBool(existMap)) { + ANS_LOGW("[HandleOnCanceledMap] fail: read existMap failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + sptr notificationMap = nullptr; + if (existMap) { + notificationMap = data.ReadParcelable(); + if (notificationMap == nullptr) { + ANS_LOGW("[HandleOnCanceledMap] fail: read NotificationSortingMap failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + int reason = 0; + if (!data.ReadInt32(reason)) { + ANS_LOGW("[HandleOnCanceledMap] fail: read reason failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + OnCanceled(notification, notificationMap, reason); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnUpdated(MessageParcel &data, MessageParcel &reply) +{ + sptr notificationMap = data.ReadParcelable(); + if (!notificationMap) { + ANS_LOGW("[HandleOnUpdated] fail: notificationMap ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + OnUpdated(notificationMap); + return ERR_OK; +} + +ErrCode AnsSubscriberStub::HandleOnDisturbModeChanged(MessageParcel &data, MessageParcel &reply) +{ + NotificationConstant::DisturbMode mode = static_cast(data.ReadUint32()); + OnDisturbModeChanged(mode); + return ERR_OK; +} + +void AnsSubscriberStub::OnSubscribeResult(NotificationConstant::SubscribeResult result) +{} + +void AnsSubscriberStub::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +{} + +void AnsSubscriberStub::OnConsumed(const sptr ¬ification) +{} + +void AnsSubscriberStub::OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{} + +void AnsSubscriberStub::OnCanceled(const sptr ¬ification) +{} + +void AnsSubscriberStub::OnCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) +{} + +void AnsSubscriberStub::OnUpdated(const sptr ¬ificationMap) +{} + +void AnsSubscriberStub::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +{} + +} // namespace Notification +} // namespace OHOS diff --git a/kits/BUILD.gn b/kits/BUILD.gn new file mode 100644 index 000000000..e153ff42e --- /dev/null +++ b/kits/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 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. + +group("kits_target") { + deps = [ + "napi:notification", + "native:native_targets", + "native/wantagent:native_wantagent", + "wantAgent:wantagent", + ] +} diff --git a/kits/napi/BUILD.gn b/kits/napi/BUILD.gn new file mode 100644 index 000000000..7f6816f85 --- /dev/null +++ b/kits/napi/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") + +cflags = [] + +config("native_module_config") { + visibility = [ ":*" ] + + include_dirs = [] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + defines = [ + "APP_LOG_TAG = \"ANS_STANDARD\"", + "LOG_DOMAIN = 0xD001800", + ] +} + +ohos_shared_library("notification") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits/napi", + "${kits_path}/napi/include", + "//third_party/node/src", + "//third_party/libuv/include", + "//third_party/jsoncpp/include", + ] + + configs = [ ":native_module_config" ] + + sources = [ + "src/cancel.cpp", + "src/common.cpp", + "src/constant.cpp", + "src/create_subscriber.cpp", + "src/get_active.cpp", + "src/init.cpp", + "src/publish.cpp", + "src/remove.cpp", + "src/slot.cpp", + "src/subscribe.cpp", + "src/unsubscribe.cpp", + ] + + deps = [ + "${innerkits_path}:ans_innerkits", + "${kits_path}/native:ans_kits", + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/ace/napi:ace_napi", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/kits/napi/include/cancel.h b/kits/napi/include/cancel.h new file mode 100644 index 000000000..88e0d1287 --- /dev/null +++ b/kits/napi/include/cancel.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_CANCEL_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CANCEL_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int CANCEL_MAX_PARA = 3; +const int CANCEL_ALL_MAX_PARA = 1; + +struct AsyncCallbackInfoCancel { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::string label; + int id; + bool hasLabel = false; + bool isCallback = false; + int errorCode = 0; +}; + +struct paraInfoCancel { + int id = 0; + std::string label; + bool hasLabel = false; +}; + +napi_value Cancel(napi_env env, napi_callback_info info); +napi_value CancelAll(napi_env env, napi_callback_info info); +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[CANCEL_MAX_PARA], const size_t &argc, + paraInfoCancel &info, napi_ref &callback); +napi_value ParseParametersByAll( + const napi_env &env, const napi_value (&argv)[CANCEL_ALL_MAX_PARA], const size_t &argc, napi_ref &callback); +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoCancel *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CANCEL_H \ No newline at end of file diff --git a/kits/napi/include/common.h b/kits/napi/include/common.h new file mode 100644 index 000000000..cbe1d5392 --- /dev/null +++ b/kits/napi/include/common.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_COMMON_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_COMMON_H + +#include "ans_log_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "notification_helper.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const std::int32_t STR_MAX_SIZE = 64; +const int NO_ERROR = 0; +const int ERROR = -1; + +enum ContentType { + NOTIFICATION_CONTENT_BASIC_TEXT, + NOTIFICATION_CONTENT_LONG_TEXT, + NOTIFICATION_CONTENT_PICTURE, + NOTIFICATION_CONTENT_CONVERSATION, + NOTIFICATION_CONTENT_MULTILINE, + NOTIFICATION_CONTENT_MEDIA +}; + +enum SlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + OTHER_TYPES = 0xFFFF, +}; + +enum NotificationReason { + CLICK_REASON_DELETE, + CANCEL_REASON_DELETE, + CANCEL_ALL_REASON_DELETE, + ERROR_REASON_DELETE, + PACKAGE_CHANGED_REASON_DELETE, + USER_STOPPED_REASON_DELETE, + PACKAGE_BANNED_REASON_DELETE, + APP_CANCEL_REASON_DELETE, + APP_CANCEL_ALL_REASON_DELETE, + APP_CANCEL_REASON_OTHER +}; + +enum SemanticActionButton { + NONE_ACTION_BUTTON, + REPLY_ACTION_BUTTON, + READ_ACTION_BUTTON, + UNREAD_ACTION_BUTTON, + DELETE_ACTION_BUTTON, + ARCHIVE_ACTION_BUTTON, + MUTE_ACTION_BUTTON, + UNMUTE_ACTION_BUTTON, + THUMBS_UP_ACTION_BUTTON, + THUMBS_DOWN_ACTION_BUTTON, + CALL_ACTION_BUTTON +}; + +enum InputsSource { FREE_FORM_INPUT, OPTION }; + +enum DisturbMode { ALLOW_UNKNOWN, ALLOW_ALL, ALLOW_PRIORITY, ALLOW_NONE, ALLOW_ALARMS }; + +enum InputEditType { EDIT_AUTO, EDIT_DISABLED, EDIT_ENABLED }; + +struct NotificationSubscriberInfo { + std::vector bundleNames; + // std::vector deviceIds; + int userId = 0; + bool hasSubscriberInfo = false; +}; + +struct CallbackPromiseInfo { + napi_ref callback = nullptr; + napi_deferred deferred; + bool isCallback = false; + int errorCode = 0; +}; + +class Common { + + Common(); + + ~Common(); + +public: + static napi_value NapiGetboolean(napi_env env, const bool &isValue); + + static napi_value NapiGetNull(napi_env env); + + static napi_value GetCallbackErrorValue(napi_env env, int errCode); + + static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result); + + static void SetCallback( + const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result); + + static void SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result); + + static napi_value SetNotificationRequest( + const napi_env &env, const std::shared_ptr ¬ification, napi_value &result); + + static napi_value SetNotificationRequest2(const napi_env &env, + const std::shared_ptr &request, napi_value &result); + + static napi_value SetNotificationSortingMap( + const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result); + + static napi_value SetNotificationSorting( + const napi_env &env, const NotificationSorting &sorting, napi_value &result); + + static napi_value SetNotificationSlot(const napi_env &env, const NotificationSlot &slot, napi_value &result); + + static napi_value SetNotificationContent( + const napi_env &env, const std::shared_ptr &content, napi_value &result); + + static napi_value SetNotificationBasicContent( + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); + + static napi_value SetNotificationLongTextContent( + const napi_env &env, OHOS::Notification::NotificationLongTextContent *longTextContent, napi_value &result); + + // static napi_value SetNotificationPictureContent( + // const napi_env &env, OHOS::Notification::NotificationPictureContent * pictureContent, napi_value &result); + + // static napi_value SetNotificationConversationalContent(const napi_env &env, + // OHOS::Notification::NotificationConversationalContent * conversationalContent, napi_value &result); + + static napi_value SetNotificationMultiLineContent( + const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result); + + // static napi_value SetMessageUser( + // const napi_env &env, std::shared_ptr &messageUser, napi_value &result); + + // static napi_value SetConversationalMessage(const napi_env &env, + // std::shared_ptr &conversationalMessage, napi_value &result); + + static napi_value SetNotificationActionButton( + const napi_env &env, std::shared_ptr &actionButton, napi_value &result); + + static napi_value GetNotificationSubscriberInfo( + const napi_env &env, const napi_value &value, NotificationSubscriberInfo &result); + + static napi_value GetNotificationRequest( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationContent( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationSlot(const napi_env &env, NotificationSlot &slot, const napi_value &result); + + static bool ContentTypeJSToC(const enum ContentType &inType, enum NotificationContent::Type &outType); + + static bool ContentTypeCToJS(const enum NotificationContent::Type &inType, enum ContentType &outType); + + static bool SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstant::SlotType &outType); + + static bool SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, enum SlotType &outType); + + static bool ReasonCToJS(const int &inType, int &outType); + + static bool DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationConstant::DisturbMode &outType); + + static napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); + +private: + static const int ARGS_TWO = 2; + static const int PARAM0 = 0; + static const int PARAM1 = 1; +}; + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_COMMON_H \ No newline at end of file diff --git a/kits/napi/include/constant.h b/kits/napi/include/constant.h new file mode 100644 index 000000000..516b4422f --- /dev/null +++ b/kits/napi/include/constant.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CONSTANT_H + +#include "ans_log_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "notification_helper.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value NotificationReasonInit(napi_env env, napi_value exports); +napi_value SlotTypeInit(napi_env env, napi_value exports); +napi_value SemanticActionButtonInit(napi_env env, napi_value exports); +napi_value InputsSourceInit(napi_env env, napi_value exports); +napi_value DisturbModeInit(napi_env env, napi_value exports); +napi_value InputEditTypeInit(napi_env env, napi_value exports); +napi_value ContentTypeInit(napi_env env, napi_value exports); +napi_value ConstantInit(napi_env env, napi_value exports); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CONSTANT_H \ No newline at end of file diff --git a/kits/napi/include/create_subscriber.h b/kits/napi/include/create_subscriber.h new file mode 100644 index 000000000..0163fa8b0 --- /dev/null +++ b/kits/napi/include/create_subscriber.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_CREATE_SUBSCRIBER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CREATE_SUBSCRIBER_H + +#include +#include + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int ON_MAX_PARA = 2; +const int OFF_MAX_PARA = 1; +const std::string CONSUME = "consume"; +const std::string CANCEL = "cancel"; +const std::string UPDATE = "update"; +const std::string SUBSCRIBE = "subscribe"; +const std::string UNSUBSCRIBE = "unsubscribe"; +const std::string DIE = "die"; +const std::string DISTURB_MODE_CHANGE = "disturbModeChange"; + +class SubscriberInstance; + +struct AsyncCallbackInfoOn { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + SubscriberInstance *objectInfo; + std::string type; +}; + +struct AsyncCallbackInfoOff { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + SubscriberInstance *objectInfo; + std::string type; +}; + +struct CallbackInfo { + napi_env env; + napi_ref ref; +}; + +struct NotificationReceiveDataWorker { + napi_env env; + napi_ref ref = 0; + std::shared_ptr request = nullptr; + std::shared_ptr sortingMap = nullptr; + int deleteReason = 0; + int result = 0; + int disturbMode = 0; +}; + +class SubscriberInstance : public NotificationSubscriber { +public: + SubscriberInstance(); + + virtual ~SubscriberInstance(); + + virtual void OnCanceled(const std::shared_ptr &request) override; + + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override; + + virtual void OnConsumed(const std::shared_ptr &request) 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 OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + + virtual void OnDied() override; + + virtual void OnDisturbModeChanged(int disturbMode) override; + + void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); + +private: + void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref); + + void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); + +private: + CallbackInfo canceCallbackInfo_; + CallbackInfo consumeCallbackInfo_; + CallbackInfo updateCallbackInfo_; + CallbackInfo subscribeCallbackInfo_; + CallbackInfo unsubscribeCallbackInfo_; + CallbackInfo dieCallbackInfo_; + CallbackInfo disturbModeCallbackInfo_; +}; + +napi_value SetSubscriberCallbackData( + const napi_env &env, const std::shared_ptr &request, napi_value &result); + +napi_value SetSubscriberCallbackData(const napi_env &env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason, napi_value &result); + +napi_value NotificationSubscriberInit(napi_env env, napi_value exports); + +napi_value On(napi_env env, napi_callback_info info); + +napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const napi_value (&argv)[ON_MAX_PARA], + std::string &type, napi_ref &callback); + +napi_value Off(napi_env env, napi_callback_info info); + +napi_value ParseParametersByOff( + const napi_env &env, const size_t &argc, const napi_value (&argv)[OFF_MAX_PARA], std::string &type); + +napi_value SubscriberConstructor(napi_env env, napi_callback_info info); + +napi_value CreateSubscriber(napi_env env, napi_callback_info info); + +bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber); + +bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo); + +bool DelAsyncCallbackInfoOn(SubscriberInstance *subscriber, const std::string &type = ""); + +bool HasNotificationSubscriber(SubscriberInstance *subscriber); + +static std::mutex mutex_; +static napi_value g_NotificationSubscriber; +static std::map> g_SubscriberInstances; + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CREATE_SUBSCRIBER_H \ No newline at end of file diff --git a/kits/napi/include/get_active.h b/kits/napi/include/get_active.h new file mode 100644 index 000000000..d1ae7ad27 --- /dev/null +++ b/kits/napi/include/get_active.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_GET_ACTIVE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_GET_ACTIVE_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int ALL_ACTIVE_MAX_PARA = 2; +const int ACTIVE_OR_NUMS_MAX_PARA = 1; + +struct AsyncCallbackInfoActive { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::vector strValue; + bool isCallback = false; + napi_value result = nullptr; + int errorCode = 0; +}; + +napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info); +napi_value GetActiveNotifications(napi_env env, napi_callback_info info); +napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info); +napi_value ParseParametersByAllActive(const napi_env &env, const napi_value (&argv)[ALL_ACTIVE_MAX_PARA], + const size_t &argc, std::vector &strValue, napi_ref &callback); +napi_value ParseParameters( + const napi_env &env, const napi_value (&argv)[ACTIVE_OR_NUMS_MAX_PARA], const size_t &argc, napi_ref &callback); +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoActive *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_GET_ACTIVE_H \ No newline at end of file diff --git a/kits/napi/include/init.h b/kits/napi/include/init.h new file mode 100644 index 000000000..1690462d7 --- /dev/null +++ b/kits/napi/include/init.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_INIT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_INIT_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace NotificationNapi { +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((constructor)) void RegisterModule(void); +napi_value NotificationInit(napi_env env, napi_value exports); +static napi_value Init(napi_env env, napi_value exports); + +#ifdef __cplusplus +} +#endif + +/* + * Module define + */ +napi_module _module = { + + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "notificationnapi", + .nm_priv = ((void *)0), + .reserved = {0} + +}; + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_INIT_H diff --git a/kits/napi/include/publish.h b/kits/napi/include/publish.h new file mode 100644 index 000000000..69f94d70f --- /dev/null +++ b/kits/napi/include/publish.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H + +#include +#include "common.h" + +static const int32_t PUBLISH_NOTIFICATION_MAX = 2; + +namespace OHOS { +namespace NotificationNapi { +struct AsyncCallbackInfoPublish { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + napi_deferred deferred; + NotificationRequest notificationRequest; + std::string lable; + bool isCallback = false; + bool isPublishNotificationTwoPara = false; + int errorCode = 0; +}; + +struct NotificationLongTextContent { + std::string longText; + std::string briefText; + std::string expandedTitle; +}; + +struct NotificationPictureContent {}; + +struct NotificationConversationalContent {}; + +struct NotificationMultiLineContent {}; + +struct NotificationContentPublish { + int32_t type; + NotificationBasicContent notificationBasicContent; + NotificationLongTextContent notificationLongTextContent; + NotificationPictureContent notificationPictureContent; + NotificationConversationalContent notificationConversationalContent; + NotificationMultiLineContent notificationMultiLineContent; +}; + +struct ParseParametersPublish { + napi_env env; + size_t argc; + bool isCallback; + std::string lable; + napi_ref callback; +}; + +napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, + const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest); +void PaddingCallbackInfoInfoPublish(AsyncCallbackInfoPublish *&asynccallbackinfo, + const ParseParametersPublish &parseParameters, const NotificationRequest ¬ificationRequest); +void PaddingPublishCallbackPromise(const napi_env &env, const ParseParametersPublish &parseParameters, + AsyncCallbackInfoPublish *&asynccallbackinfo, napi_value &promise); +napi_value Publish(napi_env env, napi_callback_info info); +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H \ No newline at end of file diff --git a/kits/napi/include/remove.h b/kits/napi/include/remove.h new file mode 100644 index 000000000..bbc068154 --- /dev/null +++ b/kits/napi/include/remove.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_REMOVE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMOVE_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int REMOVE_OR_BUNDLE_MAX_PARA = 2; +const int REMOVE_ALL_MAX_PARA = 1; + +struct AsyncCallbackInfoRemove { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::string strValue; + bool isCallback = false; + int errorCode = 0; +}; + +napi_value Remove(napi_env env, napi_callback_info info); +napi_value RemoveAsBundle(napi_env env, napi_callback_info info); +napi_value RemoveAll(napi_env env, napi_callback_info info); + +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[REMOVE_OR_BUNDLE_MAX_PARA], const size_t &argc, + std::string &strValue, napi_ref &callback); + +napi_value ParseParametersByRemoveAll( + const napi_env &env, const napi_value (&argv)[REMOVE_ALL_MAX_PARA], const size_t &argc, napi_ref &callback); + +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoRemove *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMOVE_H \ No newline at end of file diff --git a/kits/napi/include/slot.h b/kits/napi/include/slot.h new file mode 100644 index 000000000..8644cb2e4 --- /dev/null +++ b/kits/napi/include/slot.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int ADD_SLOT_MAX_PARA = 2; +const int ADD_SLOTS_MAX_PARA = 2; +const int GET_SLOT_MAX_PARA = 2; +const int GET_SLOTS_MAX_PARA = 1; +const int REMOVE_SLOT_MAX_PARA = 2; + +struct AsyncCallbackInfoAddSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + NotificationSlot slot; + bool isCallback = false; + int errorCode = 0; +}; + +struct AsyncCallbackInfoAddSlots { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + std::vector slots; + bool isCallback = false; + int errorCode = 0; +}; + +struct AsyncCallbackInfoGetSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + enum NotificationConstant::SlotType outType; + bool isCallback = false; + napi_value result = nullptr; + int errorCode = 0; +}; + +struct AsyncCallbackInfoGetSlots { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + bool isCallback = false; + napi_value result = nullptr; + int errorCode = 0; +}; + +struct AsyncCallbackInfoRemoveSlot { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = nullptr; + napi_deferred deferred; + enum NotificationConstant::SlotType outType; + bool isCallback = false; + int errorCode = 0; +}; + +napi_value AddSlot(napi_env env, napi_callback_info info); +napi_value AddSlots(napi_env env, napi_callback_info info); +napi_value GetSlot(napi_env env, napi_callback_info info); +napi_value GetSlots(napi_env env, napi_callback_info info); +napi_value RemoveSlot(napi_env env, napi_callback_info info); + +napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], + const size_t &argc, NotificationSlot &slot, napi_ref &callback); + +void PaddingAsyncCallbackInfoIsByAddSlot( + const napi_env &env, AsyncCallbackInfoAddSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value ParseParametersByAddSlots(const napi_env &env, const napi_value (&argv)[ADD_SLOTS_MAX_PARA], + const size_t &argc, std::vector &slots, napi_ref &callback); + +void PaddingAsyncCallbackInfoIsByAddSlots( + const napi_env &env, AsyncCallbackInfoAddSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value ParseParametersByGetSlot(const napi_env &env, const napi_value (&argv)[GET_SLOT_MAX_PARA], + const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback); + +void PaddingAsyncCallbackInfoIsByGetSlot( + const napi_env &env, AsyncCallbackInfoGetSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value ParseParametersByGetSlots( + const napi_env &env, const napi_value (&argv)[GET_SLOTS_MAX_PARA], const size_t &argc, napi_ref &callback); + +void PaddingAsyncCallbackInfoIsByGetSlots( + const napi_env &env, AsyncCallbackInfoGetSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value ParseParametersByRemoveSlot(const napi_env &env, const napi_value (&argv)[REMOVE_SLOT_MAX_PARA], + const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback); + +void PaddingAsyncCallbackInfoIsByRemoveSlot(const napi_env &env, AsyncCallbackInfoRemoveSlot *&asynccallbackinfo, + const napi_ref &callback, napi_value &promise); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SLOT_H \ No newline at end of file diff --git a/kits/napi/include/subscribe.h b/kits/napi/include/subscribe.h new file mode 100644 index 000000000..af87eed8a --- /dev/null +++ b/kits/napi/include/subscribe.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H + +#include "create_subscriber.h" +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int SUBSRIBE_MAX_PARA = 3; + +struct AsyncCallbackInfoSubscribe { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + napi_deferred deferred; + SubscriberInstance *objectInfo = nullptr; + NotificationSubscriberInfo subscriberInfo; + bool isCallback = false; + int errorCode = 0; +}; + +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[SUBSRIBE_MAX_PARA], const size_t &argc, + NotificationSubscriberInfo &subscriberInfo, SubscriberInstance *&objectInfo, napi_ref &callback); + +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoSubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value Subscribe(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H \ No newline at end of file diff --git a/kits/napi/include/unsubscribe.h b/kits/napi/include/unsubscribe.h new file mode 100644 index 000000000..3872a2768 --- /dev/null +++ b/kits/napi/include/unsubscribe.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NAPI_INCLUDE_UNSUBSCRIBE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_UNSUBSCRIBE_H + +#include "common.h" +#include "create_subscriber.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +const int UNSUBSCRIBE_MAX_PARA = 2; + +struct AsyncCallbackInfoUnsubscribe { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + napi_deferred deferred; + SubscriberInstance *objectInfo = nullptr; + bool isCallback = false; + int errorCode = 0; +}; + +napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_value (&argv)[UNSUBSCRIBE_MAX_PARA], + SubscriberInstance *&objectInfo, napi_ref &callback); + +void PaddingAsyncCallbackInfoIs(const napi_env &env, const size_t &argc, + AsyncCallbackInfoUnsubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise); + +napi_value Unsubscribe(napi_env env, napi_callback_info info); + +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_UNSUBSCRIBE_H \ No newline at end of file diff --git a/kits/napi/src/cancel.cpp b/kits/napi/src/cancel.cpp new file mode 100644 index 000000000..e74881339 --- /dev/null +++ b/kits/napi/src/cancel.cpp @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2021 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 "cancel.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[CANCEL_MAX_PARA], const size_t &argc, + paraInfoCancel &info, napi_ref &callback) +{ + ANS_LOGI("ParseParameters start"); + + napi_valuetype valuetype; + // argv[0]: id: number + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_get_value_int32(env, argv[0], &info.id)); + + // argv[1]: label: string / callback + if (argc >= CANCEL_MAX_PARA - 1) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + if (valuetype == napi_string) { + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[1], str, STR_MAX_SIZE - 1, &strLen)); + info.label = str; + info.hasLabel = true; + } else if (valuetype == napi_function) { + napi_create_reference(env, argv[1], 1, &callback); + } else { + return nullptr; + } + } + + // argv[2]:callback + if (argc >= CANCEL_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[CANCEL_MAX_PARA - 1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[CANCEL_MAX_PARA - 1], 1, &callback); + } + + return Common::NapiGetNull(env); +} + +napi_value ParseParametersByAll( + const napi_env &env, const napi_value (&argv)[CANCEL_ALL_MAX_PARA], const size_t &argc, napi_ref &callback) +{ + ANS_LOGI("ParseParametersByAll start"); + + if (argc >= CANCEL_ALL_MAX_PARA) { + napi_valuetype valuetype; + // argv[0]:callback + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoCancel *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value Cancel(napi_env env, napi_callback_info info) +{ + ANS_LOGI("Cancel start"); + + size_t argc = CANCEL_MAX_PARA; + napi_value argv[CANCEL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + paraInfoCancel paraInfo; + if (ParseParameters(env, argv, argc, paraInfo, callback) == nullptr) { + return Common::NapiGetNull(env); + } + ANS_LOGI("Cancel id = %{public}d", paraInfo.id); + ANS_LOGI("Cancel label = %{public}s", paraInfo.label.c_str()); + + AsyncCallbackInfoCancel *asynccallbackinfo = new AsyncCallbackInfoCancel{ + .env = env, .asyncWork = nullptr, .id = paraInfo.id, .label = paraInfo.label, .hasLabel = paraInfo.hasLabel}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "cancel", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Cancel napi_create_async_work start"); + AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; + + if (asynccallbackinfo->hasLabel) { + asynccallbackinfo->errorCode = NotificationHelper::CancelNotification(asynccallbackinfo->id); + } else { + asynccallbackinfo->errorCode = + NotificationHelper::CancelNotification(asynccallbackinfo->label, asynccallbackinfo->id); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Cancel napi_create_async_work end"); + AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value CancelAll(napi_env env, napi_callback_info info) +{ + ANS_LOGI("CancelAll start"); + + size_t argc = CANCEL_ALL_MAX_PARA; + napi_value argv[CANCEL_ALL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + if (ParseParametersByAll(env, argv, argc, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoCancel *asynccallbackinfo = new AsyncCallbackInfoCancel{.env = env, .asyncWork = nullptr}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "cancelAll", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("CancelAll napi_create_async_work start"); + AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; + asynccallbackinfo->errorCode = NotificationHelper::CancelAllNotifications(); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("CancelAll napi_create_async_work end"); + AsyncCallbackInfoCancel *asynccallbackinfo = (AsyncCallbackInfoCancel *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/common.cpp b/kits/napi/src/common.cpp new file mode 100644 index 000000000..c1c124234 --- /dev/null +++ b/kits/napi/src/common.cpp @@ -0,0 +1,2918 @@ +/* + * Copyright (c) 2021 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 "common.h" +#include "notification_long_text_content.h" +#include "notification_multiline_content.h" +#include "publish.h" +#include "want_agent.h" + +namespace OHOS { +namespace NotificationNapi { +static napi_value GetIdByPublish(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationIsUnremovable( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationtapDismissed( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationRemovalWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationMaxScreenWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationAutoDeletedTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationSettingsText( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationGroupValue( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationGroupAlertType( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationGroupOverview( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationClassification( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationColorEnabled( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationIsAlertOnce( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationIsStopwatch( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationIsCountDown( + const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationVisibleness( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationProgressBar( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationStatusBarText( + const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationOnlyLocal( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationSortingKey( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationIsFloatingIcon( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationBadgeIconStyle( + const napi_env &env, const napi_value &value, NotificationRequest &request); +// static napi_value GetNotificationShortcutId( +// const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationShowDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationNotificationActionButtons( + const napi_env &env, const napi_value &value, NotificationRequest &request); +static napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type); +static napi_value GetNotificationBasicContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); +static napi_value GetNotificationLongTextContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); +static napi_value GetNotificationMultiLineContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); +static napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, + std::shared_ptr &multiLineContent); + +Common::Common() +{} + +Common::~Common() +{} + +napi_value Common::NapiGetboolean(napi_env env, const bool &isValue) +{ + napi_value result = 0; + napi_get_boolean(env, isValue, &result); + return result; +} + +napi_value Common::NapiGetNull(napi_env env) +{ + napi_value result = 0; + napi_get_null(env, &result); + return result; +} + +napi_value Common::GetCallbackErrorValue(napi_env env, int errCode) +{ + napi_value result = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); + return result; +} + +void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result) +{ + ANS_LOGI("ReturnCallbackPromise start"); + + if (info.isCallback) { + SetCallback(env, info.callback, info.errorCode, result); + } else { + SetPromise(env, info.deferred, result); + } + ANS_LOGI("ReturnCallbackPromise end"); +} + +void Common::SetCallback( + const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) +{ + ANS_LOGI("enter"); + napi_value undefined; + napi_get_undefined(env, &undefined); + + napi_value callback; + napi_value resultout; + napi_get_reference_value(env, callbackIn, &callback); + napi_value results[ARGS_TWO] = {0}; + results[PARAM0] = GetCallbackErrorValue(env, errorCode); + results[PARAM1] = result; + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM0], &resultout)); + ANS_LOGI("end"); +} + +void Common::SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +{ + ANS_LOGI("enter"); + napi_resolve_deferred(env, deferred, result); + ANS_LOGI("end"); +} + +napi_value Common::SetNotificationRequest( + const napi_env &env, const std::shared_ptr ¬ification, napi_value &result) +{ + ANS_LOGI("SetNotificationRequest start"); + + napi_value value; + NotificationRequest request = notification->GetNotificationRequest(); + + // content?NotificationContent + std::shared_ptr content = request.GetContent(); + if (content) { + napi_value contentResult; + napi_create_object(env, &contentResult); + if (!SetNotificationContent(env, content, contentResult)) { + ANS_LOGE("SetNotificationContent call failed"); + return NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "content", contentResult); + } else { + ANS_LOGE("content is nullptr"); + } + + // id:number + napi_create_int32(env, request.GetNotificationId(), &value); + ANS_LOGE("SetNotificationContent get id is: %{public}d", request.GetNotificationId()); + napi_set_named_property(env, result, "id", value); + ANS_LOGE("SetNotificationContent id is: %{public}d", request.GetNotificationId()); + // slotType?: SlotType + enum SlotType outType; + if (!SlotTypeCToJS(request.GetSlotType(), outType)) { + return NapiGetboolean(env, false); + } + napi_create_int32(env, outType, &value); + napi_set_named_property(env, result, "slotType", value); + + // isOngoing?: boolean + napi_get_boolean(env, request.IsInProgress(), &value); + napi_set_named_property(env, result, "isOngoing", value); + + // isUnremovable?: boolean + napi_get_boolean(env, request.IsUnremovable(), &value); + napi_set_named_property(env, result, "isUnremovable", value); + + // // createTime?: number + // napi_create_int64(env, request.GetCreateTime(), &value); + // napi_set_named_property(env, result, "createTime", value); + + // hashCode?: string + napi_create_string_utf8(env, notification->GetKey().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "hashCode", value); + + // deliveryTime?: number + napi_create_int64(env, request.GetDeliveryTime(), &value); + napi_set_named_property(env, result, "deliveryTime", value); + + // tapDismissed?: boolean + napi_get_boolean(env, request.IsTapDismissed(), &value); + napi_set_named_property(env, result, "tapDismissed", value); + + // autoDeletedTime?: number + napi_create_int64(env, request.GetAutoDeletedTime(), &value); + napi_set_named_property(env, result, "autoDeletedTime", value); + + // wantAgent?: WantAgent + std::shared_ptr agent = request.GetWantAgent(); + if (agent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, agent); + napi_set_named_property(env, result, "wantAgent", wantAgent); + } + // extraInfo ?: {[key:string] : any}; //do + + // // settingsText ?: string + // napi_create_string_utf8(env, request.GetSettingsText().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "settingsText", value); + + // // ownerBundleName ?: string + // napi_create_string_utf8(env, notification->GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "ownerBundleName", value); + + // // groupValue ?: string + // napi_create_string_utf8(env, request.GetGroupValue().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "groupValue", value); + + // // groupAlertType ?: number + // int groupAlertType = (int)request.GetGroupAlertType(); + // napi_create_int32(env, groupAlertType, &value); + // napi_set_named_property(env, result, "groupAlertType", value); + + // // groupOverview ?: boolean + // napi_get_boolean(env, request.IsGroupOverview(), &value); + // napi_set_named_property(env, result, "groupOverview", value); + + // removalWantAgent ? WantAgent + std::shared_ptr removalAgent = request.GetRemovalWantAgent(); + if (removalAgent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, removalAgent); + napi_set_named_property(env, result, "removalWantAgent", wantAgent); + } + + // maxScreenWantAgent ? WantAgent + std::shared_ptr maxScreenAgent = request.GetMaxScreenWantAgent(); + if (maxScreenAgent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, maxScreenAgent); + napi_set_named_property(env, result, "maxScreenWantAgent", wantAgent); + } + + // // classification ?: string + // napi_create_string_utf8(env, request.GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "classification", value); + + // color ?: number + napi_create_int32(env, request.GetColor(), &value); + napi_set_named_property(env, result, "color", value); + + // colorEnabled ?: boolean + napi_get_boolean(env, request.IsColorEnabled(), &value); + napi_set_named_property(env, result, "colorEnabled", value); + + // isAlertOnce ?: boolean + napi_get_boolean(env, request.IsAlertOneTime(), &value); + napi_set_named_property(env, result, "isAlertOnce", value); + + // isStopwatch ?: boolean + napi_get_boolean(env, request.IsShowStopwatch(), &value); + napi_set_named_property(env, result, "isStopwatch", value); + + // isCountDown ?: boolean + napi_get_boolean(env, request.IsCountdownTimer(), &value); + napi_set_named_property(env, result, "isCountDown", value); + + // showCreateTime ?: boolean; do request + // napi_get_boolean(env, request.IsCountdownTimer(), &value); + // napi_set_named_property(env, result, "showCreateTime", value); + + // // visibleness ?: number + // int visibleness = (int)request.GetVisibleness(); + // napi_create_int32(env, visibleness, &value); + // napi_set_named_property(env, result, "visibleness", value); + + // progressValue ?: number + napi_create_int32(env, request.GetProgressValue(), &value); + napi_set_named_property(env, result, "progressValue", value); + + // progressMaxValue ?: number + napi_create_int32(env, request.GetProgressMax(), &value); + napi_set_named_property(env, result, "progressMaxValue", value); + + // isIndeterminate ?: boolean + napi_get_boolean(env, request.IsProgressIndeterminate(), &value); + napi_set_named_property(env, result, "isIndeterminate", value); + + // statusBarText ?: string + napi_create_string_utf8(env, request.GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "statusBarText", value); + + // isFloatingIcon ?: boolean; do notification + + // // onlyLocal ?: boolean + // napi_get_boolean(env, request.IsOnlyLocal(), &value); + // napi_set_named_property(env, result, "onlyLocal", value); + + // // sortingKey ?: string + // napi_create_string_utf8(env, request.GetSortingKey().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "sortingKey", value); + + // // messageUsers ?: Array + // napi_value arr; + // int count = 0; + // napi_create_array(env, &arr); + // for (auto vec : request.GetMessageUsers()) { + // if (vec) { + // napi_value messageUserResult; + // napi_create_object(env, &messageUserResult); + // if (SetMessageUser(env, vec, messageUserResult)) { + // napi_set_element(env, arr, count, messageUserResult); + // count++; + // } + // } + // } + // napi_set_named_property(env, result, "messageUsers", arr); + + // label ?: string + napi_create_string_utf8(env, request.GetLabel().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "label", value); + + // badgeIconStyle ?: number + int badgeIconStyle = (int)request.GetBadgeIconStyle(); + napi_create_int32(env, badgeIconStyle, &value); + napi_set_named_property(env, result, "badgeIconStyle", value); + + // // shortcutId ?: string + // napi_create_string_utf8(env, request.GetShortcutId().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "shortcutId", value); + + // showDeliveryTime ?: boolean + napi_get_boolean(env, request.IsShowDeliveryTime(), &value); + napi_set_named_property(env, result, "showDeliveryTime", value); + + // actionButtons?: Array + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : request.GetActionButtons()) { + if (vec) { + napi_value actionButtonResult; + napi_create_object(env, &actionButtonResult); + if (SetNotificationActionButton(env, vec, actionButtonResult)) { + napi_set_element(env, arr, count, actionButtonResult); + count++; + } + } + } + napi_set_named_property(env, result, "actionButtons", arr); + + // smallIcon ?: image.PixelMap; do + // largeIcon ?: image.PixelMap; do + + // readonly creatorBundleName?: string + napi_create_string_utf8(env, notification->GetCreateBundle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); + + // readonly creatorUid?: number + napi_create_int32(env, notification->GetUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorPid?: number //do notification + // napi_create_int32(env, request.GetCreatorPid(), &value); + // napi_set_named_property(env, result, "creatorPid", value); + + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationRequest2( + const napi_env &env, const std::shared_ptr &request, napi_value &result) +{ + ANS_LOGI("SetNotificationRequest2 start"); + + napi_value value; + + // content?NotificationContent + std::shared_ptr content = request->GetContent(); + + if (content) { + napi_value contentResult; + napi_create_object(env, &contentResult); + if (!SetNotificationContent(env, content, contentResult)) { + ANS_LOGE("SetNotificationContent call failed"); + return NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "content", contentResult); + } else { + ANS_LOGE("content is nullptr"); + } + + // id:number + napi_create_int32(env, request->GetNotificationId(), &value); + ANS_LOGE("SetNotificationContent get id is: %{public}d", request->GetNotificationId()); + napi_set_named_property(env, result, "id", value); + ANS_LOGE("SetNotificationContent id is: %{public}d", request->GetNotificationId()); + + // slotType?: SlotType + enum SlotType outType; + if (!SlotTypeCToJS(request->GetSlotType(), outType)) { + return NapiGetboolean(env, false); + } + napi_create_int32(env, outType, &value); + napi_set_named_property(env, result, "slotType", value); + + // isOngoing?: boolean + napi_get_boolean(env, request->IsInProgress(), &value); + napi_set_named_property(env, result, "isOngoing", value); + + // isUnremovable?: boolean + napi_get_boolean(env, request->IsUnremovable(), &value); + napi_set_named_property(env, result, "isUnremovable", value); + + // // createTime?: number + // napi_create_int64(env, request->GetCreateTime(), &value); + // napi_set_named_property(env, result, "createTime", value); + + // hashCode?: string + napi_create_string_utf8(env, request->GetNotificationHashCode().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "hashCode", value); + + // deliveryTime?: number + napi_create_int64(env, request->GetDeliveryTime(), &value); + napi_set_named_property(env, result, "deliveryTime", value); + + // tapDismissed?: boolean + napi_get_boolean(env, request->IsTapDismissed(), &value); + napi_set_named_property(env, result, "tapDismissed", value); + + // autoDeletedTime?: number + napi_create_int64(env, request->GetAutoDeletedTime(), &value); + napi_set_named_property(env, result, "autoDeletedTime", value); + + // wantAgent?: WantAgent + std::shared_ptr agent = request->GetWantAgent(); + if (agent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, agent); + napi_set_named_property(env, result, "wantAgent", wantAgent); + } + + // extraInfo ?: {[key:string] : any}; //do + + // // settingsText ?: string + // napi_create_string_utf8(env, request->GetSettingsText().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "settingsText", value); + + // // ownerBundleName ?: string + // napi_create_string_utf8(env, notification->GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "ownerBundleName", value); + + // // groupValue ?: string + // napi_create_string_utf8(env, request->GetGroupValue().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "groupValue", value); + + // // groupAlertType ?: number + // int groupAlertType = (int)request->GetGroupAlertType(); + // napi_create_int32(env, groupAlertType, &value); + // napi_set_named_property(env, result, "groupAlertType", value); + + // // groupOverview ?: boolean + // napi_get_boolean(env, request->IsGroupOverview(), &value); + // napi_set_named_property(env, result, "groupOverview", value); + + // removalWantAgent ? WantAgent + std::shared_ptr removalAgent = request->GetRemovalWantAgent(); + if (removalAgent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, removalAgent); + napi_set_named_property(env, result, "removalWantAgent", wantAgent); + } + + // maxScreenWantAgent ? WantAgent + std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); + if (maxScreenAgent) { + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, maxScreenAgent); + napi_set_named_property(env, result, "maxScreenWantAgent", wantAgent); + } + + // // classification ?: string + // napi_create_string_utf8(env, request->GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "classification", value); + + // color ?: number + napi_create_int32(env, request->GetColor(), &value); + napi_set_named_property(env, result, "color", value); + + // colorEnabled ?: boolean + napi_get_boolean(env, request->IsColorEnabled(), &value); + napi_set_named_property(env, result, "colorEnabled", value); + + // isAlertOnce ?: boolean + napi_get_boolean(env, request->IsAlertOneTime(), &value); + napi_set_named_property(env, result, "isAlertOnce", value); + + // isStopwatch ?: boolean + napi_get_boolean(env, request->IsShowStopwatch(), &value); + napi_set_named_property(env, result, "isStopwatch", value); + + // isCountDown ?: boolean + napi_get_boolean(env, request->IsCountdownTimer(), &value); + napi_set_named_property(env, result, "isCountDown", value); + + // showCreateTime ?: boolean; do request + // napi_get_boolean(env, request->IsCountdownTimer(), &value); + // napi_set_named_property(env, result, "showCreateTime", value); + + // // visibleness ?: number + // int visibleness = (int)request->GetVisibleness(); + // napi_create_int32(env, visibleness, &value); + // napi_set_named_property(env, result, "visibleness", value); + + // progressValue ?: number + napi_create_int32(env, request->GetProgressValue(), &value); + napi_set_named_property(env, result, "progressValue", value); + + // progressMaxValue ?: number + napi_create_int32(env, request->GetProgressMax(), &value); + napi_set_named_property(env, result, "progressMaxValue", value); + + // isIndeterminate ?: boolean + napi_get_boolean(env, request->IsProgressIndeterminate(), &value); + napi_set_named_property(env, result, "isIndeterminate", value); + + // statusBarText ?: string + napi_create_string_utf8(env, request->GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "statusBarText", value); + + // isFloatingIcon ?: boolean; do notification + + // // onlyLocal ?: boolean + // napi_get_boolean(env, request->IsOnlyLocal(), &value); + // napi_set_named_property(env, result, "onlyLocal", value); + + // // sortingKey ?: string + // napi_create_string_utf8(env, request->GetSortingKey().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "sortingKey", value); + + // // messageUsers ?: Array + // napi_value arr; + // int count = 0; + // napi_create_array(env, &arr); + // for (auto vec : request->GetMessageUsers()) {notification + // label ?: string + napi_create_string_utf8(env, request->GetLabel().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "label", value); + + // badgeIconStyle ?: number + int badgeIconStyle = (int)request->GetBadgeIconStyle(); + napi_create_int32(env, badgeIconStyle, &value); + napi_set_named_property(env, result, "badgeIconStyle", value); + + // // shortcutId ?: string + // napi_create_string_utf8(env, request->GetShortcutId().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "shortcutId", value); + + // showDeliveryTime ?: boolean + napi_get_boolean(env, request->IsShowDeliveryTime(), &value); + napi_set_named_property(env, result, "showDeliveryTime", value); + + // actionButtons?: Array + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : request->GetActionButtons()) { + if (vec) { + napi_value actionButtonResult; + napi_create_object(env, &actionButtonResult); + if (SetNotificationActionButton(env, vec, actionButtonResult)) { + napi_set_element(env, arr, count, actionButtonResult); + count++; + } + } + } + napi_set_named_property(env, result, "actionButtons", arr); + + // smallIcon ?: image.PixelMap; do + // largeIcon ?: image.PixelMap; do + + // readonly creatorBundleName?: string + napi_create_string_utf8(env, request->GetCreatorBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); + + // readonly creatorUid?: number + napi_create_int32(env, request->GetCreatorUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorPid?: number //do notification + // napi_create_int32(env, request->GetCreatorPid(), &value); + // napi_set_named_property(env, result, "creatorPid", value); + + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationSortingMap( + const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result) +{ + ANS_LOGI("SetNotificationSortingMap start"); + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return NapiGetboolean(env, false); + } + if (sortingMap->GetKey().size() == 0) { + ANS_LOGE("sortingMap GetKey().size is empty"); + return NapiGetboolean(env, false); + } + + size_t count = 0; + napi_value arrSortedHashCode; + napi_create_array(env, &arrSortedHashCode); + napi_value sortingsResult; + napi_create_object(env, &sortingsResult); + for (auto key : sortingMap->GetKey()) { + NotificationSorting sorting; + if (sortingMap->GetNotificationSorting(key, sorting)) { + // sortedHashCode: Array + napi_value keyValue; + ANS_LOGI("sortingMap key = %{public}s", key.c_str()); + napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyValue); + napi_set_element(env, arrSortedHashCode, count, keyValue); + + // sortings:{[key : string] : NotificationSorting} + napi_value sortingResult; + napi_create_object(env, &sortingResult); + if (!SetNotificationSorting(env, sorting, sortingResult)) { + ANS_LOGE("SetNotificationSorting call failed"); + return NapiGetboolean(env, false); + } + napi_set_named_property(env, sortingsResult, key.c_str(), sortingResult); + count++; + } else { + ANS_LOGW("sortingMap Key: %{public}s match value is empty", key.c_str()); + } + } + napi_set_named_property(env, result, "sortedHashCode", arrSortedHashCode); + napi_set_named_property(env, result, "sortings", sortingsResult); + + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationSorting(const napi_env &env, const NotificationSorting &sorting, napi_value &result) +{ + ANS_LOGI("SetNotificationSorting start"); + + // slot: NotificationSlot + napi_value slotResult; + napi_value value = 0; + napi_create_object(env, &slotResult); + if (!SetNotificationSlot(env, sorting.GetSlot(), slotResult)) { + ANS_LOGE("SetNotificationSlot call failed"); + return NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "slot", slotResult); + + // hashCode?: string + napi_create_string_utf8(env, sorting.GetKey().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "hashCode", value); + + // ranking?: number + napi_create_int32(env, sorting.GetRanking(), &value); + napi_set_named_property(env, result, "ranking", value); + + // isDisplayBadge?: boolean + napi_get_boolean(env, sorting.IsDisplayBadge(), &value); + napi_set_named_property(env, result, "isDisplayBadge", value); + + // isHiddenNotification?: boolean + napi_get_boolean(env, sorting.IsHiddenNotification(), &value); + napi_set_named_property(env, result, "isHiddenNotification", value); + + // isSuitInterruptionFilter?: boolean ??????? do + // napi_get_boolean(env, sorting->isOrdered, &value); + // napi_set_named_property(env, result, "isSuitInterruptionFilter", value); + + // importance?: number + napi_create_int32(env, sorting.GetImportance(), &value); + napi_set_named_property(env, result, "importance", value); + + // groupKeyOverride?: string + napi_create_string_utf8(env, sorting.GetGroupKeyOverride().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "groupKeyOverride", value); + + // visiblenessOverride?: number + napi_create_int32(env, sorting.GetVisiblenessOverride(), &value); + napi_set_named_property(env, result, "visiblenessOverride", value); + + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSlot &slot, napi_value &result) +{ + ANS_LOGI("SetNotificationSlot start"); + + napi_value value = 0; + + // type: SlotType; + enum SlotType outType; + if (!SlotTypeCToJS(slot.GetType(), outType)) { + return NapiGetboolean(env, false); + } + napi_create_int32(env, outType, &value); + napi_set_named_property(env, result, "type", value); + + // // slotId: string + // napi_create_string_utf8(env, slot.GetId().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "slotId", value); + + // // slotName: string + // napi_create_string_utf8(env, slot.GetName().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "slotName", value); + + // level?: number + napi_create_int32(env, slot.GetLevel(), &value); + napi_set_named_property(env, result, "level", value); + + // desc?: string + napi_create_string_utf8(env, slot.GetDescription().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "desc", value); + + // showBadgeFlag?: boolean + napi_get_boolean(env, slot.IsShowBadge(), &value); + napi_set_named_property(env, result, "showBadgeFlag", value); + + // bypassDnd?: boolean + napi_get_boolean(env, slot.IsEnableBypassDnd(), &value); + napi_set_named_property(env, result, "bypassDnd", value); + + // lockscreenVisibility?: number + int32_t LockScreenVisibleness = (int32_t)slot.GetLockScreenVisibleness(); + napi_create_int32(env, LockScreenVisibleness, &value); + napi_set_named_property(env, result, "lockscreenVisibility", value); + + // vibrationEnabled?: boolean + napi_get_boolean(env, slot.CanVibrate(), &value); + napi_set_named_property(env, result, "vibrationEnabled", value); + + // sound?: string + napi_create_string_utf8(env, slot.GetSound().ToString().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "sound", value); + + // lightEnabled?: boolean + napi_get_boolean(env, slot.CanEnableLight(), &value); + napi_set_named_property(env, result, "lightEnabled", value); + + // lightColor?: number + napi_create_int32(env, slot.GetLedLightColor(), &value); + napi_set_named_property(env, result, "lightColor", value); + + // slotGroupId?: string + // napi_create_string_utf8(env, slot.GetSlotGroup().c_str(), NAPI_AUTO_LENGTH, &value); + // napi_set_named_property(env, result, "slotGroupId", value); + + // vibrationValues?: Array + napi_value arr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : slot.GetVibrationStyle()) { + napi_create_int64(env, vec, &value); + napi_set_element(env, arr, count, value); + count++; + } + napi_set_named_property(env, result, "vibrationValues", arr); + + return NapiGetboolean(env, true); +} +napi_value Common::SetNotificationContent( + const napi_env &env, const std::shared_ptr &content, napi_value &result) +{ + ANS_LOGI("SetNotificationContent start"); + if (content == nullptr) { + ANS_LOGE("content is null"); + return NapiGetboolean(env, false); + } + + napi_value value; + // contentType: ContentType; + NotificationContent::Type type = content->GetContentType(); + napi_create_int32(env, (int32_t)type, &value); + napi_set_named_property(env, result, "contentType", value); + + ContentType outType; + if (!ContentTypeCToJS(type, outType)) { + return NapiGetboolean(env, false); + } + + if (outType == ContentType::NOTIFICATION_CONTENT_BASIC_TEXT) { + // normal?: NotificationBasicContent + std::shared_ptr basicContent = content->GetNotificationContent(); + if (basicContent == nullptr) { + ANS_LOGI("basicContent is null"); + napi_set_named_property(env, result, "normal", NapiGetNull(env)); + } else { + napi_value basicContentResult; + napi_create_object(env, &basicContentResult); + if (SetNotificationBasicContent(env, basicContent.get(), basicContentResult)) { + napi_set_named_property(env, result, "normal", basicContentResult); + } else { + napi_set_named_property(env, result, "normal", NapiGetNull(env)); + } + } + } else if (outType == ContentType::NOTIFICATION_CONTENT_LONG_TEXT) { + // longText?: NotificationLongTextContent + OHOS::Notification::NotificationLongTextContent *longTextContent = + static_cast(content->GetNotificationContent().get()); + if (longTextContent == nullptr) { + ANS_LOGI("longTextContent is null"); + napi_set_named_property(env, result, "longText", NapiGetNull(env)); + } else { + napi_value longTextContentResult; + napi_create_object(env, &longTextContentResult); + if (SetNotificationLongTextContent(env, longTextContent, longTextContentResult)) { + napi_set_named_property(env, result, "longText", longTextContentResult); + } else { + napi_set_named_property(env, result, "longText", NapiGetNull(env)); + } + } + } else if (outType == ContentType::NOTIFICATION_CONTENT_PICTURE) { + // picture?: NotificationPictureContent + // OHOS::Notification::NotificationPictureContent * pictureContent = + // static_cast(content->GetNotificationContent().get()); + // if (pictureContent == nullptr) { + // ANS_LOGI("pictureContent is null"); + // napi_set_named_property(env, result, "picture", NapiGetNull(env)); + // } else { + // napi_value pictureContentResult; + // napi_create_object(env, &pictureContentResult); + // if (SetNotificationPictureContent(env, pictureContent, pictureContentResult)) { + // napi_set_named_property(env, result, "picture", pictureContentResult); + // } else { + // napi_set_named_property(env, result, "picture", NapiGetNull(env)); + // } + // } + } else if (outType == ContentType::NOTIFICATION_CONTENT_CONVERSATION) { + // conversational?: NotificationConversationalContent + // OHOS::Notification::NotificationConversationalContent * conversationalContent = + // static_cast(content->GetNotificationContent().get()); + // if (conversationalContent == nullptr) { + // ANS_LOGI("conversationalContent is null"); + // napi_set_named_property(env, result, "conversational", NapiGetNull(env)); + // } else { + // napi_value conversationalContentResult; + // napi_create_object(env, &conversationalContentResult); + // if (SetNotificationConversationalContent(env, conversationalContent, conversationalContentResult)) { + // napi_set_named_property(env, result, "conversational", conversationalContentResult); + // } else { + // napi_set_named_property(env, result, "conversational", NapiGetNull(env)); + // } + // } + } else if (outType == ContentType::NOTIFICATION_CONTENT_MULTILINE) { + // multiLine?: NotificationMultiLineContent + OHOS::Notification::NotificationMultiLineContent *multiLineContent = + static_cast(content->GetNotificationContent().get()); + if (multiLineContent == nullptr) { + ANS_LOGI("multiLineContent is null"); + napi_set_named_property(env, result, "multiLine", NapiGetNull(env)); + } else { + napi_value multiLineContentResult; + napi_create_object(env, &multiLineContentResult); + if (SetNotificationMultiLineContent(env, multiLineContent, multiLineContentResult)) { + napi_set_named_property(env, result, "multiLine", multiLineContentResult); + } else { + napi_set_named_property(env, result, "multiLine", NapiGetNull(env)); + } + } + } else { + ANS_LOGE("ContentType is does not exist"); + return NapiGetboolean(env, false); + } + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationBasicContent( + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result) +{ + ANS_LOGI("SetNotificationBasicContent start"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return NapiGetboolean(env, false); + } + + napi_value value; + + // title: string; + napi_create_string_utf8(env, basicContent->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "title", value); + + // text: string; + napi_create_string_utf8(env, basicContent->GetText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "text", value); + + // additionalText?: string; + napi_create_string_utf8(env, basicContent->GetAdditionalText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "additionalText", value); + + return NapiGetboolean(env, true); +} + +napi_value Common::SetNotificationLongTextContent( + const napi_env &env, OHOS::Notification::NotificationLongTextContent *longTextContent, napi_value &result) +{ + ANS_LOGI("SetNotificationLongTextContent start"); + if (longTextContent == nullptr) { + ANS_LOGE("longTextContent is null"); + return NapiGetboolean(env, false); + } + + if (!SetNotificationBasicContent(env, longTextContent, result)) { + ANS_LOGE("SetNotificationBasicContent call failed"); + return NapiGetboolean(env, false); + } + + napi_value value; + + // longText: string + napi_create_string_utf8(env, longTextContent->GetLongText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "longText", value); + + // briefText: string + napi_create_string_utf8(env, longTextContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "briefText", value); + + // expandedTitle: string + napi_create_string_utf8(env, longTextContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "expandedTitle", value); + + return NapiGetboolean(env, true); +} + +// napi_value Common::SetNotificationPictureContent( +// const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result) +// { +// ANS_LOGI("SetNotificationPictureContent start"); +// if (pictureContent == nullptr) { +// ANS_LOGE("pictureContent is null"); +// return NapiGetboolean(env, false); +// } + +// if (!SetNotificationBasicContent(env, pictureContent, result)) { +// ANS_LOGE("SetNotificationBasicContent call failed"); +// return NapiGetboolean(env, false); +// } + +// napi_value value; + +// // pictureId: number //c++ no do + +// // briefText: string +// napi_create_string_utf8(env, pictureContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "briefText", value); + +// // expandedTitle: string +// napi_create_string_utf8(env, pictureContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "expandedTitle", value); + +// // bigPicture: image.PixelMap //do + +// return NapiGetboolean(env, true); +// } + +// napi_value Common::SetNotificationConversationalContent( +// const napi_env &env, OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value +// &result) +// { +// ANS_LOGI("SetNotificationConversationalContent start"); +// if (conversationalContent == nullptr) { +// ANS_LOGE("conversationalContent is null"); +// return NapiGetboolean(env, false); +// } + +// if (!SetNotificationBasicContent(env, conversationalContent, result)) { +// ANS_LOGE("SetNotificationBasicContent call failed"); +// return NapiGetboolean(env, false); +// } + +// napi_value value; +// // conversationTitle: string +// napi_create_string_utf8(env, conversationalContent->GetConversationTitle().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "conversationTitle", value); + +// // conversationGroup: boolean +// napi_get_boolean(env, conversationalContent->IsConversationGroup(), &value); +// napi_set_named_property(env, result, "conversationGroup", value); + +// // messages: Array +// napi_value arr; +// int count = 0; +// napi_create_array(env, &arr); +// std::vector> messages = +// conversationalContent->GetAllConversationalMessages(); +// for (auto vec : messages) { +// if (vec) { +// napi_value conversationalMessageResult; +// napi_create_object(env, &conversationalMessageResult); +// if (SetConversationalMessage(env, vec, conversationalMessageResult)) { +// napi_set_element(env, arr, count, conversationalMessageResult); +// count++; +// } +// } +// } +// napi_set_named_property(env, result, "messages", arr); + +// // user: MessageUser +// napi_value messageUserResult; +// napi_create_object(env, &messageUserResult); +// if (!SetMessageUser(env, conversationalContent->GetMessageUser(), messageUserResult)) { +// messageUserResult = NapiGetNull(); +// } +// napi_set_named_property(env, result, "user", messageUserResult); + +// return NapiGetboolean(env, true); +// } + +napi_value Common::SetNotificationMultiLineContent( + const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result) +{ + ANS_LOGI("SetNotificationMultiLineContent start"); + if (multiLineContent == nullptr) { + ANS_LOGE("multiLineContent is null"); + return NapiGetboolean(env, false); + } + + if (!SetNotificationBasicContent(env, multiLineContent, result)) { + ANS_LOGE("SetNotificationBasicContent call failed"); + return NapiGetboolean(env, false); + } + + napi_value value; + // briefText: string + napi_create_string_utf8(env, multiLineContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "briefText", value); + + // longTitle: string + napi_create_string_utf8(env, multiLineContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "longTitle", value); + + // lines: Array + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : multiLineContent->GetAllLines()) { + napi_create_string_utf8(env, vec.c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_element(env, arr, count, value); + count++; + } + napi_set_named_property(env, result, "lines", arr); + + return NapiGetboolean(env, true); +} + +// napi_value Common::SetMessageUser(const napi_env &env, std::shared_ptr &messageUser, napi_value +// &result) +// { +// ANS_LOGI("SetMessageUser start"); +// if (messageUser == nullptr) { +// ANS_LOGE("SetMessageUser is null"); +// return NapiGetboolean(env, false); +// } + +// napi_value value; +// // name: string +// napi_create_string_utf8(env, messageUser->GetName().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "name", value); + +// // pixelMap: image.PixelMap //do + +// // uri: string +// napi_create_string_utf8(env, pictureContent->GetUri().ToString().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "uri", value); + +// // important: boolean +// napi_get_boolean(env, pictureContent->IsUserImportant(), &value); +// napi_set_named_property(env, result, "important", value); + +// // machine: boolean +// napi_get_boolean(env, pictureContent->IsMachine(), &value); +// napi_set_named_property(env, result, "machine", value); + +// // key: string +// napi_create_string_utf8(env, pictureContent->GetKey().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "key", value); + +// return NapiGetboolean(env, true); +// } + +// napi_value Common::SetConversationalMessage( +// const napi_env &env, std::shared_ptr &conversationalMessage, napi_value +// &result) +// { +// ANS_LOGI("SetConversationalMessage start"); +// if (conversationalMessage == nullptr) { +// ANS_LOGE("SetConversationalMessage is null"); +// return NapiGetboolean(env, false); +// } + +// napi_value value; +// // text: string +// napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "text", value); + +// // timestamp: number; +// napi_create_int64(env, conversationalMessage->GetArrivedTime(), &value); +// napi_set_named_property(env, result, "timestamp", value); + +// // mimeType: string; +// napi_create_string_utf8(env, conversationalMessage->GetMimeType().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "mimeType", value); + +// // uri: string; +// napi_create_string_utf8(env, conversationalMessage->GetUri()->ToString().c_str(), NAPI_AUTO_LENGTH, &value); +// napi_set_named_property(env, result, "uri", value); + +// // sender: MessageUser; +// napi_value messageUserResult; +// napi_create_object(env, &messageUserResult); +// if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { +// messageUserResult = NapiGetNull(); +// } +// napi_set_named_property(env, result, "sender", messageUserResult); + +// return NapiGetboolean(env, true); +// } + +napi_value Common::SetNotificationActionButton( + const napi_env &env, std::shared_ptr &actionButton, napi_value &result) +{ + ANS_LOGI("SetNotificationActionButton start"); + if (actionButton == nullptr) { + ANS_LOGE("actionButton is null"); + return NapiGetboolean(env, false); + } + + napi_value value; + + // title: string + napi_create_string_utf8(env, actionButton->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "title", value); + + // wantAgent: WantAgent + std::shared_ptr agent = actionButton->GetWantAgent(); + if (!agent) { + ANS_LOGE("wantAgent is null"); + return NapiGetboolean(env, false); + } + napi_value wantAgent; + wantAgent = CreateWantAgentByJS(env, agent); + napi_set_named_property(env, result, "wantAgent", wantAgent); + + // extras?: {[key: string]: any} //do + // icon?: image.PixelMap //do + return NapiGetboolean(env, true); +} + +napi_value Common::GetNotificationSubscriberInfo( + const napi_env &env, const napi_value &value, NotificationSubscriberInfo &result) +{ + uint32_t length = 0; + size_t strLen; + bool hasProperty = false; + napi_valuetype valuetype; + // bundleNames?: Array; + NAPI_CALL(env, napi_has_named_property(env, value, "bundleNames", &hasProperty)); + if (hasProperty) { + napi_value nbundleNames; + napi_get_named_property(env, value, "bundleNames", &nbundleNames); + napi_get_array_length(env, nbundleNames, &length); + if (length > 0) { + for (uint32_t i = 0; i < length; ++i) { + napi_value nbundleName; + char str[STR_MAX_SIZE] = {0}; + napi_get_element(env, nbundleNames, i, &nbundleName); + NAPI_CALL(env, napi_typeof(env, nbundleName, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nbundleName, str, STR_MAX_SIZE - 1, &strLen)); + result.bundleNames.emplace_back(str); + result.hasSubscriberInfo = true; + } + } + } + + // deviceIds?: Array; + // NAPI_CALL(env, napi_has_named_property(env, value, "deviceIds", &hasProperty)); + // if (hasProperty) { + // napi_value ndeviceIds; + // napi_get_named_property(env, value, "deviceIds", &ndeviceIds); + // napi_get_array_length(env, value, &length); + // if (length > 0) { + // for (uint32_t i = 0; i < length; ++i) { + // napi_value ndeviceId; + // char str[STR_MAX_SIZE] = {0}; + // napi_get_element(env, ndeviceIds, i, &ndeviceId); + // NAPI_CALL(env, napi_typeof(env, ndeviceId, &valuetype)); + // NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + // NAPI_CALL(env, napi_get_value_string_utf8(env, ndeviceId, str, STR_MAX_SIZE - 1, &strLen)); + // result.deviceIds.emplace_back(str); + // result.hasSubscriberInfo = true; + // } + // } + // } + + // userId?: number; + NAPI_CALL(env, napi_has_named_property(env, value, "userId", &hasProperty)); + if (hasProperty) { + napi_value nuserId; + napi_get_named_property(env, value, "userId", &nuserId); + NAPI_CALL(env, napi_typeof(env, nuserId, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_get_value_int32(env, nuserId, &result.userId)); + result.hasSubscriberInfo = true; + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + // content: NotificationContent + if (GetNotificationContent(env, value, request) == nullptr) { + return nullptr; + } + + // id?: number + if (GetIdByPublish(env, value, request) == nullptr) { + return nullptr; + } + + // slotType?: notification.SlotType + if (GetSlotType(env, value, request) == nullptr) { + return nullptr; + } + + // isOngoing?: boolean + if (GetNotificationIsOngoing(env, value, request) == nullptr) { + return nullptr; + } + + // isUnremovable?: boolean + if (GetNotificationIsUnremovable(env, value, request) == nullptr) { + return nullptr; + } + + // deliveryTime?: number + if (GetNotificationDeliveryTime(env, value, request) == nullptr) { + return nullptr; + } + + // tapDismissed?: boolean + if (GetNotificationtapDismissed(env, value, request) == nullptr) { + return nullptr; + } + + // wantAgent?: WantAgent + if (Common::GetNotificationWantAgent(env, value, request) == nullptr) { + return nullptr; + } + + // extraInfo?: {[key: string]: any} : do + + // removalWantAgent?: WantAgent + if (GetNotificationRemovalWantAgent(env, value, request) == nullptr) { + return nullptr; + } + + // maxScreenWantAgent?: WantAgent + if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { + return nullptr; + } + + // autoDeletedTime?: number + if (GetNotificationAutoDeletedTime(env, value, request) == nullptr) { + return nullptr; + } + + // // settingsText?: string + // if (GetNotificationSettingsText(env, value, request) == nullptr) { + // return nullptr; + // } + + // // groupValue?: string + // if (GetNotificationGroupValue(env, value, request) == nullptr) { + // return nullptr; + // } + + // // groupAlertType?: number + // if (GetNotificationGroupAlertType(env, value, request) == nullptr) { + // return nullptr; + // } + + // // groupOverview?: boolean + // if (GetNotificationGroupOverview(env, value, request) == nullptr) { + // return nullptr; + // } + + // // classification?: string + // if (GetNotificationClassification(env, value, request) == nullptr) { + // return nullptr; + // } + + // color?: number + if (GetNotificationColor(env, value, request) == nullptr) { + return nullptr; + } + + // colorEnabled?: boolean + if (GetNotificationColorEnabled(env, value, request) == nullptr) { + return nullptr; + } + + // isAlertOnce?: boolean + if (GetNotificationIsAlertOnce(env, value, request) == nullptr) { + return nullptr; + } + + // isStopwatch?: boolean + if (GetNotificationIsStopwatch(env, value, request) == nullptr) { + return nullptr; + } + + // isCountDown?: boolean + if (GetNotificationIsCountDown(env, value, request) == nullptr) { + return nullptr; + } + + // // visibleness?: number + // if (GetNotificationVisibleness(env, value, request) == nullptr) { + // return nullptr; + // } + + // progressValue?: number + // progressMaxValue?: number + // isIndeterminate?: boolean + if (GetNotificationProgressBar(env, value, request) == nullptr) { + return nullptr; + } + + // progressMaxValue?: number + // if (GetNotificationProgressMaxValueByPublish(env, value, notificationRequestData.progressMaxValue, request) == + // nullptr) { + // return nullptr; + // } + + // isIndeterminate?: boolean + // if (GetNotificationIsIndeterminateByPublish(env, value, notificationRequestData.isIndeterminate, request) == + // nullptr) { + // return nullptr; + // } + + // statusBarText?: string + if (GetNotificationStatusBarText(env, value, request) == nullptr) { + return nullptr; + } + + // // onlyLocal?: boolean + // if (GetNotificationOnlyLocal(env, value, request) == nullptr) { + // return nullptr; + // } + + // // sortingKey?: string + // if (GetNotificationSortingKey(env, value, request) == nullptr) { + // return nullptr; + // } + + // isFloatingIcon?: boolean + // if (GetNotificationIsFloatingIcon(env, value, request) == nullptr) { + // return nullptr; + // } + + // label?: string + if (GetNotificationLabel(env, value, request) == nullptr) { + return nullptr; + } + + // badgeIconStyle?: number + if (GetNotificationBadgeIconStyle(env, value, request) == nullptr) { + return nullptr; + } + + // // shortcutId?: string + // if (GetNotificationShortcutId(env, value, request) == nullptr) { + // return nullptr; + // } + + // showDeliveryTime?: boolean + if (GetNotificationShowDeliveryTime(env, value, request) == nullptr) { + return nullptr; + } + + // actionButtons?: Array + if (GetNotificationNotificationActionButtons(env, value, request) == nullptr) { + return nullptr; + } + + return Common::NapiGetNull(env); +} + +napi_value GetIdByPublish(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int32_t notificationId; + + NAPI_CALL(env, napi_has_named_property(env, value, "id", &hasProperty)); + ANS_LOGI("============GetIdByPublish hasProperty = %{public}d", hasProperty); + if (hasProperty) { + napi_get_named_property(env, value, "id", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, ¬ificationId); + request.SetNotificationId(notificationId); + ANS_LOGI("============GetIdByPublish notificationId = %{public}d", notificationId); + } else { + request.SetNotificationId(0); + } + + ANS_LOGI("end"); + return Common::NapiGetNull(env); +} + +napi_value GetSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int32_t slotType; + + NAPI_CALL(env, napi_has_named_property(env, value, "slotType", &hasProperty)); + ANS_LOGI("============GetSlotType hasProperty = %{public}d", hasProperty); + if (hasProperty) { + napi_get_named_property(env, value, "slotType", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &slotType); + + enum NotificationConstant::SlotType outType; + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + request.SetSlotType(outType); + ANS_LOGI("============GetSlotType slotType = %{public}d", slotType); + } else { + request.SetSlotType(NotificationConstant::OTHER); + } + ANS_LOGI("end"); + return Common::NapiGetNull(env); +} + +napi_value Common::GetNotificationContent(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int32_t type; + + NAPI_CALL(env, napi_has_named_property(env, value, "content", &hasProperty)); + ANS_LOGI("============GetNotificationContent hasProperty = %{public}d", hasProperty); + if (hasProperty) { + ANS_LOGI("============GetNotificationContent 000000000000000000000================"); + napi_get_named_property(env, value, "content", &result); + ANS_LOGI("============GetNotificationContent 000000001111111111111111111================"); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + ANS_LOGI("============GetNotificationContent 0000000022222222222222222================"); + ANS_LOGI("============GetNotificationContent 0000000022222222222222222================ valuetype = " + "%{public}d", + valuetype); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + ANS_LOGI("============GetNotificationContent 11111111111111================"); + if (GetNotificationContentType(env, result, type) == nullptr) { + return nullptr; + } + + NotificationContent::Type outType; + if (!ContentTypeJSToC(ContentType(type), outType)) { + return nullptr; + } + switch (outType) { + case NotificationContent::Type::BASIC_TEXT: + ANS_LOGI("============GetNotificationContent================"); + if (GetNotificationBasicContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::LONG_TEXT: + ANS_LOGI("============GetNotificationLongContentByPublish================"); + if (GetNotificationLongTextContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::PICTURE: + break; + case NotificationContent::Type::CONVERSATION: + break; + case NotificationContent::Type::MULTILINE: + ANS_LOGI("============GetNotificationMultilineContentByPublish================"); + if (GetNotificationMultiLineContent(env, result, request) == nullptr) { + return nullptr; + } + break; + case NotificationContent::Type::MEDIA: + break; + default: + return nullptr; + break; + } + } + + ANS_LOGI("end"); + return Common::NapiGetNull(env); +} + +napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isOngoing; + + NAPI_CALL(env, napi_has_named_property(env, value, "isOngoing", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isOngoing", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isOngoing); + request.SetInProgress(isOngoing); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationIsUnremovable(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isUnremovable; + + NAPI_CALL(env, napi_has_named_property(env, value, "isUnremovable", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isUnremovable", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isUnremovable); + request.SetUnremovable(isUnremovable); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationDeliveryTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int64_t deliveryTime; + + NAPI_CALL(env, napi_has_named_property(env, value, "deliveryTime", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "deliveryTime", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int64(env, result, &deliveryTime); + request.SetDeliveryTime(deliveryTime); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationtapDismissed(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool tapDismissed; + + NAPI_CALL(env, napi_has_named_property(env, value, "tapDismissed", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "tapDismissed", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &tapDismissed); + request.SetTapDismissed(tapDismissed); + } + + return Common::NapiGetNull(env); +} + +napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool hasProperty = false; + WantAgent::WantAgent *wantAgent = nullptr; + napi_value result; + napi_valuetype valuetype; + + NAPI_CALL(env, napi_has_named_property(env, value, "wantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "wantAgent", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); + napi_unwrap(env, result, (void **)&wantAgent); + if (wantAgent == nullptr) { + return nullptr; + } + std::shared_ptr sWantAgent{wantAgent}; + request.SetWantAgent(sWantAgent); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool hasProperty = false; + WantAgent::WantAgent *wantAgent = nullptr; + napi_value result; + napi_valuetype valuetype; + + NAPI_CALL(env, napi_has_named_property(env, value, "removalWantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "removalWantAgent", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); + napi_unwrap(env, result, (void **)&wantAgent); + if (wantAgent == nullptr) { + return nullptr; + } + std::shared_ptr removeWantAgent(wantAgent); + request.SetRemovalWantAgent(removeWantAgent); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool hasProperty = false; + WantAgent::WantAgent *wantAgent = nullptr; + napi_value result; + napi_valuetype valuetype; + + NAPI_CALL(env, napi_has_named_property(env, value, "maxScreenWantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "maxScreenWantAgent", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Bool expected."); + napi_unwrap(env, result, (void **)&wantAgent); + if (wantAgent == nullptr) { + return nullptr; + } + std::shared_ptr maxScreenWantAgent(wantAgent); + request.SetMaxScreenWantAgent(maxScreenWantAgent); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int64_t autoDeletedTime; + + NAPI_CALL(env, napi_has_named_property(env, value, "autoDeletedTime", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "autoDeletedTime", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int64(env, result, &autoDeletedTime); + request.SetAutoDeletedTime(autoDeletedTime); + } + + return Common::NapiGetNull(env); +} + +// napi_value GetNotificationSettingsText( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; + +// NAPI_CALL(env, napi_has_named_property(env, value, "settingsText", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "settingsText", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); +// NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); +// request.SetSettingsText(str); +// } + +// ANS_LOGI("===============GetNotificationSettingsText====settingsText = %{public}s end", str); +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationGroupValue( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; + +// NAPI_CALL(env, napi_has_named_property(env, value, "groupValue", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "groupValue", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); +// NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); +// request.SetGroupValue(str); +// } + +// ANS_LOGI("===============GetNotificationGroupValue====groupValue = %{public}s end", str); +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationGroupAlertType( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// int32_t groupAlertType; + +// NAPI_CALL(env, napi_has_named_property(env, value, "groupAlertType", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "groupAlertType", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); +// napi_get_value_int32(env, result, &groupAlertType); +// request.SetGroupAlertType(static_cast(groupAlertType)); +// } + +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationGroupOverview( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// bool groupOverview; + +// NAPI_CALL(env, napi_has_named_property(env, value, "groupOverview", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "groupOverview", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); +// napi_get_value_bool(env, result, &groupOverview); +// request.SetGroupOverview(groupOverview); +// } + +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationClassification( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; + +// NAPI_CALL(env, napi_has_named_property(env, value, "classification", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "classification", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); +// NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); +// request.SetClassification(str); +// } + +// ANS_LOGI("===============GetNotificationClassification====classification = %{public}s end", str); +// return Common::NapiGetNull(env); +// } + +napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int32_t color; + + NAPI_CALL(env, napi_has_named_property(env, value, "color", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "color", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &color); + request.SetColor(color); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationColorEnabled(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool colorEnabled; + + NAPI_CALL(env, napi_has_named_property(env, value, "colorEnabled", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "colorEnabled", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &colorEnabled); + request.SetColorEnabled(colorEnabled); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationIsAlertOnce(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isAlertOnce; + + NAPI_CALL(env, napi_has_named_property(env, value, "isAlertOnce", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isAlertOnce", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isAlertOnce); + request.SetAlertOneTime(isAlertOnce); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationIsStopwatch(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isStopwatch; + + NAPI_CALL(env, napi_has_named_property(env, value, "isStopwatch", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isStopwatch", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isStopwatch); + request.SetShowStopwatch(isStopwatch); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isCountDown; + + NAPI_CALL(env, napi_has_named_property(env, value, "isCountDown", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isCountDown", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isCountDown); + request.SetCountdownTimer(isCountDown); + } + + return Common::NapiGetNull(env); +} + +// napi_value GetNotificationVisibleness( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// int32_t visibleness; + +// NAPI_CALL(env, napi_has_named_property(env, value, "visibleness", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "visibleness", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); +// napi_get_value_int32(env, result, &visibleness); +// request.SetVisibleness(static_cast(visibleness)); +// } + +// return Common::NapiGetNull(env); +// } +napi_value GetNotificationProgressBar(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value resultProgressValue, resultProgressMaxValue, resultIsIndeterminate; + bool hasPropertyProgressValue = false; + bool hasPropertyProgressMaxValue = false; + bool hasPropertyIsIndeterminate = false; + int32_t progressValue = 0; + int32_t progressMaxValue = 0; + bool isIndeterminate = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "progressValue", &hasPropertyProgressValue)); + if (hasPropertyProgressValue) { + NAPI_CALL(env, napi_has_named_property(env, value, "progressMaxValue", &hasPropertyProgressMaxValue)); + if (hasPropertyProgressMaxValue) { + NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasPropertyIsIndeterminate)); + if (hasPropertyIsIndeterminate) { + napi_get_named_property(env, value, "progressValue", &resultProgressValue); + NAPI_CALL(env, napi_typeof(env, resultProgressValue, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, resultProgressValue, &progressValue); + + napi_get_named_property(env, value, "progressMaxValue", &resultProgressMaxValue); + NAPI_CALL(env, napi_typeof(env, resultProgressMaxValue, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, resultProgressMaxValue, &progressMaxValue); + + napi_get_named_property(env, value, "isIndeterminate", &resultIsIndeterminate); + NAPI_CALL(env, napi_typeof(env, resultIsIndeterminate, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); + napi_get_value_bool(env, resultIsIndeterminate, &isIndeterminate); + } + } + request.SetProgressBar(progressValue, progressMaxValue, isIndeterminate); + } + + return Common::NapiGetNull(env); +} + +// napi_value GetNotificationProgressMaxValueByPublish( +// const napi_env &env, const napi_value &value, int32_t &progressMaxValue, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; + +// NAPI_CALL(env, napi_has_named_property(env, value, "progressMaxValue", &hasProperty)); +// if (hasProperty) { +// // isSetRequestProperty[PROGRESSMAXVALUE] = true; +// napi_get_named_property(env, value, "progressMaxValue", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int expected."); +// napi_get_value_int32(env, result, &progressMaxValue); +// } else { +// // isSetRequestProperty[PROGRESSMAXVALUE] = false; +// } + +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationIsIndeterminateByPublish( +// const napi_env &env, const napi_value &value, bool &isIndeterminate, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; + +// NAPI_CALL(env, napi_has_named_property(env, value, "isIndeterminate", &hasProperty)); +// if (hasProperty) { +// // isSetRequestProperty[ISINDETERMINATE] = true; +// napi_get_named_property(env, value, "isIndeterminate", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); +// napi_get_value_bool(env, result, &isIndeterminate); +// } else { +// // isSetRequestProperty[ISINDETERMINATE] = false; +// } + +// return Common::NapiGetNull(env); +// } + +napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, value, "statusBarText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "statusBarText", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + request.SetStatusBarText(str); + } + + ANS_LOGI("===============GetNotificationStatusBarText====statusBarText = %{public}s end", str); + return Common::NapiGetNull(env); +} + +// napi_value GetNotificationOnlyLocal(const napi_env &env, const napi_value &value, NotificationRequest +// &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// bool onlyLocal; + +// NAPI_CALL(env, napi_has_named_property(env, value, "onlyLocal", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "onlyLocal", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); +// napi_get_value_bool(env, result, &onlyLocal); +// request.SetOnlyLocal(onlyLocal); +// } + +// return Common::NapiGetNull(env); +// } + +// napi_value GetNotificationSortingKey( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; + +// NAPI_CALL(env, napi_has_named_property(env, value, "sortingKey", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "sortingKey", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); +// NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); +// request.SetSortingKey(str); +// } + +// ANS_LOGI("===============GetNotificationSortingKey====sortingKey = %{public}s end", str); +// return Common::NapiGetNull(env); +// } + +napi_value GetNotificationIsFloatingIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool isFloatingIcon; + + NAPI_CALL(env, napi_has_named_property(env, value, "isFloatingIcon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isFloatingIcon", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); + napi_get_value_bool(env, result, &isFloatingIcon); + request.SetOnlyLocal(isFloatingIcon); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, value, "label", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "label", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + request.SetLabel(str); + } + + ANS_LOGI("===============GetNotificationLabel====label = %{public}s end", str); + return Common::NapiGetNull(env); +} + +napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + int32_t badgeIconStyle; + + NAPI_CALL(env, napi_has_named_property(env, value, "badgeIconStyle", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "badgeIconStyle", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, result, &badgeIconStyle); + request.SetBadgeIconStyle(static_cast(badgeIconStyle)); + } + + return Common::NapiGetNull(env); +} + +// napi_value GetNotificationShortcutId( +// const napi_env &env, const napi_value &value, NotificationRequest &request) +// { +// ANS_LOGI("enter"); + +// napi_valuetype valuetype; +// napi_value result; +// bool hasProperty = false; +// char str[STR_MAX_SIZE] = {0}; +// size_t strLen = 0; + +// NAPI_CALL(env, napi_has_named_property(env, value, "shortcutId", &hasProperty)); +// if (hasProperty) { +// napi_get_named_property(env, value, "shortcutId", &result); +// NAPI_CALL(env, napi_typeof(env, result, &valuetype)); +// NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); +// NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); +// request.SetShortcutId(str); +// } + +// ANS_LOGI("===============GetNotificationShortcutId====shortcutId = %{public}s end", str); +// return Common::NapiGetNull(env); +// } + +napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value result; + bool hasProperty = false; + bool showDeliveryTime; + + NAPI_CALL(env, napi_has_named_property(env, value, "showDeliveryTime", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "showDeliveryTime", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. bool expected."); + napi_get_value_bool(env, result, &showDeliveryTime); + request.SetShowDeliveryTime(showDeliveryTime); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationNotificationActionButtons( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool isArray = false; + napi_valuetype valuetype; + napi_value actionButtons; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + uint32_t length = 0; + bool hasProperty = false; + napi_value titelActionButton, wantAgentActionButton; + std::string title; + WantAgent::WantAgent *wantAgentPtr = nullptr; + std::shared_ptr wantAgent; + + napi_get_named_property(env, value, "actionButtons", &actionButtons); + napi_is_array(env, actionButtons, &isArray); + if (isArray) { + napi_get_array_length(env, actionButtons, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value actionButton; + napi_get_element(env, actionButtons, i, &actionButton); + NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "title", &titelActionButton); + NAPI_CALL(env, napi_typeof(env, titelActionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, titelActionButton, str, STR_MAX_SIZE - 1, &strLen)); + title = str; + } + + NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "wantAgent", &wantAgentActionButton); + NAPI_CALL(env, napi_typeof(env, wantAgentActionButton, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. String expected."); + napi_unwrap(env, wantAgentActionButton, (void **)&wantAgentPtr); + if (wantAgentPtr == nullptr) { + return nullptr; + } + std::shared_ptr wantAgentOut(wantAgentPtr); + wantAgent = wantAgentOut; + } + + std::vector> vec{nullptr}; + + auto pActionButton = NotificationActionButton::Create( + nullptr, title, wantAgent, nullptr, NotificationConstant::ARCHIVE_ACTION_BUTTON, false, vec, false); + request.AddActionButton(pActionButton); + } + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type) +{ + ANS_LOGI("enter"); + + napi_value contentResult; + napi_valuetype valuetype; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, result, "contentType", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, result, "contentType", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, contentResult, &type); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value contentResult, basicContentResult; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, result, "normal", &hasProperty)); + if (hasProperty) { + std::shared_ptr normalContent = std::make_shared(); + napi_get_named_property(env, result, "normal", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + normalContent->SetTitle(str); + ANS_LOGI("normal::title = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + normalContent->SetText(str); + ANS_LOGI("normal::text = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + normalContent->SetAdditionalText(str); + ANS_LOGI("normal::additionalText = %{public}s", str); + } + request.SetContent(std::make_shared(normalContent)); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value contentResult, longContentResult, basicContentResult; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); + if (hasProperty) { + std::shared_ptr longContent = + std::make_shared(); + napi_get_named_property(env, result, "longText", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetTitle(str); + ANS_LOGI("longText::title = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetText(str); + ANS_LOGI("longText::text = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetAdditionalText(str); + ANS_LOGI("longText::additionalText = %{public}s", str); + } + + napi_get_named_property(env, result, "longText", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "longText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "longText", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetLongText(str); + ANS_LOGI("longText::longText = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "briefText", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetBriefText(str); + ANS_LOGI("longText::briefText = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "expandedTitle", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetExpandedTitle(str); + ANS_LOGI("longText::expandedTitle = %{public}s", str); + } + request.SetContent(std::make_shared(longContent)); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + napi_value contentResult, multiLineContentResult, basicContentResult; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, result, "multiLine", &hasProperty)); + if (hasProperty) { + std::shared_ptr multiLineContent = + std::make_shared(); + napi_get_named_property(env, result, "multiLine", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "title", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetTitle(str); + ANS_LOGI("multiLine::title = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "text", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetText(str); + ANS_LOGI("multiLine::text = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); + NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetAdditionalText(str); + ANS_LOGI("multiLine::additionalText = %{public}s", str); + } + + napi_get_named_property(env, result, "multiLine", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetBriefText(str); + ANS_LOGI("multiLine: briefText = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetExpandedTitle(str); + ANS_LOGI("multiLine: longTitle = %{public}s", str); + } + + NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); + if (hasProperty) { + if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { + return nullptr; + } + } + + request.SetContent(std::make_shared(multiLineContent)); + } + + return Common::NapiGetNull(env); +} + +napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, + std::shared_ptr &multiLineContent) +{ + ANS_LOGI("enter"); + + bool isArray = false; + napi_valuetype valuetype; + napi_value multilines; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + uint32_t length = 0; + + napi_get_named_property(env, result, "lines", &multilines); + napi_is_array(env, multilines, &isArray); + if (isArray) { + napi_get_array_length(env, multilines, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value line; + napi_get_element(env, multilines, i, &line); + NAPI_CALL(env, napi_typeof(env, line, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, line, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->AddSingleLine(str); + ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", str); + } + } + + return Common::NapiGetNull(env); +} + +napi_value Common::GetNotificationSlot(const napi_env &env, NotificationSlot &slot, const napi_value &result) +{ + ANS_LOGI("enter"); + napi_value nobj = nullptr; + napi_valuetype valuetype; + bool hasProperty = false; + size_t strLen = 0; + uint32_t length = 0; + + // type: notification.SlotType + int slotType = 0; + napi_get_named_property(env, result, "type", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &slotType); + + enum NotificationConstant::SlotType outType; + if (!SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + slot.SetType(outType); + + // level?: number + NAPI_CALL(env, napi_has_named_property(env, result, "level", &hasProperty)); + if (hasProperty) { + int level = 0; + napi_get_named_property(env, result, "level", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &level); + ANS_LOGI("level is: %{public}d", level); + slot.SetLevel(NotificationSlot::NotificationLevel(level)); + } + + // desc?: string + NAPI_CALL(env, napi_has_named_property(env, result, "desc", &hasProperty)); + if (hasProperty) { + std::string desc; + char str[STR_MAX_SIZE] = {0}; + napi_get_named_property(env, result, "desc", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); + desc = str; + ANS_LOGI("desc is: %{public}s", desc.c_str()); + slot.SetDescription(desc); + } + + // showBadgeFlag?: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "showBadgeFlag", &hasProperty)); + if (hasProperty) { + bool showBadgeFlag = false; + napi_get_named_property(env, result, "showBadgeFlag", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, nobj, &showBadgeFlag); + ANS_LOGI("showBadgeFlag is: %{public}d", showBadgeFlag); + slot.EnableBadge(showBadgeFlag); + } + + // bypassDnd?: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "bypassDnd", &hasProperty)); + if (hasProperty) { + bool bypassDnd = false; + napi_get_named_property(env, result, "bypassDnd", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, nobj, &bypassDnd); + ANS_LOGI("bypassDnd is: %{public}d", bypassDnd); + slot.EnableBypassDnd(bypassDnd); + } + + // lockscreenVisibility?: number + NAPI_CALL(env, napi_has_named_property(env, result, "lockscreenVisibility", &hasProperty)); + if (hasProperty) { + int lockscreenVisibility = 0; + napi_get_named_property(env, result, "lockscreenVisibility", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &lockscreenVisibility); + ANS_LOGI("lockscreenVisibility is: %{public}d", lockscreenVisibility); + slot.SetLockscreenVisibleness(NotificationConstant::VisiblenessType(lockscreenVisibility)); + } + + // vibrationEnabled?: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "vibrationEnabled", &hasProperty)); + if (hasProperty) { + bool vibrationEnabled = false; + napi_get_named_property(env, result, "vibrationEnabled", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, nobj, &vibrationEnabled); + ANS_LOGI("vibrationEnabled is: %{public}d", vibrationEnabled); + slot.SetEnableVibration(vibrationEnabled); + } + + // sound?: string + NAPI_CALL(env, napi_has_named_property(env, result, "sound", &hasProperty)); + if (hasProperty) { + std::string sound; + char str[STR_MAX_SIZE] = {0}; + napi_get_named_property(env, result, "sound", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); + sound = str; + ANS_LOGI("sound is: %{public}s", sound.c_str()); + slot.SetSound(Uri(sound)); + } + + // lightEnabled?: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "lightEnabled", &hasProperty)); + if (hasProperty) { + bool lightEnabled = false; + napi_get_named_property(env, result, "lightEnabled", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, nobj, &lightEnabled); + ANS_LOGI("lightEnabled is: %{public}d", lightEnabled); + slot.SetEnableLight(lightEnabled); + } + + // lightColor?: number + NAPI_CALL(env, napi_has_named_property(env, result, "lightColor", &hasProperty)); + if (hasProperty) { + int lightColor = 0; + napi_get_named_property(env, result, "lightColor", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &lightColor); + ANS_LOGI("lightColor is: %{public}d", lightColor); + slot.SetLedLightColor(lightColor); + } + + // vibrationValues?: Array + NAPI_CALL(env, napi_has_named_property(env, result, "vibrationValues", &hasProperty)); + if (hasProperty) { + bool isArray = false; + napi_get_named_property(env, result, "vibrationValues", &nobj); + napi_is_array(env, nobj, &isArray); + if (isArray) { + napi_get_array_length(env, nobj, &length); + std::vector vibrationValues; + for (size_t i = 0; i < length; i++) { + napi_value nVibrationValue; + int64_t vibrationValue = 0; + napi_get_element(env, nobj, i, &nVibrationValue); + NAPI_CALL(env, napi_typeof(env, nVibrationValue, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int64(env, nVibrationValue, &vibrationValue); + ANS_LOGI("vibrationValue is: %{public}lld", vibrationValue); + vibrationValues.emplace_back(vibrationValue); + } + if (vibrationValues.size() > 0) { + slot.SetVibrationStyle(vibrationValues); + } + } + } + return NapiGetNull(env); +} + +bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationContent::Type &outType) +{ + switch (inType) { + case ContentType::NOTIFICATION_CONTENT_BASIC_TEXT: + outType = NotificationContent::Type::BASIC_TEXT; + break; + case ContentType::NOTIFICATION_CONTENT_LONG_TEXT: + outType = NotificationContent::Type::LONG_TEXT; + break; + case ContentType::NOTIFICATION_CONTENT_PICTURE: + outType = NotificationContent::Type::PICTURE; + break; + case ContentType::NOTIFICATION_CONTENT_CONVERSATION: + outType = NotificationContent::Type::CONVERSATION; + break; + case ContentType::NOTIFICATION_CONTENT_MULTILINE: + outType = NotificationContent::Type::MULTILINE; + break; + case ContentType::NOTIFICATION_CONTENT_MEDIA: + outType = NotificationContent::Type::MEDIA; + break; + default: + ANS_LOGI("contentType is error"); + return false; + } + return true; +} + +bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum ContentType &outType) +{ + switch (inType) { + case NotificationContent::Type::BASIC_TEXT: + outType = ContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + break; + case NotificationContent::Type::LONG_TEXT: + outType = ContentType::NOTIFICATION_CONTENT_LONG_TEXT; + break; + case NotificationContent::Type::PICTURE: + outType = ContentType::NOTIFICATION_CONTENT_PICTURE; + break; + case NotificationContent::Type::CONVERSATION: + outType = ContentType::NOTIFICATION_CONTENT_CONVERSATION; + break; + case NotificationContent::Type::MULTILINE: + outType = ContentType::NOTIFICATION_CONTENT_MULTILINE; + break; + case NotificationContent::Type::MEDIA: + outType = ContentType::NOTIFICATION_CONTENT_MEDIA; + break; + default: + ANS_LOGI("contentType is error"); + return false; + } + return true; +} + +bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstant::SlotType &outType) +{ + switch (inType) { + case SlotType::UNKNOWN_TYPE: + outType = NotificationConstant::SlotType::CUSTOM; + break; + case SlotType::SOCIAL_COMMUNICATION: + outType = NotificationConstant::SlotType::SOCIAL_COMMUNICATION; + break; + case SlotType::SERVICE_INFORMATION: + outType = NotificationConstant::SlotType::SERVICE_REMINDER; + break; + case SlotType::CONTENT_INFORMATION: + outType = NotificationConstant::SlotType::CONTENT_INFORMATION; + break; + case SlotType::OTHER_TYPES: + outType = NotificationConstant::SlotType::OTHER; + break; + default: + ANS_LOGI("slotType is error"); + return false; + } + return true; +} + +bool Common::SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, enum SlotType &outType) +{ + switch (inType) { + case NotificationConstant::SlotType::CUSTOM: + outType = SlotType::UNKNOWN_TYPE; + break; + case NotificationConstant::SlotType::SOCIAL_COMMUNICATION: + outType = SlotType::SOCIAL_COMMUNICATION; + break; + case NotificationConstant::SlotType::SERVICE_REMINDER: + outType = SlotType::SERVICE_INFORMATION; + break; + case NotificationConstant::SlotType::CONTENT_INFORMATION: + outType = SlotType::CONTENT_INFORMATION; + break; + case NotificationConstant::SlotType::OTHER: + outType = SlotType::OTHER_TYPES; + break; + default: + ANS_LOGI("slotType is error"); + return false; + } + return true; +} + +bool Common::ReasonCToJS(const int &inType, int &outType) +{ + switch (inType) { + case NotificationConstant::CLICK_REASON_DELETE: + outType = NotificationReason::CLICK_REASON_DELETE; + break; + case NotificationConstant::CANCEL_REASON_DELETE: + outType = NotificationReason::CANCEL_REASON_DELETE; + break; + case NotificationConstant::CANCEL_ALL_REASON_DELETE: + outType = NotificationReason::CANCEL_ALL_REASON_DELETE; + break; + case NotificationConstant::ERROR_REASON_DELETE: + outType = NotificationReason::ERROR_REASON_DELETE; + break; + case NotificationConstant::PACKAGE_CHANGED_REASON_DELETE: + outType = NotificationReason::PACKAGE_CHANGED_REASON_DELETE; + break; + case NotificationConstant::USER_STOPPED_REASON_DELETE: + outType = NotificationReason::USER_STOPPED_REASON_DELETE; + break; + case NotificationConstant::APP_CANCEL_REASON_DELETE: + outType = NotificationReason::APP_CANCEL_REASON_DELETE; + break; + case NotificationConstant::APP_CANCEL_ALL_REASON_DELETE: + outType = NotificationReason::APP_CANCEL_ALL_REASON_DELETE; + break; + case NotificationConstant::APP_CANCEL_REASON_OTHER: + outType = NotificationReason::APP_CANCEL_REASON_OTHER; + break; + default: + ANS_LOGI("reason is error"); + return false; + } + return true; +} + +bool Common::DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationConstant::DisturbMode &outType) +{ + switch (inType) { + case DisturbMode::ALLOW_UNKNOWN: + outType = NotificationConstant::DisturbMode::ALLOW_UNKNOWN; + break; + case DisturbMode::ALLOW_ALL: + outType = NotificationConstant::DisturbMode::ALLOW_ALL; + break; + case DisturbMode::ALLOW_PRIORITY: + outType = NotificationConstant::DisturbMode::ALLOW_PRIORITY; + break; + case DisturbMode::ALLOW_NONE: + outType = NotificationConstant::DisturbMode::ALLOW_NONE; + break; + case DisturbMode::ALLOW_ALARMS: + outType = NotificationConstant::DisturbMode::ALLOW_ALARMS; + break; + default: + ANS_LOGI("disturbMode is error"); + return false; + } + return true; +} + +napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent) +{ + if (agent == nullptr) { + ANS_LOGI("agent is nullptr"); + return nullptr; + } + napi_value wantAgent = nullptr; + napi_value wantAgentClass = nullptr; + napi_define_class(env, + "wantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); + napi_new_instance(env, wantAgentClass, 0, nullptr, &wantAgent); + napi_wrap(env, wantAgent, (void *)agent.get(), [](napi_env env, void *data, void *hint) {}, nullptr, nullptr); + + return wantAgent; +} +} // namespace NotificationNapi +} // namespace OHOS diff --git a/kits/napi/src/constant.cpp b/kits/napi/src/constant.cpp new file mode 100644 index 000000000..7744cfa77 --- /dev/null +++ b/kits/napi/src/constant.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2021 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 "constant.h" +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName) +{ + napi_value prop = nullptr; + if (napi_create_int32(env, objName, &prop) == napi_ok) { + napi_set_named_property(env, dstObj, propName, prop); + } +} + +napi_value NotificationReasonInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, NotificationReason::CLICK_REASON_DELETE, "CLICK_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::CANCEL_REASON_DELETE, "CANCEL_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::CANCEL_ALL_REASON_DELETE, "CANCEL_ALL_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::ERROR_REASON_DELETE, "ERROR_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, NotificationReason::PACKAGE_CHANGED_REASON_DELETE, "PACKAGE_CHANGED_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::USER_STOPPED_REASON_DELETE, "USER_STOPPED_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, NotificationReason::PACKAGE_BANNED_REASON_DELETE, "PACKAGE_BANNED_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::APP_CANCEL_REASON_DELETE, "APP_CANCEL_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, NotificationReason::APP_CANCEL_ALL_REASON_DELETE, "APP_CANCEL_ALL_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, NotificationReason::APP_CANCEL_REASON_OTHER, "APP_CANCEL_REASON_OTHER"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("NotificationReason", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value SlotTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, SlotType::UNKNOWN_TYPE, "UNKNOWN_TYPE"); + SetNamedPropertyByInteger(env, obj, SlotType::SOCIAL_COMMUNICATION, "SOCIAL_COMMUNICATION"); + SetNamedPropertyByInteger(env, obj, SlotType::SERVICE_INFORMATION, "SERVICE_INFORMATION"); + SetNamedPropertyByInteger(env, obj, SlotType::CONTENT_INFORMATION, "CONTENT_INFORMATION"); + SetNamedPropertyByInteger(env, obj, SlotType::OTHER_TYPES, "OTHER_TYPES"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("SlotType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value SemanticActionButtonInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, SemanticActionButton::NONE_ACTION_BUTTON, "NONE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::REPLY_ACTION_BUTTON, "REPLY_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::READ_ACTION_BUTTON, "READ_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::UNREAD_ACTION_BUTTON, "UNREAD_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::DELETE_ACTION_BUTTON, "DELETE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::ARCHIVE_ACTION_BUTTON, "ARCHIVE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::MUTE_ACTION_BUTTON, "MUTE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::UNMUTE_ACTION_BUTTON, "UNMUTE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::THUMBS_UP_ACTION_BUTTON, "THUMBS_UP_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::THUMBS_DOWN_ACTION_BUTTON, "THUMBS_DOWN_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, SemanticActionButton::CALL_ACTION_BUTTON, "CALL_ACTION_BUTTON"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("SemanticActionButton", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value InputsSourceInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, InputsSource::FREE_FORM_INPUT, "FREE_FORM_INPUT"); + SetNamedPropertyByInteger(env, obj, InputsSource::OPTION, "OPTION"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("InputsSource", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value DisturbModeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_UNKNOWN, "ALLOW_UNKNOWN"); + SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_ALL, "ALLOW_ALL"); + SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_PRIORITY, "ALLOW_PRIORITY"); + SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_NONE, "ALLOW_NONE"); + SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_ALARMS, "ALLOW_ALARMS"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("DisturbMode", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value InputEditTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_AUTO, "EDIT_AUTO"); + SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_DISABLED, "EDIT_DISABLED"); + SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_ENABLED, "EDIT_ENABLED"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("InputEditType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value ContentTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger( + env, obj, ContentType::NOTIFICATION_CONTENT_BASIC_TEXT, "NOTIFICATION_CONTENT_BASIC_TEXT"); + SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_LONG_TEXT, "NOTIFICATION_CONTENT_LONG_TEXT"); + SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_PICTURE, "NOTIFICATION_CONTENT_PICTURE"); + SetNamedPropertyByInteger( + env, obj, ContentType::NOTIFICATION_CONTENT_CONVERSATION, "NOTIFICATION_CONTENT_CONVERSATION"); + SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_MULTILINE, "NOTIFICATION_CONTENT_MULTILINE"); + SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_MEDIA, "NOTIFICATION_CONTENT_MEDIA"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("ContentType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value ConstantInit(napi_env env, napi_value exports) +{ + NotificationReasonInit(env, exports); + SlotTypeInit(env, exports); + SemanticActionButtonInit(env, exports); + InputsSourceInit(env, exports); + DisturbModeInit(env, exports); + InputEditTypeInit(env, exports); + ContentTypeInit(env, exports); + return exports; +} + +} // namespace NotificationNapi +} // namespace OHOS diff --git a/kits/napi/src/create_subscriber.cpp b/kits/napi/src/create_subscriber.cpp new file mode 100644 index 000000000..d256718b2 --- /dev/null +++ b/kits/napi/src/create_subscriber.cpp @@ -0,0 +1,988 @@ +/* + * Copyright (c) 2021 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 +#include "create_subscriber.h" + +namespace OHOS { +namespace NotificationNapi { +SubscriberInstance::SubscriberInstance() +{} + +SubscriberInstance::~SubscriberInstance() +{} + +void SubscriberInstance::OnCanceled(const std::shared_ptr &request) +{ + ANS_LOGI("OnCanceled start"); + + if (canceCallbackInfo_.ref == nullptr) { + ANS_LOGI("cancel callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + ANS_LOGI("OnCanceled NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(canceCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->request = request; + dataWorker->env = canceCallbackInfo_.env; + dataWorker->ref = canceCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnCanceled uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGI("dataWorkerData is nullptr"); + return; + } + napi_value result; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscriberCallbackData(dataWorkerData->env, dataWorkerData->request, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) +{ + ANS_LOGI("OnCanceled2 start"); + + if (canceCallbackInfo_.ref == nullptr) { + ANS_LOGI("cancel callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnCanceled2 NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + ANS_LOGI("OnCanceled2 sortingMap size = %{public}d", sortingMap->GetKey().size()); + ANS_LOGI("OnCanceled2 deleteReason = %{public}d", deleteReason); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(canceCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->request = request; + dataWorker->sortingMap = sortingMap; + dataWorker->deleteReason = deleteReason; + dataWorker->env = canceCallbackInfo_.env; + dataWorker->ref = canceCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnCanceled2 uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscriberCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + dataWorkerData->deleteReason, + result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnConsumed(const std::shared_ptr &request) +{ + ANS_LOGI("OnConsumed start"); + + if (consumeCallbackInfo_.ref == nullptr) { + ANS_LOGI("consume callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + ANS_LOGI("OnConsumed NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->request = request; + dataWorker->env = consumeCallbackInfo_.env; + dataWorker->ref = consumeCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnConsumed uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscriberCallbackData(dataWorkerData->env, dataWorkerData->request, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) +{ + ANS_LOGI("OnConsumed2 start"); + + if (consumeCallbackInfo_.ref == nullptr) { + ANS_LOGI("consume callback unset"); + return; + } + + if (request == nullptr) { + ANS_LOGE("request is null"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnConsumed2 NotificationId = %{public}d", request->GetNotificationRequest().GetNotificationId()); + ANS_LOGI("OnConsumed2 sortingMap size = %{public}d", sortingMap->GetKey().size()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->request = request; + dataWorker->sortingMap = sortingMap; + dataWorker->env = consumeCallbackInfo_.env; + dataWorker->ref = consumeCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnConsumed2 uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!SetSubscriberCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + dataWorkerData->deleteReason, + result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) +{ + ANS_LOGI("OnUpdate start"); + + if (updateCallbackInfo_.ref == nullptr) { + ANS_LOGI("update callback unset"); + return; + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return; + } + ANS_LOGI("OnUpdate sortingMap size = %{public}d", sortingMap->GetKey().size()); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(updateCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->sortingMap = sortingMap; + dataWorker->env = updateCallbackInfo_.env; + dataWorker->ref = updateCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnUpdate uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + napi_value result; + napi_create_object(dataWorkerData->env, &result); + int error = 0; + if (!Common::SetNotificationSortingMap(dataWorkerData->env, dataWorkerData->sortingMap, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + error = ERROR; + } else { + error = NO_ERROR; + } + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) +{ + ANS_LOGI("OnSubscribeResult start"); + + if (subscribeCallbackInfo_.ref == nullptr) { + ANS_LOGI("subscribe callback unset"); + return; + } + ANS_LOGI("OnSubscribeResult result = %{public}d", result); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(subscribeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->result = (int)result; + dataWorker->env = subscribeCallbackInfo_.env; + dataWorker->ref = subscribeCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnSubscribeResult uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // result: number + napi_value result; + napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +{ + ANS_LOGI("OnUnsubscribeResult start"); + + if (unsubscribeCallbackInfo_.ref == nullptr) { + ANS_LOGI("unsubscribe callback unset"); + return; + } + ANS_LOGI("OnUnsubscribeResult result = %{public}d", result); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(unsubscribeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->result = (int)result; + dataWorker->env = unsubscribeCallbackInfo_.env; + dataWorker->ref = unsubscribeCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnUnsubscribeResult uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // result: number + napi_value result; + napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnDied() +{ + ANS_LOGI("OnDied start"); + + if (dieCallbackInfo_.ref == nullptr) { + ANS_LOGE("die callback unset"); + return; + } + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(dieCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->env = dieCallbackInfo_.env; + dataWorker->ref = dieCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnDied uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + + Common::SetCallback( + dataWorkerData->env, dataWorkerData->ref, NO_ERROR, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::OnDisturbModeChanged(int disturbMode) +{ + ANS_LOGI("OnDisturbModeChanged start"); + + if (disturbModeCallbackInfo_.ref == nullptr) { + ANS_LOGI("disturbModeChange callback unset"); + return; + } + ANS_LOGI("OnDisturbModeChanged disturbMode = %{public}d", disturbMode); + + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + + NotificationReceiveDataWorker *dataWorker = new NotificationReceiveDataWorker(); + dataWorker->disturbMode = disturbMode; + dataWorker->env = disturbModeCallbackInfo_.env; + dataWorker->ref = disturbModeCallbackInfo_.ref; + + uv_work_t *work = new uv_work_t; + work->data = (void *)dataWorker; + + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + ANS_LOGI("OnDisturbModeChanged uv_work_t start"); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + return; + } + // disturbMode: number + napi_value result; + napi_create_int32(dataWorkerData->env, dataWorkerData->disturbMode, &result); + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); +} + +void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + canceCallbackInfo_.env = env; + canceCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + consumeCallbackInfo_.env = env; + consumeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + updateCallbackInfo_.env = env; + updateCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + subscribeCallbackInfo_.env = env; + subscribeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + unsubscribeCallbackInfo_.env = env; + unsubscribeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + dieCallbackInfo_.env = env; + dieCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + disturbModeCallbackInfo_.env = env; + disturbModeCallbackInfo_.ref = ref; +} + +void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) +{ + if (type == CONSUME) { + SetConsumeCallbackInfo(env, ref); + } else if (type == CANCEL) { + SetCancelCallbackInfo(env, ref); + } else if (type == UPDATE) { + SetUpdateCallbackInfo(env, ref); + } else if (type == SUBSCRIBE) { + SetSubscribeCallbackInfo(env, ref); + } else if (type == UNSUBSCRIBE) { + SetUnsubscribeCallbackInfo(env, ref); + } else if (type == DIE) { + SetDieCallbackInfo(env, ref); + } else if (type == DISTURB_MODE_CHANGE) { + SetDisturbModeCallbackInfo(env, ref); + } else { + ANS_LOGI("type is error"); + } +} + +napi_value ParseParametersByOn(const napi_env &env, const size_t &argc, const napi_value (&argv)[ON_MAX_PARA], + std::string &type, napi_ref &callback) +{ + ANS_LOGI("napi_value ParseParametersByOn start"); + napi_valuetype valuetype; + size_t strLen = 0; + char str[STR_MAX_SIZE] = {0}; + + if (argc >= ON_MAX_PARA) { + // argv[0]:type + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + type = str; + if (!(type == CONSUME || type == CANCEL || type == UPDATE || type == SUBSCRIBE || type == UNSUBSCRIBE || + type == DIE || type == DISTURB_MODE_CHANGE)) { + ANS_LOGI("type parameter is error"); + return nullptr; + } + + // argv[1]:callback + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +napi_value On(napi_env env, napi_callback_info info) +{ + ANS_LOGI("On start"); + + size_t argc = ON_MAX_PARA; + napi_value argv[ON_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ON_MAX_PARA, "Wrong number of arguments"); + + std::string type; + napi_ref callback = 0; + if (ParseParametersByOn(env, argc, argv, type, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + SubscriberInstance *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + ANS_LOGI("On objectInfo = %{public}p", objectInfo); + + AsyncCallbackInfoOn *asynccallbackinfo = new AsyncCallbackInfoOn{ + .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = callback}; + + if (!AddAsyncCallbackInfoOn(objectInfo, asynccallbackinfo)) { + return Common::NapiGetNull(env); + } + + napi_value resourceName; + napi_create_string_latin1(env, "on", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("On napi_create_async_work start"); + AsyncCallbackInfoOn *asynccallbackinfo = (AsyncCallbackInfoOn *)data; + ANS_LOGI("On asynccallbackinfo->type = %{public}s", asynccallbackinfo->type.c_str()); + asynccallbackinfo->objectInfo->SetCallbackInfo(env, asynccallbackinfo->type, asynccallbackinfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("On napi_create_async_work end"); + AsyncCallbackInfoOn *asynccallbackinfo = (AsyncCallbackInfoOn *)data; + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + return Common::NapiGetNull(env); +} + +napi_value ParseParametersByOff( + const napi_env &env, const size_t &argc, const napi_value (&argv)[OFF_MAX_PARA], std::string &type) +{ + ANS_LOGI("napi_value ParseParametersByOff start"); + napi_valuetype valuetype; + size_t strLen = 0; + char str[STR_MAX_SIZE] = {0}; + + if (argc >= OFF_MAX_PARA) { + // argv[0]:type + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + type = str; + if (!(type == CONSUME || type == CANCEL || type == UPDATE || type == SUBSCRIBE || type == UNSUBSCRIBE || + type == DIE || type == DISTURB_MODE_CHANGE)) { + ANS_LOGI("type parameter is error"); + return nullptr; + } + } + return Common::NapiGetNull(env); +} + +napi_value Off(napi_env env, napi_callback_info info) +{ + ANS_LOGI("Off start"); + + size_t argc = OFF_MAX_PARA; + napi_value argv[OFF_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= OFF_MAX_PARA, "Wrong number of arguments"); + + std::string type; + if (ParseParametersByOff(env, argc, argv, type) == nullptr) { + return Common::NapiGetNull(env); + } + + SubscriberInstance *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + ANS_LOGI("Off objectInfo = %{public}p", objectInfo); + + AsyncCallbackInfoOff *asynccallbackinfo = new AsyncCallbackInfoOff{ + .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .type = type, .callback = nullptr}; + + napi_value resourceName; + napi_create_string_latin1(env, "off", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Off napi_create_async_work start"); + AsyncCallbackInfoOff *asynccallbackinfo = (AsyncCallbackInfoOff *)data; + ANS_LOGI("Off asynccallbackinfo->type = %{public}s", asynccallbackinfo->type.c_str()); + asynccallbackinfo->objectInfo->SetCallbackInfo(env, asynccallbackinfo->type, asynccallbackinfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Off napi_create_async_work end"); + AsyncCallbackInfoOff *asynccallbackinfo = (AsyncCallbackInfoOff *)data; + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + + DelAsyncCallbackInfoOn(asynccallbackinfo->objectInfo, asynccallbackinfo->type); + + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + return Common::NapiGetNull(env); +} + +napi_value CreateSubscriber(napi_env env, napi_callback_info info) +{ + ANS_LOGI("CreateSubscriber start"); + + size_t argc = 0; + napi_value argv[1]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == 0, "Wrong number of arguments"); + + napi_value result = 0; + napi_new_instance(env, g_NotificationSubscriber, 0, nullptr, &result); + + return result; +} + +napi_value SubscriberConstructor(napi_env env, napi_callback_info info) +{ + ANS_LOGI("SubscriberConstructor start"); + + size_t argc = 0; + napi_value argv[1]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + + SubscriberInstance *objectInfo = nullptr; + if (!CreateSubscriberInstanceRecord(&objectInfo)) { + return Common::NapiGetNull(env); + } + ANS_LOGI("SubscriberConstructor objectInfo = %{public}p", objectInfo); + + napi_wrap(env, + thisVar, + objectInfo, + [](napi_env env, void *data, void *hint) { + SubscriberInstance *objectInfo = (SubscriberInstance *)data; + ANS_LOGI("SubscriberConstructor this = %{public}p, destruct", objectInfo); + + DelAsyncCallbackInfoOn(objectInfo); + + if (objectInfo) { + delete objectInfo; + objectInfo = nullptr; + } + }, + nullptr, + nullptr); + + ANS_LOGI("SubscriberConstructor end"); + return thisVar; +} + +bool CreateSubscriberInstanceRecord(SubscriberInstance **subscriber) +{ + ANS_LOGI("CreateSubscriberInstanceRecord start"); + + *subscriber = new SubscriberInstance(); + + if (*subscriber == nullptr) { + ANS_LOGE("subscriber is null"); + return false; + } + + std::vector info; + g_SubscriberInstances[*subscriber] = info; + + return true; +} + +bool AddAsyncCallbackInfoOn(SubscriberInstance *subscriber, AsyncCallbackInfoOn *asynccallbackinfo) +{ + ANS_LOGI("AddAsyncCallbackInfoOn start"); + + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null"); + return false; + } + + if (asynccallbackinfo == nullptr) { + ANS_LOGE("asynccallbackinfo is null"); + return false; + } + + std::lock_guard lock(mutex_); + auto infoItem = g_SubscriberInstances.find(subscriber); + if (infoItem != g_SubscriberInstances.end()) { + ANS_LOGI("AddAsyncCallbackInfoOn AsyncCallbackInfoOn size = %{public}d", infoItem->second.size()); + for (auto asyncCallbackInfoOn : infoItem->second) { + ANS_LOGI("AddAsyncCallbackInfoOn AsyncCallbackInfoOn ptr = %{public}p", asyncCallbackInfoOn); + ANS_LOGI("AsyncCallbackInfoOn->type = %{public}s", asyncCallbackInfoOn->type.c_str()); + if (asyncCallbackInfoOn->type == asynccallbackinfo->type) { + asyncCallbackInfoOn = asynccallbackinfo; + return true; + } + } + g_SubscriberInstances[subscriber].emplace_back(asynccallbackinfo); + } else { + ANS_LOGE("the current subscriber does not exist"); + return false; + } + + return true; +} + +bool DelAsyncCallbackInfoOn(SubscriberInstance *subscriber, const std::string &type) +{ + ANS_LOGI("DelSubscriberInstance start"); + + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null"); + return false; + } + + std::lock_guard lock(mutex_); + + auto infoItem = g_SubscriberInstances.find(subscriber); + if (infoItem != g_SubscriberInstances.end()) { + ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn size = %{public}d", infoItem->second.size()); + if (type.empty()) { + for (auto asyncCallbackInfoOn : infoItem->second) { + ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn ptr = %{public}p", asyncCallbackInfoOn); + delete asyncCallbackInfoOn; + asyncCallbackInfoOn = nullptr; + } + g_SubscriberInstances.erase(subscriber); + } else { + for (auto it = infoItem->second.begin(); it != infoItem->second.end(); ++it) { + ANS_LOGI("DelSubscriberInstance AsyncCallbackInfoOn ptr = %{public}p", *it); + ANS_LOGI("DelSubscriberInstance type = %{public}s", (*it)->type.c_str()); + if ((*it)->type == type) { + delete *it; + *it = nullptr; + infoItem->second.erase(it); + break; + } + } + if (infoItem->second.size() == 0) { + g_SubscriberInstances.erase(subscriber); + } + } + } else { + return false; + } + + return true; + + ANS_LOGI("DelSubscriberInstance end"); +} + +bool HasNotificationSubscriber(SubscriberInstance *subscriber) +{ + ANS_LOGI("HasNotificationSubscriber start"); + + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null"); + return false; + } + + std::lock_guard lock(mutex_); + + auto infoItem = g_SubscriberInstances.find(subscriber); + if (infoItem != g_SubscriberInstances.end()) { + return true; + } else { + ANS_LOGE("HasNotificationSubscriber The curren subscriber does not exist"); + return false; + } +} + +napi_value SetSubscriberCallbackData( + const napi_env &env, const std::shared_ptr &request, napi_value &result) +{ + ANS_LOGI("SetSubscriberCallbackData start"); + if (request == nullptr) { + ANS_LOGE("request is null"); + return Common::NapiGetboolean(env, false); + } + + // request: NotificationRequest + napi_value requestResult; + napi_create_object(env, &requestResult); + if (!Common::SetNotificationRequest(env, request, requestResult)) { + ANS_LOGE("SetNotificationRequest call failed"); + return Common::NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "request", requestResult); + return Common::NapiGetboolean(env, true); +} + +napi_value SetSubscriberCallbackData(const napi_env &env, + const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason, napi_value &result) +{ + ANS_LOGI("SetSubscriberCallbackData2 start"); + if (request == nullptr) { + ANS_LOGE("request is null"); + return Common::NapiGetboolean(env, false); + } + + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return Common::NapiGetboolean(env, false); + } + + // request: NotificationRequest + napi_value requestResult; + napi_create_object(env, &requestResult); + if (!Common::SetNotificationRequest(env, request, requestResult)) { + ANS_LOGE("SetNotificationRequest call failed"); + return Common::NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "request", requestResult); + + // sortingMap?: NotificationSortingMap + napi_value sortingMapResult; + napi_create_object(env, &sortingMapResult); + if (!Common::SetNotificationSortingMap(env, sortingMap, sortingMapResult)) { + ANS_LOGE("SetNotificationSortingMap call failed"); + return Common::NapiGetboolean(env, false); + } + napi_set_named_property(env, result, "sortingMap", sortingMapResult); + + // reason?: number + napi_value value = 0; + int outReason = 0; + if (!Common::ReasonCToJS(deleteReason, outReason)) { + return Common::NapiGetboolean(env, false); + } + napi_create_int32(env, outReason, &value); + napi_set_named_property(env, result, "reason", value); + + return Common::NapiGetboolean(env, true); +} + +napi_value NotificationSubscriberInit(napi_env env, napi_value exports) +{ + ANS_LOGI("NotificationSubscriberInit start"); + + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("off", Off), + }; + + NAPI_CALL(env, + napi_define_class(env, + "notificationSubscriber", + NAPI_AUTO_LENGTH, + SubscriberConstructor, + nullptr, + sizeof(properties) / sizeof(*properties), + properties, + &g_NotificationSubscriber)); + + return exports; +} +} // namespace NotificationNapi +} // namespace OHOS diff --git a/kits/napi/src/get_active.cpp b/kits/napi/src/get_active.cpp new file mode 100644 index 000000000..ce550ec57 --- /dev/null +++ b/kits/napi/src/get_active.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2021 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 "get_active.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParametersByAllActive(const napi_env &env, const napi_value (&argv)[ALL_ACTIVE_MAX_PARA], + const size_t &argc, std::vector &strValue, napi_ref &callback) +{ + ANS_LOGI("ParseParametersByAllActive start"); + + if (argc >= 1) { + napi_valuetype valuetype; + // argv[0]: hashcode: Array / callback + bool isArray = false; + napi_is_array(env, argv[0], &isArray); + if (isArray) { + uint32_t length = 0; + napi_get_array_length(env, argv[0], &length); + if (length > 0) { + for (uint32_t i = 0; i < length; ++i) { + napi_value nHashcode; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + napi_get_element(env, argv[0], i, &nHashcode); + NAPI_CALL(env, napi_typeof(env, nHashcode, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nHashcode, str, STR_MAX_SIZE - 1, &strLen)); + strValue.emplace_back(str); + } + } else { + ANS_LOGI("hashcode: Array lenth is 0"); + return nullptr; + } + } else { + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); + } + if (argc >= ALL_ACTIVE_MAX_PARA) { + // argv[1]:callback + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + } + + return Common::NapiGetNull(env); +} + +napi_value ParseParameters( + const napi_env &env, const napi_value (&argv)[ACTIVE_OR_NUMS_MAX_PARA], const size_t &argc, napi_ref &callback) +{ + ANS_LOGI("ParseParameters start"); + + if (argc >= ACTIVE_OR_NUMS_MAX_PARA) { + napi_valuetype valuetype; + // argv[0]:callback + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoActive *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) +{ + ANS_LOGI("GetAllActiveNotifications start"); + + size_t argc = ALL_ACTIVE_MAX_PARA; + napi_value argv[ALL_ACTIVE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + std::vector hashcode; + if (ParseParametersByAllActive(env, argv, argc, hashcode, callback) == nullptr) { + return Common::NapiGetNull(env); + } + ANS_LOGI("GetAllActiveNotifications hashcode.size = %{public}d", hashcode.size()); + + AsyncCallbackInfoActive *asynccallbackinfo = + new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr, .strValue = hashcode}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "getAllActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetAllActiveNotifications napi_create_async_work start"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + std::vector> notification; + if (asynccallbackinfo->strValue.size() > 0) { + asynccallbackinfo->errorCode = + NotificationHelper::GetAllActiveNotifications(asynccallbackinfo->strValue, notification); + } else { + asynccallbackinfo->errorCode = NotificationHelper::GetAllActiveNotifications(notification); + } + + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : notification) { + if (vec) { + napi_value result; + std::shared_ptr notificationSharedPtr( + static_cast(vec.GetRefPtr())); + if (Common::SetNotificationRequest(env, notificationSharedPtr, result)) { + napi_set_element(env, arr, count, result); + count++; + } + } + } + if (count > 0) { + ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + } else { + asynccallbackinfo->result = Common::NapiGetNull(env); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value GetActiveNotifications(napi_env env, napi_callback_info info) +{ + ANS_LOGI("GetActiveNotifications start"); + + size_t argc = ACTIVE_OR_NUMS_MAX_PARA; + napi_value argv[ACTIVE_OR_NUMS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + if (ParseParameters(env, argv, argc, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoActive *asynccallbackinfo = new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "getActiveNotifications", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetActiveNotifications napi_create_async_work start"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + std::vector> request; + asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotifications(request); + + napi_value arr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : request) { + if (vec) { + napi_value result; + std::shared_ptr requestSharedPtr( + static_cast(vec.GetRefPtr())); + if (Common::SetNotificationRequest2(env, requestSharedPtr, result)) { + napi_set_element(env, arr, count, result); + count++; + } + } + } + if (count > 0) { + ANS_LOGI("GetActiveNotifications count = %{public}d", count); + asynccallbackinfo->result = arr; + } else { + asynccallbackinfo->result = Common::NapiGetNull(env); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetActiveNotifications napi_create_async_work end"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value GetActiveNotificationNums(napi_env env, napi_callback_info info) +{ + ANS_LOGI("GetActiveNotificationNums start"); + + size_t argc = ACTIVE_OR_NUMS_MAX_PARA; + napi_value argv[ACTIVE_OR_NUMS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + if (ParseParameters(env, argv, argc, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoActive *asynccallbackinfo = new AsyncCallbackInfoActive{.env = env, .asyncWork = nullptr}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "getActiveNotificationNums", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetActiveNotificationNums napi_create_async_work start"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + int32_t nums = 0; + asynccallbackinfo->errorCode = NotificationHelper::GetActiveNotificationNums(nums); + ANS_LOGI("GetActiveNotificationNums nums = %{public}d", nums); + napi_create_int32(env, nums, &asynccallbackinfo->result); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetActiveNotificationNums napi_create_async_work end"); + AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/init.cpp b/kits/napi/src/init.cpp new file mode 100644 index 000000000..4c4a99ee9 --- /dev/null +++ b/kits/napi/src/init.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 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 "init.h" +#include "cancel.h" +#include "constant.h" +#include "create_subscriber.h" +#include "get_active.h" +#include "publish.h" +#include "remove.h" +#include "slot.h" +#include "subscribe.h" +#include "unsubscribe.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +EXTERN_C_START + +napi_value NotificationInit(napi_env env, napi_value exports) +{ + ANS_LOGI("notificationInit start"); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createSubscriber", CreateSubscriber), + DECLARE_NAPI_FUNCTION("subscribe", Subscribe), + DECLARE_NAPI_FUNCTION("unsubscribe", Unsubscribe), + DECLARE_NAPI_FUNCTION("publish", Publish), + DECLARE_NAPI_FUNCTION("remove", Remove), + DECLARE_NAPI_FUNCTION("removeAll", RemoveAll), + DECLARE_NAPI_FUNCTION("removeAsBundle", RemoveAsBundle), + DECLARE_NAPI_FUNCTION("getAllActiveNotifications", GetAllActiveNotifications), + DECLARE_NAPI_FUNCTION("getActiveNotifications", GetActiveNotifications), + DECLARE_NAPI_FUNCTION("getActiveNotificationNums", GetActiveNotificationNums), + DECLARE_NAPI_FUNCTION("cancel", Cancel), + DECLARE_NAPI_FUNCTION("cancelAll", CancelAll), + DECLARE_NAPI_FUNCTION("addSlot", AddSlot), + DECLARE_NAPI_FUNCTION("addSlots", AddSlots), + DECLARE_NAPI_FUNCTION("getSlot", GetSlot), + DECLARE_NAPI_FUNCTION("getSlots", GetSlots), + DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + + return exports; +} + +/* + * Module export function + */ +static napi_value Init(napi_env env, napi_value exports) +{ + /* + * Propertise define + */ + NotificationSubscriberInit(env, exports); + NotificationInit(env, exports); + ConstantInit(env, exports); + return exports; +} + +/* + * Module register function + */ +__attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +EXTERN_C_END + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/publish.cpp b/kits/napi/src/publish.cpp new file mode 100644 index 000000000..a4a457973 --- /dev/null +++ b/kits/napi/src/publish.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2021 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 "publish.h" +#include "notification_basic_content.h" +#include "notification_constant.h" +#include "notification_content.h" +#include "notification_normal_content.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +static napi_value GetCallbackByPublish( + ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype); + +napi_value Publish(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + size_t argc = PUBLISH_NOTIFICATION_MAX; + napi_value argv[PUBLISH_NOTIFICATION_MAX]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + + ParseParametersPublish parseParameters = {env, argc, false, "", nullptr}; + NotificationRequest notificationRequest; + if (ParseParametersByPublish(parseParameters, argv, notificationRequest) == nullptr) { + return Common::NapiGetNull(env); + } + AsyncCallbackInfoPublish *asynccallbackinfo = new AsyncCallbackInfoPublish{.env = env, .asyncWork = nullptr}; + napi_value promise = 0; + + PaddingCallbackInfoInfoPublish(asynccallbackinfo, parseParameters, notificationRequest); + + PaddingPublishCallbackPromise(env, parseParameters, asynccallbackinfo, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "publish", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Publish napi_create_async_work start"); + AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; + ANS_LOGI("==============Publish napi_create_async_work start notificationId = %{public}d,contentType = " + "%{public}d", + asynccallbackinfo->notificationRequest.GetNotificationId(), + asynccallbackinfo->notificationRequest.GetContent()->GetContentType()); + + asynccallbackinfo->errorCode = NotificationHelper::PublishNotification( + asynccallbackinfo->lable, asynccallbackinfo->notificationRequest); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Publish napi_create_async_work complete start"); + AsyncCallbackInfoPublish *asynccallbackinfo = (AsyncCallbackInfoPublish *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + ANS_LOGI("Publish napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseParametersByPublish(ParseParametersPublish &parseParameters, + const napi_value (&argv)[PUBLISH_NOTIFICATION_MAX], NotificationRequest ¬ificationRequest) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype; + + NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, argv[0], &valuetype)); + NAPI_ASSERT(parseParameters.env, valuetype == napi_object, "Wrong argument type. Object expected."); + + // argv[0]----NotificationRequest + if (Common::GetNotificationRequest(parseParameters.env, argv[0], notificationRequest) == nullptr) { + return nullptr; + } + + // argv[1] : callback + if (parseParameters.argc == PUBLISH_NOTIFICATION_MAX) { + GetCallbackByPublish(parseParameters, argv[1], valuetype); + } + + ANS_LOGI("end"); + return Common::NapiGetNull(parseParameters.env); +} + +napi_value GetCallbackByPublish( + ParseParametersPublish &parseParameters, const napi_value &value, napi_valuetype &valuetype) +{ + ANS_LOGI("enter"); + + NAPI_CALL(parseParameters.env, napi_typeof(parseParameters.env, value, &valuetype)); + NAPI_ASSERT(parseParameters.env, valuetype = napi_function, "Wrong argument type. Function expected."); + napi_create_reference(parseParameters.env, value, 1, &parseParameters.callback); + ANS_LOGI("end"); + return Common::NapiGetNull(parseParameters.env); +} + +void PaddingCallbackInfoInfoPublish(AsyncCallbackInfoPublish *&asynccallbackinfo, + const ParseParametersPublish &parseParameters, const NotificationRequest ¬ificationRequest) +{ + ANS_LOGI("enter"); + + asynccallbackinfo->lable = parseParameters.lable; + asynccallbackinfo->notificationRequest = notificationRequest; + + return; +} + +void PaddingPublishCallbackPromise(const napi_env &env, const ParseParametersPublish &parseParameters, + AsyncCallbackInfoPublish *&asynccallbackinfo, napi_value &promise) +{ + ANS_LOGI("enter"); + + if (parseParameters.callback != nullptr) { + asynccallbackinfo->callback = parseParameters.callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + napi_create_promise(env, &deferred, &promise); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } + + return; +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/remove.cpp b/kits/napi/src/remove.cpp new file mode 100644 index 000000000..e1c4ec600 --- /dev/null +++ b/kits/napi/src/remove.cpp @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2021 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 "remove.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[REMOVE_OR_BUNDLE_MAX_PARA], const size_t &argc, + std::string &strValue, napi_ref &callback) +{ + // argv[0]: hashCode/bundleName + size_t strLen; + char str[STR_MAX_SIZE] = {0}; + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + strValue = str; + + // argv[1]:callback + if (argc >= REMOVE_OR_BUNDLE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +napi_value ParseParametersByRemoveAll( + const napi_env &env, const napi_value (&argv)[REMOVE_ALL_MAX_PARA], const size_t &argc, napi_ref &callback) +{ + // argv[0]:callback + napi_valuetype valuetype; + if (argc >= REMOVE_ALL_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); + } + return Common::NapiGetNull(env); +} +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoRemove *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value Remove(napi_env env, napi_callback_info info) +{ + ANS_LOGI("Remove start"); + + size_t argc = REMOVE_OR_BUNDLE_MAX_PARA; + napi_value argv[REMOVE_OR_BUNDLE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + std::string hashCode; + if (ParseParameters(env, argv, argc, hashCode, callback) == nullptr) { + return Common::NapiGetNull(env); + } + ANS_LOGI("Remove hashCode = %{public}s", hashCode.c_str()); + + AsyncCallbackInfoRemove *asynccallbackinfo = + new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = hashCode}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "remove", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Remove napi_create_async_work start"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + asynccallbackinfo->errorCode = NotificationHelper::RemoveNotification(asynccallbackinfo->strValue); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Remove napi_create_async_work end"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value RemoveAsBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("RemoveAsBundle start"); + + size_t argc = REMOVE_OR_BUNDLE_MAX_PARA; + napi_value argv[REMOVE_OR_BUNDLE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + std::string bundleName; + if (ParseParameters(env, argv, argc, bundleName, callback) == nullptr) { + return Common::NapiGetNull(env); + } + ANS_LOGI("RemoveAsBundle bundleName = %{public}s", bundleName.c_str()); + + AsyncCallbackInfoRemove *asynccallbackinfo = + new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr, .strValue = bundleName}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "removeAsBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("removeAsBundle napi_create_async_work start"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + asynccallbackinfo->errorCode = NotificationHelper::RemoveNotifications(asynccallbackinfo->strValue); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("removeAsBundle napi_create_async_work end"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value RemoveAll(napi_env env, napi_callback_info info) +{ + ANS_LOGI("RemoveAll start"); + + size_t argc = REMOVE_ALL_MAX_PARA; + napi_value argv[REMOVE_ALL_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + if (ParseParametersByRemoveAll(env, argv, argc, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoRemove *asynccallbackinfo = new AsyncCallbackInfoRemove{.env = env, .asyncWork = nullptr}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "removeAll", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("RemoveAll napi_create_async_work start"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + asynccallbackinfo->errorCode = NotificationHelper::RemoveNotifications(); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("RemoveAll napi_create_async_work end"); + AsyncCallbackInfoRemove *asynccallbackinfo = (AsyncCallbackInfoRemove *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/slot.cpp b/kits/napi/src/slot.cpp new file mode 100644 index 000000000..d5c8b571b --- /dev/null +++ b/kits/napi/src/slot.cpp @@ -0,0 +1,552 @@ +/* + * Copyright (c) 2021 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 "slot.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParametersByAddSlot(const napi_env &env, const napi_value (&argv)[ADD_SLOT_MAX_PARA], + const size_t &argc, NotificationSlot &slot, napi_ref &callback) +{ + napi_valuetype valuetype; + // argv[0]: NotificationSlot + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (!Common::GetNotificationSlot(env, slot, argv[0])) { + return nullptr; + } + // argv[1]:callback + if (argc >= ADD_SLOT_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIsByAddSlot( + const napi_env &env, AsyncCallbackInfoAddSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value ParseParametersByAddSlots(const napi_env &env, const napi_value (&argv)[ADD_SLOTS_MAX_PARA], + const size_t &argc, std::vector &slots, napi_ref &callback) +{ + napi_valuetype valuetype; + // argv[0]: Array + bool isArray = false; + napi_is_array(env, argv[0], &isArray); + if (isArray) { + uint32_t length = 0; + napi_get_array_length(env, argv[0], &length); + for (size_t i = 0; i < length; i++) { + napi_value nSlot; + napi_get_element(env, argv[0], i, &nSlot); + NAPI_CALL(env, napi_typeof(env, nSlot, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + NotificationSlot slot; + if (!Common::GetNotificationSlot(env, slot, argv[0])) { + return nullptr; + } + slots.emplace_back(slot); + } + if (slots.size() == 0) { + ANS_LOGI("slots size is empyt"); + return nullptr; + } + } + // argv[1]:callback + if (argc >= ADD_SLOTS_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIsByAddSlots( + const napi_env &env, AsyncCallbackInfoAddSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value ParseParametersByGetSlot(const napi_env &env, const napi_value (&argv)[GET_SLOT_MAX_PARA], + const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback) +{ + napi_valuetype valuetype; + // argv[0]: SlotType + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + + int slotType = 0; + napi_get_value_int32(env, argv[0], &slotType); + + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + + // argv[1]:callback + if (argc >= GET_SLOT_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIsByGetSlot( + const napi_env &env, AsyncCallbackInfoGetSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value ParseParametersByGetSlots( + const napi_env &env, const napi_value (&argv)[GET_SLOTS_MAX_PARA], const size_t &argc, napi_ref &callback) +{ + // argv[0]:callback + napi_valuetype valuetype; + if (argc >= GET_SLOTS_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[0], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIsByGetSlots( + const napi_env &env, AsyncCallbackInfoGetSlots *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value ParseParametersByRemoveSlot(const napi_env &env, const napi_value (&argv)[REMOVE_SLOT_MAX_PARA], + const size_t &argc, enum NotificationConstant::SlotType &outType, napi_ref &callback) +{ + napi_valuetype valuetype; + // argv[0]: SlotType + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + + int slotType = 0; + napi_get_value_int32(env, argv[0], &slotType); + + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + + // argv[1]:callback + if (argc >= REMOVE_SLOT_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIsByRemoveSlot( + const napi_env &env, AsyncCallbackInfoRemoveSlot *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value AddSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("AddSlot start"); + + size_t argc = ADD_SLOT_MAX_PARA; + napi_value argv[ADD_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + NotificationSlot slot; + if (ParseParametersByAddSlot(env, argv, argc, slot, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoAddSlot *asynccallbackinfo = + new AsyncCallbackInfoAddSlot{.env = env, .asyncWork = nullptr, .slot = slot}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIsByAddSlot(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "addSlot", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("AddSlot napi_create_async_work start"); + AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; + asynccallbackinfo->errorCode = NotificationHelper::AddNotificationSlot(asynccallbackinfo->slot); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("AddSlot napi_create_async_work end"); + AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value AddSlots(napi_env env, napi_callback_info info) +{ + ANS_LOGI("AddSlots start"); + + size_t argc = ADD_SLOTS_MAX_PARA; + napi_value argv[ADD_SLOTS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + std::vector slots; + if (ParseParametersByAddSlots(env, argv, argc, slots, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoAddSlots *asynccallbackinfo = + new AsyncCallbackInfoAddSlots{.env = env, .asyncWork = nullptr, .slots = slots}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIsByAddSlots(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "addSlots", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("AddSlots napi_create_async_work start"); + AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; + asynccallbackinfo->errorCode = NotificationHelper::AddNotificationSlots(asynccallbackinfo->slots); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("AddSlots napi_create_async_work end"); + AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value GetSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("GetSlot start"); + + size_t argc = GET_SLOT_MAX_PARA; + napi_value argv[GET_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + enum NotificationConstant::SlotType outType; + if (ParseParametersByGetSlot(env, argv, argc, outType, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoGetSlot *asynccallbackinfo = + new AsyncCallbackInfoGetSlot{.env = env, .asyncWork = nullptr, .outType = outType}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIsByGetSlot(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "getSlot", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetSlot napi_create_async_work start"); + AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + + sptr slot; + asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, slot); + if (slot) { + napi_create_object(env, &asynccallbackinfo->result); + if (!Common::SetNotificationSlot(env, *slot, asynccallbackinfo->result)) { + asynccallbackinfo->result = Common::NapiGetNull(env); + } + } else { + asynccallbackinfo->result = Common::NapiGetNull(env); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetSlot napi_create_async_work end"); + AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value GetSlots(napi_env env, napi_callback_info info) +{ + ANS_LOGI("GetSlots start"); + + size_t argc = GET_SLOTS_MAX_PARA; + napi_value argv[GET_SLOTS_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 0, "Wrong number of arguments"); + napi_ref callback = nullptr; + + if (ParseParametersByGetSlots(env, argv, argc, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoGetSlots *asynccallbackinfo = new AsyncCallbackInfoGetSlots{.env = env, .asyncWork = nullptr}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIsByGetSlots(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "getSlots", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetSlots napi_create_async_work start"); + AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; + + std::vector> slots; + asynccallbackinfo->errorCode = NotificationHelper::GetNotificationSlots(slots); + + napi_value arr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : slots) { + if (vec) { + napi_value nSlot; + napi_create_object(env, &nSlot); + if (Common::SetNotificationSlot(env, *vec, nSlot)) { + napi_set_element(env, arr, count, nSlot); + count++; + } + } + } + ANS_LOGI("getSlots count = %{public}d", count); + if (count == 0) { + asynccallbackinfo->result = Common::NapiGetNull(env); + } + asynccallbackinfo->result = arr; + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("GetSlots napi_create_async_work end"); + AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, asynccallbackinfo->result); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +napi_value RemoveSlot(napi_env env, napi_callback_info info) +{ + ANS_LOGI("RemoveSlot start"); + + size_t argc = REMOVE_SLOT_MAX_PARA; + napi_value argv[REMOVE_SLOT_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + enum NotificationConstant::SlotType outType; + if (ParseParametersByRemoveSlot(env, argv, argc, outType, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoRemoveSlot *asynccallbackinfo = + new AsyncCallbackInfoRemoveSlot{.env = env, .asyncWork = nullptr, .outType = outType}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIsByRemoveSlot(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "removeSlot", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("removeSlot napi_create_async_work start"); + AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; + asynccallbackinfo->errorCode = NotificationHelper::RemoveNotificationSlot(asynccallbackinfo->outType); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("removeSlot napi_create_async_work end"); + AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/subscribe.cpp b/kits/napi/src/subscribe.cpp new file mode 100644 index 000000000..87074cef2 --- /dev/null +++ b/kits/napi/src/subscribe.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2021 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 "subscribe.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParameters(const napi_env &env, const napi_value (&argv)[SUBSRIBE_MAX_PARA], const size_t &argc, + NotificationSubscriberInfo &subscriberInfo, SubscriberInstance *&objectInfo, napi_ref &callback) +{ + napi_valuetype valuetype; + + // argv[0]:Subscriber + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe expected."); + + napi_unwrap(env, argv[0], (void **)&objectInfo); + if (!objectInfo) { + ANS_LOGE("ParseParameters subscriberInstance is null"); + return nullptr; + } + + ANS_LOGI("ParseParameters subscriberInstance = %{public}p start", objectInfo); + + if (!HasNotificationSubscriber(objectInfo)) { + return nullptr; + } + ANS_LOGI("================ParseParameters 1111111111111111111111================="); + // argv[1]:callback/NotificationSubscriberInfo + if (argc >= 2) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + if (valuetype == napi_function) { + napi_create_reference(env, argv[1], 1, &callback); + } else if (valuetype == napi_object) { + if (Common::GetNotificationSubscriberInfo(env, argv[1], subscriberInfo) == nullptr) { + ANS_LOGE("ParseParameters SubscriberInfo parse failed"); + return nullptr; + } + } + } + ANS_LOGI("================ParseParameters 22222222222222222222222222================="); + // argv[2]:callback + if (argc >= SUBSRIBE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + ANS_LOGI("================ParseParameters 33333333333333333333333================="); + napi_create_reference(env, argv[2], 1, &callback); + } + ANS_LOGI("================ParseParameters 444444444444444444444444444================="); + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIs( + const napi_env &env, AsyncCallbackInfoSubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (callback) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value Subscribe(napi_env env, napi_callback_info info) +{ + ANS_LOGI("Subscribe start"); + + size_t argc = SUBSRIBE_MAX_PARA; + napi_value argv[SUBSRIBE_MAX_PARA]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + napi_ref callback = nullptr; + + SubscriberInstance *objectInfo = nullptr; + NotificationSubscriberInfo subscriberInfo; + if (ParseParameters(env, argv, argc, subscriberInfo, objectInfo, callback) == nullptr) { + return Common::NapiGetNull(env); + } + ANS_LOGI("Subscribe objectInfo = %{public}p", objectInfo); + + AsyncCallbackInfoSubscribe *asynccallbackinfo = new AsyncCallbackInfoSubscribe{ + .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "subscribeNotification", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Subscribe napi_create_async_work start"); + AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; + if (asynccallbackinfo->subscriberInfo.hasSubscriberInfo) { + ANS_LOGI("Subscribe There are NotificationSubscribeInfo"); + NotificationSubscribeInfo subscribeInfo; + subscribeInfo.AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); + asynccallbackinfo->errorCode = + NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo), subscribeInfo); + } else { + asynccallbackinfo->errorCode = + NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo)); + } + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Subscribe napi_create_async_work end"); + AsyncCallbackInfoSubscribe *asynccallbackinfo = (AsyncCallbackInfoSubscribe *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/napi/src/unsubscribe.cpp b/kits/napi/src/unsubscribe.cpp new file mode 100644 index 000000000..c911bba28 --- /dev/null +++ b/kits/napi/src/unsubscribe.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2021 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 "unsubscribe.h" +#include "create_subscriber.h" + +namespace OHOS { +namespace NotificationNapi { +napi_value ParseParameters(const napi_env &env, const size_t &argc, const napi_value (&argv)[UNSUBSCRIBE_MAX_PARA], + SubscriberInstance *&objectInfo, napi_ref &callback) +{ + ANS_LOGI("ParseParameters start"); + + napi_valuetype valuetype; + // argv[0]:subscriber + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe expected."); + + napi_unwrap(env, argv[0], (void **)&objectInfo); + if (!objectInfo) { + ANS_LOGE("ParseParameters objectInfo is null"); + return nullptr; + } + + ANS_LOGI("ParseParameters objectInfo = %{public}p start", objectInfo); + + if (!HasNotificationSubscriber(objectInfo)) { + return nullptr; + } + + // argv[1]:callback + if (argc >= UNSUBSCRIBE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, &callback); + } + + return Common::NapiGetNull(env); +} + +void PaddingAsyncCallbackInfoIs(const napi_env &env, const size_t &argc, + AsyncCallbackInfoUnsubscribe *&asynccallbackinfo, const napi_ref &callback, napi_value &promise) +{ + ANS_LOGI("PaddingAsyncCallbackInfoIs start"); + + if (argc >= UNSUBSCRIBE_MAX_PARA) { + asynccallbackinfo->callback = callback; + asynccallbackinfo->isCallback = true; + } else { + napi_deferred deferred = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise)); + asynccallbackinfo->deferred = deferred; + asynccallbackinfo->isCallback = false; + } +} + +napi_value Unsubscribe(napi_env env, napi_callback_info info) +{ + ANS_LOGI("Unsubscribe start"); + + // Argument parsing + size_t argc = UNSUBSCRIBE_MAX_PARA; + napi_value argv[UNSUBSCRIBE_MAX_PARA]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + + napi_ref callback = 0; + SubscriberInstance *subscriberInstance = nullptr; + if (ParseParameters(env, argc, argv, subscriberInstance, callback) == nullptr) { + return Common::NapiGetNull(env); + } + + AsyncCallbackInfoUnsubscribe *asynccallbackinfo = + new AsyncCallbackInfoUnsubscribe{.env = env, .asyncWork = nullptr, .objectInfo = subscriberInstance}; + + napi_value promise = 0; + PaddingAsyncCallbackInfoIs(env, argc, asynccallbackinfo, callback, promise); + + napi_value resourceName; + napi_create_string_latin1(env, "Unsubscribe", NAPI_AUTO_LENGTH, &resourceName); + + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("Unsubscribe napi_create_async_work start"); + AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; + + asynccallbackinfo->errorCode = + NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("Unsubscribe napi_create_async_work end"); + AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; + + CallbackPromiseInfo info; + info.isCallback = asynccallbackinfo->isCallback; + info.callback = asynccallbackinfo->callback; + info.deferred = asynccallbackinfo->deferred; + info.errorCode = asynccallbackinfo->errorCode; + Common::ReturnCallbackPromise(env, info, Common::NapiGetNull(env)); + + DelAsyncCallbackInfoOn(asynccallbackinfo->objectInfo); + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/BUILD.gn b/kits/native/BUILD.gn new file mode 100644 index 000000000..5a8c48e6d --- /dev/null +++ b/kits/native/BUILD.gn @@ -0,0 +1,96 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") + +group("native_targets") { + deps = [ ":ans_kits" ] +} + +config("ans_kits_config") { + include_dirs = [ "${kits_path}/native/include" ] + configs = [ "${innerkits_path}:public_ans_innerkits_config" ] +} + +config("ans_kit_public_config") { + visibility = [ ":*" ] + + include_dirs = [ + "${kits_path}/native/include", + "${innerkits_path}/core/include", + "${innerkits_path}/base/include", + ] +} + +ohos_shared_library("ans_kits") { + include_dirs = [ + "${kits_path}/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//utils/system/safwk/native/include", + ] + + sources = [ + "${innerkits_path}/base/src/ans_log_wrapper.cpp", + "src/message_user.cpp", + "src/notification.cpp", + "src/notification_action_button.cpp", + "src/notification_basic_content.cpp", + "src/notification_constant.cpp", + "src/notification_content.cpp", + "src/notification_conversational_content.cpp", + "src/notification_conversational_message.cpp", + "src/notification_helper.cpp", + "src/notification_long_text_content.cpp", + "src/notification_media_content.cpp", + "src/notification_multiline_content.cpp", + "src/notification_normal_content.cpp", + "src/notification_picture_content.cpp", + "src/notification_request.cpp", + "src/notification_slot.cpp", + "src/notification_slot_group.cpp", + "src/notification_sorting.cpp", + "src/notification_sorting_map.cpp", + "src/notification_subscribe_info.cpp", + "src/notification_subscriber.cpp", + "src/notification_user_input.cpp", + ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + + public_configs = [ ":ans_kit_public_config" ] + + deps = [ + "${innerkits_path}:ans_innerkits", + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_L2:samgr_proxy", + ] + + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/kits/native/include/message_user.h b/kits/native/include/message_user.h new file mode 100644 index 000000000..3cb50e7cd --- /dev/null +++ b/kits/native/include/message_user.h @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H + +#include + +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { +class PixelMap; +class MessageUser final : public Parcelable { +public: + /** + * A constructor used to construct MessageUser + */ + MessageUser(); + + /** + * Default deconstructor used to deconstruct. + */ + ~MessageUser(); + + /** + * Sets the key used to uniquely identify this MessageUser. + * @note Sets the key used to uniquely identify this MessageUser. + * If no key is set, the name set by SetName(string) is used to uniquely identify a MessageUser. + * @param key Indicates the key to set. + */ + void SetKey(const std::string &key); + + /** + * Obtains the key of this MessageUser. + * + * @return Returns the key of this MessageUser. + */ + std::string GetKey() const; + + /** + * Sets the name of this MessageUser. + * @name Indicates the name to set. + */ + void SetName(const std::string &name); + + /** + * Obtains the name of this MessageUser. + * + * @return Returns the name of this MessageUser. + */ + std::string GetName() const; + + /** + * Sets the pixel map of this MessageUser. + * @param pixelMap Indicates the pixel map to set. + */ + void SetPixelMap(const std::shared_ptr &pixelMap); + + /** + * Obtains the pixel map of this MessageUser. + * + * @return Returns the pixel map of this MessageUser. + */ + const std::shared_ptr GetPixelMap() const; + + /** + * Sets the URI of this MessageUser. + * @param uri Indicates the URI to set. + */ + void SetUri(const Uri &uri); + + /** + * Obtains the URI of this MessageUser. + * + * @return Returns the URI of this MessageUser. + */ + Uri GetUri() const; + + /** + * Sets whether this MessageUser is a machine. + * @param machine Specifies whether this MessageUser is a machine. + * The value true indicates that it is, and the value false indicates not. + */ + void SetMachine(bool machine); + + /** + * Checks whether this MessageUser is a machine. + * + * @return Returns true if this MessageUser is a machine; returns false otherwise. + */ + bool IsMachine() const; + + /** + * Sets whether this MessageUser is important. + * @note This method can be used to denote users who frequently interact with the user of this device. + * @param userImportant Specifies whether this MessageUser is important. + * The value true indicates that it is important, and the value false indicates not. + */ + void SetUserAsImportant(bool userImportant); + + /** + * Checks whether this MessageUser is important. + * + * @return Returns true if this MessageUser is important; returns false otherwise. + */ + bool IsUserImportant() const; + + /** + * Dumps a string representation of the object. + * + * @return A string representation of the object. + */ + std::string Dump() const; + + /** + * Marshals a MessageUser object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshals a MessageUser object from a Parcel. + * + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static MessageUser *Unmarshalling(Parcel &parcel); + +private: + /** + * Read NotificationSlot object from a Parcel. + * + * @param parcel the parcel + * @return read from parcel success or fail + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string key_; + std::string name_; + std::shared_ptr pixelMap_; + Uri uri_; + bool isMachine_; + bool isUserImportant_; + + // no object in parcel + static constexpr int VALUE_NULL = -1; + // object exist in parcel + static constexpr int VALUE_OBJECT = 1; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H \ No newline at end of file diff --git a/kits/native/include/notification.h b/kits/native/include/notification.h new file mode 100644 index 000000000..b8c9d0bbd --- /dev/null +++ b/kits/native/include/notification.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_H + +#include +#include + +#include "notification_request.h" +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { + +class Notification final : public Parcelable { +public: + /** + * A constructor used to create a Notification instance by existing NotificationRequest object. + * + * @param request the existing NotificationRequest object. + */ + Notification(const sptr &request); + + /** + * @brief A constructor used to create a Notification instance by copying parameters from an existing one. + * + * @param other Indicates the Notification object. + */ + Notification(const Notification &other); + + /** + * @brief Obtains whether to enable the notification light when a notification is received on the device, provided + * that this device has a notification light. + * + * @return Return true if led light color is set. + */ + bool EnableLight() const; + + /** + * @brief Obtains the sound enabled or not, set by ANS. + * + * @return Return true if sound is set. + */ + bool EnableSound() const; + + /** + * @brief Obtains the vibrate enabled or not, set by ANS. + * + * @return Return true if vibrate style is set. + */ + bool EnableVibrate() const; + + /** + * @brief Obtains the bundle's name which publish this notification. + * + * @return Return the bundle's name. + */ + std::string GetBundleName() const; + + /** + * @brief Obtains the bundle's name which create this notification. + * + * @return Return the creator bundle name. + */ + std::string GetCreateBundle() const; + + /** + * @brief Obtains the label of this notification. + * + * @return Return the label. + */ + std::string GetLabel() const; + + /** + * @brief Obtains the color of the notification light in a NotificationSlot object + * + * @return Returns the color of the notification light. + */ + int32_t GetLedLightColor() const; + /** + * @brief Sets the notification display effect, including whether to display this notification on the lock screen, + * and how it will be presented if displayed. + * + * @return Return the display effect of this notification on the lock screen. + */ + int32_t GetLockscreenVisibleness() const; + + /** + * @brief The ID passed to setGroup(), or the override, or null. + * + * @return string of group. + */ + std::string GetGroup() const; + + /** + * @brief Obtains the id of the notification. + * + * @return The id supplied to NotificationManager::Notify(int, NotificationRequest). + */ + int32_t GetId() const; + + /** + * @brief A key for this notification record. + * + * @return A unique instance key. + */ + std::string GetKey() const; + + /** + * @brief Obtains the notificanton request set by ANS. + * + * @return Return sptr. + */ + NotificationRequest GetNotificationRequest() const; + + /** + * @brief Obtains the time notification was posted. + * + * @return The time notificationRequest was posted. + */ + int64_t GetPostTime() const; + + /** + * @brief Obtains the sound uri. + * + * @return Return the sound set by ANS. + */ + Uri GetSound() const; + + /** + * @brief Obtains bundle's uid. + * + * @return Return the uid set by ANS. + */ + int32_t GetUid() const; + + /** + * @brief Obtains the vibration style for this notifications. if + * + * @return Return the vibration style. + */ + std::vector GetVibrationStyle() const; + + /** + * @brief This notification is part of a group or not. + * + * @return true if this notification is part of a group. + */ + bool IsGroup() const; + + /** + * @brief Dumps a string representation of the object. + * + * @return A string representation of the object. + */ + std::string Dump() const; + + /** + * @brief Marshals a Notification object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + bool Marshalling(Parcel &parcel) const; + + /** + * @brief Unmarshals a Notification object from a Parcel. + * + * @param Indicates the Parcel object for unmarshalling. + * + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static Notification *Unmarshalling(Parcel &parcel); + +private: + Notification(); + void SetLedLightColor(const int32_t &color); + void SetLockScreenVisbleness(const int32_t &visbleness); + void SetPostTime(const int64_t &time); + void SetSound(const Uri &sound); + void SetVibrationStyle(const std::vector &style); + bool ReadFromParcel(Parcel &parcel); + std::string GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id); + +private: + std::string key_{""}; + int32_t ledLightColor_ = -1; + int32_t lockscreenVisibleness_; + sptr request_ = nullptr; + int64_t postTime_; + std::shared_ptr sound_ = nullptr; + std::vector vibrationStyle_{}; + + friend class AdvancedNotificationService; + friend class NotificationSlotFilter; + friend class DisturbFilter; +}; +} // namespace Notification +} // namespace OHOS +#endif \ No newline at end of file diff --git a/kits/native/include/notification_action_button.h b/kits/native/include/notification_action_button.h new file mode 100644 index 000000000..32186dce9 --- /dev/null +++ b/kits/native/include/notification_action_button.h @@ -0,0 +1,212 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H + +#include +#include +#include +#include "notification_constant.h" +#include "notification_user_input.h" +#include "want_agent.h" +#include "pac_map.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class PixelMap; + +class NotificationActionButton : public Parcelable { +public: + /** + * A static function used to create a NotificationActionButton instance with the input parameters passed. + * @param icon Indicates the icon to represent this NotificationActionButton. + * @param title Indicates the title of this NotificationActionButton. + * @param wantAgent Indicates the wantAgent to be triggered when this NotificationActionButton is triggered. + * @param extras Indicates the PacMap object containing the additional data. + * @param semanticActionButton Indicates the semantic action to add. + * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. + * @param userInputs Indicates the NotificationUserInput object to add. + * @return the shared_ptr object owns the created NotificationActionButton object otherwise return empty object if + * isContextual is true but icon or wantAgent is dempty. + */ + static std::shared_ptr Create(const std::shared_ptr &icon, + const std::string &title, const std::shared_ptr &wantAgent, + const std::shared_ptr &extras, + NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, + const std::vector> &userInputs, bool isContextual); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationActionButton() = default; + + /** + * Adds additional data to this Builder. + * @param pacMap Indicates the PacMap object containing the additional data. + */ + void AddAdditionalData(AppExecFwk::PacMap &pacMap); + + /** + * Obtains the additional data included in this NotificationActionButton. + * @return the additional data included in this NotificationActionButton. + */ + const std::shared_ptr GetAdditionalData() const; + + /** + * Obtains the icon of this NotificationActionButton. + * @return the icon of this NotificationActionButton. + */ + const std::shared_ptr GetIcon() const; + + /** + * Obtains the WantAgent of this NotificationActionButton. + * @return the WantAgent of this NotificationActionButton. + */ + const std::shared_ptr GetWantAgent() const; + + /** + * Obtains the NotificationUserInput objects that only allow values of particular MIME types + * when this NotificationActionButton is sent. + * @return the list of NotificationUserInput objects allowing only values of particular MIME types. + */ + std::vector> GetMimeTypeOnlyUserInputs() const; + + /** + * Sets a semantic action for this NotificationActionButton. + * @param semanticActionButton Indicates the semantic action to add. + * For available values, see NotificationConstant::SemanticActionButton. + */ + void SetSemanticActionButton(NotificationConstant::SemanticActionButton semanticActionButton); + + /** + * Obtains the semantic action of this NotificationActionButton. + * @return the semantic action of this NotificationActionButton, + * as enumerated in NotificationConstant::SemanticActionButton. + */ + NotificationConstant::SemanticActionButton GetSemanticActionButton() const; + + /** + * Obtains the title of this NotificationActionButton. + * @return the title of this NotificationActionButton. + */ + std::string GetTitle() const; + + /** + * Adds a NotificationUserInput object used to collect user input. + * @param userInput Indicates the NotificationUserInput object to add. + */ + void AddNotificationUserInput(const std::shared_ptr &userInput); + + /** + * Obtains the NotificationUserInput objects to be collected from the user when this NotificationActionButton + * is sent. + * @return the list of NotificationUserInput objects. + */ + std::vector> GetUserInputs() const; + + /** + * Sets whether to allow the platform to automatically generate possible replies and add them to + * NotificationUserInput::getOptions(). + * @param autoCreatedReplies Specifies whether to allow the platform to automatically generate possible replies. + * The value true means to allow generated replies; and the value false means not. + */ + void SetAutoCreatedReplies(bool autoCreatedReplies); + + /** + * Checks whether the platform can automatically generate possible replies for this NotificationActionButton. + * @return true if the platform can generate replies; returns false otherwise. + */ + bool IsAutoCreatedReplies() const; + + /** + * Sets whether this NotificationActionButton is a contextual action, that is, whether this + * NotificationActionButton is dependent on the notification message body. For example, a contextual + * NotificationActionButton provides an address in the notification for users to open a map application. + * @param isContextual Specifies whether this NotificationActionButton is a contextual action. + * The value true indicates a contextual action, and the value false indicates not. + */ + void SetContextDependent(bool isContextual); + + /** + * Checks whether this NotificationActionButton is a contextual action, that is, whether this + * NotificationActionButton is dependent on the notification message body. For example, a contextual + * NotificationActionButton provides an address in the notification for users to open a map application. + * @return true if this NotificationActionButton is a contextual action; returns false otherwise. + */ + bool IsContextDependent() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationActionButton + */ + static NotificationActionButton *Unmarshalling(Parcel &parcel); + +private: + /** + * Default constructor used to create a NotificationActionButton instance. + */ + NotificationActionButton() = default; + + /** + * A constructor used to create a NotificationActionButton instance with the input parameters passed. + * @param icon Indicates the icon to represent this NotificationActionButton. + * @param title Indicates the title of this NotificationActionButton. + * @param wantAgent Indicates the WantAgent to be triggered when this NotificationActionButton is triggered. + * @param extras Indicates the PacMap object containing the additional data. + * @param semanticActionButton Indicates the semantic action to add. + * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. + * @param userInputs Indicates the NotificationUserInput object to add. + * @param isContextual Indicates whether this NotificationActionButton is a contextual action. + */ + NotificationActionButton(const std::shared_ptr &icon, const std::string &title, + const std::shared_ptr &wantAgent, const std::shared_ptr &extras, + NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, + const std::vector> &userInputs, bool isContextual); + + /** + * Read a NotificationActionButton object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::shared_ptr icon_{}; + std::string title_{}; + std::shared_ptr wantAgent_{}; + std::shared_ptr extras_{}; + NotificationConstant::SemanticActionButton semanticActionButton_{ + NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON}; + bool autoCreatedReplies_{true}; + std::vector> userInputs_{}; + bool isContextual_{false}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H \ No newline at end of file diff --git a/kits/native/include/notification_basic_content.h b/kits/native/include/notification_basic_content.h new file mode 100644 index 000000000..c99a1cad9 --- /dev/null +++ b/kits/native/include/notification_basic_content.h @@ -0,0 +1,102 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BASIC_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BASIC_CONTENT_H + +#include +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationBasicContent : public Parcelable { +public: + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationBasicContent(); + + /** + * Sets the additional text to be included in a notification. + * The additional text is mainly a supplement to the notification text set by calling setText(std::string). + * The font of the additional text is smaller than the notification text and is displayed in a separate line. + * @param text Indicates the additional text to be included. + */ + virtual void SetAdditionalText(const std::string &additionalText); + + /** + * Obtains the additional text of a notification specified by calling setAdditionalText(std::string). + * @return the additional text of the notification. + */ + virtual std::string GetAdditionalText() const; + + /** + * Sets the text to be included in a notification. + * @param text Indicates the text to be included. + */ + virtual void SetText(const std::string &text); + + /** + * Obtains the text of a notification specified by calling setText(std::string). + * @return the text of the notification. + */ + virtual std::string GetText() const; + + /** + * Sets the title of a notification. + * @param title Indicates the title of the notification. + */ + virtual void SetTitle(const std::string &title); + + /** + * Obtains the title of a notification specified by calling the setTitle(std::string) method. + * @return the title of the notification. + */ + virtual std::string GetTitle() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + virtual std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + +protected: + /** + * Default constructor. + */ + NotificationBasicContent() = default; + + /** + * Read data from a Parcel. + * @param parcel the parcel + * @return true if read success; returns false otherwise. + */ + virtual bool ReadFromParcel(Parcel &parcel); + +protected: + std::string text_{}; + std::string title_{}; + std::string additionalText_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BASIC_CONTENT_H diff --git a/kits/native/include/notification_constant.h b/kits/native/include/notification_constant.h new file mode 100644 index 000000000..64bbddccd --- /dev/null +++ b/kits/native/include/notification_constant.h @@ -0,0 +1,155 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONSTANT_H + +#include + +namespace OHOS { +namespace Notification { +class NotificationConstant { +public: + enum DisturbMode { + ALLOW_ALARMS, // Indicates that only notifications of the NotificationRequest::CLASSIFICATION_ALARM + // category are allowed to interrupt the user in Do Not Disturb mode. + ALLOW_ALL, // Indicates that all notifications are allowed to interrupt the user in Do Not Disturb mode. + ALLOW_NONE, // Indicates that no notifications are allowed to interrupt the user in Do Not Disturb mode. + ALLOW_PRIORITY, // Indicates that only notifications meeting the specified priority criteria are allowed + // to interrupt the user in Do Not Disturb mode. + ALLOW_UNKNOWN, // Indicates the value returned if the Do Not Disturb mode type cannot be obtained. + }; + + enum InputEditType { + EDIT_AUTO, // Indicates that the system determines whether to allow the user to edit the options before they + // are sent to the application. + EDIT_DISABLED, // Indicates that the user is not allowed to edit an option before the option is sent to the + // application. + EDIT_ENABLED, // Indicates that the user is allowed to edit an option before the option is sent to the + // application. + }; + + enum InputsSource { + FREE_FORM_INPUT, // Indicates that the user manually input the content. + OPTION, // Indicates that the user selected one of the provided options. + }; + + enum SemanticActionButton { + ARCHIVE_ACTION_BUTTON, // Indicates the action of archiving the content associated with the notification. + CALL_ACTION_BUTTON, // Indicates the action of making a call. + DELETE_ACTION_BUTTON, // Indicates the action of deleting the content associated with the notification. + MUTE_ACTION_BUTTON, // Indicates the action of muting the content associated with the notification. + NONE_ACTION_BUTTON, // Indicates that no WantAgent is associated. + READ_ACTION_BUTTON, // Indicates the action of marking the content as read. + REPLY_ACTION_BUTTON, // Indicates the action of replying to a conversation. + THUMBS_DOWN_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-down. + THUMBS_UP_ACTION_BUTTON, // Indicates the action of marking the content with a thumbs-up. + UNMUTE_ACTION_BUTTON, // Indicates the action of unmuting the content associated with the notification. + UNREAD_ACTION_BUTTON, // Indicates the action of marking the content as unread. + }; + + enum SubscribeResult : uint32_t { + SUCCESS, + PREMISSION_FAIL, + RESOURCES_FAIL, + }; + + enum SlotType { + SOCIAL_COMMUNICATION, // the notification type is social communication + SERVICE_REMINDER, // the notification type is service reminder + CONTENT_INFORMATION, // the notificatin type is content information + OTHER, // the notificatin type is other + CUSTOM, // the notification type is custom + }; + + enum class VisiblenessType { + /** + * the notification display effect has not been set by NotificationRequest::setVisibleness(). + * This method is usually not used. + */ + NO_OVERRIDE, + /** + * only the basic information, such as application icon and application name is displayed on the lock screen. + */ + PRIVATE, + /** + * contents of a notification are displayed on the lock screen. + */ + PUBLIC, + /** + * notifications are not displayed on the lock screen. + */ + SECRET + }; + + /** + * Indicates that a notification is deleted because it is clicked. + */ + static const int CLICK_REASON_DELETE = 1; + + /** + * Indicates that a notification is deleted because the user clears it. + */ + static const int CANCEL_REASON_DELETE = 2; + + /** + * Indicates that a notification is deleted because the user clears all notifications. + */ + static const int CANCEL_ALL_REASON_DELETE = 3; + + /** + * Indicates that a notification is deleted because of a UI error. + */ + static const int ERROR_REASON_DELETE = 4; + + /** + * Indicates that a notification is deleted because a change has been made to the application. + */ + static const int PACKAGE_CHANGED_REASON_DELETE = 5; + + /** + * Indicates that a notification is deleted because the application context is stopped. + */ + static const int USER_STOPPED_REASON_DELETE = 6; + + /** + * Indicates that a notification is deleted because the application is banned from sending notifications. + */ + static const int PACKAGE_BANNED_REASON_DELETE = 7; + + /** + * Indicates that a notification is deleted because the application cancels it. + */ + static const int APP_CANCEL_REASON_DELETE = 8; + + /** + * Indicates that a notification is deleted because the application cancels all notifications. + */ + static const int APP_CANCEL_ALL_REASON_DELETE = 9; + + /** + * Indicates that a notification is deleted for other reasons. + */ + static const int APP_CANCEL_REASON_OTHER = 10; + + /** + * The key indicates input source. + */ + static const std::string EXTRA_INPUTS_SOURCE; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONSTANT_H \ No newline at end of file diff --git a/kits/native/include/notification_content.h b/kits/native/include/notification_content.h new file mode 100644 index 000000000..01fc7fe8c --- /dev/null +++ b/kits/native/include/notification_content.h @@ -0,0 +1,182 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H + +#include +#include +#include "notification_basic_content.h" +#include "notification_normal_content.h" +#include "notification_long_text_content.h" +#include "notification_picture_content.h" +#include "notification_conversational_content.h" +#include "notification_multiline_content.h" +#include "notification_media_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationContent : public Parcelable { +public: + enum class Type { + /** + * invalid type + */ + NONE, + /** + * Indicates basic notifications. Such notifications are created using NotificationNormalContent. + */ + BASIC_TEXT, + /** + * Indicates notifications that include a conversation among multiple users. + * Such notifications are created using NotificationConversationalContent. + */ + CONVERSATION, + /** + * Indicates notifications that include long text. + * Such notifications are created using NotificationLongTextContent. + */ + LONG_TEXT, + /** + * Indicates notifications that include media playback sessions. + * Such notifications are created using NotificationMediaContent. + */ + MEDIA, + /** + * Indicates notifications that include multiple independent lines of text. + * Such notifications are created using NotificationMultiLineContent. + */ + MULTILINE, + /** + * Indicates notifications that include a picture. + * Such notifications are created using NotificationPictureContent. + */ + PICTURE + }; + + /** + * A constructor used to create a NotificationNormalContent instance (obtained by calling GetNotificationContent()) + * and set the content type to NotificationContent::Type::BASIC_TEXT (obtained by calling GetContentType()). + * @param normalContent Indicates the NotificationNormalContent object. + */ + explicit NotificationContent(const std::shared_ptr &normalContent); + + /** + * A constructor used to create a NotificationLongTextContent instance (obtained by calling + * GetNotificationContent()) and set the content type to NotificationContent::Type::LONG_TEXT (obtained by calling + * GetContentType()). + * @param longTextContent Indicates the NotificationLongTextContent object. + */ + explicit NotificationContent(const std::shared_ptr &longTextContent); + + /** + * A constructor used to create a NotificationPictureContent instance (obtained by calling GetNotificationContent()) + * and set the content type to NotificationContent::Type::PICTURE (obtained by calling GetContentType()). + * @param pictureContent Indicates the NotificationPictureContent object. + */ + explicit NotificationContent(const std::shared_ptr &pictureContent); + + /** + * A constructor used to create a NotificationConversationalContent instance + * (obtained by calling GetNotificationContent()) and set the content type to + * NotificationContent::Type::CONVERSATION (obtained by calling GetContentType()). + * @param conversationContent Indicates the NotificationConversationalContent object. + */ + explicit NotificationContent(const std::shared_ptr &conversationContent); + + /** + * A constructor used to create a NotificationMultiLineContent instance + * (obtained by calling GetNotificationContent()) and set the content type to + * NotificationContent::Type::MULTILINE (obtained by calling GetContentType()). + * @param multiLineContent Indicates the NotificationMultiLineContent object. + */ + explicit NotificationContent(const std::shared_ptr &multiLineContent); + + /** + * A constructor used to create a NotificationMediaContent instance + * (obtained by calling GetNotificationContent()) and set the content type to + * NotificationContent::Type::MEDIA (obtained by calling GetContentType()). + * @param mediaContent Indicates the NotificationMediaContent object. + */ + explicit NotificationContent(const std::shared_ptr &mediaContent); + + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationContent(); + + /** + * Obtains the type value of the notification content. + * @return the type value of the current content, which can be + * NotificationContent::Type::BASIC_TEXT, + * NotificationContent::Type::LONG_TEXT, + * NotificationContent::Type::PICTURE, + * NotificationContent::Type::CONVERSATION, + * NotificationContent::Type::MULTILINE, or + * NotificationContent::Type::MEDIA. + */ + NotificationContent::Type GetContentType() const; + + /** + * Obtains the object matching the current notification content. + * @return the content object, which can be NotificationLongTextContent, + * NotificationNormalContent, + * NotificationPictureContent, + * NotificationConversationalContent, + * NotificationMultiLineContent, or + * NotificationMediaContent. + */ + std::shared_ptr GetNotificationContent() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationContent + */ + static NotificationContent *Unmarshalling(Parcel &parcel); + +private: + /** + * Default constructor used to create an empty NotificationContent instance. + */ + NotificationContent() = default; + + /** + * Read data from a Parcel. + * @param parcel the parcel + * @return true if read success; returns false otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + +private: + NotificationContent::Type contentType_{NotificationContent::Type::NONE}; + std::shared_ptr content_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H diff --git a/kits/native/include/notification_conversational_content.h b/kits/native/include/notification_conversational_content.h new file mode 100644 index 000000000..894db4116 --- /dev/null +++ b/kits/native/include/notification_conversational_content.h @@ -0,0 +1,144 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_CONTENT_H + +#include +#include +#include +#include "message_user.h" +#include "notification_basic_content.h" +#include "notification_conversational_message.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationConversationalContent : public NotificationBasicContent { +public: + using MessagePtr = std::shared_ptr; + using MessageVector = std::vector; + + /** + * A constructor used to create a NotificationConversationalContent instance with the MessageUser specified. + * @param messageUser Indicates the MessageUser who sends all Message objects in this conversation-like + * notification. This parameter cannot be null. + */ + NotificationConversationalContent(const MessageUser &messageUser); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationConversationalContent() = default; + + /** + * Obtains the message sender to be displayed for any messages + * sent by the user in this conversation-like notification. + * @return the message sender. + */ + MessageUser GetMessageUser() const; + + /** + * Sets the title to be displayed for the conversation. + * The title set in this method will overwrite the one set by calling setTitle(std::tring). + * @param conversationTitle Indicates the title to be displayed for the conversation. + */ + void SetConversationTitle(const std::string &conversationTitle); + + /** + * Obtains the title to be displayed for the conversation. + * @return the title to be displayed for the conversation. + */ + std::string GetConversationTitle() const; + + /** + * Checks whether this notification represents a group conversation. + * @return true if this notification represents a group conversation; returns false otherwise. + */ + bool IsConversationGroup() const; + + /** + * Sets whether this notification represents a group conversation. + * The big icon, if any, set for this notification by calling NotificationRequest::setBigIcon(PixelMap) + * will be displayed only when this method is set to true. + * @param isGroup Specifies whether this notification represents a group conversation. + */ + void SetConversationGroup(bool isGroup); + + /** + * Adds a message to this conversation-like notification based on + * the specified message content, timestamp, and MessageUser. + * All messages will be displayed in the order they are added. + * @param text Indicates the text to be displayed as the message content. + * @param timestamp Indicates the time when the message arrived. + * @param sender Indicates the MessageUser who sent the message. + */ + void AddConversationalMessage( + const std::string &text, int64_t timestamp, const MessageUser &sender); + + /** + * Adds a specified message to this conversation-like notification. + * All messages will be displayed in the order they are added. + * @param message Indicates the ConversationalMessage object to add. + */ + void AddConversationalMessage(const MessagePtr &message); + + /** + * Obtains all messages included in this conversation-like notification. + * @return the list of all Message objects included. + */ + MessageVector GetAllConversationalMessages() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationConversationalContent + */ + static NotificationConversationalContent *Unmarshalling(Parcel &parcel); + +protected: + /** + * Read a NotificationConversationalContent object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel) override; + +private: + /** + * Default constructor used to create an empty NotificationConversationalContent instance. + */ + NotificationConversationalContent() = default; + +private: + MessageUser messageUser_{}; + std::string conversationTitle_{}; + bool isGroup_{false}; + MessageVector messages_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_conversational_message.h b/kits/native/include/notification_conversational_message.h new file mode 100644 index 000000000..e18b103f1 --- /dev/null +++ b/kits/native/include/notification_conversational_message.h @@ -0,0 +1,120 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H + +#include +#include +#include "message_user.h" +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { +class NotificationConversationalMessage : public Parcelable { +public: + /** + * A constructor used to create a NotificationConversationalMessage instance with the input parameters passed. + * @param text Indicates the text to be displayed as the message content. This parameter cannot be null. + * @param timestamp Indicates the time when the message arrived. + * @param sender Indicates the MessageUser who sent the message. + */ + NotificationConversationalMessage( + const std::string &text, int64_t timestamp, const MessageUser &sender); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationConversationalMessage() = default; + + /** + * Obtains the text to be displayed as the content of this message. + * @return the message content. + */ + std::string GetText() const; + + /** + * Obtains the time when this message arrived. + * @return the time when this message arrived. + */ + int64_t GetArrivedTime() const; + + /** + * Obtains the sender of this message. + * @return the message sender. + */ + MessageUser GetSender() const; + + /** + * Sets the MIME type and URI of this message. + * @param mimeType Indicates the MIME type of this message. + * @param uri Indicates the URI that points to the message content whose type is specified by the given MIME type. + */ + void SetData(const std::string &mimeType, const std::shared_ptr &uri); + + /** + * Obtains the MIME type of this message. + * @return the MIME type of this message. + */ + std::string GetMimeType() const; + + /** + * Obtains the URI of the message content with the specific MIME type. + * @return the URI of the message content with the specific MIME type. + */ + const std::shared_ptr GetUri() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationConversationalMessage + */ + static NotificationConversationalMessage *Unmarshalling(Parcel &parcel); + +private: + /** + * Default constructor used to create an empty NotificationConversationalMessage instance. + */ + NotificationConversationalMessage() = default; + + /** + * Read a NotificationConversationalMessage object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + int64_t arrivedTime_{0}; + std::string text_{}; + MessageUser sender_{}; + std::shared_ptr uri_{}; + std::string mimeType_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H \ No newline at end of file diff --git a/kits/native/include/notification_helper.h b/kits/native/include/notification_helper.h new file mode 100644 index 000000000..236b4a41f --- /dev/null +++ b/kits/native/include/notification_helper.h @@ -0,0 +1,503 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H + +#include "notification_request.h" +#include "notification_slot.h" +#include "notification_slot_group.h" +#include "notification_sorting_map.h" +#include "notification_subscriber.h" + +namespace OHOS { +namespace Notification { +class NotificationHelper { +public: + /** + * Creates a notification slot. + * @note You can call the NotificationRequest::SetSlotType(NotificationConstant::SlotType) method to bind the slot + * for publishing. A NotificationSlot instance cannot be used directly after being initialized. Instead, you have to + * call this method to create a notification slot and bind the slot ID to a NotificationRequest object so that the + * notification published can have all the characteristics set in the NotificationSlot. After a notification slot is + * created by using this method, only the name and description of the notification slot can be changed. Changes to + * the other attributes, such as the vibration status and notification tone, will no longer take effect. + * + * @param slot Indicates the notification slot to be created, which is set by NotificationSlot. + * This parameter must be specified. + * @return Returns add notification slot result. + */ + static ErrCode AddNotificationSlot(const NotificationSlot &slot); + + /** + * Creates multiple notification slots. + * + * @param slots Indicates the notification slots to create. + * @return Returns add notification slots result. + */ + static ErrCode AddNotificationSlots(const std::vector &slots); + + /** + * Deletes a created notification slot based on the slot ID. + * + * @param slotType Indicates the type of the slot, which is created by AddNotificationSlot + * This parameter must be specified. + * @return Returns remove notification slot result. + */ + static ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + + /** + * Queries a created notification slot. + * + * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot(NotificationSlot). This + * parameter must be specified. + * @param slot Indicates the created NotificationSlot. + * @return Returns the get notification slot result. + */ + static ErrCode GetNotificationSlot(const NotificationConstant::SlotType &slotType, sptr &slot); + + /** + * Obtains all notification slots of this application. + * @param slots Indicates the created NotificationSlot. + * @return Returns all notification slots of this application. + */ + static ErrCode GetNotificationSlots(std::vector> &slots); + + /** + * Creates a notification slot group to which a NotificationSlot object can be bound by + * calling NotificationSlot::SetSlotGroup(string). + * @note A NotificationSlotGroup instance cannot be used directly after being initialized. + * Instead, you have to call this method to create a notification slot group so that you can bind + * NotificationSlot objects to it. + * + * @param slotGroup Indicates the notification slot group to be created, which is set by NotificationSlotGroup. + * This parameter must be specified. the notification slot to be created, which is set by + * NotificationSlot. + * @return Returns add notification slot group result. + */ + static ErrCode AddNotificationSlotGroup(const NotificationSlotGroup &slotGroup); + + /** + * Creates multiple notification slot groups. + * @note The precautions for using this method are similar to those for + * AddNotificationSlotGroup(NotificationSlotGroup). + * + * @param slotGroups Indicates a list of NotificationSlotGroup objects to create. This parameter cannot be null. + * @return Returns add notification slot groups result. + */ + static ErrCode AddNotificationSlotGroups(const std::vector &slotGroups); + + /** + * Deletes a created notification slot group based on the slot group ID. + * + * @param slotGroupId Indicates the ID of the notification slot group, which is created by + * AddNotificationSlotGroup(NotificationSlotGroup) This parameter must be specified. + * @return Returns remove notification slot group result. + */ + static ErrCode RemoveNotificationSlotGroup(const std::string &slotGroupId); + + /** + * Queries a created notification slot group. + * + * @param groupId Indicates the ID of the slot group. + * @param group Indicates the created NotificationSlotGroup. + * @return Returns get notification slot group result. + */ + static ErrCode GetNotificationSlotGroup(const std::string &groupId, sptr &group); + + /** + * Obtains a list of created notification slot groups. + * + * @param groups Indicates a list of created notification slot groups. + * @return Returns get notification slot groups result. + */ + static ErrCode GetNotificationSlotGroups(std::vector> &groups); + + /** + * Publishes a notification. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + static ErrCode PublishNotification(const NotificationRequest &request); + + /** + * Publishes a notification with a specified label. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param label Indicates the label of the notification to publish. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + static ErrCode PublishNotification(const std::string &label, const NotificationRequest &request); + + /** + * Publishes a notification on a specified remote device. + * @note If a notification with the same ID has been published by the current application and has not been deleted, + * this method will update the notification. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @param deviceId Indicates the ID of the remote device. If this parameter is null or an empty string, + * the notification will be published on the local device. + * @return Returns publish notification result. + */ + static ErrCode PublishNotification(const NotificationRequest &request, const std::string &deviceId); + + /** + * Cancels a published notification. + * + * @param notificationId Indicates the unique notification ID in the application. + * The value must be the ID of a published notification. + * Otherwise, this method does not take effect. + * @return Returns cancel notification result. + */ + static ErrCode CancelNotification(int32_t notificationId); + + /** + * Cancels a published notification matching the specified label and notificationId. + * + * @param label Indicates the label of the notification to cancel. + * @param notificationId Indicates the ID of the notification to cancel. + * @return Returns cancel notification result. + */ + static ErrCode CancelNotification(const std::string &label, int32_t notificationId); + + /** + * Cancels all the published notifications. + * @note To cancel a specified notification, see CancelNotification(int_32). + * @return Returns cancel all notifications result. + */ + static ErrCode CancelAllNotifications(); + + /** + * Obtains the number of active notifications of the current application in the system. + * + * @param nums Indicates the number of active notifications of the current application. + * @return Returns get active notification nums result. + */ + static ErrCode GetActiveNotificationNums(int32_t &num); + + /** + * Obtains active notifications of the current application in the system. + * @param request Indicates active NotificationRequest objects of the current application. + * @return Returns get active notifications result. + */ + static ErrCode GetActiveNotifications(std::vector> &request); + + /** + * Obtains the map for sorting notifications of the current application. + * + * @param sortingMap Indicates the NotificationSortingMap object for the current application. + * @return Returns get current app sorting result. + */ + static ErrCode GetCurrentAppSorting(sptr &sortingMap); + + /** + * Allows another application to act as an agent to publish notifications in the name of your application bundle. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application. + * @return Returns set notification agent result. + */ + static ErrCode SetNotificationAgent(const std::string &agent); + + /** + * Obtains the name of the application bundle that can publish notifications in the name of your application. + * + * @param agent Indicates the name of the application bundle that can publish notifications for your application if + * any; returns null otherwise. + * @return Returns get notification agent result. + */ + static ErrCode GetNotificationAgent(std::string &agent); + + /** + * Checks whether your application has permission to publish notifications by calling + * PublishNotificationAsBundle(string, NotificationRequest) in the name of another application indicated by the + * given representativeBundle. + * + * @param representativeBundle Indicates the name of application bundle your application is representing. + * @param canPublish Indicates whether your application has permission to publish notifications. + * @return Returns can publish notification as bundle result. + */ + static ErrCode CanPublishNotificationAsBundle(const std::string &representativeBundle, bool &canPublish); + + /** + * Publishes a notification in the name of a specified application bundle. + * @note If the notification to be published has the same ID as a published notification that has not been canceled, + * the existing notification will be replaced by the new one. + * + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @param representativeBundle Indicates the name of the application bundle that allows your application to publish + * notifications for it by calling setNotificationAgent. + * @return publish notification as bundle result. + */ + static ErrCode PublishNotificationAsBundle( + const std::string &representativeBundle, const NotificationRequest &request); + + /** + * Sets the number of active notifications of the current application as the number to be displayed on the + * notification badge. + * @return Returns set notification badge num result. + */ + static ErrCode SetNotificationBadgeNum(); + + /** + * Sets the number to be displayed on the notification badge of the application. + * + * @param num Indicates the number to display. A negative number indicates that the badge setting remains unchanged. + * The value 0 indicates that no badge is displayed on the application icon. + * If the value is greater than 99, 99+ will be displayed. + * @return Returns set notification badge num result. + */ + static ErrCode SetNotificationBadgeNum(int32_t num); + + /** + * Checks whether this application has permission to publish notifications. + * + * @param allowed True if this application has the permission; returns false otherwise + * @return Returns is allowed notify result. + */ + static ErrCode IsAllowedNotify(bool &allowed); + + /** + * Checks whether this application is in the suspended state.Applications in this state cannot publish + * notifications. + * + * @param suspended True if this application is suspended; returns false otherwise. + * @return Returns are notifications suspended. + */ + static ErrCode AreNotificationsSuspended(bool &suspended); + + /** + * Checks whether this application has permission to modify the Do Not Disturb (DND) notification policy. + * + * @param hasPermission True if this application is suspended; returns false otherwise. + * @return Returns has notification policy access permission. + */ + static ErrCode HasNotificationPolicyAccessPermission(bool &hasPermission); + + /** + * Obtains the importance level of this application. + * + * @param importance the importance level of this application, which can be LEVEL_NONE, + LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, LEVEL_HIGH, or LEVEL_UNDEFINED. + * @return Returns get bundle importance result + */ + static ErrCode GetBundleImportance(NotificationSlot::NotificationLevel &importance); + + /** + * Subscribes to notifications from all applications. This method can be called only by applications + * with required system permissions. + * @note To subscribe to a notification, inherit the {NotificationSubscriber} class, override its + * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to notifications published only by specified sources, for example, notifications from + * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} + * method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + + /** + * Subscribes to all notifications based on the filtering criteria. This method can be called only + * by applications with required system permissions. + * @note After {subscribeInfo} is specified, a subscriber receives only the notifications that + * meet the filter criteria specified by {subscribeInfo}. + * To subscribe to a notification, inherit the {NotificationSubscriber} class, override its + * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. + * After the notification is published, subscribers that meet the filter criteria can receive the + * notification. To subscribe to and receive all notifications, call the + * {SubscribeNotification(NotificationSubscriber)} method. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + static ErrCode SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + + /** + * Unsubscribes from all notifications. This method can be called only by applications with required + * system permissions. + * @note Generally, you subscribe to a notification by calling the + * {SubscribeNotification(NotificationSubscriber)} method. If you do not want your application + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + + /** + * Unsubscribes from all notifications based on the filtering criteria. This method can be called + * only by applications with required system permissions. + * @note A subscriber will no longer receive the notifications from specified notification sources. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + + /** + * Removes a specified removable notification of other applications. + * @note Your application must have platform signature to use this method. + * + * @param key Indicates the key of the notification to remove. + * @return Returns remove notification result. + */ + static ErrCode RemoveNotification(const std::string &key); + + /** + * Removes all removable notifications of a specified bundle. + * @note Your application must have platform signature to use this method. + * + * @param bundleName Indicates the bundle name of the application whose notifications are to be removed. + * @return Returns remove notifications result. + */ + static ErrCode RemoveNotifications(const std::string &bundleName); + + /** + * Removes all removable notifications in the system. + * @note Your application must have platform signature to use this method. + * @return Returns remove notifications result. + */ + static ErrCode RemoveNotifications(); + + /** + * Returns all notification slots belonging to the specified bundle. + * + * @param bundleName Indicates the application name. + * @param slots Indicates a list of notification slots. + * @return Returns get notification slots for bundle result. + */ + static ErrCode GetNotificationSlotsForBundle( + const std::string &bundleName, std::vector> &slots); + + /** + * Obtains all active notifications in the current system. The caller must have system permissions to + * call this method. + * + * @param notification Indicates all active notifications of this application. + * @return Returns get all active notifications + */ + static ErrCode GetAllActiveNotifications(std::vector> ¬ification); + + /** + * Obtains the active notifications corresponding to the specified key in the system. To call this method + * to obtain particular active notifications, you must have received the notifications and obtained the key + * via {Notification::GetKey()}. + * + * @param key Indicates the key array for querying corresponding active notifications. + * If this parameter is null, this method returns all active notifications in the system. + * @return Returns the set of active notifications corresponding to the specified key. + */ + static ErrCode GetAllActiveNotifications( + const std::vector key, std::vector> ¬ification); + + /** + * Checks whether a specified application has the permission to publish notifications. If bundle specifies + * the current application, no permission is required for calling this method. If bundle specifies another + * application, the caller must have system permissions. + * + * @param bundle Indicates the bundle name of the application to check. + * @param allowed True if the application has permissions; returns false otherwise. + * @return Returns is allowed notify result. + */ + static ErrCode IsAllowedNotify(const std::string &bundle, bool &allowed); + + /** + * Sets whether to allow all applications to publish notifications on a specified device. The caller must have + * system permissions to call this method. + * + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only + * be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow all applications to publish notifications. The value true + * indicates that notifications are allowed, and the value false indicates that notifications are not + * allowed. + * @return Returns set notifications enabled for all bundles result. + */ + static ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled); + + /** + * Sets whether to allow the current application to publish notifications on a specified device. The caller + * must have system permissions to call this method. + * + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can + * only be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow the current application to publish notifications. The value + * true indicates that notifications are allowed, and the value false indicates that + * notifications are not allowed.\ + * @return Returns set notifications enabled for default bundle result. + */ + static ErrCode SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled); + + /** + * Sets whether to allow a specified application to publish notifications on a specified device. The caller + * must have system permissions to call this method. + * + * @param bundle Indicates the bundle name of the application. + * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only + * be null or an empty string, indicating the current device. + * @param enabled Specifies whether to allow the given application to publish notifications. The value + * true indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. + * @return Returns set notifications enabled for specified bundle result. + */ + static ErrCode SetNotificationsEnabledForSpecifiedBundle( + const std::string &bundle, std::string &deviceId, bool enabled); + + /** + * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications + * that are allowed to interrupt users. + * @note Your application must have system signature to call this method. + * + * @param mode Indicates the Do Not Disturb mode to set. The value must be + * {NotificationConstant.DisturbMode.ALLOW_ALL}, {NotificationConstant.DisturbMode.ALLOW_PRIORITY}, + * {NotificationConstant.DisturbMode.ALLOW_NONE}, or {NotificationConstant.DisturbMode.ALLOW_ALARMS}. + * @return Returns set disturb mode result. + */ + static ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); + + /** + * Obtains the Disturb Mode. + * @param disturbMode The current type of the Do Not Disturb mode. + * @return Returns get disturb mode result. + */ + static ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H \ No newline at end of file diff --git a/kits/native/include/notification_long_text_content.h b/kits/native/include/notification_long_text_content.h new file mode 100644 index 000000000..c01757c78 --- /dev/null +++ b/kits/native/include/notification_long_text_content.h @@ -0,0 +1,124 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_LONG_TEXT_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_LONG_TEXT_CONTENT_H + +#include +#include +#include "notification_basic_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationLongTextContent : public NotificationBasicContent { +public: + /** + * Default constructor used to create a NotificationLongTextContent instance. + */ + NotificationLongTextContent() = default; + + /** + * A constructor used to create a NotificationLongTextContent instance with the input parameter longText passed. + * @param longText Indicates the long text to be included. The value contains a maximum of 1024 characters. + */ + explicit NotificationLongTextContent(const std::string &longText); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationLongTextContent() = default; + + /** + * Sets the title to be displayed when this long text notification is expanded. After this title is set, + * the title set by setTitle(string) will be displayed only when this notification is in the collapsed state. + * @param exTitle Indicates the title to be displayed when this notification is expanded. + */ + void SetExpandedTitle(const std::string &exTitle); + + /** + * Obtains the title that will be displayed for this long text notification when it is expanded. + * @return the title to be displayed when this notification is expanded. + */ + std::string GetExpandedTitle() const; + + /** + * Sets the brief text to be included in a long text notification. + * The brief text is a summary of a long text notification and is displayed in the first line of the notification. + * Similar to setAdditionalText(string), the font of the brief text is also smaller than the notification text. + * The positions where the brief text and additional text will display may conflict. + * If both texts are set, only the additional text will be displayed. + * @param briefText Indicates the brief text to be included. + */ + void SetBriefText(const std::string &briefText); + + /** + * Obtains the brief text of a long text notification specified by calling the setBriefText(string) method. + * @return the brief text of the long text notification. + */ + std::string GetBriefText() const; + + /** + * Sets the long text to be included in a long text notification. + * @param longText Indicates the long text to be included. The value contains a maximum of 1024 characters. + */ + void SetLongText(const std::string &longText); + + /** + * Obtains a notification's long text, which is set by calling the setLongText(string) method. + * @return the long text. + */ + std::string GetLongText() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationLongTextContent + */ + static NotificationLongTextContent *Unmarshalling(Parcel &parcel); + +protected: + /** + * Read a NotificationLongTextContent object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel) override; + +private: + /** + * the maximum lenth of longtext is 1024 characters. + */ + static const std::size_t MAX_LONGTEXT_LENGTH; + +private: + std::string longText_{}; + std::string expandedTitle_{}; + std::string briefText_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_LONG_TEXT_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_media_content.h b/kits/native/include/notification_media_content.h new file mode 100644 index 000000000..00d29f750 --- /dev/null +++ b/kits/native/include/notification_media_content.h @@ -0,0 +1,108 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MEDIA_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MEDIA_CONTENT_H + +#include +#include +#include +#include "notification_basic_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class AVToken; + +class NotificationMediaContent : public NotificationBasicContent { +public: + /** + * Default constructor used to create a NotificationMediaContent instance. + */ + NotificationMediaContent() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationMediaContent() = default; + + /** + * Attaches a specified AVToken to this media playback notification. + * After an AVToken is attached, this notification can interact with the associated AVSession + * so that users can control media playback in this notification. + * @param avToken Indicates the AVToken to attach. + */ + void SetAVToken(const std::shared_ptr &avToken); + + /** + * Obtains the AVToken attached to this media playback notification. + * @return the AVToken attached to this notification. + */ + const std::shared_ptr GetAVToken() const; + + /** + * Sets up to three NotificationActionButton objects to be shown in this media playback notification. + * Before publishing this notification, you should also call + * NotificationRequest::addActionButton(NotificationActionButton) to add specified NotificationActionButton objects + * for this notification so that this method can take effect. The added action buttons will be assigned sequence + * numbers in the order they were added. The sequence numbers specified in the value of actions for this method + * must match those assigned to added action buttons. Otherwise, the notification will fail to publish. By default, + * the sequence number starts from 0. If you want to show three action buttons, the value of actions should be 0, + * 1, 2. + * @param actions Indicates the list of sequence numbers representing the NotificationActionButton objects + * to be shown in this notification. + */ + void SetShownActions(const std::vector &actions); + + /** + * Obtains the list of sequence numbers representing the NotificationActionButton objects + * to be shown in this media playback notification. + * @return the list of the action buttons to be shown. + */ + std::vector GetShownActions() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationMediaContent + */ + static NotificationMediaContent *Unmarshalling(Parcel &parcel); + +protected: + /** + * Read a NotificationMediaContent object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel) override; + +private: + std::shared_ptr avToken_{}; + std::vector sequenceNumbers_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MEDIA_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_multiline_content.h b/kits/native/include/notification_multiline_content.h new file mode 100644 index 000000000..db0f4db89 --- /dev/null +++ b/kits/native/include/notification_multiline_content.h @@ -0,0 +1,121 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MULTILINE_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MULTILINE_CONTENT_H + +#include +#include +#include "notification_basic_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationMultiLineContent : public NotificationBasicContent { +public: + /** + * Default constructor used to create a NotificationMultiLineContent instance. + */ + NotificationMultiLineContent() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationMultiLineContent() = default; + + /** + * Sets the title to be displayed when this multi-line notification is expanded. + * After this title is set, the title set by setTitle(string) will be displayed only + * when this notification is in the collapsed state. + * @param exTitle Indicates the title to be displayed when this notification is expanded. + */ + void SetExpandedTitle(const std::string &exTitle); + + /** + * Obtains the title that will be displayed for this multi-line notification when it is expanded. + * @return the title to be displayed when this notification is expanded. + */ + std::string GetExpandedTitle() const; + + /** + * Sets the brief text to be included in a multi-line notification. + * The brief text is a summary of this multi-line notification and is displayed in the first line of + * the notification. Similar to setAdditionalText(string), the font of the brief text is also + * smaller than the notification text set by calling setText(string). + * The positions where the brief text and additional text will display may conflict. + * If both texts are set, only the additional text will be displayed. + * @param briefText Indicates the brief text to be included. + */ + void SetBriefText(const std::string &briefText); + + /** + * Obtains the brief text that has been set by calling setBriefText(string) for this multi-line notification. + * @return the brief text of this notification. + */ + std::string GetBriefText() const; + + /** + * Adds a single line of text to this notification. + * You can call this method up to seven times to add seven lines to a notification. + * @param oneLine Indicates the single line of text to be included. + */ + void AddSingleLine(const std::string &oneLine); + + /** + * Obtains the list of lines included in this multi-line notification. + * @return the list of lines included in this notification. + */ + std::vector GetAllLines() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationMultiLineContent + */ + static NotificationMultiLineContent *Unmarshalling(Parcel &parcel); + +protected: + /** + * Read a NotificationMultiLineContent object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel) override; + +private: + /** + * the maximum size of vector is 7. + */ + static const std::vector::size_type MAX_LINES; + +private: + std::string expandedTitle_{}; + std::string briefText_{}; + std::vector allLines_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MULTILINE_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_normal_content.h b/kits/native/include/notification_normal_content.h new file mode 100644 index 000000000..b9145ceb7 --- /dev/null +++ b/kits/native/include/notification_normal_content.h @@ -0,0 +1,58 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_NORMAL_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_NORMAL_CONTENT_H + +#include +#include "notification_basic_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationNormalContent : public NotificationBasicContent { +public: + /** + * Default constructor used to create a NotificationNormalContent instance. + */ + NotificationNormalContent() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationNormalContent() = default; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationNormalContent + */ + static NotificationNormalContent *Unmarshalling(Parcel &parcel); +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_NORMAL_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_picture_content.h b/kits/native/include/notification_picture_content.h new file mode 100644 index 000000000..45dda0608 --- /dev/null +++ b/kits/native/include/notification_picture_content.h @@ -0,0 +1,115 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_PICTURE_CONTENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_PICTURE_CONTENT_H + +#include +#include +#include "notification_basic_content.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class PixelMap; + +class NotificationPictureContent : public NotificationBasicContent { +public: + /** + * Default constructor used to create an empty NotificationPictureContent instance. + */ + NotificationPictureContent() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationPictureContent() = default; + + /** + * Sets the title to be displayed when this picture-attached notification is expanded. + * After this title is set, the title set by setTitle(string) will be displayed only + * when this notification is in the collapsed state. + * @param exTitle Indicates the title to be displayed when this notification is expanded. + */ + void SetExpandedTitle(const std::string &exTitle); + + /** + * Obtains the title that will be displayed for this picture-attached notification when it is expanded. + * @return the title to be displayed when this notification is expanded. + */ + std::string GetExpandedTitle() const; + + /** + * Sets the brief text to be included in a picture-attached notification. + * The brief text is a summary of a picture-attached notification and is displayed in the first line of the + * notification. Similar to setAdditionalText(string), the font of the brief text is also smaller than the + * notification text. The positions where the brief text and additional text will display may conflict. If both + * texts are set, only the additional text will be displayed. + * @param briefText Indicates the brief text to be included. + */ + void SetBriefText(const std::string &briefText); + + /** + * Obtains the brief text of a picture-attached notification specified by calling the setBriefText(string) method. + * @return the brief text of the picture-attached notification. + */ + std::string GetBriefText() const; + + /** + * Sets the picture to be included in a notification. + * @param bigPicture Indicates the PixelMap of the picture to be included. + */ + void SetBigPicture(const std::shared_ptr &bigPicture); + + /** + * Obtains the PixelMap of the picture specified by calling the setBigPicture(PixelMap) method. + * @return the PixelMap of the picture included in the notification. + */ + const std::shared_ptr GetBigPicture() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump() override; + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationPictureContent + */ + static NotificationPictureContent *Unmarshalling(Parcel &parcel); + +protected: + /** + * Read a NotificationPictureContent object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel) override; + +private: + std::string expandedTitle_{}; + std::string briefText_{}; + std::shared_ptr bigPicture_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_PICTURE_CONTENT_H \ No newline at end of file diff --git a/kits/native/include/notification_request.h b/kits/native/include/notification_request.h new file mode 100644 index 000000000..c6e677199 --- /dev/null +++ b/kits/native/include/notification_request.h @@ -0,0 +1,996 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H + +#include +#include +#include +#include "message_user.h" +#include "notification_action_button.h" +#include "notification_content.h" +#include "want_agent.h" +#include "context.h" +#include "ohos/aafwk/content/want_params.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class ComponentProvider; +class PixelMap; + +class NotificationRequest : public Parcelable { +public: + enum class BadgeStyle { + /** + * displays only numbers. + */ + NONE, + /** + * displayed as a large icon. + */ + BIG, + /** + * displayed as a small icon. + */ + LITTLE + }; + + enum class GroupAlertType { + /** + * all notifications in a group have sound or vibration if sound or vibration is enabled + * for the associated NotificationSlot objects. + */ + ALL, + /** + * child notifications have sound or vibration but the overview notification is muted (no sound or vibration) + * in a group if sound or vibration is enabled for the associated NotificationSlot objects. + */ + CHILD, + /** + * the overview notification has sound or vibration but child notifications are muted (no sound or vibration) + * in a group if sound or vibration is enabled for the associated NotificationSlot objects. + */ + OVERVIEW + }; + + /** + * Indicates the classification of notifications for alarms or timers. + */ + static const std::string CLASSIFICATION_ALARM; + /** + * Indicates the classification of notifications for incoming calls or similar synchronous communication requests. + */ + static const std::string CLASSIFICATION_CALL; + /** + * Indicates the classification of notifications for emails. + */ + static const std::string CLASSIFICATION_EMAIL; + /** + * Indicates the classification of notifications for errors occurred during background operations or identity + * authentication. + */ + static const std::string CLASSIFICATION_ERROR; + /** + * Indicates the classification of notifications for calendar events. + */ + static const std::string CLASSIFICATION_EVENT; + /** + * Indicates the classification of notifications for short messages or instant messages. + */ + static const std::string CLASSIFICATION_MESSAGE; + /** + * Indicates the classification of notifications for map navigation. + */ + static const std::string CLASSIFICATION_NAVIGATION; + /** + * Indicates the classification of notifications for processes that are operated in the background for a long time. + */ + static const std::string CLASSIFICATION_PROGRESS; + /** + * Indicates the classification of notifications for advertisement or promotion information. + */ + static const std::string CLASSIFICATION_PROMO; + /** + * Indicates the classification of notifications for specific and timely recommendations of a particular + * transaction. + */ + static const std::string CLASSIFICATION_RECOMMENDATION; + /** + * Indicates the classification of notifications for reminders previously set by the user. + */ + static const std::string CLASSIFICATION_REMINDER; + /** + * Indicates the classification of notifications for ongoing background services. + */ + static const std::string CLASSIFICATION_SERVICE; + /** + * Indicates the classification of notifications for social network or sharing updates. + */ + static const std::string CLASSIFICATION_SOCIAL; + /** + * Indicates the classification of notifications for ongoing information about the device and contextual status. + */ + static const std::string CLASSIFICATION_STATUS; + /** + * Indicates the classification of notifications for system or device status updates. + */ + static const std::string CLASSIFICATION_SYSTEM; + /** + * Indicates the classification of notifications for media transport control during playback. + */ + static const std::string CLASSIFICATION_TRANSPORT; + + /** + * Indicates the default notification background color, which means that no color is displayed. + */ + static const int32_t COLOR_DEFAULT; + +private: + /** + * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). + */ + static const int32_t COLOR_MASK; + + /** + * the maximum number of user input history is 5. + */ + static const std::size_t MAX_USER_INPUT_HISTORY; + + /** + * the maximum number of action buttons is 3. + */ + static const std::size_t MAX_ACTION_BUTTONS; + +public: + /** + * Default constructor used to create a NotificationRequest instance. + */ + NotificationRequest() = default; + + /** + * A constructor used to create a NotificationRequest instance with the input parameter notificationId passed. + * @param notificationId notification ID + */ + explicit NotificationRequest(int32_t notificationId); + + /** + * A constructor used to create a NotificationRequest instance based on the specified context and notification ID. + * To publish a notification with a custom view, you must call such a constructor with the Context specified. + * @param context the specified context + * @param notificationId notification ID + */ + NotificationRequest(const std::shared_ptr &context, int32_t notificationId); + + /** + * A constructor used to create a NotificationRequest instance by copying parameters from an existing one. + * @param other the existing object + */ + NotificationRequest(const NotificationRequest &other); + + /** + * A constructor used to create a NotificationRequest instance by copying parameters from an existing one. + * @param other the existing object + */ + NotificationRequest &operator=(const NotificationRequest &other); + + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationRequest(); + + /** + * Checks whether this notification is in progress. + * @return true if this notification is in progress; returns false otherwise. + */ + bool IsInProgress() const; + + /** + * Sets whether this notification is in progress. + * Users cannot directly dismiss notifications in progress because + * they usually contain some ongoing background services such as music playback. + * @param isOngoing Specifies whether this notification is in progress. + */ + void SetInProgress(bool isOngoing); + + /** + * Checks whether this notification is unremovable. + * @return true if this notification is unremovable; returns false otherwise. + */ + bool IsUnremovable() const; + + /** + * Sets whether this notification is unremovable. + * If it is set to be unremovable, it cannot be removed by users. + * @param isUnremovable Specifies whether this notification is unremovable. + */ + void SetUnremovable(bool isUnremovable); + + /** + * Sets the number to be displayed for this notification. + * @param number Indicates the number to set. + */ + void SetBadgeNumber(int32_t number); + + /** + * Obtains the number to be displayed for this notification. + * @return the number to be displayed for this notification. + */ + int32_t GetBadgeNumber() const; + + /** + * Sets the current notification ID to uniquely identify the notification in the application. + * After a notification is received, its ID is obtained by using the getNotificationId() method. + * @param notificationId Indicates the ID of the notification to be set. + */ + void SetNotificationId(int32_t notificationId); + + /** + * Obtains the notification ID, which is unique in the current application. + * @return the notification ID. + */ + int32_t GetNotificationId() const; + + /** + * Adds an WantAgent to this notification. + * After a notification is tapped, + * subsequent operations such as ability and common events will be triggered as set by WantAgent. + * @param wantAgent Indicates the operation triggered by tapping the notification, which can be set by + * WantAgent. + */ + void SetWantAgent(const std::shared_ptr &wantAgent); + + /** + * Obtains the WantAgent contained in this notification. + * @return the WantAgent contained in this notification. + */ + const std::shared_ptr GetWantAgent() const; + + /** + * Sets an WantAgent object that is triggered when the user explicitly removes this notification. + * @param wantAgent Indicates the WantAgent object to be triggered. + */ + void SetRemovalWantAgent(const std::shared_ptr &wantAgent); + + /** + * Obtains the WantAgent object that is triggered when the user explicitly removes this notification. + * @return the WantAgent object to be triggered. + */ + const std::shared_ptr GetRemovalWantAgent() const; + + /** + * Sets the WantAgent to start when the device is not in use, + * instead of showing this notification in the status bar. + * When the device is in use, the system UI displays a pop-up notification + * instead of starting the WantAgent specified by maxScreenWantAgent. + * Your application must have the ohos.permission.USE_WHOLE_SCREEN permission to use this method. + * @param wantAgent Indicates the WantAgent object containing information about the to-be-started ability that + * uses the Page template. + */ + void SetMaxScreenWantAgent(const std::shared_ptr &wantAgent); + + /** + * Obtains the full-screen WantAgent set by calling setMaxScreenWantAgent(WantAgent). + * @return the full-screen WantAgent. + */ + const std::shared_ptr GetMaxScreenWantAgent() const; + + /** + * Sets extra parameters that are stored as key-value pairs for the notification. + * @param extras Indicates the WantParams object containing the extra parameters in key-value pair format. + */ + void SetAdditionalData(const std::shared_ptr &extras); + + /** + * Obtains the WantParams object set in the notification. + * @return the WantParams object. + */ + const std::shared_ptr GetAdditionalData() const; + + /** + * Sets the time to deliver a notification. + * @param deliveryTime Indicates the time in milliseconds. + */ + void SetDeliveryTime(int64_t deliveryTime); + + /** + * Obtains the time when a notification is delivered. + * @return the time in milliseconds. + */ + int64_t GetDeliveryTime() const; + + /** + * Checks whether the notification delivery time is displayed for this notification. + * @return true if the time is displayed; returns false otherwise. + */ + bool IsShowDeliveryTime() const; + + /** + * Sets whether to show the notification delivery time for this notification. + * This method is valid only when the notification delivery time has been set by calling setDeliveryTime(int64_t). + * @param showDeliveryTime Specifies whether to show the notification delivery time. + */ + void SetShowDeliveryTime(bool showDeliveryTime); + + /** + * Adds a NotificationActionButton to this notification. + * The system typically places action buttons next to the notification content. + * Each action button must contain an icon, a title, and an WantAgent. When a notification is expanded, + * a maximum of three action buttons can be displayed from left to right in the order they were added. + * When the notification is collapsed, no action buttons will be displayed. + * @param actionButton Indicates the NotificationActionButton object to add. + */ + void AddActionButton(const std::shared_ptr &actionButton); + + /** + * Obtains the list of all NotificationActionButton objects included in this notification. + * @return the list of NotificationActionButton objects. + */ + const std::vector> GetActionButtons() const; + + /** + * Checks whether the platform is allowed to generate contextual NotificationActionButton objects for this + * notification. + * @return true if the platform is allowed to generate contextual NotificationActionButton objects; + * returns false otherwise. + */ + bool IsPermitSystemGeneratedContextualActionButtons() const; + + /** + * Sets whether to allow the platform to generate contextual NotificationActionButton objects for this notification. + * @param permitted Specifies whether to allow the platform to generate contextual NotificationActionButton objects. + * The default value true indicates that the platform is allowed to generate contextual action buttons, + * and the value false indicates not. + */ + void SetPermitSystemGeneratedContextualActionButtons(bool permitted); + + /** + * Adds a MessageUser object and associates it with this notification. + * @param messageUser Indicates the MessageUser object to add. + */ + void AddMessageUser(const std::shared_ptr &messageUser); + + /** + * Obtains all MessageUser objects associated with this notification. + * @return the list of MessageUser objects associated with this notification. + */ + const std::vector> GetMessageUsers() const; + + /** + * Checks whether this notification is set to alert only once, + * which means that sound or vibration will no longer be played + * for notifications with the same ID upon their updates. + * @return true if this notification is set to alert only once; returns false otherwise. + */ + bool IsAlertOneTime() const; + + /** + * Sets whether to have this notification alert only once. + * If a notification alerts only once, sound or vibration will no longer be played + * for notifications with the same ID upon their updates after they are published. + * @param isAlertOnce Specifies whether to have this notification alert only once. + */ + void SetAlertOneTime(bool isAlertOnce); + + /** + * Sets the time to delete a notification. + * @param deletedTime Indicates the time in milliseconds. + * The default value is 0, indicating that the notification will not be automatically deleted. + * To enable the notification to be automatically deleted, set this parameter to an integer greater than 0. + */ + void SetAutoDeletedTime(int64_t deletedTime); + + /** + * Obtains the period during which a notification is deleted. + * @return the period in milliseconds. + */ + int64_t GetAutoDeletedTime() const; + + /** + * Sets the little icon of the notification. + * @param littleIcon Indicates the icon of the notification. + */ + void SetLittleIcon(const std::shared_ptr &littleIcon); + + /** + * Obtains the icon of the notification. + * @return the notification icon. + */ + const std::shared_ptr GetLittleIcon() const; + + /** + * Sets the large icon of this notification, which is usually displayed on the right of the notification. + * @param bigIcon Indicates the large icon to set. It must be a PixelMap object. + */ + void SetBigIcon(const std::shared_ptr &bigIcon); + + /** + * Obtains the large icon of this notification. + * @return the large icon of this notification. + */ + const std::shared_ptr GetBigIcon() const; + + /** + * Sets the classification of this notification, which describes the purpose of this notification. + * Notification classifications are used to filter and sort notifications. + * @param classification Indicates the notification classification predefined in the system, + * such as CLASSIFICATION_CALL or CLASSIFICATION_NAVIGATION etc. + */ + void SetClassification(const std::string &classification); + + /** + * Obtains the classification of this notification. + * @return the classification of this notification. + */ + std::string GetClassification() const; + + /** + * Sets the background color of this notification. + * This method is valid only when background color has been enabled by calling setColorEnabled(bool). + * @param color Indicates the background color to set. For details about the value range, see Color. + */ + void SetColor(int32_t color); + + /** + * Obtains the background color of this notification. + * The return value, except for the default color COLOR_DEFAULT, + * is the bitwise OR operation result of 0xFF000000 and the ARGB value set by setColor(int32_t). + * @return the background color of this notification. + */ + int32_t GetColor() const; + + /** + * Checks whether background color is enabled for this notification. + * @return true if background color is enabled; returns false otherwise. + */ + bool IsColorEnabled(); + + /** + * Sets whether to enable background color for this notification. + * If colorEnabled is set to true, this method takes effect only + * when the notification content type has been set to NotificationRequest. + * NotificationMediaContent in the NotificationRequest object through + * NotificationRequest::setContent(NotificationContent) and an AVToken has been attached to + * that NotificationMediaContent object through NotificationMediaContent::setAVToken(AVToken). + * @param colorEnabled Specifies whether to enable background color. + */ + void SetColorEnabled(bool colorEnabled); + + /** + * Sets the notification content type to NotificationNormalContent, NotificationLongTextContent, + * or NotificationPictureContent etc. + * Each content type indicates a particular notification content. + * @param content Indicates the notification content type. + */ + void SetContent(const std::shared_ptr &content); + + /** + * Obtains the notification content set by calling the setContent(NotificationContent) method. + * @return the notification content. + */ + const std::shared_ptr GetContent() const; + + /** + * Obtains the notification type. + * @return the type of the current notification, which can be + * NotificationContent::Type::BASIC_TEXT, + * NotificationContent::Type::LONG_TEXT, + * NotificationContent::Type::PICTURE, + * NotificationContent::Type::CONVERSATION, + * NotificationContent::Type::MULTILINE, + * or NotificationContent::Type::MEDIA. + */ + NotificationContent::Type GetNotificationType() const; + + /** + * Checks whether the notification creation time is displayed as a countdown timer. + * @return true if the time is displayed as a countdown timer; returns false otherwise. + */ + bool IsCountdownTimer() const; + + /** + * Sets whether to show the notification creation time as a countdown timer. + * This method is valid only when setShowStopwatch(boolean) is set to true. + * @param isCountDown Specifies whether to show the notification creation time as a countdown timer. + */ + void SetCountdownTimer(bool isCountDown); + + /** + * Sets the custom view to be displayed when this notification is expanded. + * @param view Indicates the ComponentProvider object defining the custom view. + */ + void SetCustomBigView(const std::shared_ptr &view); + + /** + * Obtains the ComponentProvider object defining the custom view to be displayed when this notification is expanded + * The ComponentProvider object is set in setCustomBigView(ComponentProvider). + * @return the ComponentProvider object defining the custom view. + */ + const std::shared_ptr GetCustomBigView() const; + + /** + * Sets the custom view to be displayed when this notification is shown as a floating window at the top of the + * screen + * @param view Indicates the ComponentProvider object defining the custom view. + */ + void SetCustomFloatView(const std::shared_ptr &view); + + /** + * Obtains the ComponentProvider object defining the custom view to be displayed + * when this notification is shown as a floating window at the top of the screen. + * The ComponentProvider object is set in setCustomFloatView(ComponentProvider). + * @return the ComponentProvider object defining the custom view. + */ + const std::shared_ptr GetCustomFloatView() const; + + /** + * Sets the custom view of this notification. + * @param view Indicates the ComponentProvider object defining the custom view. + */ + void SetCustomView(const std::shared_ptr &view); + + /** + * Obtains the ComponentProvider object defining the custom view set in this notification. + * The ComponentProvider object is set in setCustomView(ComponentProvider). + * @return the ComponentProvider object defining the custom view. + */ + const std::shared_ptr GetCustomView() const; + + /** + * Sets the group alert type for this notification, + * which determines how the group overview and other notifications in a group are published. + * The group information must have been set by calling setGroupValue(string). + * Otherwise, this method does not take effect. + * @param type Indicates the group alert type to set. which can be GroupAlertType::ALL (default value), + * GroupAlertType::OVERVIEW, or GroupAlertType::CHILD etc. + */ + void SetGroupAlertType(NotificationRequest::GroupAlertType type); + + /** + * Obtains the group alert type of this notification. + * @return the group alert type of this notification. + */ + NotificationRequest::GroupAlertType GetGroupAlertType() const; + + /** + * Checks whether this notification is the group overview. + * @return true if this notification is the group overview; returns false otherwise. + */ + bool IsGroupOverview() const; + + /** + * Sets whether to use this notification as the overview of its group. + * This method helps display the notifications that are assigned the same group value by calling + * setGroupValue(string) as one stack in the notification bar. + * Each group requires only one group overview. After a notification is set as the group overview, + * it becomes invisible if another notification in the same group is published. + * @param overView Specifies whether to set this notification as the group overview. + */ + void SetGroupOverview(bool overView); + + /** + * Sets the group information for this notification. + * If no groups are set for notifications, all notifications from the same application will appear + * in the notification bar as one stack with the number of stacked notifications displayed. + * If notifications are grouped and there are multiple groups identified by different groupValue, + * notifications with different groupValue will appear in separate stacks. + * Note that one of the notifications in a group must be set as the overview of its group by calling + * setGroupOverview(bool), and other notifications are considered as child notifications. + * Otherwise, notifications will not be displayed as one group even if they are assigned the same groupValue by + * calling setGroupValue(string). + * @param groupValue Specifies whether to set this notification as the group overview. + */ + void SetGroupValue(const std::string &groupValue); + + /** + * Obtains the group information about this notification. + * @return the group information about this notification. + */ + std::string GetGroupValue() const; + + /** + * Checks whether this notification is relevant only to the local device and cannot be displayed on remote devices. + * @return true if this notification is relevant only to the local device; returns false otherwise. + */ + bool IsOnlyLocal() const; + + /** + * Sets whether this notification is relevant only to the local device and cannot be displayed on remote devices. + * This method takes effect only for notifications published by calling + * NotificationHelper::publishNotification(NotificationRequest) or + * NotificationHelper#publishNotification(string, NotificationRequest). + * Notifications published using NotificationHelper::publishNotification(NotificationRequest, string) + * in a distributed system will not be affected. + * @param flag Specifies whether this notification can be displayed only on the local device. + */ + void SetOnlyLocal(bool flag); + + /** + * Sets the text that will be displayed as a link to the settings of the application. + * Calling this method is invalid if the notification content type has been set to NotificationLongTextContent + * or NotificationPictureContent in the NotificationRequest object through setContent(NotificationContent). + * @param text Indicates the text to be included. You can set it to any valid link. + */ + void SetSettingsText(const std::string &text); + + /** + * Obtains the text that will be displayed as a link to the settings of the application. + * @return the text displayed as the link to the application settings. + */ + std::string GetSettingsText() const; + + /** + * Deprecated. + * Obtains the time when a notification is created. + * @return the time in milliseconds. + */ + int64_t GetCreateTime() const; + + /** + * Checks whether the notification creation time is displayed as a stopwatch. + * @return true if the time is displayed as a stopwatch; returns false otherwise. + */ + bool IsShowStopwatch() const; + + /** + * Sets whether to show the notification creation time as a stopwatch. + * This method is valid only when the notification creation time has been set by calling setDeliveryTime(int64_t). + * When the notification creation time is set to be shown as a stopwatch, the interval between the current time + * and the creation time set by setDeliveryTime(int64_t) is dynamically displayed for this notification + * in Minutes: Seconds format. If the interval is longer than 60 minutes, it will be displayed + * in Hours: Minutes: Seconds format. If this method and setShowDeliveryTime(boolean) are both set to true, only + * this method takes effect, that is, the notification creation time will be shown as a stopwatch. + * @param isShow Specifies whether to show the notification creation time as a stopwatch. + */ + void SetShowStopwatch(bool isShow); + + /** + * Sets the slot type of a notification to bind the created NotificationSlot object. + * You can use NotificationSlot to create a slot object, + * then set the notification vibration and lock screen display, and use the current method to bind the slot. + * The value must be the type of an existing NotificationSlot object. + * @param slotType Indicates the unique type of the NotificationSlot object. + */ + void SetSlotType(NotificationConstant::SlotType slotType); + + /** + * Obtains the slot type of a notification set by calling the setSlotType(string) method. + * @return the notification slot type. + */ + NotificationConstant::SlotType GetSlotType() const; + + /** + * Sets a key used for sorting notifications from the same application bundle. + * @param key Indicates the key to set. + */ + void SetSortingKey(const std::string &key); + + /** + * Obtains the key used for sorting notifications from the same application bundle. + * @return the key for sorting notifications. + */ + std::string GetSortingKey() const; + + /** + * Sets the scrolling text to be displayed in the status bar when this notification is received. + * @param text Indicates the scrolling text to be displayed. + */ + void SetStatusBarText(const std::string &text); + + /** + * Obtains the scrolling text that will be displayed in the status bar when this notification is received. + * @return the scrolling notification text. + */ + std::string GetStatusBarText() const; + + /** + * Checks whether the current notification will be automatically dismissed after being tapped. + * @return true if the notification will be automatically dismissed; returns false otherwise. + */ + bool IsTapDismissed() const; + + /** + * Sets whether to automatically dismiss a notification after being tapped. + * If you set tapDismissed to true, + * you must call the setWantAgent(WantAgent) method to make the settings take effect. + * @param isDismissed Specifies whether a notification will be automatically dismissed after being tapped. + */ + void SetTapDismissed(bool isDismissed); + + /** + * Sets the notification display effect, including whether to display this notification on the lock screen, + * and how it will be presented if displayed. + * For details, see NotificationSlot::setLockscreenVisibleness(int). + * If the lock screen display effect is set for a NotificationRequest object + * and its associated NotificationSlot object, the display effect set in the NotificationRequest object prevails. + * @param type Indicates the notification display effect on the lock screen. + */ + void SetVisibleness(NotificationConstant::VisiblenessType type); + + /** + * Obtains the display effect of this notification on the lock screen. + * @return the display effect of this notification on the lock screen. + */ + NotificationConstant::VisiblenessType GetVisibleness() const; + + /** + * Sets the badge icon style for this notification. + * This method does not take effect if the home screen does not support badge icons. + * @param style Indicates the type of the badge icon to be displayed for this notification. + * The value must be BadgeStyle::NONE, BadgeStyle::LITTLE, or BadgeStyle::BIG. + */ + void SetBadgeIconStyle(NotificationRequest::BadgeStyle style); + + /** + * Obtains the badge icon style of this notification. + * @return the badge icon style of this notification. + */ + NotificationRequest::BadgeStyle GetBadgeIconStyle() const; + + /** + * Sets the shortcut ID for this notification. + * After a shortcut ID is set for a notification, the notification will be associated with the corresponding + * home-screen shortcut, and the shortcut will be hidden when the Home application displays the badge or content + * of the notification. + * @param shortcutId Indicates the shortcut ID to set. + */ + void SetShortcutId(const std::string &shortcutId); + + /** + * Obtains the shortcut ID associated with this notification. + * @return the shortcut ID of this notification. + */ + std::string GetShortcutId() const; + + /** + * Sets whether this notification is displayed as a floating icon on top of the screen. + * @param floatingIcon Specifies whether a notification is displayed as a floating icon on top of the screen. + */ + void SetFloatingIcon(bool floatingIcon); + + /** + * Checks whether this notification is displayed as a floating icon on top of the screen. + * @return true if this notification is displayed as a floating icon; returns false otherwise. + */ + bool IsFloatingIcon() const; + + /** + * Sets how the progress bar will be displayed for this notification. + * A progress bar is usually used in notification scenarios such as download. + * @param progress Indicates the current value displayed for the notification progress bar. + * @param progressMax Indicates the maximum value displayed for the notification progress bar. + * @param indeterminate Specifies whether the progress bar is indeterminate. The value true indicates that + * the progress bar is indeterminate, and users cannot see its current and maximum values. + */ + void SetProgressBar(int32_t progress, int32_t progressMax, bool indeterminate); + + /** + * Obtains the maximum value displayed for the progress bar of this notification. + * @return the maximum value of the notification progress bar. + */ + int32_t GetProgressMax() const; + + /** + * Obtains the current value displayed for the progress bar of this notification. + * @return the current value of the notification progress bar. + */ + int32_t GetProgressValue() const; + + /** + * Checks whether the progress bar of this notification is indeterminate. + * @return true if the notification progress bar is indeterminate; returns false otherwise. + */ + bool IsProgressIndeterminate() const; + + /** + * Sets the most recent NotificationUserInput records that have been sent through this notification. + * The most recent input must be stored in index 0, + * the second most recent input must be stored in index 1, and so on. + * The system displays a maximum of five inputs. + * @param text Indicates the list of inputs to set. + */ + void SetNotificationUserInputHistory(const std::vector &text); + + /** + * Obtains the most recent NotificationUserInput records + * @return the most recent NotificationUserInput records + */ + std::vector GetNotificationUserInputHistory() const; + + /** + * Sets an alternative notification to be displayed on the lock screen for this notification. + * The display effect (whether and how this alternative notification will be displayed) is subject to + * the configuration in NotificationSlot::setLockscreenVisibleness(int). + * @param other Indicates the alternative notification to be displayed on the lock screen. + */ + void SetPublicNotification(const std::shared_ptr &other); + + /** + * Obtains the alternative notification to be displayed on the lock screen for this notification. + * @return the alternative notification to be displayed on the lock screen for this notification. + */ + const std::shared_ptr GetPublicNotification() const; + + /** + * Obtains the unique hash code of a notification in the current application. + * To obtain a valid hash code, you must have subscribed to and received the notification. + * A valid notification hash code is a string composed of multiple attributes separated by an underscore (_), + * including the notification ID, creator bundle name, creator UID, and owner bundle name. + * @return the hash code of the notification. + */ + std::string GetNotificationHashCode() const; + + /** + * Sets the bundle name of the notification owner. + * The notification owner refers to the application that subscribes to the notification. + * @param ownerName the bundle name of the notification owner. + */ + void SetOwnerBundleName(const std::string &ownerName); + + /** + * Obtains the bundle name of the notification owner. + * The notification owner refers to the application that subscribes to the notification. + * @return the bundle name of the notification owner. + */ + std::string GetOwnerBundleName() const; + + /** + * Sets the bundle name of the notification creator. + * The notification creator refers to the application that publishes the notification. + * @param creatorName the bundle name of the notification creator. + */ + void SetCreatorBundleName(const std::string &creatorName); + + /** + * Obtains the bundle name of the notification creator. + * The notification creator refers to the application that publishes the notification. + * @return the bundle name of the notification creator. + */ + std::string GetCreatorBundleName() const; + + /** + * Sets the PID of the notification creator. + * @param pid the PID of the notification creator. + */ + void SetCreatorPid(pid_t pid); + + /** + * Obtains the PID of the notification creator. + * @return the PID of the notification creator. + */ + pid_t GetCreatorPid() const; + + /** + * Sets the UID of the notification creator. + * @param uid the UID of the notification creator. + */ + void SetCreatorUid(uid_t uid); + + /** + * Obtains the UID of the notification creator. + * @return the UID of the notification creator. + */ + uid_t GetCreatorUid() const; + + /** + * Sets the label of this notification. + * @param label the label of this notification. + */ + void SetLabel(const std::string &label); + + /** + * Obtains the label of this notification. + * The label is set via NotificationHelper::publishNotification(string, NotificationRequest). + * This method returns null if no specific label is set for this notification. + * @return the label of this notification. + */ + std::string GetLabel() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a NotificationRequest object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationRequest + */ + static NotificationRequest *Unmarshalling(Parcel &parcel); + +private: + /** + * Read a NotificationRequest object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * Obtains the current system time in milliseconds. + * @return the current system time in milliseconds. + */ + int64_t GetNowSysTime(); + +private: + int32_t notificationId_{0}; + int32_t color_{NotificationRequest::COLOR_DEFAULT}; + int32_t badgeNumber_{0}; + int32_t progressValue_{0}; + int32_t progressMax_{0}; + int64_t createTime_{0}; + int64_t deliveryTime_{0}; + int64_t autoDeletedTime_{0}; + + pid_t creatorPid_{0}; + uid_t creatorUid_{0}; + + std::string settingsText_{}; + std::string creatorBundleName_{}; + std::string ownerBundleName_{}; + std::string groupValue_{}; + std::string statusBarText_{}; + std::string label_{}; + std::string shortcutId_{}; + std::string sortingKey_{}; + std::string classification_{}; + + NotificationConstant::SlotType slotType_{NotificationConstant::SlotType::OTHER}; + NotificationRequest::GroupAlertType groupAlertType_{NotificationRequest::GroupAlertType::ALL}; + NotificationConstant::VisiblenessType visiblenessType_{NotificationConstant::VisiblenessType::NO_OVERRIDE}; + NotificationRequest::BadgeStyle badgeStyle_{NotificationRequest::BadgeStyle::NONE}; + NotificationContent::Type notificationContentType_{NotificationContent::Type::NONE}; + + bool showDeliveryTime_{false}; + bool tapDismissed_{false}; + bool colorEnabled_{false}; + bool alertOneTime_{false}; + bool showStopwatch_{false}; + bool isCountdown_{false}; + bool inProgress_{false}; + bool groupOverview_{false}; + bool progressIndeterminate_{false}; + bool unremovable_{false}; + bool floatingIcon_{false}; + bool onlyLocal_{false}; + bool permitted_{true}; + + std::shared_ptr context_{}; + std::shared_ptr wantAgent_{}; + std::shared_ptr removalWantAgent_{}; + std::shared_ptr maxScreenWantAgent_{}; + std::shared_ptr additionalParams_{}; + std::shared_ptr littleIcon_{}; + std::shared_ptr bigIcon_{}; + std::shared_ptr notificationContent_{}; + std::shared_ptr customBigView_{}; + std::shared_ptr customFloatView_{}; + std::shared_ptr customView_{}; + std::shared_ptr publicNotification_{}; + + std::vector> actionButtons_{}; + std::vector> messageUsers_{}; + std::vector userInputHistory_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H diff --git a/kits/native/include/notification_slot.h b/kits/native/include/notification_slot.h new file mode 100644 index 000000000..84951f800 --- /dev/null +++ b/kits/native/include/notification_slot.h @@ -0,0 +1,372 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_H + +#include + +#include "notification_content.h" +#include "notification_request.h" +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { +class NotificationSlot : public Parcelable { +public: + enum NotificationLevel { + LEVEL_NONE, // the notification function is disabled. + LEVEL_MIN, // the notifications function is disabled on the notification panel, + // with no banner or prompt tone + LEVEL_LOW, // the notifications are displayed on the notification panel, + // with no banner or prompt tone + LEVEL_DEFAULT, // the notification function is enabled and notifications are displayed + // on the notification panel, with a banner and a prompt tone. + LEVEL_HIGH, // the notifications are displayed on the notification panel, + // with a banner and a prompt tone + LEVEL_UNDEFINED, // the notification does not define an level. + }; + + /** + * A constructor used to initialize the type of a NotificationSlot object. + * + * @param type Specifies the type of the NotificationSlot object, + */ + NotificationSlot(NotificationConstant::SlotType type = NotificationConstant::SlotType::CUSTOM); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationSlot(); + + /** + * Obtains whether the notification light is enabled in a NotificationSlot object, + * which is set by SetEnableLight(bool). + * + * @return Returns true if the notification light is enabled; returns false otherwise. + */ + bool CanEnableLight() const; + + /** + * Specifies whether to enable the notification light when a notification is received on the device, + * provided that this device has a notification light. + * @note SetEnableLight must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is + * called. Otherwise, the settings will not take effect. + * + * @param isLightEnabled Specifies whether to enable the pulse notification light. + * The value true indicates to enable the notification light, + * and the value false indicates not to enable it. + */ + void SetEnableLight(bool isLightEnabled); + + /** + * Obtains the vibration status of a NotificationSlot object, + * which is set by SetEnableVibration(bool). + * + * @return Returns true if vibration is enabled; returns false otherwise. + */ + bool CanVibrate() const; + + /** + * Sets whether to enable vibration when a notification is received. + * @note SetEnableVibration(bool) must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) + * method is called. Otherwise, the settings will not take effect. + * + * @param vibration Indicates whether to enable vibration when a notification is received. + * If the value is true, vibration is enabled; if the value is false, vibration is disabled. + */ + void SetEnableVibration(bool vibration); + + /** + * Obtains the description of a NotificationSlot object, which is set by SetDescription(string). + * + * @return Returns the description of the NotificationSlot object. + */ + std::string GetDescription() const; + + /** + * Sets the description for a NotificationSlot object. + * @note The setting of setDescription is effective regardless of whether a NotificationSlot object has been created + * by NotificationHelper::AddNotificationSlot(NotificationSlot). + * + * @param description Describes the NotificationSlot object. + * The description is visible to users and its length must not exceed 1000 characters + * (the excessive part is automatically truncated). + */ + void SetDescription(const std::string &description); + + /** + * Obtains the ID of a NotificationSlot object. + * + * @return Returns the ID of the NotificationSlot object, + * which is set by NotificationSlot(string, string, NotificationLevel). + */ + std::string GetId() const; + + /** + * Obtains the color of the notification light in a NotificationSlot object, + * which is set by SetLedLightColor(int32_t). + * + * @return Returns the color of the notification light. + */ + int32_t GetLedLightColor() const; + + /** + * Sets the color of the notification light to flash when a notification is received on the device, + * provided that this device has a notification light and setEnableLight is called with the value true. + * @note SetLedLightColor must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is + * called. Otherwise, the settings will not take effect. + * + * @param color Indicates the color of the notification light. + */ + void SetLedLightColor(int32_t color); + + /** + * Obtains the level of a NotificationSlot object, which is set by SetLevel(NotificationLevel). + * + * @return Returns the level of the NotificationSlot object. + */ + NotificationLevel GetLevel() const; + + /** + * Sets the level of a NotificationSlot object. + * @note SetLevel must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is called. + * Otherwise, the settings will not take effect. + * + * @param level Specifies the level of the NotificationSlot object, which determines the notification display + * effect. The value can be LEVEL_NONE, LEVEL_MIN, LEVEL_LOW, LEVEL_DEFAULT, or LEVEL_HIGH. + */ + void SetLevel(NotificationLevel level); + + /** + * Obtains the type of a NotificationSlot object, which is set by SetType(SlotType). + * + * @return Returns the Type of the NotificationSlot object. + */ + NotificationConstant::SlotType GetType() const; + + /** + * Sets the type of a NotificationSlot object. + * @note Settype must be set before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is called. + * Otherwise, the settings will not take effect. + * + * @param type Specifies the type of the NotificationSlot object, which determines the notification remind mode. + * The value can be DEFAULT, SOCIAL_COMMUNICATION, SERVICE_REMINDER, CONTENT_INFORMATION, or OTHER. + */ + void SetType(NotificationConstant::SlotType type); + + /** + * Obtains the notification display effect of a NotificationSlot object on the lock screen, + * which is set by SetLockscreenVisibleness(int32_t). + * @note This method specifies different effects for displaying notifications on the lock screen in order to protect + * user privacy. The setting takes effect only when the lock screen notifications function is enabled for an + * application in system notification settings. + * + * @return Returns the notification display effect of the NotificationSlot object on the lock screen. + */ + NotificationConstant::VisiblenessType GetLockScreenVisibleness() const; + + /** + * Sets whether and how to display notifications on the lock screen. + * + * @param visibleness Specifies the notification display effect on the lock screen, which can be set to + * NO_OVERRIDE, PUBLIC, PRIVATE, or SECRET. + */ + void SetLockscreenVisibleness(NotificationConstant::VisiblenessType visibleness); + + /** + * Obtains the name of a NotificationSlot object. + * + * @return Returns the name of the NotificationSlot object, which is set by SetName(string). + */ + std::string GetName() const; + + /** + * Obtains the ID of the NotificationSlotGroup object to which this NotificationSlot object belongs, + * which is set by SetSlotGroup(string). + * + * @return Returns the ID of the NotificationSlotGroup to which this NotificationSlot object belongs. + */ + std::string GetSlotGroup() const; + + /** + * Binds a NotificationSlot object to a specified NotificationSlotGroup. + * @note SetSlotGroup must be called before the NotificationHelper::AddNotificationSlot(NotificationSlot) method is + * called. Otherwise, this method will not take effect. + * @param groupId Indicates the ID of the NotificationSlotGroup object to bind, + * which must have been created by calling + * NotificationHelper::AddNotificationSlotGroup(NotificationSlotGroup). + */ + void SetSlotGroup(const std::string &groupId); + + /** + * Obtains the prompt tone of a NotificationSlot object, which is set by SetSound(Uri). + * + * @return Returns the prompt tone of the NotificationSlot object. + */ + Uri GetSound() const; + + /** + * Sets a prompt tone for a NotificationSlot object, which will be played after a notification is received. + * @note SetSound must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is called. + * Otherwise, the settings will not take effect. + * + * @param sound Specifies the path for the prompt tone. + */ + void SetSound(const Uri &sound); + + /** + * Obtains the vibration style of notifications in this NotificationSlot. + * + * @return Returns the vibration style of this NotificationSlot. + */ + std::vector GetVibrationStyle() const; + + /** + * Sets the vibration style for notifications in this NotificationSlot. + * @note If an empty array or null is passed to this method, the system then calls + * SetEnableVibration(bool) with the input parameter set to false. + * If a valid value is passed to this method, the system calls SetEnableVibration(bool) with the input + * parameter set to true. This method takes effect only before + * NotificationHelper::AddNotificationSlot(NotificationSlot) is called. + * + * @param vibration Indicates the vibration style to set. + */ + void SetVibrationStyle(const std::vector &vibration); + + /** + * Obtains whether DND mode is bypassed for a NotificationSlot object, + * which is set by EnableBypassDnd(bool). + * + * @return Returns true if DND mode is bypassed; returns false otherwise. + */ + bool IsEnableBypassDnd() const; + + /** + * Sets whether to bypass Do not disturb (DND) mode in the system. + * @note The setting of EnableBypassDnd takes effect only when the Allow interruptions function + * is enabled for an application in system notification settings. + * + * @param isBypassDnd Specifies whether to bypass DND mode for an application. + * If the value is true, DND mode is bypassed; + * if the value is false, DND mode is not bypassed. + */ + void EnableBypassDnd(bool isBypassDnd); + + /** + * Obtains the application icon badge status of a NotificationSlot object, + * which is set by EnableBadge(bool). + * + * @return Returns true if the application icon badge is enabled; returns false otherwise. + */ + bool IsShowBadge() const; + + /** + * Sets whether to display application icon badges (digits or dots in the corner of the application icon) + * on the home screen after a notification is received. + * @note EnableBadge must be set before the NotificationHelper:AddNotificationSlot(NotificationSlot) method is + * called. Otherwise, the settings will not take effect. + * + * @param isShowBadge Specifies whether to display the application icon badge. + * If the value is true, the application icon badge is enabled; + * if the value is false, the application icon badge is disabled.. + */ + void EnableBadge(bool isShowBadge); + + /** + * Dumps a string representation of the object. + * + * @return A string representation of the object. + */ + std::string Dump() const; + + /** + * Marshals a NotificationSlot object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshals a NotificationSlot object from a Parcel. + * + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static NotificationSlot *Unmarshalling(Parcel &parcel); + +private: + /** + * Read NotificationSlot object from a Parcel. + * + * @param parcel the parcel + * @return read from parcel success or fail + */ + bool ReadFromParcel(Parcel &parcel); + + /** + * Merge the contents of vector and output a string + * + * @param mergeVector The vector which will be merged + * @return Returns the string that has contents of the vector + */ + std::string MergeVectorToString(const std::vector &mergeVector) const; + + /** + * If string length exceed 1000 characters, the excessive part is automatically truncated. + * + * @param in The sting which will be truncated + * @return Returns the string that has been truncated. + */ + std::string TruncateString(const std::string &in); + + /** + * Sets the name of a NotificationSlot object. + * @note The setting of SetName is effective regardless of whether a NotificationSlot object has been created by + * NotificationHelper:AddNotificationSlot(NotificationSlot). + * + * @param name Specifies the name of the NotificationSlot object. + * The name is visible to users, and its length must not exceed 1000 characters + * (the excessive part is automatically truncated). + */ + void SetName(const std::string &name); + +private: + std::string id_; + std::string name_; + bool isLightEnabled_; + bool isVibrationEnabled_; + bool isShowBadge_ = true; + bool isBypassDnd_; + std::string description_; + int32_t lightColor_ = 0; + NotificationLevel level_; + NotificationConstant::SlotType type_; + NotificationConstant::VisiblenessType lockScreenVisibleness_{NotificationConstant::VisiblenessType::NO_OVERRIDE}; + std::string groupId_; + Uri sound_; + std::vector vibrationValues_; + + // no object in parcel + static constexpr int VALUE_NULL = -1; + // object exist in parcel + static constexpr int VALUE_OBJECT = 1; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_H \ No newline at end of file diff --git a/kits/native/include/notification_slot_group.h b/kits/native/include/notification_slot_group.h new file mode 100644 index 000000000..ba95b6af4 --- /dev/null +++ b/kits/native/include/notification_slot_group.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_GROUP_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_GROUP_H + +#include + +#include "notification_slot.h" + +namespace OHOS { +namespace Notification { +class NotificationSlotGroup : public Parcelable { +public: + /** + * Default constructor used to create a NotificationSlotGroup instance. + */ + NotificationSlotGroup(); + + /** + * A constructor used to create a NotificationSlotGroup instance with the group ID and name initialized. + * + * @param id Indicates the ID of the NotificationSlotGroup. + * The ID must be unique and its length must not exceed 1000 characters (the excess part is automatically + * truncated). + * @param name Indicates the name of the NotificationSlotGroup. + * Its length must not exceed 1000 characters (the excess part is automatically truncated). + */ + NotificationSlotGroup(const std::string &id, const std::string &name); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationSlotGroup(); + + /** + * Obtains the description of this NotificationSlotGroup object, which is set by SetDescription(string). + * + * @return Returns the description of this NotificationSlotGroup. + */ + std::string GetDescription() const; + + /** + * Obtains the ID of this NotificationSlotGroup object, which is set by NotificationSlotGroup(string, string). + * + * @return Returns the ID of this NotificationSlotGroup. + */ + std::string GetId() const; + + /** + * Obtains the name of this NotificationSlotGroup object, which is set by NotificationSlotGroup(string, string). + * + * @return Returns the name of this NotificationSlotGroup. + */ + std::string GetName() const; + + /** + * Obtains a list of notification slots bound to this NotificationSlotGroup object. + * @note NotificationSlot::SetSlotGroup(string) is used to bind a notification slot to a notification slot group. + * + * @return Returns the list of notification slots bound to this NotificationSlotGroup. + */ + std::vector GetSlots() const; + + /** + * Checks whether this NotificationSlotGroup is disabled. + * + * @return Returns true if this NotificationSlotGroup is disabled; returns false otherwise. + */ + bool IsDisabled() const; + + /** + * Sets the description for this NotificationSlotGroup object. + * + * @param description Describes this NotificationSlotGroup object. + * Its length must not exceed 1000 characters (the excess part is automatically truncated). + */ + void SetDescription(const std::string &description); + + /** + * Dumps a string representation of the object. + * + * @return A string representation of the object. + */ + std::string Dump() const; + + /** + * Marshals NotificationSlotGroup objects and writes them into Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshals a NotificationSlotGroup object from a Parcel. + * + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static NotificationSlotGroup *Unmarshalling(Parcel &parcel); + + /** + * If string length exceed 1000 characters, the excessive part is automatically truncated. + * + * @param truncatedString The sting which will be truncated + * @return Returns the string that has been truncated. + */ + std::string TruncateString(const std::string &inPutString); + +private: + /** + * Read NotificationSlotGroup object from a Parcel. + * + * @param parcel the parcel + * @return read from parcel success or fail + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string id_; + std::string name_; + std::string description_; + std::vector slots_; + bool isDisabled_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_GROUP_H \ No newline at end of file diff --git a/kits/native/include/notification_sorting.h b/kits/native/include/notification_sorting.h new file mode 100644 index 000000000..4b273f938 --- /dev/null +++ b/kits/native/include/notification_sorting.h @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_H + +#include +#include + +#include "ans_log_wrapper.h" +#include "notification_slot.h" +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { + +class NotificationSorting final : public Parcelable { +public: + /** + * @brief Default constructor used to create an empty NotificationSorting instance. + */ + NotificationSorting(); + + /** + * @brief Default deconstructor used to deconstruct. + */ + ~NotificationSorting(); + + /** + * @brief A constructor used to create a NotificationSorting instance by copying parameters from an existing one. + * + * @param sorting Indicates the NotificationSorting object. + */ + NotificationSorting(const NotificationSorting &sorting); + + /** + * @brief Obtains the sequence number of a notification among all the active notifications. + * + * @return Returns the sequence number of the notification. + */ + inline int32_t GetRanking() const + { + return ranking_; + }; + + /** + * @brief Obtains the notification hash code, which is unique in the current application. + * Generally, the notification hash code is a string in the format + * Notification ID_Creator package name_Creator UID_Owner package name. + * + * @return Returns the notification hash code. + */ + inline std::string GetKey() const + { + return key_; + }; + + /** + * @brief Obtains the importance level of the current notification set in the corresponding NotificationSlot. + * + * @return Returns the importance level of the notification. + */ + inline int32_t GetImportance() const + { + return importance_; + }; + + /** + * @brief Obtains the NotificationSlot the current notification belongs to. + * Each notification must be in a particular NotificationSlot. + * + * @return Returns the NotificationSlot of the notification. + */ + inline NotificationSlot GetSlot() const + { + return *slot_; + }; + + /** + * @brief Obtains the visibility of the current notification on the lock screen set. + * + * @return Returns the visibility of the notification on the lock screen. + */ + inline int32_t GetVisiblenessOverride() const + { + return visiblenessOverride_; + }; + + /** + * @brief Checks whether the badge is displayed for the current notification. + * + * @return Returns true if the badge is displayed; returns false otherwise. + */ + inline bool IsDisplayBadge() const + { + return isDisplayBadge_; + }; + + /** + * @brief Checks whether the current notification is hidden. + * A notification should be hidden if the application sending the notification is suspended. + * + * @return Returns true if the notification is hidden; returns false otherwise. + */ + inline bool IsHiddenNotification() const + { + return isHiddenNotification_; + }; + + /** + * @brief Obtains the overridden notification group key. If the system has overridden the group key, + * a non-null value will be returned. + * + * @return Returns the overridden notification group key used to bind notifications. + */ + inline std::string GetGroupKeyOverride() const + { + return groupKeyOverride_; + }; + + /** + * @brief Marshals a NotificationSorting object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals a NotificationSorting object from a Parcel. + * + * @param Indicates the Parcel object for unmarshalling. + * + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static NotificationSorting *Unmarshalling(Parcel &parcel); + + /** + * @brief Dump sorting info + * + * @return Sorting info + */ + std::string Dump() const; + +private: + void SetGroupKeyOverride(const std::string &str); + void SetKey(const std::string &key); + void SetImportance(const int32_t &importance); + void SetRanking(const int32_t &ranking); + void SetSlot(const sptr &slot); + void SetVisiblenessOverride(const int32_t &visibleness); + void SetDisplayBadge(const bool &isDisplayBadge); + void SetHiddenNotification(const bool &isHiddenNotfication); + bool ReadFromParcel(Parcel &parcel); + +private: + std::string key_{}; + int32_t ranking_{-1}; + int32_t importance_{-1}; + bool isDisplayBadge_{true}; + bool isHiddenNotification_{}; + std::string groupKeyOverride_{}; + int32_t visiblenessOverride_{}; + sptr slot_{nullptr}; + + friend class AdvancedNotificationService; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_H \ No newline at end of file diff --git a/kits/native/include/notification_sorting_map.h b/kits/native/include/notification_sorting_map.h new file mode 100644 index 000000000..32a8163cb --- /dev/null +++ b/kits/native/include/notification_sorting_map.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_MAP_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_MAP_H + +#include +#include +#include + +#include "notification_sorting.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { + +class NotificationSortingMap final : public Parcelable { +public: + /** + * @brief Default constructor used to create an empty NotificationMap instance. + */ + NotificationSortingMap(); + + /** + * @brief Default deconstructor used to deconstruct. + */ + ~NotificationSortingMap(); + + /** + * @brief A constructor used to create a NotificationSortingMap instance by copying parameters from an existing one. + * + * @param Indicates the NotificationSortingMap object. + */ + NotificationSortingMap(const std::vector &sortingList); + + /** + * @brief Obtains the list of sorted hash codes. + * + * @return Returns the list of sorted hash codes. + */ + inline std::vector GetKey() + { + return sortedKey_; + } + + /** + * @brief Obtains NotificationSorting based on the hash codes. + * + * @param key Indicates the hash codes obtained by using getkey(). + * + * @param sorting Indicates the sorting information about the hash codes. + * + */ + bool GetNotificationSorting(const std::string &key, NotificationSorting &sorting) const; + + /** + * @brief Marshals a NotificationSortingMap object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + * + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals a NotificationSortingMap object from a Parcel. + * + * @param Indicates the Parcel object for unmarshalling. + */ + static NotificationSortingMap *Unmarshalling(Parcel &parcel); + + /** + * @brief Dump sorting map info + * + * @return Return sorting map info to string. + */ + std::string Dump() const; + +private: + void SetKey(const std::string &key); + void SetNotificationSorting(const std::vector &sortingList); + +private: + std::vector sortedKey_{}; + std::map sortings_{}; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_MAP_H \ No newline at end of file diff --git a/kits/native/include/notification_subscribe_info.h b/kits/native/include/notification_subscribe_info.h new file mode 100644 index 000000000..49dc6fc29 --- /dev/null +++ b/kits/native/include/notification_subscribe_info.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATIN_SUBSCRIBER_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATIN_SUBSCRIBER_INFO_H + +#include +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace Notification { + +class NotificationSubscribeInfo final : public Parcelable { +public: + /** + * @brief Default constructor used to create a instance. + */ + NotificationSubscribeInfo(); + + /** + * @brief Default deconstructor used to deconstruct. + */ + ~NotificationSubscribeInfo(); + + /** + * @brief A constructor used to create a NotificationSubscribeInfo instance by copying parameters from an existing + * one. + * + * @param Indicates the NotificationSubscribeInfo object. + */ + NotificationSubscribeInfo(const NotificationSubscribeInfo &subscribeInfo); + + /** + * @brief Sets a single application name as the filter criterion, + * which means to subscribe to notifications of this application. + * + * @param appName Indicates the application name. + **/ + void AddAppName(const std::string appName); + + /** + * @brief Sets multiple application names as the filter criteria, + * which means to subscribe to notifications of these applications. + * + * @param appNames Indicates the set of application names. + **/ + void AddAppNames(const std::vector &appNames); + + /** + * @brief Obtains the application names in the current NotificationSubscribeInfo object. + * The application names can be set by calling AddAppNames. + * + * @return Returns the set of application names. + **/ + std::vector GetAppNames() const; + + /** + * @brief Marshals a NotificationSubscribeInfo object into a Parcel. + * + * @param parcel Indicates the Parcel object for marshalling. + */ + bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals a NotificationSubscribeInfo object from a Parcel. + * + * @param parcel Indicates the Parcel object for unmarshalling. + */ + static NotificationSubscribeInfo *Unmarshalling(Parcel &parcel); + + /** + * @brief Dump subscribe info. + * + * @return Return subscribe info. + */ + std::string Dump(); + +private: + bool ReadFromParcel(Parcel &parcel); + +private: + std::vector appNames_{}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATIN_SUBSCRIBER_INFO_H \ No newline at end of file diff --git a/kits/native/include/notification_subscriber.h b/kits/native/include/notification_subscriber.h new file mode 100644 index 000000000..24b1c4ac3 --- /dev/null +++ b/kits/native/include/notification_subscriber.h @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SUBSCRIBER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SUBSCRIBER_H + +#include + +#include "ans_manager_interface.h" +#include "ans_subscriber_stub.h" +#include "notification_constant.h" +#include "notification_request.h" +#include "notification_sorting.h" +#include "notification_sorting_map.h" + +namespace OHOS { +namespace Notification { + +class NotificationSubscriber { +public: + /** + * @brief Default constructor used to create a instance. + */ + NotificationSubscriber() + { + impl_ = new SubscriberImpl(*this); + }; + + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the canceled Notification object. + **/ + virtual void OnCanceled(const std::shared_ptr &request) = 0; + + /** + * @brief Called back when a notification is canceled. + * + * @param request Indicates the canceled Notification object. + * @param sortingMap Indicates the sorting map used by the current subscriber + * to obtain notification ranking information. + * @param deleteReason Indicates the reason for the deletion. For details, see NotificationConstant. + **/ + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) = 0; + + /** + * @brief Called back when the subscriber is connected to the Advanced Notification Service (ANS). + * + * @param result Indicates subscribe result. + **/ + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) = 0; + + /** + * @brief Called back when the subscriber receives a new notification. + * + * @param request Indicates the received Notification object. + **/ + virtual void OnConsumed(const std::shared_ptr &request) = 0; + + /** + * @brief Called back when the subscriber receives a new notification. + * + * @param request Indicates the received Notification object. + * @param sortingMap Indicates the sorting map used by the current subscriber to obtain + * notification ranking information. + **/ + virtual void OnConsumed( + const std::shared_ptr &request, const std::shared_ptr &sortingMap) = 0; + + /** + * @brief Called back when the subscriber is disconnected from the ANS. + * + * @param result Indicates unsubscribe result. + **/ + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) = 0; + + /** + * @brief Called back when the ranking information about the current notification changes. + * + * @param sortingMap Indicates the sorting map used to obtain notification ranking information. + **/ + virtual void OnUpdate(const std::shared_ptr &sortingMap) = 0; + + /** + * @brief Called back when connection to the ANS has died. + **/ + virtual void OnDied() = 0; + + /** + * @brief Called when the Do Not Disturb mode type changes. + * + * @param disturbMode Indicates the current Do Not Disturb mode type. + **/ + virtual void OnDisturbModeChanged(int disturbMode) = 0; + +private: + class SubscriberImpl final : public AnsSubscriberStub { + public: + class DeathRecipient final : public IRemoteObject::DeathRecipient { + public: + DeathRecipient(SubscriberImpl &subscriberImpl); + + ~DeathRecipient(); + + void OnRemoteDied(const wptr &object) override; + + private: + SubscriberImpl &subscriberImpl_; + }; + + public: + SubscriberImpl(NotificationSubscriber &subscriber); + + void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + + void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + + void OnConsumed(const sptr ¬ification) override; + + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override; + + void OnCanceled(const sptr ¬ification) override; + + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int deleteReason) override; + + void OnUpdated(const sptr ¬ificationMap) override; + + void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + + bool GetAnsManagerProxy(); + + public: + NotificationSubscriber &subscriber_; + sptr recipient_{nullptr}; + sptr proxy_{nullptr}; + std::mutex mutex_{}; + }; + +private: + const sptr GetImpl() const; + +private: + sptr impl_ = nullptr; + + friend class AnsNotification; +}; +} // namespace Notification +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/kits/native/include/notification_user_input.h b/kits/native/include/notification_user_input.h new file mode 100644 index 000000000..97b34ed89 --- /dev/null +++ b/kits/native/include/notification_user_input.h @@ -0,0 +1,281 @@ +/* + * Copyright (c); 2021 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H + +#include +#include +#include +#include +#include "notification_constant.h" +#include "pac_map.h" +#include "want.h" +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace Notification { +class PixelMap; + +class NotificationUserInput : public Parcelable { +public: + /** + * Sets the input source of this NotificationUserInput object. + * @param want Indicates the Want to which the input result is to be added. + * @param source Indicates the input source. For available values, see NotificationConstant::InputSource. + */ + static void SetInputsSource(AAFwk::Want &want, NotificationConstant::InputsSource source); + + /** + * Obtains the input source of this NotificationUserInput object. + * @param want Indicates the Want containing the input result. + * @return the input source of this NotificationUserInput object, + * as enumerated in NotificationConstant::InputSource. + */ + static NotificationConstant::InputsSource GetInputsSource(const AAFwk::Want &want); + + /** + * Adds a list of NotificationUserInput objects to a Want. This method should only be called by user input + * collection services when sending input results to an WantAgent. + * @param userInputs Indicates the list of NotificationUserInput objects for which the input results are provided. + * @param want Indicates the Want to which the input results are to be added. + * @param pacMap Indicates the PacMap object holding the input results. + * The PacMap key must match the keys contained in the objects specified in userInputs. + */ + static void AddInputsToWant(const std::vector> &userInputs, + AAFwk::Want &want, const AppExecFwk::PacMap &pacMap); + + /** + * Obtains the input text results from a specified Want. + * @param want Indicates the Want object containing one or more user input results. + * @return the PacMap object containing the input text results. + */ + static std::shared_ptr GetInputsFromWant(const AAFwk::Want &want); + + /** + * Adds the given NotificationUserInput object of a specified MIME type to an Want. This method is similar to + * addInputsToWant(NotificationUserInput, Want, PacMap) except that the MIME type must be specified. + * @param userInput Indicates the NotificationUserInput object for which the input results are provided. + * @param want Indicates the Want to which the input results are to be added. + * @param results Indicates a map containing the MIME type and its URI result. + */ + static void AddMimeInputToWant(const NotificationUserInput &userInput, AAFwk::Want &want, + const std::map> &results); + + /** + * Obtains the input results of a particular MIME type from a specified Want. This method is similar to + * GetInputsFromWant(Want) but uses the key of the NotificationUserInput. + * @param want Indicates the Want object containing one or more user input results. + * @param inputKey Indicates the key of the NotificationUserInput results to obtain. + * @return a map containing the MIME type and its URI result. + */ + static std::map> GetMimeInputsFromWant( + const AAFwk::Want &want, const std::string &inputKey); + +public: + /** + * A static function used to create a NotificationUserInput instance with the input parameters passed. + * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if + * inputKey is empty. + */ + static std::shared_ptr Create(const std::string &inputKey); + + /** + * A static function used to create a NotificationUserInput instance with the input parameters passed. + * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param tag Indicates the tag to be displayed. + * @param options Indicates the list of predefined options to be provided for user input. + * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, + * indicating that arbitrary text values are allowed. If this parameter is set to false, you must pass a non-empty + * std::vector of options or a non-empty std::set of permitMimeTypes. Otherwise, return empty object. + * @param permitMimeTypes Indicates the MIME type allowed. + * @param pacMap Indicates the PacMap object containing the additional data. + * @param editType Indicates the edit type to set. For details about available values, see + * NotificationConstant::InputEditType. + * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if + * permitFreeFormInput is false but editType is InputEditType::EDIT_ENABLED. + */ + static std::shared_ptr Create(const std::string &inputKey, const std::string &tag, + const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, + const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationUserInput() = default; + + /** + * Obtains the key of this NotificationUserInput object. + * @return the key of this NotificationUserInput object. + */ + std::string GetInputKey() const; + + /** + * Adds additional data to this Builder. + * The value of pacMap will replace the existing extras value in this Builder. + * @param pacMap Indicates the PacMap object containing the additional data. + */ + void AddAdditionalData(AppExecFwk::PacMap &pacMap); + + /** + * Obtains the additional data included in this NotificationUserInput object. + * @return the additional data in this NotificationUserInput object. + */ + const std::shared_ptr GetAdditionalData() const; + + /** + * Sets the edit type of the options provided by this NotificationUserInput object. + * The edit type determines whether an option can be edited when the user taps the option. + * @param inputEditType Indicates the edit type to set. For details about available values, + * see NotificationConstant::InputEditType. + */ + void SetEditType(NotificationConstant::InputEditType inputEditType); + + /** + * Obtains the edit type of the options provided by this NotificationUserInput object. + * @return the edit type of options. + */ + NotificationConstant::InputEditType GetEditType() const; + + /** + * Sets the options provided to users to satisfy user input needs. All options are displayed in a single line. + * Due to limited space, some or all of the options may be hidden if the options are too long or + * there are too many options. + * @param options Indicates the list of predefined options to be provided for user input. + */ + void SetOptions(const std::vector &options); + + /** + * Obtains the options provided to the user to satisfy user input needs. + * @return the list of predefined options. + */ + std::vector GetOptions() const; + + /** + * Sets whether users can input values of the given MIME type. + * @param mimeType Indicates the MIME type allowed. + * @param doPermit Specifies whether to allow the given MIME type. + * The value true means to allow it, and the value false means not. + */ + void SetPermitMimeTypes(const std::string &mimeType, bool doPermit); + + /** + * Obtains the MIME types allowed by this NotificationUserInput object. + * @return the list of allowed MIME types. + */ + std::set GetPermitMimeTypes() const; + + /** + * Checks whether this NotificationUserInput object allows only values of particular MIME types. + * @return true if this object allows only values of particular MIME types; returns false otherwise. + */ + bool IsMimeTypeOnly() const; + + /** + * Sets the tag to be displayed to the user when collecting this input from the user. + * @param tag Indicates the tag to be displayed. + */ + void SetTag(const std::string tag); + + /** + * Obtains the tag to be displayed to the user when collecting this input from the user. + * @return the tag to be displayed to the user. + */ + std::string GetTag() const; + + /** + * Sets whether users can input arbitrary text values. + * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, + * indicating that arbitrary text values are allowed. If this parameter is set to false, you must either call + * SetOptions(std::vector) to set a non-null and non-empty list or call + * SetPermitMimeTypes(std::string, bool) to allow a MIME type. + */ + void SetPermitFreeFormInput(bool permitFreeFormInput); + + /** + * Checks whether users can provide arbitrary values for this NotificationUserInput object. + * @return true if this object allows arbitrary values; returns false otherwise. + */ + bool IsPermitFreeFormInput() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationUserInput + */ + static NotificationUserInput *Unmarshalling(Parcel &parcel); + +private: + /** + * Default constructor used to create a NotificationUserInput instance. + */ + NotificationUserInput() = default; + + /** + * A constructor used to create a NotificationUserInput instance with the input parameters passed. + * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + */ + explicit NotificationUserInput(const std::string &inputKey); + + /** + * A constructor used to create a NotificationUserInput instance with the input parameters passed. + * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param tag Indicates the tag to be displayed. + * @param options Indicates the list of predefined options to be provided for user input. + * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, + * indicating that arbitrary text values are allowed. If this parameter is set to false, you must either call + * setOptions(const std::vector &) to set a non-empty list or call + * setPermitMimeTypes(std::string, bool) to allow a MIME type. + * @param permitMimeTypes Indicates the MIME type allowed. + * @param pacMap Indicates the PacMap object containing the additional data. + * @param editType Indicates the edit type to set. For details about available values, see + * NotificationConstant::InputEditType. + */ + NotificationUserInput(const std::string &inputKey, const std::string &tag, const std::vector &options, + bool permitFreeFormInput, const std::set &permitMimeTypes, + const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType); + + /** + * Read a NotificationUserInput object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string inputKey_{}; + std::string tag_{}; + std::vector options_{}; + bool permitFreeFormInput_{true}; + std::set permitMimeTypes_{}; + std::shared_ptr pacMap_{}; + NotificationConstant::InputEditType editType_{NotificationConstant::InputEditType::EDIT_AUTO}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H diff --git a/kits/native/src/message_user.cpp b/kits/native/src/message_user.cpp new file mode 100644 index 000000000..d91769912 --- /dev/null +++ b/kits/native/src/message_user.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2021 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 "message_user.h" + +namespace OHOS { +namespace Notification { + +MessageUser::MessageUser() + : uri_("") +{} + +MessageUser::~MessageUser() +{} + +void MessageUser::SetKey(const std::string &key) +{ + key_ = key; +} + +std::string MessageUser::GetKey() const +{ + return key_; +} + +void MessageUser::SetName(const std::string &name) +{ + name_ = name; +} + +std::string MessageUser::GetName() const +{ + return name_; +} + +void MessageUser::SetPixelMap(const std::shared_ptr &pixelMap) +{ + pixelMap_ = pixelMap; +} + +const std::shared_ptr MessageUser::GetPixelMap() const +{ + return pixelMap_; +} + +void MessageUser::SetUri(const Uri &uri) +{ + uri_ = uri; +} + +Uri MessageUser::GetUri() const +{ + return uri_; +} + +void MessageUser::SetMachine(bool machine) +{ + isMachine_ = machine; +} + +bool MessageUser::IsMachine() const +{ + return isMachine_; +} + +void MessageUser::SetUserAsImportant(bool userImportant) +{ + isUserImportant_ = userImportant; +} + +bool MessageUser::IsUserImportant() const +{ + return isUserImportant_; +} + +std::string MessageUser::Dump() const +{ + return "MessageUser[key = " + key_ + + ", name = " + name_ + + ", pixelMap = " + (pixelMap_ ? "not null" : "null") + + ", uri = " + uri_.ToString() + + ", isMachine = " + std::to_string(isMachine_) + + ", isUserImportant = " + std::to_string(isUserImportant_) + "]"; +} + +bool MessageUser::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(key_)) { + return false; + } + + if (!parcel.WriteString(name_)) { + return false; + } + + if (!parcel.WriteBool(isMachine_)) { + return false; + } + + if (!parcel.WriteBool(isUserImportant_)) { + return false; + } + + if (uri_.ToString().empty()) { + if (!parcel.WriteInt32(VALUE_NULL)) { + return false; + } + } else { + if (!parcel.WriteInt32(VALUE_OBJECT)) { + return false; + } + if (!parcel.WriteString((uri_.ToString()))) { + return false; + } + } + + return true; +} + +bool MessageUser::ReadFromParcel(Parcel &parcel) +{ + key_ = parcel.ReadString(); + name_ = parcel.ReadString(); + isMachine_ = parcel.ReadBool(); + isUserImportant_ = parcel.ReadBool(); + + int empty = VALUE_NULL; + if (!parcel.ReadInt32(empty)) { + return false; + } + + if (empty == VALUE_OBJECT) { + uri_ = Uri((parcel.ReadString())); + } + + return true; +} + +MessageUser *MessageUser::Unmarshalling(Parcel &parcel) +{ + MessageUser *messageUser = new MessageUser(); + + if (messageUser && !messageUser->ReadFromParcel(parcel)) { + delete messageUser; + messageUser = nullptr; + } + + return messageUser; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification.cpp b/kits/native/src/notification.cpp new file mode 100644 index 000000000..c333f0789 --- /dev/null +++ b/kits/native/src/notification.cpp @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2021 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 "notification.h" + +#include + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +Notification::Notification(){}; + +Notification::Notification(const sptr &request) +{ + request_ = request; + key_ = GenerateNotificationKey(GetUid(), GetLabel(), GetId()); +} + +Notification::Notification(const Notification &other) +{ + key_ = other.key_; + ledLightColor_ = other.ledLightColor_; + lockscreenVisibleness_ = other.lockscreenVisibleness_; + request_ = other.request_; + postTime_ = other.postTime_; + sound_ = other.sound_; + vibrationStyle_ = other.vibrationStyle_; +} + +bool Notification::EnableLight() const +{ + if (ledLightColor_ == -1) { + return false; + } + return true; +} + +bool Notification::EnableSound() const +{ + if (sound_ == nullptr) { + return false; + } + return true; +} + +bool Notification::EnableVibrate() const +{ + if (!vibrationStyle_.size()) { + return false; + } + return true; +} + +std::string Notification::GetBundleName() const +{ + if (request_ == nullptr) { + return ""; + } + return request_->GetOwnerBundleName(); +} + +std::string Notification::GetCreateBundle() const +{ + if (request_ == nullptr) { + return ""; + } + return request_->GetCreatorBundleName(); +} + +std::string Notification::GetLabel() const +{ + if (request_ == nullptr) { + return ""; + } + return request_->GetLabel(); +} + +int32_t Notification::GetLedLightColor() const +{ + return ledLightColor_; +} + +int32_t Notification::GetLockscreenVisibleness() const +{ + return lockscreenVisibleness_; +} + +std::string Notification::GetGroup() const +{ + if (request_ == nullptr) { + return ""; + } + return request_->GetGroupValue(); +} + +int32_t Notification::GetId() const +{ + if (request_ == nullptr) { + return -1; + } + return request_->GetNotificationId(); +} + +std::string Notification::GetKey() const +{ + return key_; +} + +NotificationRequest Notification::GetNotificationRequest() const +{ + return *request_; +} + +int64_t Notification::GetPostTime() const +{ + return postTime_; +} + +Uri Notification::GetSound() const +{ + return *sound_; +} + +int32_t Notification::GetUid() const +{ + if (request_ == nullptr) { + return -1; + } + return request_->GetCreatorUid(); +} + +std::vector Notification::GetVibrationStyle() const +{ + return vibrationStyle_; +} + +bool Notification::IsGroup() const +{ + if (request_ == nullptr) { + return false; + } + return !(request_->GetGroupValue() == ""); +} + +bool Notification::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(key_)) { + ANS_LOGE("Can't wirte key"); + return false; + } + if (!parcel.WriteInt32(ledLightColor_)) { + ANS_LOGE("Can't write ledLigthColor"); + return false; + } + + if (!parcel.WriteInt32(lockscreenVisibleness_)) { + ANS_LOGE("Can't write visbleness"); + return false; + } + + if (!parcel.WriteStrongParcelable(request_)) { + ANS_LOGE("Can't write request"); + return false; + } + + if (!parcel.WriteInt64(postTime_)) { + ANS_LOGE("Can't write postTime"); + return false; + } + + if (!parcel.WriteString(sound_->ToString())) { + ANS_LOGE("Can't write sound"); + return false; + } + + if (!parcel.WriteInt64Vector(vibrationStyle_)) { + ANS_LOGE("Can't write vibrationStyle"); + return false; + } + + return true; +} + +bool Notification::ReadFromParcel(Parcel &parcel) +{ + // Read key_ + key_ = parcel.ReadString(); + + // Read ledLightColor_ + ledLightColor_ = parcel.ReadInt32(); + + // Read lockscreenVisibleness_ + lockscreenVisibleness_ = parcel.ReadInt32(); + + // Read request_ + request_ = parcel.ReadStrongParcelable(); + + // Read postTime_ + postTime_ = parcel.ReadInt64(); + + // Read sound_ + sound_ = std::make_shared(parcel.ReadString()); + + // Read vibrationStyle_ + parcel.ReadInt64Vector(&vibrationStyle_); + + return true; +} + +Notification *Notification::Unmarshalling(Parcel &parcel) +{ + Notification *n = new Notification(); + if (n && !n->ReadFromParcel(parcel)) { + ANS_LOGE("Read from parcel error"); + delete n; + n = nullptr; + } + return n; +} + +void Notification::SetLedLightColor(const int32_t &color) +{ + ledLightColor_ = color; +} + +void Notification::SetLockScreenVisbleness(const int32_t &visbleness) +{ + lockscreenVisibleness_ = visbleness; +} + +void Notification::SetPostTime(const int64_t &time) +{ + postTime_ = time; +} + +void Notification::SetSound(const Uri &sound) +{ + sound_ = std::make_shared(sound.ToString()); +} + +void Notification::SetVibrationStyle(const std::vector &style) +{ + vibrationStyle_ = style; +} + +std::string Notification::GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id) +{ + const char *KEY_SPLITER = "_"; + + std::stringstream stream; + stream << uid << KEY_SPLITER << label << KEY_SPLITER << id; + + return stream.str(); +} + +std::string Notification::Dump() const +{ + std::string dump = "Notification{ key = " + key_ + ", ledLightColor = " + std::to_string(ledLightColor_) + + ", lockscreenVisbleness = " + std::to_string(lockscreenVisibleness_) + ",request = "; + if (request_ == nullptr) { + dump += "nullptr"; + } else { + dump += request_->Dump(); + } + dump = dump + ",postTime = " + std::to_string(postTime_) + ",sound = " + sound_->ToString() + "vibrationStyle = "; + for (auto &style : vibrationStyle_) { + dump += std::to_string(style); + dump += ","; + } + return dump; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_action_button.cpp b/kits/native/src/notification_action_button.cpp new file mode 100644 index 000000000..fcc2f4e22 --- /dev/null +++ b/kits/native/src/notification_action_button.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c); 2021 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 "notification_action_button.h" + +#include +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +std::shared_ptr NotificationActionButton::Create(const std::shared_ptr &icon, + const std::string &title, const std::shared_ptr &wantAgent, + const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, + bool autoCreatedReplies, const std::vector> &userInputs, bool isContextual) +{ + if (isContextual && (!icon || !wantAgent)) { + ANS_LOGE("icon or wantAgent can not be null when isContextual is true"); + return {}; + } + + auto realExtras = extras; + if (!realExtras) { + realExtras = std::make_shared(); + } + + auto pActionButton = new (std::nothrow) NotificationActionButton( + icon, title, wantAgent, realExtras, semanticActionButton, autoCreatedReplies, userInputs, isContextual); + if (pActionButton == nullptr) { + ANS_LOGE("create NotificationActionButton object failed"); + return {}; + } + + return std::shared_ptr(pActionButton); +} + +NotificationActionButton::NotificationActionButton(const std::shared_ptr &icon, const std::string &title, + const std::shared_ptr &wantAgent, const std::shared_ptr &extras, + NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, + const std::vector> &userInputs, bool isContextual) + : icon_(icon), + title_(title), + wantAgent_(wantAgent), + extras_(extras), + semanticActionButton_(semanticActionButton), + autoCreatedReplies_(autoCreatedReplies), + userInputs_(userInputs), + isContextual_(isContextual) +{} + +void NotificationActionButton::AddAdditionalData(AppExecFwk::PacMap &pacMap) +{ + extras_->PutAll(pacMap); +} + +const std::shared_ptr NotificationActionButton::GetAdditionalData() const +{ + return extras_; +} + +const std::shared_ptr NotificationActionButton::GetIcon() const +{ + return icon_; +} + +const std::shared_ptr NotificationActionButton::GetWantAgent() const +{ + return wantAgent_; +} + +std::vector> NotificationActionButton::GetMimeTypeOnlyUserInputs() const +{ + return {}; +} + +void NotificationActionButton::SetSemanticActionButton(NotificationConstant::SemanticActionButton semanticActionButton) +{ + semanticActionButton_ = semanticActionButton; +} + +NotificationConstant::SemanticActionButton NotificationActionButton::GetSemanticActionButton() const +{ + return semanticActionButton_; +} + +std::string NotificationActionButton::GetTitle() const +{ + return title_; +} + +void NotificationActionButton::AddNotificationUserInput(const std::shared_ptr &userInput) +{ + if (!userInput) { + ANS_LOGE("The userInput is invalid."); + return; + } + + userInputs_.emplace_back(userInput); +} + +std::vector> NotificationActionButton::GetUserInputs() const +{ + return userInputs_; +} + +bool NotificationActionButton::IsAutoCreatedReplies() const +{ + return autoCreatedReplies_; +} + +void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies) +{ + autoCreatedReplies_ = autoCreatedReplies; +} + +bool NotificationActionButton::IsContextDependent() const +{ + return isContextual_; +} + +void NotificationActionButton::SetContextDependent(bool isContextual) +{ + isContextual_ = isContextual; +} + +std::string NotificationActionButton::Dump() +{ + return "NotificationActionButton[ title = " + title_ + + ", semanticActionButton = " + std::to_string(static_cast(semanticActionButton_)) + + ", autoCreatedReplies = " + (autoCreatedReplies_ ? "true" : "false") + + ", isContextual = " + (isContextual_ ? "true" : "false") + " ]"; +} + +bool NotificationActionButton::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(title_)) { + ANS_LOGE("Failed to write title"); + return false; + } + + if (!parcel.WriteBool(autoCreatedReplies_)) { + ANS_LOGE("Failed to write flag autoCreatedReplies"); + return false; + } + + if (!parcel.WriteBool(isContextual_)) { + ANS_LOGE("Failed to write flag isContextual"); + return false; + } + + if (!parcel.WriteInt32(static_cast(semanticActionButton_))) { + ANS_LOGE("Failed to write semanticActionButton"); + return false; + } + + bool valid{false}; + + // valid = icon_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether icon is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(icon_.get())) { + // ANS_LOGE("Failed to write icon"); + // return false; + // } + // } + + valid = wantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether wantAgent is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(wantAgent_.get())) { + ANS_LOGE("Failed to write wantAgent"); + return false; + } + } + + valid = extras_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether extras is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(extras_.get())) { + ANS_LOGE("Failed to write extras"); + return false; + } + } + + if (!parcel.WriteInt32(static_cast(userInputs_.size()))) { + ANS_LOGE("Failed to write the size of userInputs"); + return false; + } + + for (auto it = userInputs_.begin(); it != userInputs_.end(); ++it) { + valid = (*it) ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether userInput is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(it->get())) { + ANS_LOGE("Failed to write userInput"); + return false; + } + } + } + + return true; +} + +NotificationActionButton *NotificationActionButton::Unmarshalling(Parcel &parcel) +{ + auto pButton = new NotificationActionButton(); + if ((nullptr != pButton) && !pButton->ReadFromParcel(parcel)) { + delete pButton; + pButton = nullptr; + } + + return pButton; +} + +bool NotificationActionButton::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(title_)) { + ANS_LOGE("Failed to read title"); + return false; + } + + autoCreatedReplies_ = parcel.ReadBool(); + + isContextual_ = parcel.ReadBool(); + + semanticActionButton_ = static_cast(parcel.ReadInt32()); + + bool valid{false}; + + // valid = parcel.ReadBool(); + // if (valid) { + // icon_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!icon_) { + // ANS_LOGE("Failed to read icon"); + // return false; + // } + // } + + valid = parcel.ReadBool(); + if (valid) { + wantAgent_ = std::shared_ptr(parcel.ReadParcelable()); + if (!wantAgent_) { + ANS_LOGE("Failed to read wantAgent"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + extras_ = std::shared_ptr(parcel.ReadParcelable()); + if (!extras_) { + ANS_LOGE("Failed to read extras"); + return false; + } + } + + auto vsize = parcel.ReadInt32(); + for (auto it = 0; it < vsize; ++it) { + valid = parcel.ReadBool(); + NotificationUserInput *member{nullptr}; + if (valid) { + member = parcel.ReadParcelable(); + if (nullptr == member) { + ANS_LOGE("Failed to read userInput"); + return false; + } + } + + userInputs_.emplace_back(member); + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_basic_content.cpp b/kits/native/src/notification_basic_content.cpp new file mode 100644 index 000000000..718ecd0f3 --- /dev/null +++ b/kits/native/src/notification_basic_content.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c); 2021 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 "notification_basic_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationBasicContent::~NotificationBasicContent() +{} + +void NotificationBasicContent::SetAdditionalText(const std::string &additionalText) +{ + additionalText_ = additionalText; +} + +std::string NotificationBasicContent::GetAdditionalText() const +{ + return additionalText_; +} + +void NotificationBasicContent::SetText(const std::string &text) +{ + text_ = text; +} + +std::string NotificationBasicContent::GetText() const +{ + return text_; +} + +void NotificationBasicContent::SetTitle(const std::string &title) +{ + title_ = title; +} + +std::string NotificationBasicContent::GetTitle() const +{ + return title_; +} + +std::string NotificationBasicContent::Dump() +{ + return "title = " + title_ + ", text = " + text_ + ", additionalText = " + additionalText_; +} + +bool NotificationBasicContent::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(text_)) { + ANS_LOGE("Failed to write text"); + return false; + } + + if (!parcel.WriteString(title_)) { + ANS_LOGE("Failed to write title"); + return false; + } + + if (!parcel.WriteString(additionalText_)) { + ANS_LOGE("Failed to write additional text"); + return false; + } + + return true; +} + +bool NotificationBasicContent::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(text_)) { + ANS_LOGE("Failed to read text"); + return false; + } + + if (!parcel.ReadString(title_)) { + ANS_LOGE("Failed to read title"); + return false; + } + + if (!parcel.ReadString(additionalText_)) { + ANS_LOGE("Failed to read additional text"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_constant.cpp b/kits/native/src/notification_constant.cpp new file mode 100644 index 000000000..7fff8410e --- /dev/null +++ b/kits/native/src/notification_constant.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c); 2021 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 "notification_constant.h" + +namespace OHOS { +namespace Notification { +const std::string NotificationConstant::EXTRA_INPUTS_SOURCE{"notification_user_input_source"}; + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_content.cpp b/kits/native/src/notification_content.cpp new file mode 100644 index 000000000..26106dea4 --- /dev/null +++ b/kits/native/src/notification_content.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c); 2021 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 "notification_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationContent::NotificationContent(const std::shared_ptr &normalContent) +{ + if (!normalContent) { + ANS_LOGE("NotificationNormalContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::BASIC_TEXT; + content_ = normalContent; +} + +NotificationContent::NotificationContent(const std::shared_ptr &longTextContent) +{ + if (!longTextContent) { + ANS_LOGE("NotificationLongTextContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::LONG_TEXT; + content_ = longTextContent; +} + +NotificationContent::NotificationContent(const std::shared_ptr &pictureContent) +{ + if (!pictureContent) { + ANS_LOGE("NotificationPictureContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::PICTURE; + content_ = pictureContent; +} + +NotificationContent::NotificationContent(const std::shared_ptr &conversationContent) +{ + if (!conversationContent) { + ANS_LOGE("NotificationConversationalContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::CONVERSATION; + content_ = conversationContent; +} + +NotificationContent::NotificationContent(const std::shared_ptr &multiLineContent) +{ + if (!multiLineContent) { + ANS_LOGE("NotificationMultiLineContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::MULTILINE; + content_ = multiLineContent; +} + +NotificationContent::NotificationContent(const std::shared_ptr &mediaContent) +{ + if (!mediaContent) { + ANS_LOGE("NotificationMediaContent can not be null"); + return; + } + + contentType_ = NotificationContent::Type::MEDIA; + content_ = mediaContent; +} + +NotificationContent::~NotificationContent() +{} + +NotificationContent::Type NotificationContent::GetContentType() const +{ + return contentType_; +} + +std::shared_ptr NotificationContent::GetNotificationContent() const +{ + return content_; +} + +std::string NotificationContent::Dump() +{ + std::string contentTypeStr = (contentType_ == NotificationContent::Type::BASIC_TEXT) ? "BASIC_TEXT" + : (contentType_ == NotificationContent::Type::CONVERSATION) ? "CONVERSATION" + : (contentType_ == NotificationContent::Type::LONG_TEXT) ? "LONG_TEXT" + : (contentType_ == NotificationContent::Type::MEDIA) ? "MEDIA" + : (contentType_ == NotificationContent::Type::MULTILINE) ? "MULTILINE" + : (contentType_ == NotificationContent::Type::PICTURE) ? "PICTURE" : "NONE"; + + return "NotificationContent[ contentType = " + contentTypeStr + + ", content = " + (content_ ? "not null" : "null") + "]"; +} + +bool NotificationContent::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(static_cast(contentType_))) { + ANS_LOGE("Failed to write contentType"); + return false; + } + + auto valid = content_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether content is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(content_.get())) { + ANS_LOGE("Failed to write content"); + return false; + } + } + + return true; +} + +NotificationContent *NotificationContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationContent::ReadFromParcel(Parcel &parcel) +{ + contentType_ = static_cast(parcel.ReadInt32()); + + auto valid = parcel.ReadBool(); + if (!valid) { + return true; + } + + switch (contentType_) { + case NotificationContent::Type::BASIC_TEXT: { + std::shared_ptr normalContent( + parcel.ReadParcelable()); + if (!normalContent) { + ANS_LOGE("Failed to read normal content"); + return false; + } + content_ = std::dynamic_pointer_cast(normalContent); + } break; + case NotificationContent::Type::CONVERSATION: { + std::shared_ptr conversationalContent( + parcel.ReadParcelable()); + if (!conversationalContent) { + ANS_LOGE("Failed to read conversational content"); + return false; + } + content_ = std::dynamic_pointer_cast(conversationalContent); + } break; + case NotificationContent::Type::LONG_TEXT: { + std::shared_ptr longTextContent( + parcel.ReadParcelable()); + if (!longTextContent) { + ANS_LOGE("Failed to read long text content"); + return false; + } + content_ = std::dynamic_pointer_cast(longTextContent); + } break; + case NotificationContent::Type::MEDIA: { + std::shared_ptr mediaContent(parcel.ReadParcelable()); + if (!mediaContent) { + ANS_LOGE("Failed to read media content"); + return false; + } + content_ = std::dynamic_pointer_cast(mediaContent); + } break; + case NotificationContent::Type::MULTILINE: { + std::shared_ptr multiLineContent( + parcel.ReadParcelable()); + if (!multiLineContent) { + ANS_LOGE("Failed to read multiLine content"); + return false; + } + content_ = std::dynamic_pointer_cast(multiLineContent); + } break; + case NotificationContent::Type::PICTURE: { + std::shared_ptr pictureContent( + parcel.ReadParcelable()); + if (!pictureContent) { + ANS_LOGE("Failed to read picture content"); + return false; + } + content_ = std::dynamic_pointer_cast(pictureContent); + } break; + default: { + return false; + } break; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_conversational_content.cpp b/kits/native/src/notification_conversational_content.cpp new file mode 100644 index 000000000..51ce80bf6 --- /dev/null +++ b/kits/native/src/notification_conversational_content.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c); 2021 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 "notification_conversational_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationConversationalContent::NotificationConversationalContent(const MessageUser &messageUser) + : messageUser_(messageUser) +{} + +MessageUser NotificationConversationalContent::GetMessageUser() const +{ + return messageUser_; +} + +void NotificationConversationalContent::SetConversationTitle(const std::string &conversationTitle) +{ + conversationTitle_ = conversationTitle; +} + +std::string NotificationConversationalContent::GetConversationTitle() const +{ + return conversationTitle_; +} + +bool NotificationConversationalContent::IsConversationGroup() const +{ + return isGroup_; +} + +void NotificationConversationalContent::SetConversationGroup(bool isGroup) +{ + isGroup_ = isGroup; +} + +void NotificationConversationalContent::AddConversationalMessage( + const std::string &text, int64_t timestamp, const MessageUser &sender) +{ + auto message = std::make_shared(text, timestamp, sender); + if (!message) { + ANS_LOGE("Failed to create message"); + return; + } + + messages_.emplace_back(message); +} + +void NotificationConversationalContent::AddConversationalMessage(const MessagePtr &message) +{ + if (!message) { + ANS_LOGE("Message can not be null"); + return; + } + + messages_.emplace_back(message); +} + +NotificationConversationalContent::MessageVector NotificationConversationalContent::GetAllConversationalMessages() const +{ + return messages_; +} + +std::string NotificationConversationalContent::Dump() +{ + return "NotificationConversationalContent[ " + NotificationBasicContent::Dump() + + ", conversationTitle = " + conversationTitle_ + ", isGroup = " + (isGroup_ ? "true" : "false") + + ", messageUser = " + messageUser_.Dump() + + ", messages = " + (!messages_.empty() ? "not empty" : "empty") + " ]"; +} + +bool NotificationConversationalContent::Marshalling(Parcel &parcel) const +{ + if (!NotificationBasicContent::Marshalling(parcel)) { + ANS_LOGE("Failed to write basic"); + return false; + } + + if (!parcel.WriteString(conversationTitle_)) { + ANS_LOGE("Failed to write conversation title"); + return false; + } + + if (!parcel.WriteBool(isGroup_)) { + ANS_LOGE("Failed to write flag group"); + return false; + } + + if (!parcel.WriteParcelable(&messageUser_)) { + ANS_LOGE("Failed to write messageUser"); + return false; + } + + if (!parcel.WriteInt32(static_cast(messages_.size()))) { + ANS_LOGE("Failed to write the size of messages"); + return false; + } + + for (auto it = messages_.begin(); it != messages_.end(); ++it) { + auto valid = (*it) ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether message is null"); + return false; + } + + if (!valid) { + ANS_LOGE("Invalid message, write to parcel failed"); + return false; + } + + if (!parcel.WriteParcelable(it->get())) { + ANS_LOGE("Failed to write message"); + return false; + } + } + + return true; +} + +NotificationConversationalContent *NotificationConversationalContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationConversationalContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationConversationalContent::ReadFromParcel(Parcel &parcel) +{ + if (!NotificationBasicContent::ReadFromParcel(parcel)) { + ANS_LOGE("Failed to read basic"); + return false; + } + + if (!parcel.ReadString(conversationTitle_)) { + ANS_LOGE("Failed to read conversation title"); + return false; + } + + isGroup_ = parcel.ReadBool(); + + auto pUser = parcel.ReadParcelable(); + if (pUser == nullptr) { + ANS_LOGE("Failed to read messageUser"); + return false; + } + messageUser_ = *pUser; + + auto vsize = parcel.ReadInt32(); + for (auto it = 0; it < vsize; ++it) { + auto valid = parcel.ReadBool(); + if (!valid) { + ANS_LOGE("Invalid message, read from parcel failed"); + return false; + } + + auto member = parcel.ReadParcelable(); + if (member == nullptr) { + ANS_LOGE("Failed to read message"); + return false; + } + + messages_.emplace_back(member); + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_conversational_message.cpp b/kits/native/src/notification_conversational_message.cpp new file mode 100644 index 000000000..e2f3b9e3a --- /dev/null +++ b/kits/native/src/notification_conversational_message.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c); 2021 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 "notification_conversational_message.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationConversationalMessage::NotificationConversationalMessage( + const std::string &text, int64_t timestamp, const MessageUser &sender) + : arrivedTime_(timestamp), text_(text), sender_(sender) +{} + +std::string NotificationConversationalMessage::GetText() const +{ + return text_; +} + +int64_t NotificationConversationalMessage::GetArrivedTime() const +{ + return arrivedTime_; +} + +MessageUser NotificationConversationalMessage::GetSender() const +{ + return sender_; +} + +void NotificationConversationalMessage::SetData(const std::string &mimeType, const std::shared_ptr &uri) +{ + mimeType_ = mimeType; + uri_ = uri; +} + +std::string NotificationConversationalMessage::GetMimeType() const +{ + return mimeType_; +} + +const std::shared_ptr NotificationConversationalMessage::GetUri() const +{ + return uri_; +} + +std::string NotificationConversationalMessage::Dump() +{ + return "NotificationConversationalMessage[ text = " + text_ + ", arrivedTime = " + std::to_string(arrivedTime_) + + ", mimeType = " + mimeType_ + ", uri = " + (uri_ ? uri_->ToString() : "null") + + ", sender = " + sender_.Dump() + " ]"; +} + +bool NotificationConversationalMessage::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt64(arrivedTime_)) { + ANS_LOGE("Failed to write arrived time"); + return false; + } + + if (!parcel.WriteString(text_)) { + ANS_LOGE("Failed to write text"); + return false; + } + + if (!parcel.WriteParcelable(&sender_)) { + ANS_LOGE("Failed to write sender"); + return false; + } + + auto valid = uri_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether uri is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(uri_.get())) { + ANS_LOGE("Failed to write uri"); + return false; + } + } + + if (!parcel.WriteString(mimeType_)) { + ANS_LOGE("Failed to write MIME type"); + return false; + } + + return true; +} + +NotificationConversationalMessage *NotificationConversationalMessage::Unmarshalling(Parcel &parcel) +{ + auto pMessage = new NotificationConversationalMessage(); + if ((nullptr != pMessage) && !pMessage->ReadFromParcel(parcel)) { + delete pMessage; + pMessage = nullptr; + } + + return pMessage; +} + +bool NotificationConversationalMessage::ReadFromParcel(Parcel &parcel) +{ + arrivedTime_ = parcel.ReadInt64(); + + if (!parcel.ReadString(text_)) { + ANS_LOGE("Failed to read text"); + return false; + } + + auto pUser = parcel.ReadParcelable(); + if (pUser == nullptr) { + ANS_LOGE("Failed to read sender"); + return false; + } + sender_ = *pUser; + + auto valid = parcel.ReadBool(); + if (valid) { + uri_ = std::shared_ptr(parcel.ReadParcelable()); + if (!uri_) { + ANS_LOGE("Failed to read uri"); + return false; + } + } + + if (!parcel.ReadString(mimeType_)) { + ANS_LOGE("Failed to read MIME type"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_helper.cpp b/kits/native/src/notification_helper.cpp new file mode 100644 index 000000000..2570e4d09 --- /dev/null +++ b/kits/native/src/notification_helper.cpp @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2021 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 "notification_helper.h" +#include "ans_notification.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +ErrCode NotificationHelper::AddNotificationSlot(const NotificationSlot &slot) +{ + return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); +} + +ErrCode NotificationHelper::AddNotificationSlots(const std::vector &slots) +{ + return DelayedSingleton::GetInstance()->AddNotificationSlots(slots); +} + +ErrCode NotificationHelper::RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) +{ + return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); +} + +ErrCode NotificationHelper::GetNotificationSlot( + const NotificationConstant::SlotType &slotType, sptr &slot) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlot(slotType, slot); +} + +ErrCode NotificationHelper::GetNotificationSlots(std::vector> &slots) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlots(slots); +} + +ErrCode NotificationHelper::AddNotificationSlotGroup(const NotificationSlotGroup &slotGroup) +{ + return DelayedSingleton::GetInstance()->AddNotificationSlotGroup(slotGroup); +} + +ErrCode NotificationHelper::AddNotificationSlotGroups(const std::vector &slotGroups) +{ + return DelayedSingleton::GetInstance()->AddNotificationSlotGroups(slotGroups); +} + +ErrCode NotificationHelper::RemoveNotificationSlotGroup(const std::string &slotGroupId) +{ + return DelayedSingleton::GetInstance()->RemoveNotificationSlotGroup(slotGroupId); +} + +ErrCode NotificationHelper::GetNotificationSlotGroup(const std::string &groupId, sptr &group) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlotGroup(groupId, group); +} + +ErrCode NotificationHelper::GetNotificationSlotGroups(std::vector> &groups) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlotGroups(groups); +} + +ErrCode NotificationHelper::PublishNotification(const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishNotification(request); +} + +ErrCode NotificationHelper::PublishNotification(const std::string &label, const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishNotification(label, request); +} + +ErrCode NotificationHelper::PublishNotification(const NotificationRequest &request, const std::string &deviceId) +{ + return DelayedSingleton::GetInstance()->PublishNotification(request, deviceId); +} + +ErrCode NotificationHelper::CancelNotification(int32_t notificationId) +{ + return DelayedSingleton::GetInstance()->CancelNotification(notificationId); +} + +ErrCode NotificationHelper::CancelNotification(const std::string &label, int32_t notificationId) +{ + return DelayedSingleton::GetInstance()->CancelNotification(label, notificationId); +} + +ErrCode NotificationHelper::CancelAllNotifications() +{ + return DelayedSingleton::GetInstance()->CancelAllNotifications(); +} + +ErrCode NotificationHelper::GetActiveNotificationNums(int32_t &num) +{ + return DelayedSingleton::GetInstance()->GetActiveNotificationNums(num); +} + +ErrCode NotificationHelper::GetActiveNotifications(std::vector> &request) +{ + return DelayedSingleton::GetInstance()->GetActiveNotifications(request); +} + +ErrCode NotificationHelper::GetCurrentAppSorting(sptr &sortingMap) +{ + return DelayedSingleton::GetInstance()->GetCurrentAppSorting(sortingMap); +} + +ErrCode NotificationHelper::SetNotificationAgent(const std::string &agent) +{ + return DelayedSingleton::GetInstance()->SetNotificationAgent(agent); +} + +ErrCode NotificationHelper::GetNotificationAgent(std::string &agent) +{ + return DelayedSingleton::GetInstance()->GetNotificationAgent(agent); +} + +ErrCode NotificationHelper::CanPublishNotificationAsBundle(const std::string &representativeBundle, bool &canPublish) +{ + return DelayedSingleton::GetInstance()->CanPublishNotificationAsBundle( + representativeBundle, canPublish); +} + +ErrCode NotificationHelper::PublishNotificationAsBundle( + const std::string &representativeBundle, const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishNotificationAsBundle(representativeBundle, request); +} + +ErrCode NotificationHelper::SetNotificationBadgeNum() +{ + return DelayedSingleton::GetInstance()->SetNotificationBadgeNum(); +} + +ErrCode NotificationHelper::SetNotificationBadgeNum(int32_t num) +{ + return DelayedSingleton::GetInstance()->SetNotificationBadgeNum(num); +} + +ErrCode NotificationHelper::IsAllowedNotify(bool &allowed) +{ + return DelayedSingleton::GetInstance()->IsAllowedNotify(allowed); +} + +ErrCode NotificationHelper::AreNotificationsSuspended(bool &suspended) +{ + return DelayedSingleton::GetInstance()->AreNotificationsSuspended(suspended); +} + +ErrCode NotificationHelper::HasNotificationPolicyAccessPermission(bool &hasPermission) +{ + return DelayedSingleton::GetInstance()->HasNotificationPolicyAccessPermission(hasPermission); +} + +ErrCode NotificationHelper::GetBundleImportance(NotificationSlot::NotificationLevel &importance) +{ + return DelayedSingleton::GetInstance()->GetBundleImportance(importance); +} + +ErrCode NotificationHelper::SubscribeNotification(const NotificationSubscriber &subscriber) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber); +} + +ErrCode NotificationHelper::SubscribeNotification( + const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, subscribeInfo); +} + +ErrCode NotificationHelper::UnSubscribeNotification(NotificationSubscriber &subscriber) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber); +} + +ErrCode NotificationHelper::UnSubscribeNotification( + NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber, subscribeInfo); +} + +ErrCode NotificationHelper::RemoveNotification(const std::string &key) +{ + return DelayedSingleton::GetInstance()->RemoveNotification(key); +} + +ErrCode NotificationHelper::RemoveNotifications(const std::string &bundleName) +{ + return DelayedSingleton::GetInstance()->RemoveNotifications(bundleName); +} + +ErrCode NotificationHelper::RemoveNotifications() +{ + return DelayedSingleton::GetInstance()->RemoveNotifications(); +} + +ErrCode NotificationHelper::GetNotificationSlotsForBundle( + const std::string &bundleName, std::vector> &slots) +{ + return DelayedSingleton::GetInstance()->GetNotificationSlotsForBundle(bundleName, slots); +} + +ErrCode NotificationHelper::GetAllActiveNotifications(std::vector> ¬ification) +{ + return DelayedSingleton::GetInstance()->GetAllActiveNotifications(notification); +} + +ErrCode NotificationHelper::GetAllActiveNotifications( + const std::vector key, std::vector> ¬ification) +{ + return DelayedSingleton::GetInstance()->GetAllActiveNotifications(key, notification); +} + +ErrCode NotificationHelper::IsAllowedNotify(const std::string &bundle, bool &allowed) +{ + return DelayedSingleton::GetInstance()->IsAllowedNotify(bundle, allowed); +} + +ErrCode NotificationHelper::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetNotificationsEnabledForAllBundles(deviceId, enabled); +} + +ErrCode NotificationHelper::SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetNotificationsEnabledForDefaultBundle(deviceId, enabled); +} + +ErrCode NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( + const std::string &bundle, std::string &deviceId, bool enabled) +{ + return DelayedSingleton::GetInstance()->SetNotificationsEnabledForSpecifiedBundle( + bundle, deviceId, enabled); +} + +ErrCode NotificationHelper::SetDisturbMode(NotificationConstant::DisturbMode mode) +{ + return DelayedSingleton::GetInstance()->SetDisturbMode(mode); +} + +ErrCode NotificationHelper::GetDisturbMode(NotificationConstant::DisturbMode &disturbMode) +{ + return DelayedSingleton::GetInstance()->GetDisturbMode(disturbMode); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_long_text_content.cpp b/kits/native/src/notification_long_text_content.cpp new file mode 100644 index 000000000..e7dc470b2 --- /dev/null +++ b/kits/native/src/notification_long_text_content.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (c); 2021 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 +#include "notification_long_text_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH{1024}; + +NotificationLongTextContent::NotificationLongTextContent(const std::string &longText) +{ + SetLongText(longText); +} + +void NotificationLongTextContent::SetExpandedTitle(const std::string &exTitle) +{ + expandedTitle_ = exTitle; +} + +std::string NotificationLongTextContent::GetExpandedTitle() const +{ + return expandedTitle_; +} + +void NotificationLongTextContent::SetBriefText(const std::string &briefText) +{ + briefText_ = briefText; +} + +std::string NotificationLongTextContent::GetBriefText() const +{ + return briefText_; +} + +void NotificationLongTextContent::SetLongText(const std::string &longText) +{ + if (longText.empty()) { + longText_.clear(); + return; + } + + auto length = std::min(NotificationLongTextContent::MAX_LONGTEXT_LENGTH, longText.length()); + longText_.assign(longText.begin(), longText.begin() + length); +} + +std::string NotificationLongTextContent::GetLongText() const +{ + return longText_; +} + +std::string NotificationLongTextContent::Dump() +{ + return "NotificationLongTextContent[ " + NotificationBasicContent::Dump() + + " longText = " + longText_ + " briefText = " + briefText_ + + " expandedTitle = " + expandedTitle_ + " ]"; +} + +bool NotificationLongTextContent::Marshalling(Parcel &parcel) const +{ + if (!NotificationBasicContent::Marshalling(parcel)) { + ANS_LOGE("Failed to write basic"); + return false; + } + + if (!parcel.WriteString(expandedTitle_)) { + ANS_LOGE("Failed to write expanded title"); + return false; + } + + if (!parcel.WriteString(briefText_)) { + ANS_LOGE("Failed to write brief text"); + return false; + } + + if (!parcel.WriteString(longText_)) { + ANS_LOGE("Failed to write longText"); + return false; + } + + return true; +} + +NotificationLongTextContent *NotificationLongTextContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationLongTextContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationLongTextContent::ReadFromParcel(Parcel &parcel) +{ + if (!NotificationBasicContent::ReadFromParcel(parcel)) { + ANS_LOGE("Failed to read basic"); + return false; + } + + if (!parcel.ReadString(expandedTitle_)) { + ANS_LOGE("Failed to read expanded title"); + return false; + } + + if (!parcel.ReadString(briefText_)) { + ANS_LOGE("Failed to read brief text"); + return false; + } + + if (!parcel.ReadString(longText_)) { + ANS_LOGE("Failed to read longtext"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_media_content.cpp b/kits/native/src/notification_media_content.cpp new file mode 100644 index 000000000..daf3ace8b --- /dev/null +++ b/kits/native/src/notification_media_content.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c); 2021 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 +#include "notification_media_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +void NotificationMediaContent::SetAVToken(const std::shared_ptr &avToken) +{ + avToken_ = avToken; +} + +const std::shared_ptr NotificationMediaContent::GetAVToken() const +{ + return avToken_; +} + +void NotificationMediaContent::SetShownActions(const std::vector &actions) +{ + sequenceNumbers_ = actions; +} + +std::vector NotificationMediaContent::GetShownActions() const +{ + return sequenceNumbers_; +} + +std::string NotificationMediaContent::Dump() +{ + std::string numbers{}; + std::for_each(sequenceNumbers_.begin(), sequenceNumbers_.end(), [&numbers](int32_t num) { + numbers += std::to_string(num) + " "; + }); + + return "NotificationMediaContent[ " + NotificationBasicContent::Dump() + + ", avToken = " + (avToken_ ? "not null" : "null") + ", sequenceNumbers = " + numbers + " ]"; +} + +bool NotificationMediaContent::Marshalling(Parcel &parcel) const +{ + if (!NotificationBasicContent::Marshalling(parcel)) { + ANS_LOGE("Failed to write basic"); + return false; + } + + // auto valid = avToken_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether avToken is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(avToken_.get())) { + // ANS_LOGE("Failed to write avToken"); + // return false; + // } + // } + + if (!parcel.WriteUInt32Vector(sequenceNumbers_)) { + ANS_LOGE("Failed to write sequence numbers"); + return false; + } + + return true; +} + +NotificationMediaContent *NotificationMediaContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationMediaContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationMediaContent::ReadFromParcel(Parcel &parcel) +{ + if (!NotificationBasicContent::ReadFromParcel(parcel)) { + ANS_LOGE("Failed to read basic"); + return false; + } + + // auto valid = parcel.ReadBool(); + // if (valid) { + // avToken_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!avToken_) { + // ANS_LOGE("Failed to read avToken"); + // return false; + // } + // } + + if (!parcel.ReadUInt32Vector(&sequenceNumbers_)) { + ANS_LOGE("Failed to read sequence numbers"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_multiline_content.cpp b/kits/native/src/notification_multiline_content.cpp new file mode 100644 index 000000000..495c25715 --- /dev/null +++ b/kits/native/src/notification_multiline_content.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c); 2021 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 +#include "notification_multiline_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +const std::vector::size_type NotificationMultiLineContent::MAX_LINES{7}; + +void NotificationMultiLineContent::SetExpandedTitle(const std::string &exTitle) +{ + expandedTitle_ = exTitle; +} + +std::string NotificationMultiLineContent::GetExpandedTitle() const +{ + return expandedTitle_; +} + +void NotificationMultiLineContent::SetBriefText(const std::string &briefText) +{ + briefText_ = briefText; +} + +std::string NotificationMultiLineContent::GetBriefText() const +{ + return briefText_; +} + +void NotificationMultiLineContent::AddSingleLine(const std::string &oneLine) +{ + if (allLines_.size() >= NotificationMultiLineContent::MAX_LINES) { + ANS_LOGW("already added seven lines"); + return; + } + + allLines_.emplace_back(oneLine); +} + +std::vector NotificationMultiLineContent::GetAllLines() const +{ + return allLines_; +} + +std::string NotificationMultiLineContent::Dump() +{ + std::string lines{}; + std::for_each( + allLines_.begin(), allLines_.end(), [&lines](const std::string &line) { lines += " " + line + ","; }); + lines.pop_back(); + + return "NotificationMultiLineContent[ " + NotificationBasicContent::Dump() + ", briefText = " + briefText_ + + ", expandedTitle = " + expandedTitle_ + ", allLines = [" + lines + " ] ]"; +} + +bool NotificationMultiLineContent::Marshalling(Parcel &parcel) const +{ + if (!NotificationBasicContent::Marshalling(parcel)) { + ANS_LOGE("Failed to write basic"); + return false; + } + + if (!parcel.WriteString(expandedTitle_)) { + ANS_LOGE("Failed to write expanded title"); + return false; + } + + if (!parcel.WriteString(briefText_)) { + ANS_LOGE("Failed to write brief text"); + return false; + } + + if (!parcel.WriteStringVector(allLines_)) { + ANS_LOGE("Failed to write all lines"); + return false; + } + + return true; +} + +NotificationMultiLineContent *NotificationMultiLineContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationMultiLineContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationMultiLineContent::ReadFromParcel(Parcel &parcel) +{ + if (!NotificationBasicContent::ReadFromParcel(parcel)) { + ANS_LOGE("Failed to read basic"); + return false; + } + + if (!parcel.ReadString(expandedTitle_)) { + ANS_LOGE("Failed to read expanded title"); + return false; + } + + if (!parcel.ReadString(briefText_)) { + ANS_LOGE("Failed to read brief text"); + return false; + } + + if (!parcel.ReadStringVector(&allLines_)) { + ANS_LOGE("Failed to read all lines"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_normal_content.cpp b/kits/native/src/notification_normal_content.cpp new file mode 100644 index 000000000..dec172656 --- /dev/null +++ b/kits/native/src/notification_normal_content.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c); 2021 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 "notification_normal_content.h" + +namespace OHOS { +namespace Notification { +std::string NotificationNormalContent::Dump() +{ + return "NotificationNormalContent[ " + NotificationBasicContent::Dump() + " ]"; +} + +bool NotificationNormalContent::Marshalling(Parcel &parcel) const +{ + return NotificationBasicContent::Marshalling(parcel); +} + +NotificationNormalContent *NotificationNormalContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationNormalContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_picture_content.cpp b/kits/native/src/notification_picture_content.cpp new file mode 100644 index 000000000..d155eb4a6 --- /dev/null +++ b/kits/native/src/notification_picture_content.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c); 2021 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 "notification_picture_content.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +void NotificationPictureContent::SetExpandedTitle(const std::string &exTitle) +{ + expandedTitle_ = exTitle; +} + +std::string NotificationPictureContent::GetExpandedTitle() const +{ + return expandedTitle_; +} + +void NotificationPictureContent::SetBriefText(const std::string &briefText) +{ + briefText_ = briefText; +} + +std::string NotificationPictureContent::GetBriefText() const +{ + return briefText_; +} + +void NotificationPictureContent::SetBigPicture(const std::shared_ptr &bigPicture) +{ + bigPicture_ = bigPicture; +} + +const std::shared_ptr NotificationPictureContent::GetBigPicture() const +{ + return bigPicture_; +} + +std::string NotificationPictureContent::Dump() +{ + return "NotificationPictureContent[ " + NotificationBasicContent::Dump() + ", briefText = " + briefText_ + + ", expandedTitle = " + expandedTitle_ + ", bigPicture = " + (bigPicture_ ? "not null" : "null") + " ]"; +} + +bool NotificationPictureContent::Marshalling(Parcel &parcel) const +{ + if (!NotificationBasicContent::Marshalling(parcel)) { + ANS_LOGE("Failed to write basic"); + return false; + } + + if (!parcel.WriteString(expandedTitle_)) { + ANS_LOGE("Failed to write expanded title"); + return false; + } + + if (!parcel.WriteString(briefText_)) { + ANS_LOGE("Failed to write brief text"); + return false; + } + + // auto valid = bigPicture_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether bigPicture is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(bigPicture_.get())) { + // ANS_LOGE("Failed to write bigPicture"); + // return false; + // } + // } + + return true; +} + +NotificationPictureContent *NotificationPictureContent::Unmarshalling(Parcel &parcel) +{ + auto pContent = new NotificationPictureContent(); + if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + delete pContent; + pContent = nullptr; + } + + return pContent; +} + +bool NotificationPictureContent::ReadFromParcel(Parcel &parcel) +{ + if (!NotificationBasicContent::ReadFromParcel(parcel)) { + ANS_LOGE("Failed to read basic"); + return false; + } + + if (!parcel.ReadString(expandedTitle_)) { + ANS_LOGE("Failed to read expanded title"); + return false; + } + + if (!parcel.ReadString(briefText_)) { + ANS_LOGE("Failed to read brief text"); + return false; + } + + // auto valid = parcel.ReadBool(); + // if (valid) { + // bigPicture_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!bigPicture_) { + // ANS_LOGE("Failed to read bigPicture"); + // return false; + // } + // } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_request.cpp b/kits/native/src/notification_request.cpp new file mode 100644 index 000000000..1b850292c --- /dev/null +++ b/kits/native/src/notification_request.cpp @@ -0,0 +1,1398 @@ +/* + * Copyright (c); 2021 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 +#include +#include "notification_request.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +const std::string NotificationRequest::CLASSIFICATION_ALARM{"alarm"}; +const std::string NotificationRequest::CLASSIFICATION_CALL{"call"}; +const std::string NotificationRequest::CLASSIFICATION_EMAIL{"email"}; +const std::string NotificationRequest::CLASSIFICATION_ERROR{"err"}; +const std::string NotificationRequest::CLASSIFICATION_EVENT{"event"}; +const std::string NotificationRequest::CLASSIFICATION_MESSAGE{"msg"}; +const std::string NotificationRequest::CLASSIFICATION_NAVIGATION{"navigation"}; +const std::string NotificationRequest::CLASSIFICATION_PROGRESS{"progress"}; +const std::string NotificationRequest::CLASSIFICATION_PROMO{"promo"}; +const std::string NotificationRequest::CLASSIFICATION_RECOMMENDATION{"recommendation"}; +const std::string NotificationRequest::CLASSIFICATION_REMINDER{"reminder"}; +const std::string NotificationRequest::CLASSIFICATION_SERVICE{"service"}; +const std::string NotificationRequest::CLASSIFICATION_SOCIAL{"social"}; +const std::string NotificationRequest::CLASSIFICATION_STATUS{"status"}; +const std::string NotificationRequest::CLASSIFICATION_SYSTEM{"sys"}; +const std::string NotificationRequest::CLASSIFICATION_TRANSPORT{"transport"}; + +const int32_t NotificationRequest::COLOR_DEFAULT{0}; + +const int32_t NotificationRequest::COLOR_MASK{0xFF000000}; +const std::size_t NotificationRequest::MAX_USER_INPUT_HISTORY{5}; +const std::size_t NotificationRequest::MAX_ACTION_BUTTONS{3}; + +NotificationRequest::NotificationRequest(int32_t notificationId) : notificationId_(notificationId) +{ + createTime_ = GetNowSysTime(); + deliveryTime_ = GetNowSysTime(); +} + +NotificationRequest::NotificationRequest(const std::shared_ptr &context, int32_t notificationId) + : notificationId_(notificationId), context_(context) +{ + createTime_ = GetNowSysTime(); + deliveryTime_ = GetNowSysTime(); +} + +NotificationRequest::NotificationRequest(const NotificationRequest &other) +{ + this->notificationId_ = other.notificationId_; + this->color_ = other.color_; + this->badgeNumber_ = other.badgeNumber_; + this->progressValue_ = other.progressValue_; + this->progressMax_ = other.progressMax_; + this->createTime_ = other.createTime_; + this->deliveryTime_ = other.deliveryTime_; + this->autoDeletedTime_ = other.autoDeletedTime_; + + this->creatorPid_ = other.creatorPid_; + this->creatorUid_ = other.creatorUid_; + + this->slotType_ = other.slotType_; + this->settingsText_ = other.settingsText_; + this->creatorBundleName_ = other.creatorBundleName_; + this->ownerBundleName_ = other.ownerBundleName_; + this->groupValue_ = other.groupValue_; + this->statusBarText_ = other.statusBarText_; + this->label_ = other.label_; + this->shortcutId_ = other.shortcutId_; + this->sortingKey_ = other.sortingKey_; + this->classification_ = other.classification_; + + this->groupAlertType_ = other.groupAlertType_; + this->visiblenessType_ = other.visiblenessType_; + this->badgeStyle_ = other.badgeStyle_; + this->notificationContentType_ = other.notificationContentType_; + + this->showDeliveryTime_ = other.showDeliveryTime_; + this->tapDismissed_ = other.tapDismissed_; + this->colorEnabled_ = other.colorEnabled_; + this->alertOneTime_ = other.alertOneTime_; + this->showStopwatch_ = other.showStopwatch_; + this->isCountdown_ = other.isCountdown_; + this->inProgress_ = other.inProgress_; + this->groupOverview_ = other.groupOverview_; + this->progressIndeterminate_ = other.progressIndeterminate_; + this->unremovable_ = other.unremovable_; + this->floatingIcon_ = other.floatingIcon_; + this->onlyLocal_ = other.onlyLocal_; + this->permitted_ = other.permitted_; + + this->context_ = other.context_; + this->wantAgent_ = other.wantAgent_; + this->removalWantAgent_ = other.removalWantAgent_; + this->maxScreenWantAgent_ = other.maxScreenWantAgent_; + this->additionalParams_ = other.additionalParams_; + this->littleIcon_ = other.littleIcon_; + this->bigIcon_ = other.bigIcon_; + this->notificationContent_ = other.notificationContent_; + this->customBigView_ = other.customBigView_; + this->customFloatView_ = other.customFloatView_; + this->customView_ = other.customView_; + this->publicNotification_ = other.publicNotification_; + + this->actionButtons_ = other.actionButtons_; + this->messageUsers_ = other.messageUsers_; + this->userInputHistory_ = other.userInputHistory_; +} + +NotificationRequest &NotificationRequest::operator=(const NotificationRequest &other) +{ + this->notificationId_ = other.notificationId_; + this->color_ = other.color_; + this->badgeNumber_ = other.badgeNumber_; + this->progressValue_ = other.progressValue_; + this->progressMax_ = other.progressMax_; + this->createTime_ = other.createTime_; + this->deliveryTime_ = other.deliveryTime_; + this->autoDeletedTime_ = other.autoDeletedTime_; + + this->creatorPid_ = other.creatorPid_; + this->creatorUid_ = other.creatorUid_; + + this->slotType_ = other.slotType_; + this->settingsText_ = other.settingsText_; + this->creatorBundleName_ = other.creatorBundleName_; + this->ownerBundleName_ = other.ownerBundleName_; + this->groupValue_ = other.groupValue_; + this->statusBarText_ = other.statusBarText_; + this->label_ = other.label_; + this->shortcutId_ = other.shortcutId_; + this->sortingKey_ = other.sortingKey_; + this->classification_ = other.classification_; + + this->groupAlertType_ = other.groupAlertType_; + this->visiblenessType_ = other.visiblenessType_; + this->badgeStyle_ = other.badgeStyle_; + this->notificationContentType_ = other.notificationContentType_; + + this->showDeliveryTime_ = other.showDeliveryTime_; + this->tapDismissed_ = other.tapDismissed_; + this->colorEnabled_ = other.colorEnabled_; + this->alertOneTime_ = other.alertOneTime_; + this->showStopwatch_ = other.showStopwatch_; + this->isCountdown_ = other.isCountdown_; + this->inProgress_ = other.inProgress_; + this->groupOverview_ = other.groupOverview_; + this->progressIndeterminate_ = other.progressIndeterminate_; + this->unremovable_ = other.unremovable_; + this->floatingIcon_ = other.floatingIcon_; + this->onlyLocal_ = other.onlyLocal_; + this->permitted_ = other.permitted_; + + this->context_ = other.context_; + this->wantAgent_ = other.wantAgent_; + this->removalWantAgent_ = other.removalWantAgent_; + this->maxScreenWantAgent_ = other.maxScreenWantAgent_; + this->additionalParams_ = other.additionalParams_; + this->littleIcon_ = other.littleIcon_; + this->bigIcon_ = other.bigIcon_; + this->notificationContent_ = other.notificationContent_; + this->customBigView_ = other.customBigView_; + this->customFloatView_ = other.customFloatView_; + this->customView_ = other.customView_; + this->publicNotification_ = other.publicNotification_; + + this->actionButtons_ = other.actionButtons_; + this->messageUsers_ = other.messageUsers_; + this->userInputHistory_ = other.userInputHistory_; + + return *this; +} + +NotificationRequest::~NotificationRequest() +{} + +bool NotificationRequest::IsInProgress() const +{ + return inProgress_; +} + +void NotificationRequest::SetInProgress(bool isOngoing) +{ + inProgress_ = isOngoing; +} + +bool NotificationRequest::IsUnremovable() const +{ + return unremovable_; +} + +void NotificationRequest::SetUnremovable(bool isUnremovable) +{ + unremovable_ = isUnremovable; +} + +void NotificationRequest::SetBadgeNumber(int32_t number) +{ + badgeNumber_ = number; +} + +int32_t NotificationRequest::GetBadgeNumber() const +{ + return badgeNumber_; +} + +void NotificationRequest::SetNotificationId(int32_t notificationId) +{ + notificationId_ = notificationId; +} + +int32_t NotificationRequest::GetNotificationId() const +{ + return notificationId_; +} + +void NotificationRequest::SetWantAgent(const std::shared_ptr &wantAgent) +{ + wantAgent_ = wantAgent; +} + +const std::shared_ptr NotificationRequest::GetWantAgent() const +{ + return wantAgent_; +} + +void NotificationRequest::SetRemovalWantAgent(const std::shared_ptr &wantAgent) +{ + removalWantAgent_ = wantAgent; +} + +const std::shared_ptr NotificationRequest::GetRemovalWantAgent() const +{ + return removalWantAgent_; +} + +void NotificationRequest::SetMaxScreenWantAgent(const std::shared_ptr &wantAgent) +{ + maxScreenWantAgent_ = wantAgent; +} + +const std::shared_ptr NotificationRequest::GetMaxScreenWantAgent() const +{ + return maxScreenWantAgent_; +} + +void NotificationRequest::SetAdditionalData(const std::shared_ptr &extras) +{ + additionalParams_ = extras; +} + +const std::shared_ptr NotificationRequest::GetAdditionalData() const +{ + return additionalParams_; +} + +void NotificationRequest::SetDeliveryTime(int64_t deliveryTime) +{ + deliveryTime_ = deliveryTime; +} + +int64_t NotificationRequest::GetDeliveryTime() const +{ + return deliveryTime_; +} + +bool NotificationRequest::IsShowDeliveryTime() const +{ + return (0 != deliveryTime_) && showDeliveryTime_; +} + +void NotificationRequest::SetShowDeliveryTime(bool showDeliveryTime) +{ + showDeliveryTime_ = showDeliveryTime; +} + +void NotificationRequest::AddActionButton(const std::shared_ptr &actionButton) +{ + if (!actionButton) { + ANS_LOGW("actionButton can not be null"); + return; + } + + if (actionButtons_.size() >= NotificationRequest::MAX_ACTION_BUTTONS) { + ANS_LOGW("three action buttons have been already added"); + return; + } + + actionButtons_.emplace_back(actionButton); +} + +const std::vector> NotificationRequest::GetActionButtons() const +{ + return actionButtons_; +} + +bool NotificationRequest::IsPermitSystemGeneratedContextualActionButtons() const +{ + return permitted_; +} + +void NotificationRequest::SetPermitSystemGeneratedContextualActionButtons(bool permitted) +{ + permitted_ = permitted; +} + +void NotificationRequest::AddMessageUser(const std::shared_ptr &messageUser) +{ + if (!messageUser) { + ANS_LOGI("messageUser can not be null"); + return; + } + + messageUsers_.emplace_back(messageUser); +} + +const std::vector> NotificationRequest::GetMessageUsers() const +{ + return messageUsers_; +} + +bool NotificationRequest::IsAlertOneTime() const +{ + return alertOneTime_; +} + +void NotificationRequest::SetAlertOneTime(bool isAlertOnce) +{ + alertOneTime_ = isAlertOnce; +} + +void NotificationRequest::SetAutoDeletedTime(int64_t deletedTime) +{ + autoDeletedTime_ = deletedTime; +} + +int64_t NotificationRequest::GetAutoDeletedTime() const +{ + return autoDeletedTime_; +} + +void NotificationRequest::SetLittleIcon(const std::shared_ptr &littleIcon) +{ + littleIcon_ = littleIcon; +} + +const std::shared_ptr NotificationRequest::GetLittleIcon() const +{ + return littleIcon_; +} + +void NotificationRequest::SetBigIcon(const std::shared_ptr &bigIcon) +{ + bigIcon_ = bigIcon; +} + +const std::shared_ptr NotificationRequest::GetBigIcon() const +{ + return bigIcon_; +} + +void NotificationRequest::SetClassification(const std::string &classification) +{ + classification_ = classification; +} + +std::string NotificationRequest::GetClassification() const +{ + return classification_; +} + +void NotificationRequest::SetColor(int32_t color) +{ + color_ = color; + if (NotificationRequest::COLOR_DEFAULT != color) { + color_ = color | NotificationRequest::COLOR_MASK; + } +} + +int32_t NotificationRequest::GetColor() const +{ + return color_; +} + +bool NotificationRequest::IsColorEnabled() +{ + if (!colorEnabled_) { + return false; + } + + // no valid content + if (!notificationContent_) { + ANS_LOGI("no valid notification content"); + return false; + } + + // not a media content + if (NotificationContent::Type::MEDIA != notificationContentType_) { + ANS_LOGI("not a media notification content"); + return false; + } + + auto basicContent = notificationContent_->GetNotificationContent(); + auto mediaContent = std::static_pointer_cast(basicContent); + if (!mediaContent->GetAVToken()) { + ANS_LOGI("AVToken has not been attached"); + return false; + } + + return true; +} + +void NotificationRequest::SetColorEnabled(bool colorEnabled) +{ + colorEnabled_ = colorEnabled; +} + +void NotificationRequest::SetContent(const std::shared_ptr &content) +{ + notificationContent_ = content; + + if (notificationContent_) { + notificationContentType_ = notificationContent_->GetContentType(); + return; + } + + notificationContentType_ = NotificationContent::Type::NONE; +} + +const std::shared_ptr NotificationRequest::GetContent() const +{ + return notificationContent_; +} + +NotificationContent::Type NotificationRequest::GetNotificationType() const +{ + return notificationContentType_; +} + +bool NotificationRequest::IsCountdownTimer() const +{ + return isCountdown_; +} + +void NotificationRequest::SetCountdownTimer(bool isCountDown) +{ + isCountdown_ = isCountDown; +} + +void NotificationRequest::SetCustomBigView(const std::shared_ptr &view) +{ + customBigView_ = view; +} + +const std::shared_ptr NotificationRequest::GetCustomBigView() const +{ + return customBigView_; +} + +void NotificationRequest::SetCustomFloatView(const std::shared_ptr &view) +{ + customFloatView_ = view; +} + +const std::shared_ptr NotificationRequest::GetCustomFloatView() const +{ + return customFloatView_; +} + +void NotificationRequest::SetCustomView(const std::shared_ptr &view) +{ + customView_ = view; +} + +const std::shared_ptr NotificationRequest::GetCustomView() const +{ + return customView_; +} + +void NotificationRequest::SetGroupAlertType(NotificationRequest::GroupAlertType type) +{ + groupAlertType_ = type; +} + +NotificationRequest::GroupAlertType NotificationRequest::GetGroupAlertType() const +{ + return groupAlertType_; +} + +bool NotificationRequest::IsGroupOverview() const +{ + return groupOverview_; +} + +void NotificationRequest::SetGroupOverview(bool overView) +{ + groupOverview_ = overView; +} + +void NotificationRequest::SetGroupValue(const std::string &groupValue) +{ + groupValue_ = groupValue; +} + +std::string NotificationRequest::GetGroupValue() const +{ + return groupValue_; +} + +bool NotificationRequest::IsOnlyLocal() const +{ + return onlyLocal_; +} + +void NotificationRequest::SetOnlyLocal(bool flag) +{ + onlyLocal_ = flag; +} + +void NotificationRequest::SetSettingsText(const std::string &text) +{ + if ((NotificationContent::Type::LONG_TEXT == notificationContentType_) || + (NotificationContent::Type::PICTURE == notificationContentType_)) { + ANS_LOGW("This method is invalid if the notification content type has been set to LONG_TEXT or PICTURE."); + return; + } + + settingsText_ = text; +} + +std::string NotificationRequest::GetSettingsText() const +{ + return settingsText_; +} + +int64_t NotificationRequest::GetCreateTime() const +{ + return createTime_; +} + +bool NotificationRequest::IsShowStopwatch() const +{ + return showStopwatch_; +} + +void NotificationRequest::SetShowStopwatch(bool isShow) +{ + showStopwatch_ = isShow; +} + +void NotificationRequest::SetSlotType(NotificationConstant::SlotType slotType) +{ + slotType_ = slotType; +} + +NotificationConstant::SlotType NotificationRequest::GetSlotType() const +{ + return slotType_; +} + +void NotificationRequest::SetSortingKey(const std::string &key) +{ + sortingKey_ = key; +} + +std::string NotificationRequest::GetSortingKey() const +{ + return sortingKey_; +} + +void NotificationRequest::SetStatusBarText(const std::string &text) +{ + statusBarText_ = text; +} + +std::string NotificationRequest::GetStatusBarText() const +{ + return statusBarText_; +} + +bool NotificationRequest::IsTapDismissed() const +{ + return tapDismissed_; +} + +void NotificationRequest::SetTapDismissed(bool isDismissed) +{ + tapDismissed_ = isDismissed; +} + +void NotificationRequest::SetVisibleness(NotificationConstant::VisiblenessType type) +{ + visiblenessType_ = type; +} + +NotificationConstant::VisiblenessType NotificationRequest::GetVisibleness() const +{ + return visiblenessType_; +} + +void NotificationRequest::SetBadgeIconStyle(NotificationRequest::BadgeStyle style) +{ + badgeStyle_ = style; +} + +NotificationRequest::BadgeStyle NotificationRequest::GetBadgeIconStyle() const +{ + return badgeStyle_; +} + +void NotificationRequest::SetShortcutId(const std::string &shortcutId) +{ + shortcutId_ = shortcutId; +} + +std::string NotificationRequest::GetShortcutId() const +{ + return shortcutId_; +} + +void NotificationRequest::SetFloatingIcon(bool floatingIcon) +{ + floatingIcon_ = floatingIcon; +} + +bool NotificationRequest::IsFloatingIcon() const +{ + return floatingIcon_; +} + +void NotificationRequest::SetProgressBar(int32_t progress, int32_t progressMax, bool indeterminate) +{ + progressValue_ = progress; + progressMax_ = progressMax; + progressIndeterminate_ = indeterminate; +} + +int32_t NotificationRequest::GetProgressMax() const +{ + return progressMax_; +} + +int32_t NotificationRequest::GetProgressValue() const +{ + return progressValue_; +} + +bool NotificationRequest::IsProgressIndeterminate() const +{ + return progressIndeterminate_; +} + +void NotificationRequest::SetNotificationUserInputHistory(const std::vector &text) +{ + if (text.empty()) { + userInputHistory_.clear(); + return; + } + + auto vsize = std::min(NotificationRequest::MAX_USER_INPUT_HISTORY, text.size()); + userInputHistory_.assign(text.begin(), text.begin() + vsize); +} + +std::vector NotificationRequest::GetNotificationUserInputHistory() const +{ + return userInputHistory_; +} + +void NotificationRequest::SetPublicNotification(const std::shared_ptr &other) +{ + publicNotification_ = other; +} + +const std::shared_ptr NotificationRequest::GetPublicNotification() const +{ + return publicNotification_; +} + +std::string NotificationRequest::GetNotificationHashCode() const +{ + if (creatorBundleName_.empty() || (0 == creatorUid_) || ownerBundleName_.empty()) { + return ""; + } + + return std::to_string(notificationId_) + "_" + creatorBundleName_ + "_" + std::to_string(creatorUid_) + "_" + + ownerBundleName_; +} + +void NotificationRequest::SetOwnerBundleName(const std::string &ownerName) +{ + ownerBundleName_ = ownerName; +} + +std::string NotificationRequest::GetOwnerBundleName() const +{ + return ownerBundleName_; +} + +void NotificationRequest::SetCreatorBundleName(const std::string &creatorName) +{ + creatorBundleName_ = creatorName; +} + +std::string NotificationRequest::GetCreatorBundleName() const +{ + return creatorBundleName_; +} + +void NotificationRequest::SetCreatorPid(pid_t pid) +{ + creatorPid_ = pid; +} + +pid_t NotificationRequest::GetCreatorPid() const +{ + return creatorPid_; +} + +void NotificationRequest::SetCreatorUid(uid_t uid) +{ + creatorUid_ = uid; +} + +uid_t NotificationRequest::GetCreatorUid() const +{ + return creatorUid_; +} + +void NotificationRequest::SetLabel(const std::string &label) +{ + label_ = label; +} + +std::string NotificationRequest::GetLabel() const +{ + return label_; +} + +std::string NotificationRequest::Dump() +{ + return "NotificationRequest[ notificationId = " + std::to_string(notificationId_) + + ", slotType = " + std::to_string(static_cast(slotType_)) + + ", createTime = " + std::to_string(createTime_) + ", deliveryTime = " + std::to_string(deliveryTime_) + + ", autoDeletedTime = " + std::to_string(autoDeletedTime_) + ", settingsText = " + settingsText_ + + ", creatorBundleName = " + creatorBundleName_ + + ", creatorPid = " + std::to_string(static_cast(creatorPid_)) + + ", creatorUid = " + std::to_string(static_cast(creatorUid_)) + + ", ownerBundleName = " + ownerBundleName_ + ", groupValue = " + groupValue_ + + ", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ + + ", sortingKey = " + sortingKey_ + + ", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) + + ", color = " + std::to_string(color_) + ", badgeNumber = " + std::to_string(badgeNumber_) + + ", visiblenessType = " + std::to_string(static_cast(visiblenessType_)) + + ", progressValue = " + std::to_string(progressValue_) + ", progressMax = " + std::to_string(progressMax_) + + ", badgeStyle = " + std::to_string(static_cast(badgeStyle_)) + + ", classification = " + classification_ + + ", notificationContentType = " + std::to_string(static_cast(notificationContentType_)) + + ", showDeliveryTime = " + (showDeliveryTime_ ? "true" : "false") + + ", tapDismissed = " + (tapDismissed_ ? "true" : "false") + + ", colorEnabled = " + (colorEnabled_ ? "true" : "false") + + ", alertOneTime = " + (alertOneTime_ ? "true" : "false") + + ", showStopwatch = " + (showStopwatch_ ? "true" : "false") + + ", isCountdown = " + (isCountdown_ ? "true" : "false") + + ", inProgress = " + (inProgress_ ? "true" : "false") + + ", groupOverview = " + (groupOverview_ ? "true" : "false") + + ", progressIndeterminate = " + (progressIndeterminate_ ? "true" : "false") + + ", unremovable = " + (unremovable_ ? "true" : "false") + + ", floatingIcon = " + (floatingIcon_ ? "true" : "false") + + ", onlyLocal = " + (onlyLocal_ ? "true" : "false") + ", permitted = " + (permitted_ ? "true" : "false") + + ", context = " + (context_ ? "not null" : "null") + ", wantAgent = " + (wantAgent_ ? "not null" : "null") + + ", removalWantAgent = " + (removalWantAgent_ ? "not null" : "null") + + ", maxScreenWantAgent = " + (maxScreenWantAgent_ ? "not null" : "null") + + ", additionalParams = " + (additionalParams_ ? "not null" : "null") + + ", littleIcon = " + (littleIcon_ ? "not null" : "null") + + ", bigIcon = " + (bigIcon_ ? "not null" : "null") + + ", notificationContent = " + (notificationContent_ ? "not null" : "null") + + ", customBigView = " + (customBigView_ ? "not null" : "null") + + ", customFloatView = " + (customFloatView_ ? "not null" : "null") + + ", customView = " + (customView_ ? "not null" : "null") + + ", publicNotification = " + (publicNotification_ ? "not null" : "null") + + ", actionButtons = " + (!actionButtons_.empty() ? "not empty" : "empty") + + ", messageUsers = " + (!messageUsers_.empty() ? "not empty" : "empty") + + ", userInputHistory = " + (!userInputHistory_.empty() ? "not empty" : "empty") + " ]"; +} + +bool NotificationRequest::Marshalling(Parcel &parcel) const +{ + // write int + if (!parcel.WriteInt32(notificationId_)) { + ANS_LOGE("Failed to write notification Id"); + return false; + } + + if (!parcel.WriteInt32(color_)) { + ANS_LOGE("Failed to write color"); + return false; + } + + if (!parcel.WriteInt32(badgeNumber_)) { + ANS_LOGE("Failed to write badge number"); + return false; + } + + if (!parcel.WriteInt32(progressValue_)) { + ANS_LOGE("Failed to write progress value"); + return false; + } + + if (!parcel.WriteInt32(progressMax_)) { + ANS_LOGE("Failed to write progress max"); + return false; + } + + if (!parcel.WriteInt64(createTime_)) { + ANS_LOGE("Failed to write create time"); + return false; + } + + if (!parcel.WriteInt64(deliveryTime_)) { + ANS_LOGE("Failed to write delivery time"); + return false; + } + + if (!parcel.WriteInt64(autoDeletedTime_)) { + ANS_LOGE("Failed to write auto deleted time"); + return false; + } + + if (!parcel.WriteInt32(static_cast(creatorPid_))) { + ANS_LOGE("Failed to write creator pid"); + return false; + } + + if (!parcel.WriteInt32(static_cast(creatorUid_))) { + ANS_LOGE("Failed to write creator uid"); + return false; + } + + // write std::string + if (!parcel.WriteString(settingsText_)) { + ANS_LOGE("Failed to write settings text"); + return false; + } + + if (!parcel.WriteString(creatorBundleName_)) { + ANS_LOGE("Failed to write creator bundle name"); + return false; + } + + if (!parcel.WriteString(ownerBundleName_)) { + ANS_LOGE("Failed to write owner bundle name"); + return false; + } + + if (!parcel.WriteString(groupValue_)) { + ANS_LOGE("Failed to write group value"); + return false; + } + + if (!parcel.WriteString(statusBarText_)) { + ANS_LOGE("Failed to write status bar text"); + return false; + } + + if (!parcel.WriteString(label_)) { + ANS_LOGE("Failed to write label"); + return false; + } + + if (!parcel.WriteString(shortcutId_)) { + ANS_LOGE("Failed to write shortcut Id"); + return false; + } + + if (!parcel.WriteString(sortingKey_)) { + ANS_LOGE("Failed to write sorting key"); + return false; + } + + if (!parcel.WriteString(classification_)) { + ANS_LOGE("Failed to write classification"); + return false; + } + + // write enum + if (!parcel.WriteInt32(static_cast(slotType_))) { + ANS_LOGE("Failed to write slot type"); + return false; + } + + if (!parcel.WriteInt32(static_cast(groupAlertType_))) { + ANS_LOGE("Failed to write group alert type"); + return false; + } + + if (!parcel.WriteInt32(static_cast(visiblenessType_))) { + ANS_LOGE("Failed to write visibleness type"); + return false; + } + + if (!parcel.WriteInt32(static_cast(badgeStyle_))) { + ANS_LOGE("Failed to write badge type"); + return false; + } + + if (!parcel.WriteInt32(static_cast(notificationContentType_))) { + ANS_LOGE("Failed to write notification content type"); + return false; + } + + // write bool + if (!parcel.WriteBool(showDeliveryTime_)) { + ANS_LOGE("Failed to write flag indicating whether to show delivery time"); + return false; + } + + if (!parcel.WriteBool(tapDismissed_)) { + ANS_LOGE("Failed to write flag tap dismissed"); + return false; + } + + if (!parcel.WriteBool(colorEnabled_)) { + ANS_LOGE("Failed to write flag indicating whether to enable background color"); + return false; + } + + if (!parcel.WriteBool(alertOneTime_)) { + ANS_LOGE("Failed to write flag indicating whether to have this notification alert only once"); + return false; + } + + if (!parcel.WriteBool(showStopwatch_)) { + ANS_LOGE("Failed to write flag show stop watch"); + return false; + } + + if (!parcel.WriteBool(isCountdown_)) { + ANS_LOGE("Failed to write flag indicating whether to show the notification creation time as a countdown timer"); + return false; + } + + if (!parcel.WriteBool(inProgress_)) { + ANS_LOGE("Failed to write flag indicating whether in progress"); + return false; + } + + if (!parcel.WriteBool(groupOverview_)) { + ANS_LOGE("Failed to write flag indicating whether to use this notification as the overview of its group"); + return false; + } + + if (!parcel.WriteBool(progressIndeterminate_)) { + ANS_LOGE("Failed to write progress indeterminate"); + return false; + } + + if (!parcel.WriteBool(unremovable_)) { + ANS_LOGE("Failed to write flag indicating whether unremovable"); + return false; + } + + if (!parcel.WriteBool(floatingIcon_)) { + ANS_LOGE("Failed to write flag floating icon"); + return false; + } + + if (!parcel.WriteBool(onlyLocal_)) { + ANS_LOGE("Failed to write flag only local"); + return false; + } + + if (!parcel.WriteBool(permitted_)) { + ANS_LOGE("Failed to write flag indicating whether to allow the platform to \ + generate contextual NotificationActionButton objects"); + return false; + } + + // write objects which managed by std::shared_ptr + bool valid{false}; + + valid = wantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether wantAgent is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(wantAgent_.get())) { + ANS_LOGE("Failed to write wantAgent"); + return false; + } + } + + valid = removalWantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether removalWantAgent is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(removalWantAgent_.get())) { + ANS_LOGE("Failed to write removalWantAgent"); + return false; + } + } + + valid = maxScreenWantAgent_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether maxScreenWantAgent is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(maxScreenWantAgent_.get())) { + ANS_LOGE("Failed to write maxScreenWantAgent"); + return false; + } + } + + valid = additionalParams_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether additionalParams is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(additionalParams_.get())) { + ANS_LOGE("Failed to write additionalParams"); + return false; + } + } + + // valid = littleIcon_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether littleIcon is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(littleIcon_.get())) { + // ANS_LOGE("Failed to write littleIcon"); + // return false; + // } + // } + + // valid = bigIcon_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether bigIcon is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(bigIcon_.get())) { + // ANS_LOGE("Failed to write bigIcon"); + // return false; + // } + // } + + valid = notificationContent_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether notificationContent is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(notificationContent_.get())) { + ANS_LOGE("Failed to write notificationContent"); + return false; + } + } + + // valid = customBigView_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether customBigView is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(customBigView_.get())) { + // ANS_LOGE("Failed to write customBigView"); + // return false; + // } + // } + + // valid = customFloatView_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether customFloatView is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(customFloatView_.get())) { + // ANS_LOGE("Failed to write customFloatView"); + // return false; + // } + // } + + // valid = customView_ ? true : false; + // if (!parcel.WriteBool(valid)) { + // ANS_LOGE("Failed to write the flag which indicate whether customView is null"); + // return false; + // } + + // if (valid) { + // if (!parcel.WriteParcelable(customView_.get())) { + // ANS_LOGE("Failed to write customView"); + // return false; + // } + // } + + valid = publicNotification_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether publicNotification is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(publicNotification_.get())) { + ANS_LOGE("Failed to write publicNotification"); + return false; + } + } + + // write std::vector + if (!parcel.WriteInt32(static_cast(actionButtons_.size()))) { + ANS_LOGE("Failed to write the size of actionButtons"); + return false; + } + + for (auto it = actionButtons_.begin(); it != actionButtons_.end(); ++it) { + if (!parcel.WriteParcelable(it->get())) { + ANS_LOGE("Failed to write actionButton"); + return false; + } + } + + if (!parcel.WriteInt32(static_cast(messageUsers_.size()))) { + ANS_LOGE("Failed to write the size of messageUsers"); + return false; + } + + for (auto it = messageUsers_.begin(); it != messageUsers_.end(); ++it) { + if (!parcel.WriteParcelable(it->get())) { + ANS_LOGE("Failed to write messageUser"); + return false; + } + } + + if (!parcel.WriteStringVector(userInputHistory_)) { + ANS_LOGE("Failed to write userInputHistory"); + return false; + } + + return true; +} + +NotificationRequest *NotificationRequest::Unmarshalling(Parcel &parcel) +{ + auto objptr = new NotificationRequest(); + if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + + return objptr; +} + +bool NotificationRequest::ReadFromParcel(Parcel &parcel) +{ + notificationId_ = parcel.ReadInt32(); + color_ = parcel.ReadInt32(); + badgeNumber_ = parcel.ReadInt32(); + progressValue_ = parcel.ReadInt32(); + progressMax_ = parcel.ReadInt32(); + createTime_ = parcel.ReadInt64(); + deliveryTime_ = parcel.ReadInt64(); + autoDeletedTime_ = parcel.ReadInt64(); + + creatorPid_ = static_cast(parcel.ReadInt32()); + creatorUid_ = static_cast(parcel.ReadInt32()); + + if (!parcel.ReadString(settingsText_)) { + ANS_LOGE("Failed to read settings text"); + return false; + } + + if (!parcel.ReadString(creatorBundleName_)) { + ANS_LOGE("Failed to read creator bundle name"); + return false; + } + + if (!parcel.ReadString(ownerBundleName_)) { + ANS_LOGE("Failed to read owner bundle name"); + return false; + } + + if (!parcel.ReadString(groupValue_)) { + ANS_LOGE("Failed to read group value"); + return false; + } + + if (!parcel.ReadString(statusBarText_)) { + ANS_LOGE("Failed to read status bar text"); + return false; + } + + if (!parcel.ReadString(label_)) { + ANS_LOGE("Failed to read label"); + return false; + } + + if (!parcel.ReadString(shortcutId_)) { + ANS_LOGE("Failed to read shortcut Id"); + return false; + } + + if (!parcel.ReadString(sortingKey_)) { + ANS_LOGE("Failed to read sorting key"); + return false; + } + + if (!parcel.ReadString(classification_)) { + ANS_LOGE("Failed to read classification"); + return false; + } + + slotType_ = static_cast(parcel.ReadInt32()); + groupAlertType_ = static_cast(parcel.ReadInt32()); + visiblenessType_ = static_cast(parcel.ReadInt32()); + badgeStyle_ = static_cast(parcel.ReadInt32()); + notificationContentType_ = static_cast(parcel.ReadInt32()); + + showDeliveryTime_ = parcel.ReadBool(); + tapDismissed_ = parcel.ReadBool(); + colorEnabled_ = parcel.ReadBool(); + alertOneTime_ = parcel.ReadBool(); + showStopwatch_ = parcel.ReadBool(); + isCountdown_ = parcel.ReadBool(); + inProgress_ = parcel.ReadBool(); + groupOverview_ = parcel.ReadBool(); + progressIndeterminate_ = parcel.ReadBool(); + unremovable_ = parcel.ReadBool(); + floatingIcon_ = parcel.ReadBool(); + onlyLocal_ = parcel.ReadBool(); + permitted_ = parcel.ReadBool(); + + bool valid{false}; + + valid = parcel.ReadBool(); + if (valid) { + wantAgent_ = std::shared_ptr(parcel.ReadParcelable()); + if (!wantAgent_) { + ANS_LOGE("Failed to read wantAgent"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + removalWantAgent_ = std::shared_ptr(parcel.ReadParcelable()); + if (!removalWantAgent_) { + ANS_LOGE("Failed to read removalWantAgent"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + maxScreenWantAgent_ = std::shared_ptr(parcel.ReadParcelable()); + if (!maxScreenWantAgent_) { + ANS_LOGE("Failed to read maxScreenWantAgent"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + additionalParams_ = std::shared_ptr(parcel.ReadParcelable()); + if (!additionalParams_) { + ANS_LOGE("Failed to read additionalParams"); + return false; + } + } + + // valid = parcel.ReadBool(); + // if (valid) { + // littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!littleIcon_) { + // ANS_LOGE("Failed to read littleIcon"); + // return false; + // } + // } + + // valid = parcel.ReadBool(); + // if (valid) { + // bigIcon_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!bigIcon_) { + // ANS_LOGE("Failed to read bigIcon"); + // return false; + // } + // } + + valid = parcel.ReadBool(); + if (valid) { + notificationContent_ = std::shared_ptr(parcel.ReadParcelable()); + if (!notificationContent_) { + ANS_LOGE("Failed to read notificationContent"); + return false; + } + } + + // valid = parcel.ReadBool(); + // if (valid) { + // customBigView_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!customBigView_) { + // ANS_LOGE("Failed to read customBigView"); + // return false; + // } + // } + + // valid = parcel.ReadBool(); + // if (valid) { + // customFloatView_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!customFloatView_) { + // ANS_LOGE("Failed to read customFloatView"); + // return false; + // } + // } + + // valid = parcel.ReadBool(); + // if (valid) { + // customView_ = std::shared_ptr(parcel.ReadParcelable()); + // if (!customView_) { + // ANS_LOGE("Failed to read customView"); + // return false; + // } + // } + + valid = parcel.ReadBool(); + if (valid) { + publicNotification_ = std::shared_ptr(parcel.ReadParcelable()); + if (!publicNotification_) { + ANS_LOGE("Failed to read publicNotification"); + return false; + } + } + + auto vsize = parcel.ReadInt32(); + for (auto it = 0; it < vsize; ++it) { + auto member = parcel.ReadParcelable(); + if (nullptr == member) { + ANS_LOGE("Failed to read actionButton"); + return false; + } + + actionButtons_.emplace_back(member); + } + + vsize = parcel.ReadInt32(); + for (auto it = 0; it < vsize; ++it) { + auto member = parcel.ReadParcelable(); + if (nullptr == member) { + ANS_LOGE("Failed to read messageUser"); + return false; + } + + messageUsers_.emplace_back(member); + } + + if (!parcel.ReadStringVector(&userInputHistory_)) { + ANS_LOGE("Failed to read userInputHistory"); + return false; + } + + return true; +} + +int64_t NotificationRequest::GetNowSysTime() +{ + std::chrono::time_point nowSys = std::chrono::system_clock::now(); + auto epoch = nowSys.time_since_epoch(); + auto value = std::chrono::duration_cast(epoch); + int64_t duration = value.count(); + return duration; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_slot.cpp b/kits/native/src/notification_slot.cpp new file mode 100644 index 000000000..7661db84e --- /dev/null +++ b/kits/native/src/notification_slot.cpp @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2021 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 "notification_slot.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + +const int MAX_TEXT_LENGTH = 1000; + +NotificationSlot::NotificationSlot(NotificationConstant::SlotType type) : sound_("") +{ + SetType(type); +} + +NotificationSlot::~NotificationSlot() +{} + +bool NotificationSlot::CanEnableLight() const +{ + return isLightEnabled_; +} + +void NotificationSlot::SetEnableLight(bool isLightEnabled) +{ + isLightEnabled_ = isLightEnabled; +} + +bool NotificationSlot::CanVibrate() const +{ + return isVibrationEnabled_; +} + +void NotificationSlot::SetEnableVibration(bool vibration) +{ + isVibrationEnabled_ = vibration; +} + +std::string NotificationSlot::GetDescription() const +{ + return description_; +} + +void NotificationSlot::SetDescription(const std::string &description) +{ + description_ = TruncateString(description); +} + +std::string NotificationSlot::GetId() const +{ + return id_; +} + +int32_t NotificationSlot::GetLedLightColor() const +{ + return lightColor_; +} + +void NotificationSlot::SetLedLightColor(int32_t color) +{ + lightColor_ = color; +} + +NotificationSlot::NotificationLevel NotificationSlot::GetLevel() const +{ + return level_; +} + +void NotificationSlot::SetLevel(NotificationLevel level) +{ + level_ = level; +} + +NotificationConstant::SlotType NotificationSlot::GetType() const +{ + return type_; +} + +void NotificationSlot::SetType(NotificationConstant::SlotType type) +{ + type_ = NotificationConstant::SlotType::CUSTOM; + switch (type) { + case NotificationConstant::SlotType::SOCIAL_COMMUNICATION: + id_ = "SOCIAL_COMMUNICATION"; + SetName("SOCIAL_COMMUNICATION"); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + SetEnableVibration(true); + break; + case NotificationConstant::SlotType::SERVICE_REMINDER: + id_ = "SERVICE_REMINDER"; + SetName("SERVICE_REMINDER"); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); + SetEnableVibration(true); + break; + case NotificationConstant::SlotType::CONTENT_INFORMATION: + id_ = "CONTENT_INFORMATION"; + SetName("CONTENT_INFORMATION"); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PRIVATE); + SetEnableVibration(false); + break; + case NotificationConstant::SlotType::OTHER: + id_ = "OTHER"; + SetName("OTHER"); + SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PRIVATE); + SetEnableVibration(false); + break; + default: + break; + } + type_ = type; +} + +NotificationConstant::VisiblenessType NotificationSlot::GetLockScreenVisibleness() const +{ + return lockScreenVisibleness_; +} + +void NotificationSlot::SetLockscreenVisibleness(NotificationConstant::VisiblenessType visibleness) +{ + lockScreenVisibleness_ = visibleness; +} + +std::string NotificationSlot::GetName() const +{ + return name_; +} + +void NotificationSlot::SetName(const std::string &name) +{ + name_ = TruncateString(name); +} + +std::string NotificationSlot::GetSlotGroup() const +{ + return groupId_; +} + +void NotificationSlot::SetSlotGroup(const std::string &groupId) +{ + groupId_ = groupId; +} + +Uri NotificationSlot::GetSound() const +{ + return sound_; +} + +void NotificationSlot::SetSound(const Uri &sound) +{ + sound_ = sound; +} + +std::vector NotificationSlot::GetVibrationStyle() const +{ + return vibrationValues_; +} + +void NotificationSlot::SetVibrationStyle(const std::vector &vibrationValues) +{ + isVibrationEnabled_ = (vibrationValues.size() > 0); + vibrationValues_ = vibrationValues; +} + +bool NotificationSlot::IsEnableBypassDnd() const +{ + return isBypassDnd_; +} + +void NotificationSlot::EnableBypassDnd(bool isBypassDnd) +{ + isBypassDnd_ = isBypassDnd; +} + +bool NotificationSlot::IsShowBadge() const +{ + return isShowBadge_; +} + +void NotificationSlot::EnableBadge(bool isShowBadge) +{ + isShowBadge_ = isShowBadge; +} + +std::string NotificationSlot::Dump() const +{ + return "NotificationSlot[id = " + id_ + ", name = " + name_ + ", description = " + description_ + + ", type = " + std::to_string(static_cast(type_)) + + ", level = " + std::to_string(static_cast(level_)) + + ", isBypassDnd = " + std::to_string(isBypassDnd_) + + ", visibleness = " + std::to_string(static_cast(lockScreenVisibleness_)) + + ", sound = " + sound_.ToString() + ", isLightEnabled = " + std::to_string(isLightEnabled_) + + ", lightColor = " + std::to_string(lightColor_) + ", isVibrate = " + std::to_string(isVibrationEnabled_) + + ", vibration = " + MergeVectorToString(vibrationValues_) + + ", isShowBadge = " + std::to_string(isShowBadge_) + ", groupId = " + groupId_ + "]"; +} + +bool NotificationSlot::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(id_)) { + return false; + } + + if (!parcel.WriteString(name_)) { + return false; + } + + if (!parcel.WriteBool(isLightEnabled_)) { + return false; + } + + if (!parcel.WriteBool(isVibrationEnabled_)) { + return false; + } + + if (!parcel.WriteBool(isShowBadge_)) { + return false; + } + + if (!parcel.WriteBool(isBypassDnd_)) { + return false; + } + + if (!parcel.WriteString(description_)) { + return false; + } + + if (!parcel.WriteInt32(lightColor_)) { + return false; + } + + if (!parcel.WriteInt32(static_cast(level_))) { + return false; + } + + if (!parcel.WriteInt32(static_cast(type_))) { + return false; + } + + if (!parcel.WriteInt32(static_cast(lockScreenVisibleness_))) { + return false; + } + + if (!parcel.WriteString(groupId_)) { + return false; + } + + if (sound_.ToString().empty()) { + if (!parcel.WriteInt32(VALUE_NULL)) { + return false; + } + } else { + if (!parcel.WriteInt32(VALUE_OBJECT)) { + return false; + } + if (!parcel.WriteString((sound_.ToString()))) { + return false; + } + } + + if (!parcel.WriteInt64Vector(vibrationValues_)) { + return false; + } + + return true; +} + +bool NotificationSlot::ReadFromParcel(Parcel &parcel) +{ + id_ = parcel.ReadString(); + name_ = parcel.ReadString(); + isLightEnabled_ = parcel.ReadBool(); + isVibrationEnabled_ = parcel.ReadBool(); + isShowBadge_ = parcel.ReadBool(); + isBypassDnd_ = parcel.ReadBool(); + description_ = parcel.ReadString(); + lightColor_ = parcel.ReadInt32(); + level_ = static_cast(parcel.ReadInt32()); + type_ = static_cast(parcel.ReadInt32()); + lockScreenVisibleness_ = static_cast(parcel.ReadInt32()); + groupId_ = parcel.ReadString(); + + int empty = VALUE_NULL; + if (!parcel.ReadInt32(empty)) { + return false; + } + + if (empty == VALUE_OBJECT) { + sound_ = Uri((parcel.ReadString())); + } + + parcel.ReadInt64Vector(&vibrationValues_); + return true; +} + +NotificationSlot *NotificationSlot::Unmarshalling(Parcel &parcel) +{ + NotificationSlot *notificationSlot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + + if (notificationSlot && !notificationSlot->ReadFromParcel(parcel)) { + delete notificationSlot; + notificationSlot = nullptr; + } + + return notificationSlot; +} + +std::string NotificationSlot::MergeVectorToString(const std::vector &mergeVector) const +{ + std::string contents; + for (auto it = mergeVector.begin(); it != mergeVector.end(); ++it) { + contents += std::to_string(*it); + if (it != mergeVector.end() - 1) { + contents += ", "; + } + } + return contents; +} + +std::string NotificationSlot::TruncateString(const std::string &in) +{ + std::string temp = in; + if (in.length() > MAX_TEXT_LENGTH) { + temp = in.substr(0, MAX_TEXT_LENGTH); + } + return temp; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_slot_group.cpp b/kits/native/src/notification_slot_group.cpp new file mode 100644 index 000000000..6de656121 --- /dev/null +++ b/kits/native/src/notification_slot_group.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 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 "notification_slot_group.h" + +#include "string_ex.h" + +namespace OHOS { +namespace Notification { +const int MAX_TEXT_LENGTH = 1000; +const std::string LINE_SEPARATOR = "\n"; + +NotificationSlotGroup::NotificationSlotGroup() +{} + +NotificationSlotGroup::NotificationSlotGroup(const std::string &id, const std::string &name) : id_(id), name_(name) +{ + id_ = TruncateString(id); + name_ = TruncateString(name); +} + +NotificationSlotGroup::~NotificationSlotGroup() +{} + +std::string NotificationSlotGroup::GetDescription() const +{ + return description_; +} + +std::string NotificationSlotGroup::GetId() const +{ + return id_; +} + +std::string NotificationSlotGroup::GetName() const +{ + return name_; +} + +std::vector NotificationSlotGroup::GetSlots() const +{ + return slots_; +} + +bool NotificationSlotGroup::IsDisabled() const +{ + return isDisabled_; +} + +void NotificationSlotGroup::SetDescription(const std::string &description) +{ + description_ = TruncateString(description); +} + +std::string NotificationSlotGroup::Dump() const +{ + std::string contents; + for (auto it = slots_.begin(); it != slots_.end(); ++it) { + contents += it->Dump(); + if (it != slots_.end() - 1) { + contents += ","; + } + } + return "NotificationSlotGroup[id = " + id_ + + ", name = " + name_ + + ", description = " + description_ + + ", slots = " + contents + + ", isDisabled = " + std::to_string(isDisabled_) + "]"; +} + +bool NotificationSlotGroup::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(id_)) { + return false; + } + + if (!parcel.WriteString(name_)) { + return false; + } + + if (!parcel.WriteString(description_)) { + return false; + } + + if (slots_.size() == 0) { + if (!parcel.WriteInt32(0)) { + return false; + } + } else { + if (!parcel.WriteInt32(slots_.size())) { + return false; + } + for (auto it = slots_.begin(); it != slots_.end(); ++it) { + if (!it->Marshalling(parcel)) { + return false; + } + } + } + + if (!parcel.WriteBool(isDisabled_)) { + return false; + } + + return true; +} + +bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel) +{ + id_ = parcel.ReadString(); + name_ = parcel.ReadString(); + description_ = parcel.ReadString(); + + if (slots_.size() == 0) { + if (!parcel.ReadInt32()) { + return false; + } + } else { + if (!parcel.ReadInt32()) { + return false; + } + for (auto it = slots_.begin(); it != slots_.end(); ++it) { + slots_.emplace_back(*it->Unmarshalling(parcel)); + } + } + + isDisabled_ = parcel.ReadBool(); + + return true; +} + +NotificationSlotGroup *NotificationSlotGroup::Unmarshalling(Parcel &parcel) +{ + NotificationSlotGroup *notificationSlotGroup = new NotificationSlotGroup(); + + if (!notificationSlotGroup && !notificationSlotGroup->ReadFromParcel(parcel)) { + delete notificationSlotGroup; + notificationSlotGroup = nullptr; + } + + return notificationSlotGroup; +} + +std::string NotificationSlotGroup::TruncateString(const std::string &inPutString) +{ + std::string temp = inPutString; + if (inPutString.length() > MAX_TEXT_LENGTH) { + temp = inPutString.substr(0, MAX_TEXT_LENGTH); + } + return temp; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_sorting.cpp b/kits/native/src/notification_sorting.cpp new file mode 100644 index 000000000..22fbba79b --- /dev/null +++ b/kits/native/src/notification_sorting.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2021 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 "notification_sorting.h" + +#include "string_ex.h" + +namespace OHOS { +namespace Notification { +NotificationSorting::NotificationSorting() +{} + +NotificationSorting::~NotificationSorting() +{} + +NotificationSorting::NotificationSorting(const NotificationSorting &sorting) +{ + key_ = sorting.key_; + ranking_ = sorting.ranking_; + importance_ = sorting.importance_; + isDisplayBadge_ = sorting.isDisplayBadge_; + isHiddenNotification_ = sorting.isHiddenNotification_; + visiblenessOverride_ = sorting.visiblenessOverride_; + groupKeyOverride_ = sorting.groupKeyOverride_; + slot_ = sorting.slot_; +} + +void NotificationSorting::SetSlot(const sptr &slot) +{ + slot_ = slot; +} + +void NotificationSorting::SetGroupKeyOverride(const std::string &groupKeyOverride) +{ + groupKeyOverride_ = groupKeyOverride; +} + +std::string NotificationSorting::Dump() const +{ + std::string contents{""}; + if (slot_ != nullptr) { + contents = slot_->Dump(); + } else { + contents = "nullptr"; + } + return "NotificationSorting[key =" + key_ + ", ranking =" + std::to_string(ranking_) + + ", importance =" + std::to_string(importance_) + + ", visiblenessOverride =" + std::to_string(visiblenessOverride_) + + ", isDisplayBadge =" + std::to_string(isDisplayBadge_) + + ", isHiddenNotification =" + std::to_string(isHiddenNotification_) + + ", groupKeyOverride =" + groupKeyOverride_ + ", slot_ =" + contents + "]"; +} + +bool NotificationSorting::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(key_)) { + ANS_LOGE("Can't write key"); + return false; + } + + if (!parcel.WriteInt32(ranking_)) { + ANS_LOGE("Can't write ranking"); + return false; + } + + if (!parcel.WriteInt32(importance_)) { + ANS_LOGE("Can't write importance"); + return false; + } + + if (!parcel.WriteInt32(visiblenessOverride_)) { + ANS_LOGE("Can't write importance"); + return false; + } + + if (!parcel.WriteBool(isDisplayBadge_)) { + ANS_LOGE("Can't write isDisplayBadge"); + return false; + } + + if (!parcel.WriteBool(isHiddenNotification_)) { + ANS_LOGE("Can't write is HiddenNotification"); + return false; + } + + if (!parcel.WriteString(groupKeyOverride_)) { + ANS_LOGE("Can't write groupKey groupKeyOverride"); + return false; + } + + if (!parcel.WriteStrongParcelable(slot_)) { + ANS_LOGE("Can't write slot"); + return false; + } + + return true; +} + +bool NotificationSorting::ReadFromParcel(Parcel &parcel) +{ + // read key_ + key_ = parcel.ReadString(); + + // read ranking_ + ranking_ = parcel.ReadInt32(); + + // read importance_ + importance_ = parcel.ReadInt32(); + + // read visiblenessOverride_ + visiblenessOverride_ = parcel.ReadInt32(); + + // read isDisplayBadge_ + isDisplayBadge_ = parcel.ReadBool(); + + // read isHiddenNotification_ + isHiddenNotification_ = parcel.ReadBool(); + + // read groupKeyOverride_ + groupKeyOverride_ = parcel.ReadString(); + + // read slot_ + slot_ = parcel.ReadStrongParcelable(); + + return true; +} + +NotificationSorting *NotificationSorting::Unmarshalling(Parcel &parcel) +{ + NotificationSorting *sorting = new NotificationSorting(); + if (sorting && !sorting->ReadFromParcel(parcel)) { + delete sorting; + sorting = nullptr; + } + return sorting; +} + +void NotificationSorting::SetKey(const std::string &key) +{ + key_ = key; +} + +void NotificationSorting::SetImportance(const int32_t &importance) +{ + importance_ = importance; +} + +void NotificationSorting::SetRanking(const int32_t &ranking) +{ + ranking_ = ranking; +} + +void NotificationSorting::SetVisiblenessOverride(const int32_t &visibleness) +{ + visiblenessOverride_ = visibleness; +} + +void NotificationSorting::SetDisplayBadge(const bool &isDisplayBadge) +{ + isDisplayBadge_ = isDisplayBadge; +} + +void NotificationSorting::SetHiddenNotification(const bool &isHiddenNotification) +{ + isHiddenNotification_ = isHiddenNotification; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_sorting_map.cpp b/kits/native/src/notification_sorting_map.cpp new file mode 100644 index 000000000..6fa30aae2 --- /dev/null +++ b/kits/native/src/notification_sorting_map.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 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 "notification_sorting_map.h" + +#include "parcel.h" + +namespace OHOS { +namespace Notification { +NotificationSortingMap::NotificationSortingMap() +{} + +NotificationSortingMap::~NotificationSortingMap() +{} + +NotificationSortingMap::NotificationSortingMap(const std::vector &sortingList) +{ + for (auto item : sortingList) { + sortedKey_.push_back(item.GetKey()); + sortings_[item.GetKey()] = item; + } +} + +void NotificationSortingMap::SetKey(const std::string &key) +{ + auto it = std::find(sortedKey_.cbegin(), sortedKey_.cend(), key); + if (it == sortedKey_.cend()) { + sortedKey_.emplace_back(key); + } +} + +bool NotificationSortingMap::GetNotificationSorting(const std::string &key, NotificationSorting &sorting) const +{ + for (auto item : sortings_) { + if (item.first == key) { + sorting = item.second; + return true; + } + } + + return false; +} + +void NotificationSortingMap::SetNotificationSorting(const std::vector &sortingList) +{ + for (auto item : sortingList) { + sortedKey_.push_back(item.GetKey()); + sortings_[item.GetKey()] = item; + } +} + +bool NotificationSortingMap::Marshalling(Parcel &parcel) const +{ + bool ret = true; + if (!parcel.WriteInt32(sortings_.size())) { + ANS_LOGE("Can't write sorting size"); + return false; + } + for_each(sortings_.begin(), sortings_.end(), [&](std::pair sorting) { + if (!parcel.WriteParcelable(&sorting.second)) { + ANS_LOGE("Can't write sorting"); + ret = false; + } + }); + + return ret; +} + +NotificationSortingMap *NotificationSortingMap::Unmarshalling(Parcel &parcel) +{ + std::vector sortings; + // read sorting num + int32_t size; + parcel.ReadInt32(size); + + for (int i = 0; i < size; i++) { + // read sorting + NotificationSorting a = *parcel.ReadParcelable(); + sortings.push_back(a); + } + + NotificationSortingMap *sortingMap = new NotificationSortingMap(sortings); + return sortingMap; +} +std::string NotificationSortingMap::Dump() const +{ + int keyNum = 0; + std::string separator; + std::string keys = " sortedkey = "; + for (auto item : sortedKey_) { + if (keyNum == 0) { + separator = ""; + } else { + separator = ", "; + } + keys = keys + separator + item; + keyNum++; + } + return "NotificationSortingMap[" + keys + "]"; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_subscribe_info.cpp b/kits/native/src/notification_subscribe_info.cpp new file mode 100644 index 000000000..542404270 --- /dev/null +++ b/kits/native/src/notification_subscribe_info.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 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 "notification_subscribe_info.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + +NotificationSubscribeInfo::NotificationSubscribeInfo() +{} + +NotificationSubscribeInfo::~NotificationSubscribeInfo() +{} + +NotificationSubscribeInfo::NotificationSubscribeInfo(const NotificationSubscribeInfo &subscribeInfo) +{ + appNames_ = subscribeInfo.GetAppNames(); +} + +void NotificationSubscribeInfo::AddAppName(const std::string appName) +{ + appNames_.push_back(appName); +} + +void NotificationSubscribeInfo::AddAppNames(const std::vector &appNames) +{ + appNames_.insert(appNames_.end(), appNames.begin(), appNames.end()); +} + +std::vector NotificationSubscribeInfo::GetAppNames() const +{ + return appNames_; +} + +bool NotificationSubscribeInfo::Marshalling(Parcel &parcel) const +{ + // write appNames_ + if (!parcel.WriteStringVector(appNames_)) { + ANS_LOGE("Can't write appNames_"); + return false; + } + return true; +} + +NotificationSubscribeInfo *NotificationSubscribeInfo::Unmarshalling(Parcel &parcel) +{ + NotificationSubscribeInfo *info = new NotificationSubscribeInfo(); + if (info && !info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + + return info; +} + +bool NotificationSubscribeInfo::ReadFromParcel(Parcel &parcel) +{ + parcel.ReadStringVector(&appNames_); + return true; +} + +std::string NotificationSubscribeInfo::Dump() +{ + return "Dump"; +} + +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/src/notification_subscriber.cpp b/kits/native/src/notification_subscriber.cpp new file mode 100644 index 000000000..cc16b2845 --- /dev/null +++ b/kits/native/src/notification_subscriber.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 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 "notification_subscriber.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { + +const sptr NotificationSubscriber::GetImpl() const +{ + return impl_; +} + +NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &subscriber) : subscriber_(subscriber) +{ + recipient_ = new DeathRecipient(*this); +}; + +void NotificationSubscriber::SubscriberImpl::OnSubscribeResult(NotificationConstant::SubscribeResult result) +{ + if (result == 0 && GetAnsManagerProxy()) { + proxy_->AsObject()->AddDeathRecipient(recipient_); + ANS_LOGD("%s, Add death recipient.", __func__); + } + subscriber_.OnSubscribeResult(result); +} + +void NotificationSubscriber::SubscriberImpl::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +{ + if (result == 0 && GetAnsManagerProxy()) { + proxy_->AsObject()->RemoveDeathRecipient(recipient_); + ANS_LOGD("%s, Remove death recipient.", __func__); + } + subscriber_.OnUnsubscribeResult(result); +} + +void NotificationSubscriber::SubscriberImpl::OnConsumed(const sptr ¬ification) +{ + subscriber_.OnConsumed(std::make_shared(*notification)); +} + +void NotificationSubscriber::SubscriberImpl::OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{ + subscriber_.OnConsumed( + std::make_shared(*notification), std::make_shared(*notificationMap)); +} + +void NotificationSubscriber::SubscriberImpl::OnCanceled(const sptr ¬ification) +{ + subscriber_.OnCanceled(std::make_shared(*notification)); +} + +void NotificationSubscriber::SubscriberImpl::OnCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) +{ + subscriber_.OnCanceled(std::make_shared(*notification), + std::make_shared(*notificationMap), + deleteReason); +} + +void NotificationSubscriber::SubscriberImpl::OnUpdated(const sptr ¬ificationMap) +{ + subscriber_.OnUpdate(std::make_shared(*notificationMap)); +} + +void NotificationSubscriber::SubscriberImpl::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +{ + subscriber_.OnDisturbModeChanged(mode); +} + +bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy() +{ + if (nullptr == proxy_) { + std::lock_guard lock(mutex_); + if (nullptr == proxy_) { + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + return false; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (!remoteObject) { + return false; + } + + proxy_ = iface_cast(remoteObject); + if ((nullptr == proxy_) || (nullptr == proxy_->AsObject())) { + return false; + } + } + } + + return true; +} + +NotificationSubscriber::SubscriberImpl::DeathRecipient::DeathRecipient(SubscriberImpl &subscriberImpl) + : subscriberImpl_(subscriberImpl){}; + +NotificationSubscriber::SubscriberImpl::DeathRecipient::~DeathRecipient(){}; + +void NotificationSubscriber::SubscriberImpl::DeathRecipient::OnRemoteDied(const wptr &object) +{ + subscriberImpl_.proxy_ = nullptr; + subscriberImpl_.subscriber_.OnDied(); +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/kits/native/src/notification_user_input.cpp b/kits/native/src/notification_user_input.cpp new file mode 100644 index 000000000..5c6e96027 --- /dev/null +++ b/kits/native/src/notification_user_input.cpp @@ -0,0 +1,320 @@ +/* + * Copyright (c); 2021 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 "notification_user_input.h" + +#include +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +void NotificationUserInput::SetInputsSource(AAFwk::Want &want, NotificationConstant::InputsSource source) +{ + want.SetParam(NotificationConstant::EXTRA_INPUTS_SOURCE, static_cast(source)); +} + +NotificationConstant::InputsSource NotificationUserInput::GetInputsSource(const AAFwk::Want &want) +{ + auto inputsSource = want.GetIntParam(NotificationConstant::EXTRA_INPUTS_SOURCE, + static_cast(NotificationConstant::InputsSource::FREE_FORM_INPUT)); + return static_cast(inputsSource); +} + +void NotificationUserInput::AddInputsToWant(const std::vector> &userInputs, + AAFwk::Want &want, const AppExecFwk::PacMap &pacMap) +{} + +std::shared_ptr NotificationUserInput::GetInputsFromWant(const AAFwk::Want &want) +{ + return {}; +} + +void NotificationUserInput::AddMimeInputToWant(const NotificationUserInput &userInput, AAFwk::Want &want, + const std::map> &results) +{} + +std::map> NotificationUserInput::GetMimeInputsFromWant( + const AAFwk::Want &want, const std::string &inputKey) +{ + return {}; +} + +std::shared_ptr NotificationUserInput::Create(const std::string &inputKey) +{ + if (inputKey.empty()) { + ANS_LOGE("The param of inputKey is empty"); + return {}; + } + + auto pUserInput = new (std::nothrow) NotificationUserInput(inputKey); + if (pUserInput == nullptr) { + ANS_LOGE("create NotificationUserInput object failed"); + return {}; + } + + return std::shared_ptr(pUserInput); +} + +std::shared_ptr NotificationUserInput::Create(const std::string &inputKey, + const std::string &tag, const std::vector &options, bool permitFreeFormInput, + const std::set &permitMimeTypes, const std::shared_ptr &pacMap, + NotificationConstant::InputEditType editType) +{ + if (inputKey.empty()) { + ANS_LOGE("The param of inputKey is empty"); + return {}; + } + + if (!permitFreeFormInput) { + if (editType == NotificationConstant::InputEditType::EDIT_ENABLED) { + ANS_LOGE("Setting editType to enable requires permitFreeFormInput to be set to true"); + return {}; + } + + if (options.empty() && permitMimeTypes.empty()) { + ANS_LOGE("options and permitMimeTypes cannot be empty at the same time"); + return {}; + } + } + + auto realPacMap = pacMap; + if (!realPacMap) { + realPacMap = std::make_shared(); + } + + auto pUserInput = new (std::nothrow) + NotificationUserInput(inputKey, tag, options, permitFreeFormInput, permitMimeTypes, realPacMap, editType); + if (pUserInput == nullptr) { + ANS_LOGE("create NotificationUserInput object failed"); + return {}; + } + + return std::shared_ptr(pUserInput); +} + +NotificationUserInput::NotificationUserInput(const std::string &inputKey) + : inputKey_(inputKey), pacMap_(std::make_shared()) +{} + +NotificationUserInput::NotificationUserInput(const std::string &inputKey, const std::string &tag, + const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, + const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType) + : inputKey_(inputKey), + tag_(tag), + options_(options), + permitFreeFormInput_(permitFreeFormInput), + permitMimeTypes_(permitMimeTypes), + pacMap_(pacMap), + editType_(editType) +{} + +std::string NotificationUserInput::GetInputKey() const +{ + return inputKey_; +} + +void NotificationUserInput::AddAdditionalData(AppExecFwk::PacMap &pacMap) +{ + pacMap_->PutAll(pacMap); +} + +const std::shared_ptr NotificationUserInput::GetAdditionalData() const +{ + return pacMap_; +} + +void NotificationUserInput::SetEditType(NotificationConstant::InputEditType inputEditType) +{ + editType_ = inputEditType; +} + +NotificationConstant::InputEditType NotificationUserInput::GetEditType() const +{ + return editType_; +} + +void NotificationUserInput::SetOptions(const std::vector &options) +{ + options_ = options; +} + +std::vector NotificationUserInput::GetOptions() const +{ + return options_; +} + +void NotificationUserInput::SetPermitMimeTypes(const std::string &mimeType, bool doPermit) +{ + if (mimeType.empty()) { + ANS_LOGE("The mimeType is invalid."); + return; + } + + if (doPermit) { + permitMimeTypes_.emplace(mimeType); + return; + } + + permitMimeTypes_.erase(mimeType); +} + +std::set NotificationUserInput::GetPermitMimeTypes() const +{ + return permitMimeTypes_; +} + +bool NotificationUserInput::IsMimeTypeOnly() const +{ + return !permitFreeFormInput_ && options_.empty() && !permitMimeTypes_.empty(); +} + +void NotificationUserInput::SetTag(const std::string tag) +{ + tag_ = tag; +} + +std::string NotificationUserInput::GetTag() const +{ + return tag_; +} + +void NotificationUserInput::SetPermitFreeFormInput(bool permitFreeFormInput) +{ + permitFreeFormInput_ = permitFreeFormInput; +} + +bool NotificationUserInput::IsPermitFreeFormInput() const +{ + return permitFreeFormInput_; +} + +std::string NotificationUserInput::Dump() +{ + return "NotificationUserInput[ inputKey = " + inputKey_ + " tag = " + tag_ + + " permitFreeFormInput = " + (permitFreeFormInput_ ? "true" : "false") + + " editType = " + std::to_string(static_cast(editType_)) + " ]"; +} + +bool NotificationUserInput::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(inputKey_)) { + ANS_LOGE("Failed to write inputKey"); + return false; + } + + if (!parcel.WriteString(tag_)) { + ANS_LOGE("Failed to write tag"); + return false; + } + + if (!parcel.WriteBool(permitFreeFormInput_)) { + ANS_LOGE("Failed to write flag permitFreeFormInput"); + return false; + } + + if (!parcel.WriteInt32(static_cast(editType_))) { + ANS_LOGE("Failed to write editType"); + return false; + } + + auto valid = pacMap_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether pacMap is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(pacMap_.get())) { + ANS_LOGE("Failed to write pacMap"); + return false; + } + } + + if (!parcel.WriteStringVector(options_)) { + ANS_LOGE("Failed to write options"); + return false; + } + + if (!parcel.WriteInt32(static_cast(permitMimeTypes_.size()))) { + ANS_LOGE("Failed to write the size of permitMimeTypes"); + return false; + } + + for (auto it = permitMimeTypes_.begin(); it != permitMimeTypes_.end(); ++it) { + if (!parcel.WriteString(*it)) { + ANS_LOGE("Failed to write permitMimeTypes"); + return false; + } + } + + return true; +} + +NotificationUserInput *NotificationUserInput::Unmarshalling(Parcel &parcel) +{ + auto pUserInput = new NotificationUserInput(); + if ((nullptr != pUserInput) && !pUserInput->ReadFromParcel(parcel)) { + delete pUserInput; + pUserInput = nullptr; + } + + return pUserInput; +} + +bool NotificationUserInput::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(inputKey_)) { + ANS_LOGE("Failed to read inputKey"); + return false; + } + + if (!parcel.ReadString(tag_)) { + ANS_LOGE("Failed to read tag"); + return false; + } + + permitFreeFormInput_ = parcel.ReadBool(); + + editType_ = static_cast(parcel.ReadInt32()); + + auto valid = parcel.ReadBool(); + if (valid) { + pacMap_ = std::shared_ptr(parcel.ReadParcelable()); + if (!pacMap_) { + ANS_LOGE("Failed to read pacMap"); + return false; + } + } + + if (!parcel.ReadStringVector(&options_)) { + ANS_LOGE("Failed to read options"); + return false; + } + + auto ssize = parcel.ReadInt32(); + for (auto it = 0; it < ssize; ++it) { + std::string member{}; + if (!parcel.ReadString(member)) { + ANS_LOGE("Failed to read permitMimeTypes"); + return false; + } + + permitMimeTypes_.emplace(member); + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/kits/native/wantagent/BUILD.gn b/kits/native/wantagent/BUILD.gn new file mode 100644 index 000000000..6dce5f3aa --- /dev/null +++ b/kits/native/wantagent/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") + +group("native_wantagent") { + deps = [ ":wantagent_kits" ] +} + +config("wantagent_kit_public_config") { + visibility = [ ":*" ] + + include_dirs = [ + "${innerkits_path}/core/include", + "${innerkits_path}/base/include", + "${kits_path}/native/wantagent/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + ] +} + +ohos_shared_library("wantagent_kits") { + include_dirs = [ + "//utils/native/base/include", + "//foundation/aafwk/standard/services/common/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//base/notification/ces_standard/cesfwk/innerkits/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + ] + + sources = [ + "src/completed_dispatcher.cpp", + "src/pending_want.cpp", + "src/trigger_info.cpp", + "src/want_agent.cpp", + "src/want_agent_helper.cpp", + "src/want_agent_info.cpp", + "src/want_agent_log_wrapper.cpp", + ] + + configs = [ "//utils/native/base:utils_config" ] + + public_configs = [ ":wantagent_kit_public_config" ] + + deps = [ + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_L2:samgr_proxy", + ] + + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/kits/native/wantagent/include/cancel_listener.h b/kits/native/wantagent/include/cancel_listener.h new file mode 100644 index 000000000..10cea7b5f --- /dev/null +++ b/kits/native/wantagent/include/cancel_listener.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H + +namespace OHOS::Notification::WantAgent { +class CancelListener { + /** + * Called when a Cancel operation as completed. + * + * @param resultCode The final result code determined by the Send. + */ +public: + virtual void OnCancelled(int resultCode) = 0; + virtual ~CancelListener() = default; +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H \ No newline at end of file diff --git a/kits/native/wantagent/include/completed_callback.h b/kits/native/wantagent/include/completed_callback.h new file mode 100644 index 000000000..5740a899d --- /dev/null +++ b/kits/native/wantagent/include/completed_callback.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H + +#include +#include +#include "want.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +class CompletedCallback { + + /** + * Called when a Send operation as completed. + * + * @param want The original Want that was sent. + * @param resultCode The final result code determined by the Send. + * @param resultData The final data collected by a broadcast. + * @param resultExtras The final extras collected by a broadcast. + */ +public: + virtual ~CompletedCallback() = default; + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) = 0; +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H \ No newline at end of file diff --git a/kits/native/wantagent/include/completed_dispatcher.h b/kits/native/wantagent/include/completed_dispatcher.h new file mode 100644 index 000000000..bd17fbecf --- /dev/null +++ b/kits/native/wantagent/include/completed_dispatcher.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H + +#include +#include +#include "completed_callback.h" +#include "event_handler.h" +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" + +namespace OHOS::Notification::WantAgent { +class PendingWant; +class CompletedDispatcher : public AAFwk::WantReceiverStub { +private: + const std::shared_ptr pendingWant_; + const std::shared_ptr callback_; + const std::shared_ptr handler_; + AAFwk::Want want_; + int resultCode_ = 0; + std::string resultData_; + AAFwk::WantParams resultExtras_; + +public: + CompletedDispatcher(const std::shared_ptr &pendingWant, + const std::shared_ptr &callback, const std::shared_ptr &handler); + virtual ~CompletedDispatcher() = default; + + void Send(const int32_t resultCode) override; + + void PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; + + void Run(); +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H \ No newline at end of file diff --git a/kits/native/wantagent/include/pending_want.h b/kits/native/wantagent/include/pending_want.h new file mode 100644 index 000000000..b86b1a3cb --- /dev/null +++ b/kits/native/wantagent/include/pending_want.h @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H + +#include +#include +#include +#include +#include "cancel_listener.h" +#include "context.h" +#include "completed_dispatcher.h" +#include "event_handler.h" +#include "want.h" +#include "want_agent_constant.h" +#include "want_receiver_stub.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +class PendingWant final : public std::enable_shared_from_this, public Parcelable { +public: + PendingWant(){}; + PendingWant(const sptr &target); + PendingWant(const sptr &target, const sptr whitelistToken); + virtual ~PendingWant() = default; + + WantAgentConstant::OperationType GetType(const sptr &target); + + /** + * Retrieve a PendingWant that will start a new ability. + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param want Want of the ability to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE}, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbility(const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags); + + /** + * Retrieve a PendingWant that will start a new ability + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param want Want of the ability to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * @param options Additional options for how the ability should be started. + * May be null if there are no options. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbility(const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags, + const std::shared_ptr &options); + + /** + * Like GetAbility(Context, int, Want, int)}, but allows an + * array of Wants to be supplied. The last Want in the array is + * taken as the primary key for the PendingWant, like the single Want + * given to GetAbility(Context, int, Want, int). + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param wants Array of Wants of the abilities to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags); + + /** + * Like GetAbility(Context, int, Want, int)}, but allows an + * array of Wants to be supplied. The last Want in the array is + * taken as the primary key for the PendingWant, like the single Want + * given to GetAbility(Context, int, Want, int). + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param wants Array of Wants of the abilities to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT} link #FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags, + const std::shared_ptr &options); + + /** + * Retrieve a PendingWant that will perform a common event. + * + * @param context The Context in which this PendingWant should perform + * the common event. + * @param requestCode Private request code for the sender + * @param want The Want to be common event. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetCommonEvent(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * Note that current user will be interpreted at the time the + * common event is sent, not when the pending want is created. + */ + static std::shared_ptr GetCommonEventAsUser(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, int uid); + + /** + * Retrieve a PendingWant that will start a service. + * + * @param context The Context in which this PendingWant should start + * the service. + * @param requestCode Private request code for the sender + * @param want An Want describing the service to be started. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + *FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetService(const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags); + + /** + * Retrieve a PendingWant that will start a foreground service. + * + * @param context The Context in which this PendingWant should start + * the service. + * @param requestCode Private request code for the sender + * @param want An Want describing the service to be started. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE . + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetForegroundService(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * @description: Marshals a Want into a Parcel. + * Fields in the Want are marshalled separately. If any field fails to be marshalled, false is returned. + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const; + + /** + * @description: Unmarshals a Want from a Parcel. + * Fields in the Want are unmarshalled separately. If any field fails to be unmarshalled, false is returned. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static PendingWant *Unmarshalling(Parcel &parcel); + + static bool Equals( + const std::shared_ptr &targetPendingWant, const std::shared_ptr &otherPendingWant); + + void Cancel(const sptr &target); + + void Send(const sptr &target); + + void Send(int resultCode, const sptr &target); + + void Send(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &target); + + void Send(int resultCode, const sptr &onCompleted, const sptr &target); + + void Send(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const sptr &target); + + void Send(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const std::string &requiredPermission, const sptr &target); + + void Send(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const std::string &requiredPermission, const std::shared_ptr &options, + const sptr &target); + + int SendAndReturnResult(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const std::string &requiredPermission, const std::shared_ptr &options, + const sptr &target); + + std::string GetBundleName(const sptr &target); + + int GetUid(const sptr &target); + + sptr GetTarget(); + + void SetTarget(const sptr &target); + + void RegisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target); + + void NotifyCancelListeners(int32_t resultCode); + + void UnregisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target); + + int GetHashCode(const sptr &target); + + std::shared_ptr GetWant(const sptr &target); + +private: + std::mutex lock_object; + sptr target_; + sptr cancelReceiver_; + sptr whitelistToken_; + std::vector> cancelListeners_; + + class CancelReceiver : public AAFwk::WantReceiverStub { + private: + std::weak_ptr outerInstance_; + + public: + explicit CancelReceiver(const std::weak_ptr &outerInstance); + virtual ~CancelReceiver() = default; + + void Send(const int32_t resultCode) override; + void PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; + }; + + static std::shared_ptr BuildServicePendingWant(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, + WantAgentConstant::OperationType serviceKind); +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H \ No newline at end of file diff --git a/kits/native/wantagent/include/trigger_info.h b/kits/native/wantagent/include/trigger_info.h new file mode 100644 index 000000000..9e6eff4e1 --- /dev/null +++ b/kits/native/wantagent/include/trigger_info.h @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H + +#include +#include +#include "want.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +class TriggerInfo final : public std::enable_shared_from_this { + /** + * Default constructor used to create a {@code TriggerInfo} instance. + * + */ +public: + TriggerInfo(); + + /** + * A constructor used to create a {@code TriggerInfo} instance based on the input parameters. + * + * @param permission Indicates the permission required for an {@link WantAgent} recipient. + * This parameter is valid only when the {@link WantAgent} is triggered to send common events. + * @param extraInfo Indicates the custom extra data you want to add for triggering an {@link WantAgent}. + * @param want Indicates the extra {@link ohos.aafwk.content.Want}. + * If {@code flags} in {@link WantAgentInfo} contains {@link WantAgentConstant.Flags#CONSTANT_FLAG}, + * this parameter is invalid. If flags contains {@link WantAgentConstant.Flags#REPLACE_ELEMENT}, + * {@link WantAgentConstant.Flags#REPLACE_ACTION}, {@link WantAgentConstant.Flags#REPLACE_URI}, + * {@link WantAgentConstant.Flags#REPLACE_ENTITIES}, and {@link WantAgentConstant.Flags#REPLACE_BUNDLE}, + * the {@code element}, {@code action}, {@code uri}, {@code entities}, and {@code bundleName} attributes of the + * {@link ohos.aafwk.content.Want} specified in this parameter will be used to replace the + * corresponding attributes in the original {@link ohos.aafwk.content.Want}, respectively. + * If this parameter is null, the original {@link ohos.aafwk.content.Want} remains unchanged. + * @param code Indicates the result code provided for the target of the {@link WantAgent}. + */ + TriggerInfo(const std::string &permission, const std::shared_ptr &extraInfo, + const std::shared_ptr &want, int resultCode); + + /** + * A constructor used to create a {@code TriggerInfo} instance by copying parameters from an existing one. + * + * @param paramInfo Indicates the existing {@code TriggerInfo} object. + */ + explicit TriggerInfo(const TriggerInfo ¶mInfo); + + /** + * Obtains the permission from the current {@code TriggerInfo} object. + * + * @return Returns the permission name. + */ + std::string GetPermission() const; + + /** + * Obtains the extra data from the {@code TriggerInfo} object. + * + * @return Returns the extra data. + */ + std::shared_ptr GetExtraInfo() const; + + /** + * Obtains the {@link ohos.aafwk.content.Want} used for triggering an {@link WantAgent}. + * + * @return Returns an {@link ohos.aafwk.content.Want} object. + */ + std::shared_ptr GetWant() const; + + /** + * Obtains the result code provided for the target of the {@link WantAgent}. + * + * @return Returns the result code provided for the target of the {@link WantAgent}. + */ + int GetResultCode() const; + + /** + * A builder class for {@link TriggerInfo} objects. + * + */ +public: + class Builder final : public std::enable_shared_from_this { + private: + std::string permission_; + std::shared_ptr params_; + std::shared_ptr want_; + int resultCode_ = 0; + + /** + * Default constructor used to create a {@code Builder} instance. + * + */ + public: + Builder(); + + /** + * Sets the permission that the {@link WantAgent} recipient must have. + * + * @param permission Indicates the permission to set. This parameter is valid only when the {@link WantAgent} + * to trigger is intended to send a common event. + * @return Returns this {@code Builder} object with the specified permission. + */ + std::shared_ptr SetPermission(const std::string &permission); + + /** + * Sets custom data. + * + * @param params Indicates the custom data to set. + * @return Returns this {@code Builder} object with the custom data. + */ + std::shared_ptr SetWantParams(const std::shared_ptr ¶ms); + + /** + * Sets a custom {@link ohos.aafwk.content.Want}. + * + * @param want Indicates the custom {@code Want} to set. If the member variable {@code flags} of the + * {@link WantAgentInfo} contains {@link WantAgentConstant.Flags#CONSTANT_FLAG}, this parameter does not + * take effect. If {@code flags} contains {@link WantAgentConstant.Flags#REPLACE_ELEMENT}, + * {@link WantAgentConstant.Flags#REPLACE_ACTION}, {@link WantAgentConstant.Flags#REPLACE_URI}, + * {@link WantAgentConstant.Flags#REPLACE_ENTITIES}, and {@link WantAgentConstant.Flags#REPLACE_BUNDLE}, + * the {@code element}, {@code action}, {@code uri}, {@code entities}, and {@code bundleName} attributes of the + * {@link ohos.aafwk.content.Want} specified in this parameter will be used to replace the corresponding + * attributes in the original {@link ohos.aafwk.content.Want}, respectively. If this parameter is null, the + * original {@link ohos.aafwk.content.Want} remains unchanged. + * @return Returns this {@code Builder} object with the custom {@code Want}. + */ + std::shared_ptr SetWant(const std::shared_ptr &want); + + /** + * Sets the result code provided for the target of the {@link WantAgent}. + * + * @param code Indicates the result code provided for the target of the {@link WantAgent}. + * @return Returns this {@code Builder} object with the specified result code. + */ + std::shared_ptr SetResultCode(int resultCode); + + /** + * Creates a {@link TriggerInfo} object using all of the settings. + * + * @return Returns the created {@code TriggerInfo} object. + */ + std::shared_ptr Build(); + }; + +private: + std::string permission_; + std::shared_ptr extraInfo_; + std::shared_ptr want_; + int resultCode_ = 0; +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H \ No newline at end of file diff --git a/kits/native/wantagent/include/want_agent.h b/kits/native/wantagent/include/want_agent.h new file mode 100644 index 000000000..6b8251f14 --- /dev/null +++ b/kits/native/wantagent/include/want_agent.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H + +#include +#include +#include "parcel.h" +#include "pending_want.h" +#include "want.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +class WantAgent final : public std::enable_shared_from_this, public Parcelable { +private: + std::shared_ptr pendingWant_; + + /** + * Constructor. + * + * @param obj The proxy object. + */ +public: + WantAgent(){}; + explicit WantAgent(const std::shared_ptr &pendingWant); + + /** + * Gets proxy obj. + * + * @return Return obj. + */ + std::shared_ptr GetPendingWant(); + + /** + * Sets proxy obj. + * + * @return Return obj. + */ + void SetPendingWant(const std::shared_ptr &pendingWant); + + /** + * @description: Marshals a Want into a Parcel. + * Fields in the Want are marshalled separately. If any field fails to be marshalled, false is returned. + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const; + + /** + * @description: Unmarshals a Want from a Parcel. + * Fields in the Want are unmarshalled separately. If any field fails to be unmarshalled, false is returned. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static WantAgent *Unmarshalling(Parcel &parcel); +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H \ No newline at end of file diff --git a/kits/native/wantagent/include/want_agent_constant.h b/kits/native/wantagent/include/want_agent_constant.h new file mode 100644 index 000000000..867be3a99 --- /dev/null +++ b/kits/native/wantagent/include/want_agent_constant.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H + +namespace OHOS::Notification::WantAgent { +/// +/// Provides enumerated constants that are used for setting object attributes in the methods provided by +/// . +/// +/// +class WantAgentConstant final { + /// + /// Enumerates flags for using an . + /// + /// +public: + enum class Flags { + /// + /// Indicates that the can be used only once. + /// + ONE_TIME_FLAG, + + /// + /// Indicates that {@code null} is returned if the does not exist. + /// + NO_BUILD_FLAG, + + /// + /// Indicates that the existing should be canceled before the new object is + /// generated. + /// + CANCEL_PRESENT_FLAG, + + /// + /// Indicates that the system only replaces the extra data of the existing + /// with that of the new object. + /// + UPDATE_PRESENT_FLAG, + + /// + /// Indicates that the created should be immutable. + /// + CONSTANT_FLAG, + + /// + /// Indicates that the current value of {@code element} can be replaced + /// when the is triggered. + /// + REPLACE_ELEMENT, + + /// + /// Indicates that the current value of {@code action} can be replaced + /// when the is triggered. + /// + REPLACE_ACTION, + + /// + /// Indicates that the current value of {@code uri} can be replaced when the is + /// triggered. + /// + REPLACE_URI, + + /// + /// Indicates that the current value of {@code entities} can be replaced + /// when the is triggered. + /// + REPLACE_ENTITIES, + + /// + /// Indicates that the current value of {@code bundleName} can be replaced + /// when the is triggered. + /// + REPLACE_BUNDLE + }; + + /// + /// Identifies the operation for using an , such as starting an ability or sending a + /// common event. + /// + /// +public: + enum class OperationType { + /// + /// Unknown operation. + /// + UNKNOWN_TYPE, + + /// + /// Starts an ability with a UI. + /// + START_ABILITY, + + /// + /// Starts multiple abilities. + /// + START_ABILITIES, + + /// + /// Starts an ability without a UI. + /// + START_SERVICE, + + /// + /// Sends a common event. + /// + SEND_COMMON_EVENT, + + /// + /// Starts a foreground ability without a UI. + /// + START_FOREGROUND_SERVICE + }; + +private: + WantAgentConstant(){}; +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H diff --git a/kits/native/wantagent/include/want_agent_helper.h b/kits/native/wantagent/include/want_agent_helper.h new file mode 100644 index 000000000..e217e5bdb --- /dev/null +++ b/kits/native/wantagent/include/want_agent_helper.h @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H + +#include +#include +#include "context.h" +#include "completed_callback.h" +#include "completed_dispatcher.h" +#include "event_handler.h" +#include "trigger_info.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_info.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +/** + * A helper class used to obtain, trigger, cancel, and compare WantAgent objects and to obtain + * the bundle name, UID, and hash code value of an WantAgent object. + * + */ + +static const int FLAG_ONE_SHOT = 1 << 30; +static const int FLAG_NO_CREATE = 1 << 29; +static const int FLAG_CANCEL_CURRENT = 1 << 28; +static const int FLAG_UPDATE_CURRENT = 1 << 27; +static const int FLAG_IMMUTABLE = 1 << 26; + +class WantAgentHelper final : public std::enable_shared_from_this { +private: + WantAgentHelper(); + + /** + * Obtains an WantAgent object. + * The WantAgent class does not have any constructor, and you can only use this method to create an + * WantAgent object. + * + * @param context Indicates the context of the caller. This parameter cannot be null. + * @param paramsInfo Indicates the WantAgentInfo object that contains parameters of the + * WantAgent object to create. + * @return Returns the created WantAgent object. + */ +public: + static std::shared_ptr GetWantAgent( + const std::shared_ptr &context, const WantAgentInfo ¶msInfo); + + /** + * Obtains an WantAgent object. + * + * The WantAgent class does not have any constructor, and you can only use this method to create an + * WantAgent object. + * + * @param paramsInfo Indicates the WantAgentInfo object that contains parameters of the + * WantAgent object to create. + * @return Returns the created WantAgent object. + */ + static std::shared_ptr GetWantAgent(const WantAgentInfo ¶msInfo); + + static WantAgentConstant::OperationType GetType(const std::shared_ptr &agent); + + /** + * Triggers an WantAgent. + * + * After this method is called, events associated with the specified WantAgent will be executed, + * such as starting an ability or sending a common event. + * + * @param context Indicates the context of the caller. This parameter cannot be null. + * @param agent Indicates the WantAgent to trigger. + * @param onCompleted Indicates the callback method to be called after the WantAgent is triggered. + * This parameter can be null. + * @param handler Indicates the thread for executing the callback indicated by OnCompleted. + * If this parameter is null, the callback method will be executed in a thread in the thread pool of + * the current process. + * @param paramsInfo Indicates the TriggerInfo object that contains triggering parameters. + */ + static void TriggerWantAgent(const std::shared_ptr &context, + const std::shared_ptr &agent, const std::shared_ptr &callback, + const TriggerInfo ¶msInfo); + + /** + * Cancels an WantAgent. + * + * Only the application that creates the WantAgent can cancel it. + * + * @param agent Indicates the WantAgent to cancel. + */ + static void Cancel(const std::shared_ptr &agent); + + /** + * Checks whether two WantAgent objects are the same. + * + * @param agent Indicates one of the WantAgent object to compare. + * @param otherAgent Indicates the other WantAgent object to compare. + * @return Returns true If the two objects are the same; returns false otherwise. + */ + static bool JudgeEquality(const std::shared_ptr &agent, const std::shared_ptr &otherAgent); + + /** + * Obtains the hash code value of an WantAgent. + * + * @param agent Indicates the antAgent whose hash code value is to be obtained. + * @return Returns the hash code value of the WantAgent. + */ + static int GetHashCode(const std::shared_ptr &agent); + + /** + * Obtains the bundle name of an WantAgent. + * + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + * @return Returns the bundle name of the WantAgent if any; returns {@code null} otherwise. + */ + static std::string GetBundleName(const std::shared_ptr &agent); + + /** + * Obtains the user ID (UID) of an WantAgent. + * + * @param agent Indicates the WantAgent whose UID is to be obtained. + * @return Returns the UID of the WantAgent if any; returns -1} otherwise. + */ + static int GetUid(const std::shared_ptr &agent); + + /** + * Obtains the Want WantAgent. + * + * @param agent Indicates the WantAgent whose Want is to be obtained. + * @return Returns the Want of the WantAgent. + */ + static std::shared_ptr GetWant(const std::shared_ptr &agent); + + static void RegisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + + static void UnregisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + +private: + static void Send(const std::shared_ptr &context, + const std::shared_ptr &pendingWant, WantAgentConstant::OperationType type, + const sptr &callBack, const TriggerInfo ¶msInfo); + + static unsigned int FlagsTransformer(const std::vector &flags); +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H \ No newline at end of file diff --git a/kits/native/wantagent/include/want_agent_info.h b/kits/native/wantagent/include/want_agent_info.h new file mode 100644 index 000000000..168443c26 --- /dev/null +++ b/kits/native/wantagent/include/want_agent_info.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H + +#include +#include +#include "want.h" +#include "want_agent_constant.h" +#include "want_params.h" + +namespace OHOS::Notification::WantAgent { +/** + * A parametric class that contains the parameters required by WantAgentHelper GetWantAgent. + * + * This class is used to encapsulate parameters requestCode, operationType, + * flag, Wants, and extraInfo. It is used as the input parameter for + * the WantAgentHelper GetWantAgent method. + * + */ +class WantAgentInfo final : public std::enable_shared_from_this { +private: + int requestCode_ = 0; + WantAgentConstant::OperationType operationType_ = WantAgentConstant::OperationType::UNKNOWN_TYPE; + std::vector flags_ = std::vector(); + std::vector> wants_ = std::vector>(); + std::shared_ptr extraInfo_; + + /** + * Default constructor used to create an empty WantAgentInfo instance. + * + */ +public: + WantAgentInfo(); + ~WantAgentInfo() = default; + + /** + * A constructor used to create an WantAgentInfo instance based on the input parameters. + * + * @param requestCode Indicates the request code to set. It is a private value defined by the user. + * @param operationType Indicates the type of the operation to be performed by the WantAgent object. + * For details about the value range, see WantAgentConstant.OperationType. + * @param flag Indicates the flag for handling the WantAgent. + * For details about the value range, see WantAgentConstant.Flags. + * @param Wants Indicates the collection of Want objects to be used for creating the WantAgent + * object. The number of Wants in the collection is determined by WantAgentConstant.OperationType. + * @param extraInfo Indicates the extra information to be used for creating the WantAgent object. + */ + WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, WantAgentConstant::Flags flag, + std::vector> &Wants, const std::shared_ptr &extraInfo); + + /** + * A constructor used to create an WantAgentInfo instance based on the input parameters. + * + * @param requestCode Indicates the request code to set. It is a private value defined by the user. + * @param operationType Indicates the type of the operation to be performed by the WantAgent object. + * For details about the value range, see WantAgentConstant.OperationType. + * @param flags Indicates the flags for handling the WantAgent. + * For details about the value range, see WantAgentConstant.Flags. + * @param Wants Indicates the collection of Want objects to be used for creating the WantAgent + * object. The number of Wants in the collection is determined by WantAgentConstant.OperationType. + * @param extraInfo Indicates the extra information to be used for creating the WantAgent object. + */ + WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + const std::vector &flags, std::vector> &Wants, + const std::shared_ptr &extraInfo); + + /** + * A constructor used to create an WantAgentInfo instance by copying parameters from an existing one. + * + * @param paramInfo Indicates the existing WantAgentInfo object. + */ + explicit WantAgentInfo(const std::shared_ptr ¶mInfo); + + /** + * Obtains the requestCode of the WantAgent object. + * + * @return Returns the requestCode of the WantAgent object. + */ + int GetRequestCode() const; + + /** + * Obtains the operationType of the WantAgent object. + * + * @return Returns the operationType of the WantAgent object. + */ + WantAgentConstant::OperationType GetOperationType() const; + + /** + * Obtains the flag of the WantAgent object. + * + * @return Returns the flag of the WantAgent object. + */ + std::vector GetFlags() const; + + /** + * Obtains the collection of all Wants of the WantAgent object. + * + * @return Returns the collection of all Wants of the WantAgent object. + */ + std::vector> GetWants() const; + + /** + * Obtains the extra information of the WantAgent object. + * + * @return Returns the extra information of the WantAgent object. + */ + std::shared_ptr GetExtraInfo() const; +}; +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H \ No newline at end of file diff --git a/kits/native/wantagent/include/want_agent_log_wrapper.h b/kits/native/wantagent/include/want_agent_log_wrapper.h new file mode 100644 index 000000000..1ecaab5e1 --- /dev/null +++ b/kits/native/wantagent/include/want_agent_log_wrapper.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H + +#include "hilog/log.h" +#include + +namespace OHOS::Notification::WantAgent { +#ifndef LOG_DOMAIN +#define LOG_DOMAIN 0xD001100 +#endif +#ifndef APP_LOG_TAG +#define APP_LOG_TAG NULL +#endif + +enum class WantAgentLogLevel { DEBUG = 0, INFO, WARN, ERROR, FATAL }; + +static constexpr OHOS::HiviewDFX::HiLogLabel Want_Agent_LABEL = {LOG_CORE, LOG_DOMAIN, APP_LOG_TAG}; + +class WantAgentLogWrapper { +public: + static bool JudgeLevel(const WantAgentLogLevel &level); + + static void SetLogLevel(const WantAgentLogLevel &level) + { + level_ = level; + } + + static const WantAgentLogLevel &GetLogLevel() + { + return level_; + } + + static std::string GetBriefFileName(const char *str); + +private: + static WantAgentLogLevel level_; +}; + +#define PRINT_LOG(LEVEL, Level, fmt, ...) \ + if (WantAgentLogWrapper::JudgeLevel(WantAgentLogLevel::LEVEL)) \ + OHOS::HiviewDFX::HiLog::Level(Want_Agent_LABEL, \ + "[%{public}s(%{public}s)] " fmt, \ + WantAgentLogWrapper::GetBriefFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + ##__VA_ARGS__) + +#define WANT_AGENT_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +} // namespace OHOS::Notification::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H diff --git a/kits/native/wantagent/src/completed_dispatcher.cpp b/kits/native/wantagent/src/completed_dispatcher.cpp new file mode 100644 index 000000000..44ceed2db --- /dev/null +++ b/kits/native/wantagent/src/completed_dispatcher.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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 "completed_dispatcher.h" + +namespace OHOS::Notification::WantAgent { +CompletedDispatcher::CompletedDispatcher(const std::shared_ptr &pendingWant, + const std::shared_ptr &callback, const std::shared_ptr &handler) + : pendingWant_(pendingWant), callback_(callback), handler_(handler) +{} + +void CompletedDispatcher::Send(const int32_t resultCode) +{} + +void CompletedDispatcher::PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) +{ + want_ = want; + resultCode_ = resultCode; + resultData_ = data; + resultExtras_ = extras; + if (handler_ == nullptr) { + Run(); + } +} + +void CompletedDispatcher::Run() +{ + if (callback_ != nullptr) { + callback_->OnSendFinished(want_, resultCode_, resultData_, resultExtras_); + } +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/src/pending_want.cpp b/kits/native/wantagent/src/pending_want.cpp new file mode 100644 index 000000000..a65cc57b9 --- /dev/null +++ b/kits/native/wantagent/src/pending_want.cpp @@ -0,0 +1,413 @@ +/* + * Copyright (c) 2021 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 "pending_want.h" +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "pending_want_record.h" +#include "want_agent_log_wrapper.h" +#include "want_sender_info.h" + +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; + +namespace OHOS::Notification::WantAgent { +PendingWant::PendingWant(const sptr &target) + : target_(target), cancelReceiver_(nullptr), whitelistToken_(nullptr) +{} + +PendingWant::PendingWant(const sptr &target, const sptr whitelistToken) + : target_(target), cancelReceiver_(nullptr), whitelistToken_(whitelistToken) +{} + +WantAgentConstant::OperationType PendingWant::GetType(const sptr &target) +{ + int32_t operationType = 0; + AbilityManagerClient::GetInstance()->GetPendingWantType(target, operationType); + return (WantAgentConstant::OperationType)operationType; +} + +std::shared_ptr PendingWant::GetAbility( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return GetAbility(context, requestCode, want, flags, nullptr); +} + +std::shared_ptr PendingWant::GetAbility(const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags, const std::shared_ptr &options) +{ + WANT_AGENT_LOGI("PendingWant::GetAbility begin."); + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetAbility invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + wantsInfo.want = *want; + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + if (options != nullptr) { + wantsInfo.want.SetParams(*options); + } + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::START_ABILITY; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = 0; + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + WANT_AGENT_LOGI("PendingWant::GetAbility end."); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, int requestCode, + std::vector> &wants, unsigned int flags) +{ + return GetAbilities(context, requestCode, wants, flags, nullptr); +} + +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, int requestCode, + std::vector> &wants, unsigned int flags, const std::shared_ptr &options) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetAbilities invalid input param."); + return nullptr; + } + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::START_ABILITIES; + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = 0; + wantSenderInfo.requestCode = requestCode; + for (auto want : wants) { + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + if (options != nullptr) { + wantsInfo.want.SetParams(*options); + } + wantSenderInfo.allWants.push_back(wantsInfo); + } + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetCommonEvent( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return GetCommonEventAsUser(context, requestCode, want, flags, 0); +} + +std::shared_ptr PendingWant::GetCommonEventAsUser(const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags, int uid) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetCommonEventAsUser invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::SEND_COMMON_EVENT; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = 0; + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetService( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return BuildServicePendingWant(context, requestCode, want, flags, WantAgentConstant::OperationType::START_SERVICE); +} + +std::shared_ptr PendingWant::GetForegroundService( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return BuildServicePendingWant( + context, requestCode, want, flags, WantAgentConstant::OperationType::START_FOREGROUND_SERVICE); +} + +std::shared_ptr PendingWant::BuildServicePendingWant(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, + WantAgentConstant::OperationType serviceKind) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::BuildServicePendingWant invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)serviceKind; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = 0; + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +void PendingWant::Cancel(const sptr &target) +{ + AbilityManagerClient::GetInstance()->CancelWantSender(target); +} + +void PendingWant::Send(const sptr &target) +{ + Send(nullptr, 0, nullptr, nullptr, "", nullptr, target); +} + +void PendingWant::Send(int resultCode, const sptr &target) +{ + Send(nullptr, resultCode, nullptr, nullptr, "", nullptr, target); +} + +void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, + const sptr &target) +{ + Send(context, resultCode, want, nullptr, "", nullptr, target); +} + +void PendingWant::Send( + int resultCode, const sptr &onCompleted, const sptr &target) +{ + Send(nullptr, resultCode, nullptr, onCompleted, "", nullptr, target); +} + +void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const sptr &target) +{ + Send(context, resultCode, want, onCompleted, "", nullptr, target); +} + +void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const sptr &target) +{ + Send(context, resultCode, want, onCompleted, requiredPermission, nullptr, target); +} + +void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if (SendAndReturnResult(context, resultCode, want, onCompleted, requiredPermission, options, target) != 0) { + WANT_AGENT_LOGE("PendingWant::SendAndReturnResult failed."); + } +} + +int PendingWant::SendAndReturnResult(const std::shared_ptr &context, int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const std::string &requiredPermission, const std::shared_ptr &options, + const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::SendAndReturnResult invalid input param."); + return 1; + } + + SenderInfo senderInfo; + senderInfo.resolvedType = want != nullptr ? want->GetType() : ""; + if (want != nullptr) { + senderInfo.want = *want; + } + if (options != nullptr) { + senderInfo.want.SetParams(*options); + } + senderInfo.requiredPermission = requiredPermission; + senderInfo.code = resultCode; + senderInfo.finishedReceiver = onCompleted; + + return AbilityManagerClient::GetInstance()->SendWantSender(target, senderInfo); +} + +bool PendingWant::Equals( + const std::shared_ptr &targetPendingWant, const std::shared_ptr &otherPendingWant) +{ + if (targetPendingWant == nullptr && otherPendingWant == nullptr) { + return true; + } + if (targetPendingWant == nullptr || otherPendingWant == nullptr) { + return false; + } + return targetPendingWant->GetHashCode(targetPendingWant->GetTarget()) == + targetPendingWant->GetHashCode(otherPendingWant->GetTarget()); +} + +sptr PendingWant::GetTarget() +{ + return target_; +} + +void PendingWant::SetTarget(const sptr &target) +{ + target_ = target; +} + +PendingWant::CancelReceiver::CancelReceiver(const std::weak_ptr &outerInstance) + : outerInstance_(outerInstance) +{} + +void PendingWant::CancelReceiver::PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) +{} + +void PendingWant::CancelReceiver::Send(const int32_t resultCode) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (outerInstance_.lock() != nullptr) { + outerInstance_.lock()->NotifyCancelListeners(resultCode); + } +} + +void PendingWant::RegisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (cancelListener == nullptr) { + WANT_AGENT_LOGE("PendingWant::RegisterCancelListener invalid input param."); + return; + } + std::scoped_lock lock(lock_object); + if (cancelReceiver_ == nullptr) { + cancelReceiver_ = new (std::nothrow) CancelReceiver(weak_from_this()); + } + bool isEmpty = cancelListeners_.empty(); + cancelListeners_.push_back(cancelListener); + if (isEmpty) { + AbilityManagerClient::GetInstance()->RegisterCancelListener(target, cancelReceiver_); + } +} + +void PendingWant::NotifyCancelListeners(int32_t resultCode) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + std::vector> cancelListeners; + { + std::scoped_lock lock(lock_object); + cancelListeners = std::vector>(cancelListeners_); + } + for (auto cancelListener : cancelListeners) { + if (cancelListener != nullptr) { + cancelListener->OnCancelled(resultCode); + } + } +} + +void PendingWant::UnregisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (cancelListener == nullptr) { + WANT_AGENT_LOGE("PendingWant::UnregisterCancelListener invalid input param."); + return; + } + + std::scoped_lock lock(lock_object); + bool isEmpty = cancelListeners_.empty(); + cancelListeners_.erase(remove_if(cancelListeners_.begin(), + cancelListeners_.end(), + [cancelListener](std::shared_ptr x) { return x == cancelListener; }), + cancelListeners_.end()); + if (cancelListeners_.empty() && !isEmpty) { + AbilityManagerClient::GetInstance()->UnregisterCancelListener(target, cancelReceiver_); + } +} + +int PendingWant::GetHashCode(const sptr &target) +{ + int32_t code = -1; + AbilityManagerClient::GetInstance()->GetPendingWantCode(target, code); + return code; +} + +int PendingWant::GetUid(const sptr &target) +{ + int32_t uid = -1; + AbilityManagerClient::GetInstance()->GetPendingWantUid(target, uid); + return uid; +} + +std::string PendingWant::GetBundleName(const sptr &target) +{ + std::string bundleName = ""; + AbilityManagerClient::GetInstance()->GetPendingWantBundleName(target, bundleName); + return bundleName; +} + +std::shared_ptr PendingWant::GetWant(const sptr &target) +{ + std::shared_ptr want = std::make_shared(); + int ret = AbilityManagerClient::GetInstance()->GetPendingRequestWant(target, want); + return ret ? nullptr : want; +} + +bool PendingWant::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(target_->AsObject())) { + WANT_AGENT_LOGE("parcel WriteString failed"); + return false; + } + + return true; +} + +PendingWant *PendingWant::Unmarshalling(Parcel &parcel) +{ + PendingWant *pendingWant = new (std::nothrow) PendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("read from parcel failed"); + delete pendingWant; + pendingWant = nullptr; + } + sptr target = iface_cast(parcel.ReadParcelable()); + if (target == nullptr) { + return nullptr; + } + pendingWant->SetTarget(target); + + return pendingWant; +} + +} // namespace OHOS::Notification::WantAgent diff --git a/kits/native/wantagent/src/trigger_info.cpp b/kits/native/wantagent/src/trigger_info.cpp new file mode 100644 index 000000000..1e5763b34 --- /dev/null +++ b/kits/native/wantagent/src/trigger_info.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 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 "trigger_info.h" + +using namespace OHOS::AAFwk; + +namespace OHOS::Notification::WantAgent { +TriggerInfo::TriggerInfo() : permission_(""), extraInfo_(nullptr), want_(nullptr), resultCode_(0) +{} + +TriggerInfo::TriggerInfo(const std::string &permission, const std::shared_ptr &extraInfo, + const std::shared_ptr &want, int resultCode) +{ + permission_ = permission; + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } + if (want != nullptr) { + want_ = std::make_shared(*want); + } + resultCode_ = resultCode; +} + +TriggerInfo::TriggerInfo(const TriggerInfo ¶mInfo) +{ + permission_ = paramInfo.GetPermission(); + if (paramInfo.GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo.GetExtraInfo()); + } + if (paramInfo.GetWant() != nullptr) { + want_ = std::make_shared(*paramInfo.GetWant()); + } + resultCode_ = paramInfo.GetResultCode(); +} + +std::string TriggerInfo::GetPermission() const +{ + return permission_; +} + +std::shared_ptr TriggerInfo::GetExtraInfo() const +{ + return extraInfo_; +} + +std::shared_ptr TriggerInfo::GetWant() const +{ + return want_; +} + +int TriggerInfo::GetResultCode() const +{ + return resultCode_; +} + +TriggerInfo::Builder::Builder() +{} + +std::shared_ptr TriggerInfo::Builder::SetPermission(const std::string &permission) +{ + permission_ = permission; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetWantParams(const std::shared_ptr ¶ms) +{ + params_ = params; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetWant(const std::shared_ptr &want) +{ + want_ = want; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetResultCode(int resultCode) +{ + resultCode_ = resultCode; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::Build() +{ + return std::make_shared(permission_, params_, want_, resultCode_); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/src/want_agent.cpp b/kits/native/wantagent/src/want_agent.cpp new file mode 100644 index 000000000..0cf03073a --- /dev/null +++ b/kits/native/wantagent/src/want_agent.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 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 "want_agent.h" +#include "want_agent_log_wrapper.h" + +namespace OHOS::Notification::WantAgent { +WantAgent::WantAgent(const std::shared_ptr &pendingWant) +{ + pendingWant_ = pendingWant; +} + +std::shared_ptr WantAgent::GetPendingWant() +{ + return pendingWant_; +} + +void WantAgent::SetPendingWant(const std::shared_ptr &pendingWant) +{ + pendingWant_ = pendingWant; +} + +bool WantAgent::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(pendingWant_.get())) { + WANT_AGENT_LOGE("parcel WriteString failed"); + return false; + } + + return true; +} + +WantAgent *WantAgent::Unmarshalling(Parcel &parcel) +{ + WantAgent *agent = new (std::nothrow) WantAgent(); + if (agent == nullptr) { + WANT_AGENT_LOGE("read from parcel failed"); + delete agent; + agent = nullptr; + } + std::shared_ptr pendingWant(parcel.ReadParcelable()); + agent->SetPendingWant(pendingWant); + + return agent; +} +} // namespace OHOS::Notification::WantAgent diff --git a/kits/native/wantagent/src/want_agent_helper.cpp b/kits/native/wantagent/src/want_agent_helper.cpp new file mode 100644 index 000000000..2a59abfc5 --- /dev/null +++ b/kits/native/wantagent/src/want_agent_helper.cpp @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2021 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 "want_agent_helper.h" +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "pending_want.h" +#include "want_agent_log_wrapper.h" +#include "want_sender_interface.h" +#include "want_sender_info.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS::Notification::WantAgent { +WantAgentHelper::WantAgentHelper() +{} + +unsigned int WantAgentHelper::FlagsTransformer(const std::vector &flags) +{ + unsigned int wantFlags = 0; + if (flags.empty()) { + return wantFlags; + } + + for (auto flag : flags) { + switch (flag) { + case WantAgentConstant::Flags::ONE_TIME_FLAG: + wantFlags |= FLAG_ONE_SHOT; + break; + case WantAgentConstant::Flags::NO_BUILD_FLAG: + wantFlags |= FLAG_NO_CREATE; + break; + case WantAgentConstant::Flags::CANCEL_PRESENT_FLAG: + wantFlags |= FLAG_CANCEL_CURRENT; + break; + case WantAgentConstant::Flags::UPDATE_PRESENT_FLAG: + wantFlags |= FLAG_UPDATE_CURRENT; + break; + case WantAgentConstant::Flags::CONSTANT_FLAG: + wantFlags |= FLAG_IMMUTABLE; + break; + default: + WANT_AGENT_LOGE("WantAgentHelper::flags is error."); + break; + } + } + return wantFlags; +} + +std::shared_ptr WantAgentHelper::GetWantAgent( + const std::shared_ptr &context, const WantAgentInfo ¶msInfo) +{ + WANT_AGENT_LOGI("WantAgentHelper::GetWantAgent begin."); + if (context == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + std::vector> wants = paramsInfo.GetWants(); + if (wants.empty() || paramsInfo.GetFlags().size() != wants.size()) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + HILOG_INFO("%{public}s:bundle name = %{public}s; ability name = %{public}s", + __func__, + wants[0]->GetElement().GetBundleName().c_str(), + wants[0]->GetElement().GetAbilityName().c_str()); + + unsigned int flags = FlagsTransformer(paramsInfo.GetFlags()); + if (flags == 0) { + WANT_AGENT_LOGE("WantAgentHelper::flags invalid."); + return nullptr; + } + + std::shared_ptr extraInfo = paramsInfo.GetExtraInfo(); + std::shared_ptr pendingWant = nullptr; + int requestCode = paramsInfo.GetRequestCode(); + WantAgentConstant::OperationType operationType = paramsInfo.GetOperationType(); + switch (operationType) { + case WantAgentConstant::OperationType::START_ABILITY: + pendingWant = PendingWant::GetAbility(context, requestCode, wants[0], flags, extraInfo); + break; + case WantAgentConstant::OperationType::START_ABILITIES: + pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags, extraInfo); + break; + case WantAgentConstant::OperationType::START_SERVICE: + pendingWant = PendingWant::GetService(context, requestCode, wants[0], flags); + break; + case WantAgentConstant::OperationType::START_FOREGROUND_SERVICE: + pendingWant = PendingWant::GetForegroundService(context, requestCode, wants[0], flags); + break; + case WantAgentConstant::OperationType::SEND_COMMON_EVENT: + pendingWant = PendingWant::GetCommonEvent(context, requestCode, wants[0], flags); + break; + default: + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent operation type is error."); + break; + } + + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent the wants does not meet the requirements."); + return nullptr; + } + + std::shared_ptr agent = std::make_shared(pendingWant); + WANT_AGENT_LOGI("WantAgentHelper::GetWantAgent end."); + return agent; +} + +std::shared_ptr WantAgentHelper::GetWantAgent(const WantAgentInfo ¶msInfo) +{ + std::vector> wants = paramsInfo.GetWants(); + if (wants.empty() || (paramsInfo.GetFlags().size() != wants.size())) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + std::shared_ptr want = wants[0]; + if (want == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + wantsInfo.want = *want; + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + if (paramsInfo.GetExtraInfo() != nullptr) { + wantsInfo.want.SetParams(*paramsInfo.GetExtraInfo()); + } + + HILOG_INFO("%{public}s:bundle name = %{public}s; ability name = %{public}s", + __func__, + wantsInfo.want.GetElement().GetBundleName().c_str(), + wantsInfo.want.GetElement().GetAbilityName().c_str()); + + WantSenderInfo wantSenderInfo; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = want->GetOperation().GetBundleName(); + wantSenderInfo.flags = FlagsTransformer(paramsInfo.GetFlags()); + + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + if (target == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent target is nullptr."); + return nullptr; + } + std::shared_ptr agent = std::make_shared(std::make_shared(target)); + + return agent; +} + +WantAgentConstant::OperationType WantAgentHelper::GetType(const std::shared_ptr &agent) +{ + if (agent == nullptr || agent->GetPendingWant() == nullptr) { + return WantAgentConstant::OperationType::UNKNOWN_TYPE; + } + + return agent->GetPendingWant()->GetType(agent->GetPendingWant()->GetTarget()); +} + +void WantAgentHelper::TriggerWantAgent(const std::shared_ptr &context, const std::shared_ptr &agent, + const std::shared_ptr &callback, const TriggerInfo ¶msInfo) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if ((context == nullptr) || (agent == nullptr)) { + WANT_AGENT_LOGE("WantAgentHelper::TriggerWantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + WantAgentConstant::OperationType type = GetType(agent); + sptr dispatcher = nullptr; + if (callback != nullptr) { + dispatcher = new (std::nothrow) CompletedDispatcher(pendingWant, callback, nullptr); + } + + Send(context, pendingWant, type, dispatcher, paramsInfo); +} + +void WantAgentHelper::Send(const std::shared_ptr &context, const std::shared_ptr &pendingWant, + WantAgentConstant::OperationType type, const sptr &callBack, const TriggerInfo ¶msInfo) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if ((context == nullptr) || (pendingWant == nullptr)) { + WANT_AGENT_LOGE("WantAgentHelper::Send invalid input param."); + return; + } + + pendingWant->Send(context, + paramsInfo.GetResultCode(), + paramsInfo.GetWant(), + callBack, + paramsInfo.GetPermission(), + paramsInfo.GetExtraInfo(), + pendingWant->GetTarget()); +} + +void WantAgentHelper::Cancel(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::Cancel WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::Cancel PendingWant invalid input param."); + return; + } + + pendingWant->Cancel(pendingWant->GetTarget()); +} + +bool WantAgentHelper::JudgeEquality( + const std::shared_ptr &agent, const std::shared_ptr &otherAgent) +{ + if ((agent == nullptr) && (otherAgent == nullptr)) { + return true; + } + + if ((agent == nullptr) || (otherAgent == nullptr)) { + return false; + } + + return PendingWant::Equals(agent->GetPendingWant(), otherAgent->GetPendingWant()); +} + +int WantAgentHelper::GetHashCode(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetHashCode WantAgent invalid input param."); + return 0; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetHashCode PendingWant invalid input param."); + return 0; + } + + return pendingWant->GetHashCode(pendingWant->GetTarget()); +} + +std::string WantAgentHelper::GetBundleName(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetBundleName WantAgent invalid input param."); + return ""; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetBundleName PendingWant invalid input param."); + return ""; + } + + return pendingWant->GetBundleName(pendingWant->GetTarget()); +} + +int WantAgentHelper::GetUid(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetUid WantAgent invalid input param."); + return -1; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetUid PendingWant invalid input param."); + return -1; + } + + return pendingWant->GetUid(pendingWant->GetTarget()); +} + +std::shared_ptr WantAgentHelper::GetWant(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + return nullptr; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + return nullptr; + } + + return pendingWant->GetWant(pendingWant->GetTarget()); +} + +void WantAgentHelper::RegisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + return; + } + + pendingWant->RegisterCancelListener(cancelListener, pendingWant->GetTarget()); +} + +void WantAgentHelper::UnregisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + return; + } + + pendingWant->UnregisterCancelListener(cancelListener, pendingWant->GetTarget()); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/src/want_agent_info.cpp b/kits/native/wantagent/src/want_agent_info.cpp new file mode 100644 index 000000000..4d66a12ae --- /dev/null +++ b/kits/native/wantagent/src/want_agent_info.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c); 2021 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 "want_agent_info.h" +#include "want.h" +#include "want_params.h" + +using namespace OHOS::AAFwk; + +namespace OHOS::Notification::WantAgent { +WantAgentInfo::WantAgentInfo() : WantAgentInfo(nullptr) +{} + +WantAgentInfo::WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + WantAgentConstant::Flags flag, std::vector> &wants, + const std::shared_ptr &extraInfo) +{ + requestCode_ = requestCode; + operationType_ = operationType; + flags_.push_back(flag); + if (!wants.empty()) { + for (auto want : wants) { + if (want != nullptr) { + wants_.push_back(std::make_shared(*want)); + } + } + } + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } +} + +WantAgentInfo::WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + const std::vector &flags, std::vector> &wants, + const std::shared_ptr &extraInfo) +{ + requestCode_ = requestCode; + operationType_ = operationType; + if (!flags.empty()) { + flags_.insert(flags_.end(), flags.begin(), flags.end()); + } + if (!wants.empty()) { + for (auto want : wants) { + if (want != nullptr) { + wants_.push_back(std::make_shared(*want)); + } + } + } + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } +} + +WantAgentInfo::WantAgentInfo(const std::shared_ptr ¶mInfo) +{ + if (paramInfo != nullptr) { + requestCode_ = paramInfo->GetRequestCode(); + operationType_ = paramInfo->GetOperationType(); + flags_.insert(flags_.end(), paramInfo->GetFlags().begin(), paramInfo->GetFlags().end()); + if (!paramInfo->GetWants().empty()) { + for (auto want : paramInfo->GetWants()) { + wants_.push_back(std::make_shared(*want)); + } + } + if (paramInfo->GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo->GetExtraInfo()); + } + } +} + +int WantAgentInfo::GetRequestCode() const +{ + return requestCode_; +} + +WantAgentConstant::OperationType WantAgentInfo::GetOperationType() const +{ + return operationType_; +} + +std::vector WantAgentInfo::GetFlags() const +{ + return flags_; +} + +std::vector> WantAgentInfo::GetWants() const +{ + return wants_; +} + +std::shared_ptr WantAgentInfo::GetExtraInfo() const +{ + return extraInfo_; +} + +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/src/want_agent_log_wrapper.cpp b/kits/native/wantagent/src/want_agent_log_wrapper.cpp new file mode 100644 index 000000000..059ffb295 --- /dev/null +++ b/kits/native/wantagent/src/want_agent_log_wrapper.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 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 "want_agent_log_wrapper.h" +#include + +namespace OHOS::Notification::WantAgent { +// initial static member object +WantAgentLogLevel WantAgentLogWrapper::level_ = WantAgentLogLevel::DEBUG; + +bool WantAgentLogWrapper::JudgeLevel(const WantAgentLogLevel &level) +{ + const WantAgentLogLevel &curLevel = WantAgentLogWrapper::GetLogLevel(); + if (level < curLevel) { + return false; + } + return true; +} + +std::string WantAgentLogWrapper::GetBriefFileName(const char *str) +{ + if (!str) { + return std::string(); + } + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + if (pos == std::string::npos) { + return std::string(); + } + return fullPath.substr(pos + 1); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/BUILD.gn b/kits/native/wantagent/test/BUILD.gn new file mode 100644 index 000000000..9c2a2b1cc --- /dev/null +++ b/kits/native/wantagent/test/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2021 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. + +group("unittest") { + testonly = true + + deps = [ + "unittest/completed_dispatcher_test:unittest", + "unittest/pending_want_test:unittest", + "unittest/trigger_Info_test:unittest", + "unittest/want_agent_helper_test:unittest", + "unittest/want_agent_info_test:unittest", + "unittest/want_agent_test:unittest", + ] +} diff --git a/kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn b/kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn new file mode 100644 index 000000000..64fc48665 --- /dev/null +++ b/kits/native/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("completed_dispatcher_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + + sources = [ "completed_dispatcher_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":completed_dispatcher_test" ] +} diff --git a/kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp b/kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp new file mode 100644 index 000000000..2dfb828e1 --- /dev/null +++ b/kits/native/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2021 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 +#include "completed_callback.h" +#define private public +#define protected public +#include "completed_dispatcher.h" +#undef private +#undef protected +#include "element_name.h" +#include "event_handler.h" +#include "pending_want.h" +#include "ohos/aafwk/base/base_types.h" +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class CompletedDispatcherTest : public testing::Test { +public: + CompletedDispatcherTest() + {} + ~CompletedDispatcherTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName); + + class CompletedCallbackSon : public CompletedCallback { + /** + * Called when a Send operation as completed. + * + * @param want The original Want that was sent. + * @param resultCode_ The final result code determined by the Send. + * @param resultData The final data collected by a broadcast. + * @param resultExtras The final extras collected by a broadcast. + */ + public: + void OnSendFinished(const AAFwk::Want &want, int resultCode_, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override; + static int code; + }; +}; + +int CompletedDispatcherTest::CompletedCallbackSon::code = 0; + +void CompletedDispatcherTest::CompletedCallbackSon::OnSendFinished( + const AAFwk::Want &want, int resultCode_, const std::string &resultData, const AAFwk::WantParams &resultExtras) +{ + code = 100; +} + +Want CompletedDispatcherTest::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + return want; +} + +void CompletedDispatcherTest::SetUpTestCase(void) +{} + +void CompletedDispatcherTest::TearDownTestCase(void) +{} + +void CompletedDispatcherTest::SetUp(void) +{} + +void CompletedDispatcherTest::TearDown(void) +{} + +/* + * @tc.number : CompletedDispatcher_0100 + * @tc.name : CompletedDispatcher Constructors + * @tc.desc : 1.The parameter is nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0100, Function | MediumTest | Level1) +{ + CompletedDispatcher completedDispatcher(nullptr, nullptr, nullptr); + EXPECT_EQ(completedDispatcher.pendingWant_, nullptr); + EXPECT_EQ(completedDispatcher.callback_, nullptr); + EXPECT_EQ(completedDispatcher.handler_, nullptr); +} + +/* + * @tc.number : CompletedDispatcher_0200 + * @tc.name : CompletedDispatcher Constructors + * @tc.desc : 1.The parameter is not nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0200, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + EXPECT_EQ(completedDispatcher.pendingWant_, nullptr); + EXPECT_EQ(completedDispatcher.callback_, callBack); + EXPECT_EQ(completedDispatcher.handler_, nullptr); +} + +/* + * @tc.number : CompletedDispatcher_0300 + * @tc.name : CompletedDispatcher PerformReceive + * @tc.desc : 1.The parameter is not nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0300, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + + Want want = MakeWant("device", "ability", "bundleName"); + std::string key = "key"; + bool value = true; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + completedDispatcher.PerformReceive(want, 10, "test", wParams, 0, 0, 1); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(completedDispatcher.resultCode_, 10); + EXPECT_EQ(completedDispatcher.resultData_, "test"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(completedDispatcher.resultExtras_.GetParam(key))), value); + EXPECT_EQ(CompletedCallbackSon::code, 100); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0400 + * @tc.name : CompletedDispatcher PerformReceive + * @tc.desc : 1.The parameter is not nullptr + * 2.called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0400, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + std::shared_ptr handler = std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, handler); + + Want want = MakeWant("device", "ability", "bundleName"); + std::string key = "key"; + bool value = false; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + completedDispatcher.PerformReceive(want, 10, "test", wParams, 0, 0, 1); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(completedDispatcher.resultCode_, 10); + EXPECT_EQ(completedDispatcher.resultData_, "test"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(completedDispatcher.resultExtras_.GetParam(key))), value); + EXPECT_EQ(CompletedCallbackSon::code, 0); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0500 + * @tc.name : CompletedDispatcher Run + * @tc.desc : 1.The parameter is not nullptr + * 2.called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0500, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + EXPECT_EQ(completedDispatcher.callback_, callBack); + completedDispatcher.Run(); + EXPECT_EQ(CompletedCallbackSon::code, 100); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0600 + * @tc.name : CompletedDispatcher Run + * @tc.desc : 1.The parameter is nullptr + * 2.no called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0600, Function | MediumTest | Level1) +{ + CompletedDispatcher completedDispatcher(nullptr, nullptr, nullptr); + EXPECT_EQ(completedDispatcher.callback_, nullptr); + completedDispatcher.Run(); + EXPECT_EQ(CompletedCallbackSon::code, 0); + CompletedCallbackSon::code = 0; +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn b/kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn new file mode 100644 index 000000000..7a5f16587 --- /dev/null +++ b/kits/native/wantagent/test/unittest/pending_want_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("pending_want_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//utils/system/safwk/native/include", + "//utils/native/base/include", + ] + + sources = [ "pending_want_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":pending_want_test" ] +} diff --git a/kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp new file mode 100644 index 000000000..1fd7b5c73 --- /dev/null +++ b/kits/native/wantagent/test/unittest/pending_want_test/pending_want_test.cpp @@ -0,0 +1,723 @@ +/* + * Copyright (c) 2021 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 +#include "ability_context.h" +#include "ability_manager_client.h" +#include "cancel_listener.h" +#include "completed_callback.h" +#include "completed_dispatcher.h" +#include "context.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "iservice_registry.h" +#include "ohos/aafwk/base/base_types.h" +#define private public +#define protected public +#include "pending_want.h" +#undef private +#undef protected +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "want.h" +#include "wants_info.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_agent_helper.h" +#include "want_sender_info.h" +#include "want_sender_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class PendingWantTest : public testing::Test { +public: + PendingWantTest() + {} + ~PendingWantTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName); + + static int callBackCancelListenerConnt; + + class CompletedCallbackSon : public CompletedCallback { + /** + * Called when a Send operation as completed. + * + * @param want The original Want that was sent. + * @param resultCode The final result code determined by the Send. + * @param resultData The final data collected by a broadcast. + * @param resultExtras The final extras collected by a broadcast. + */ + public: + void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override; + static int code; + }; + + class WantSender : public AAFwk::WantSenderStub { + public: + virtual void Send(SenderInfo &senderInfo) override; + }; + + class CancelListenerSon : public CancelListener { + public: + virtual void OnCancelled(int resultCode) override; + }; +}; + +int PendingWantTest::CompletedCallbackSon::code = 0; +int PendingWantTest::callBackCancelListenerConnt = 0; + +void PendingWantTest::CompletedCallbackSon::OnSendFinished( + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) +{ + code = 100; +} + +void PendingWantTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void PendingWantTest::CancelListenerSon::OnCancelled(int resultCode) +{ + callBackCancelListenerConnt++; +} + +Want PendingWantTest::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + return want; +} + +void PendingWantTest::SetUpTestCase(void) +{} + +void PendingWantTest::TearDownTestCase(void) +{} + +void PendingWantTest::SetUp(void) +{} + +void PendingWantTest::TearDown(void) +{} + +/* + * @tc.number : PendingWant_0100 + * @tc.name : PendingWant Constructors + * @tc.desc : 1.The parameter is nullptr + */ +HWTEST_F(PendingWantTest, PendingWant_0100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + EXPECT_EQ(pendingWant.target_, nullptr); + EXPECT_EQ(pendingWant.cancelReceiver_, nullptr); + EXPECT_EQ(pendingWant.whitelistToken_, nullptr); +} + +/* + * @tc.number : PendingWant_0200 + * @tc.name : PendingWant Constructors + * @tc.desc : 1.The parameter target is not nullptr + */ +HWTEST_F(PendingWantTest, PendingWant_0200, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + PendingWant pendingWant(target); + EXPECT_EQ(pendingWant.target_, target); + EXPECT_EQ(pendingWant.cancelReceiver_, nullptr); + EXPECT_EQ(pendingWant.whitelistToken_, nullptr); +} + +/* + * @tc.number : PendingWant_0300 + * @tc.name : PendingWant GetType + * @tc.desc : 1.Get PendingWant Type (UNKNOWN_TYPE) + */ +HWTEST_F(PendingWantTest, PendingWant_0300, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + PendingWant pendingWant(target); + EXPECT_EQ(pendingWant.target_, target); + EXPECT_EQ(pendingWant.GetType(target), WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : PendingWant_0400 + * @tc.name : PendingWant GetAbility + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0400, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbility(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0500 + * @tc.name : PendingWant GetAbility + * @tc.desc : 1.Get pendingWant (START_ABILITY) + */ +HWTEST_F(PendingWantTest, PendingWant_0500, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0600 + * @tc.name : PendingWant GetAbility + * @tc.desc : 1.Get pendingWant (options is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0600, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags, wParams); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0700 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0700, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities(nullptr, requestCode, wants, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0800 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (context is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0900 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (options is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0900, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags, wParams); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1000 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1000, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(nullptr, requestCode, want, flags, 0); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1100 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (context is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1100, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1200 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1200, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want; + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1300 + * @tc.name : PendingWant GetService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1300, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want; + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetService(context, requestCode, want, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1400 + * @tc.name : PendingWant GetService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1400, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetService(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1500 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1500, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want; + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetForegroundService(context, requestCode, want, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1600 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1600, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetForegroundService(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1700 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1700, Function | MediumTest | Level1) +{ + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want; + int flags = 1; + flags |= FLAG_NO_CREATE; + WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + std::shared_ptr pendingWant = + PendingWant::BuildServicePendingWant(context, requestCode, want, flags, type); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1800 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1800, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + int flags = 1; + flags |= FLAG_NO_CREATE; + WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + std::shared_ptr pendingWant = + PendingWant::BuildServicePendingWant(nullptr, requestCode, want, flags, type); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1900 + * @tc.name : PendingWant Equals + * @tc.desc : 1.Equals + */ +HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + sptr target2(nullptr); + std::shared_ptr pendingWant2 = std::make_shared(target2); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); +} + +/* + * @tc.number : PendingWant_2000 + * @tc.name : PendingWant Equals + * @tc.desc : 1.Equals + */ +HWTEST_F(PendingWantTest, PendingWant_2000, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2(nullptr); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); +} + +/* + * @tc.number : PendingWant_2100 + * @tc.name : PendingWant SendAndReturnResult + * @tc.desc : SendAndReturnResult + */ +HWTEST_F(PendingWantTest, PendingWant_2100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr context = std::make_shared(); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::shared_ptr wParams = std::make_shared(); + std::string key = "key"; + wParams->SetParam(key, Boolean::Box(value)); + int flags = 1; + flags |= FLAG_NO_CREATE; + AbilityManagerClient::GetInstance()->Connect(); + EXPECT_EQ(INNER_ERR, + pendingWant.SendAndReturnResult(context, requestCode, want, nullptr, "Permission", nullptr, nullptr)); +} + +/* + * @tc.number : PendingWant_2200 + * @tc.name : PendingWant SendAndReturnResult + * @tc.desc : SendAndReturnResult + */ +HWTEST_F(PendingWantTest, PendingWant_2200, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::shared_ptr wParams = std::make_shared(); + std::string key = "key"; + wParams->SetParam(key, Boolean::Box(value)); + int flags = 1; + flags |= FLAG_NO_CREATE; + AbilityManagerClient::GetInstance()->Connect(); + EXPECT_EQ(1, pendingWant.SendAndReturnResult(nullptr, requestCode, want, nullptr, "Permission", nullptr, nullptr)); +} + +/* + * @tc.number : PendingWant_2300 + * @tc.name : PendingWant Equals + * @tc.desc : Equals + */ +HWTEST_F(PendingWantTest, PendingWant_2300, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2 = std::make_shared(target); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); +} + +/* + * @tc.number : PendingWant_2400 + * @tc.name : PendingWant GetTarget + * @tc.desc : 1.GetTarget + */ +HWTEST_F(PendingWantTest, PendingWant_2400, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + auto target = pendingWant.GetTarget(); + EXPECT_EQ(target, nullptr); +} + +/* + * @tc.number : PendingWant_2500 + * @tc.name : PendingWant GetTarget + * @tc.desc : 1.GetTarget + */ +HWTEST_F(PendingWantTest, PendingWant_2500, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + PendingWant pendingWant(target); + auto target1 = pendingWant.GetTarget(); + EXPECT_EQ(target1, target); +} + +/* + * @tc.number : PendingWant_2600 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2600, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 2); +} + +/* + * @tc.number : PendingWant_2700 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2700, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); +} + +/* + * @tc.number : PendingWant_2800 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2800, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_2900 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_2900, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 2); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3000 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_3000, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 1); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3100 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_3100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 0); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3200 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3200, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 2); + pendingWant.UnregisterCancelListener(cancelListener1, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); +} + +/* + * @tc.number : PendingWant_3300 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3300, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); + pendingWant.UnregisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_3400 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3400, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.UnregisterCancelListener(nullptr, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_3500 + * @tc.name : PendingWant GetWant + * @tc.desc : 1.GetWant + */ +HWTEST_F(PendingWantTest, PendingWant_3500, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + auto want = pendingWant.GetWant(nullptr); + EXPECT_EQ(want, nullptr); +} + +/* + * @tc.number : PendingWant_3600 + * @tc.name : PendingWant Equals + * @tc.desc : Equals + */ +HWTEST_F(PendingWantTest, PendingWant_3700, Function | MediumTest | Level1) +{ + std::shared_ptr pendingWant(nullptr); + std::shared_ptr pendingWant2(nullptr); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn b/kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn new file mode 100644 index 000000000..f4d9729ef --- /dev/null +++ b/kits/native/wantagent/test/unittest/trigger_Info_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("trigger_Info_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + + sources = [ "trigger_Info_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":trigger_Info_test" ] +} diff --git a/kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp b/kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp new file mode 100644 index 000000000..0fb2e984f --- /dev/null +++ b/kits/native/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 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 + +#include "completed_callback.h" +#include "event_handler.h" +#include "element_name.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#define private public +#define protected public +#include "trigger_info.h" +#undef private +#undef protected +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class TriggerInfoTest : public testing::Test { +public: + TriggerInfoTest() + {} + ~TriggerInfoTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void TriggerInfoTest::SetUpTestCase(void) +{} + +void TriggerInfoTest::TearDownTestCase(void) +{} + +void TriggerInfoTest::SetUp(void) +{} + +void TriggerInfoTest::TearDown(void) +{} + +/* + * @tc.number : TriggerInfo_0100 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.def Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0100, Function | MediumTest | Level1) +{ + TriggerInfo triggerInfo; + EXPECT_EQ(triggerInfo.permission_, ""); + EXPECT_EQ(triggerInfo.extraInfo_, nullptr); + EXPECT_EQ(triggerInfo.want_, nullptr); + EXPECT_EQ(triggerInfo.resultCode_, 0); +} + +/* + * @tc.number : TriggerInfo_0200 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.def Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0200, Function | MediumTest | Level1) +{ + std::string permission = "nihao"; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int resultCode = 10; + TriggerInfo triggerInfo(permission, wParams, want, resultCode); + EXPECT_EQ(triggerInfo.permission_, permission); + EXPECT_NE(triggerInfo.extraInfo_, wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo.want_, want); + EXPECT_EQ(triggerInfo.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo.resultCode_, resultCode); +} + +/* + * @tc.number : TriggerInfo_0300 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.copy Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0300, Function | MediumTest | Level1) +{ + std::string permission = "nihao"; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int resultCode = 10; + TriggerInfo triggerInfo(permission, wParams, want, resultCode); + EXPECT_EQ(triggerInfo.permission_, permission); + EXPECT_NE(triggerInfo.extraInfo_, wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo.want_, want); + EXPECT_EQ(triggerInfo.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo.resultCode_, resultCode); + TriggerInfo triggerInfo1(triggerInfo); + EXPECT_EQ(triggerInfo1.permission_, triggerInfo.permission_); + EXPECT_NE(triggerInfo1.extraInfo_, triggerInfo.extraInfo_); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo1.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo1.want_, triggerInfo.want_); + EXPECT_EQ(triggerInfo1.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo1.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo1.resultCode_, triggerInfo.resultCode_); +} + +/* + * @tc.number : TriggerInfo_0400 + * @tc.name : TriggerInfo::Builder SetPermission + * @tc.desc : 1.SetPermission + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0400, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + builder->SetPermission("nihao"); + EXPECT_EQ(builder->permission_, "nihao"); +} + +/* + * @tc.number : TriggerInfo_0500 + * @tc.name : TriggerInfo::Builder SetWantParams + * @tc.desc : 1.SetWantParams + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0500, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + builder->SetWantParams(wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(builder->params_->GetParam(key))), value); +} + +/* + * @tc.number : TriggerInfo_0600 + * @tc.name : TriggerInfo::Builder SetWant + * @tc.desc : 1.SetWant + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0600, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + builder->SetWant(want); + EXPECT_EQ(builder->want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(builder->want_->GetElement().GetAbilityName(), "abilityName"); +} + +/* + * @tc.number : TriggerInfo_0700 + * @tc.name : TriggerInfo::Builder SetResultCode + * @tc.desc : 1.SetResultCode + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0700, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + int resultCode = 100; + builder->SetResultCode(resultCode); + EXPECT_EQ(builder->resultCode_, resultCode); +} + +/* + * @tc.number : TriggerInfo_0800 + * @tc.name : TriggerInfo::Builder Build + * @tc.desc : 1.Build,Great TriggerInfo object + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0800, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + builder->SetPermission("nihao"); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + builder->SetWantParams(wParams); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + builder->SetWant(want); + int resultCode = 100; + builder->SetResultCode(resultCode); + + auto info = builder->Build(); + EXPECT_NE(info, nullptr); + EXPECT_EQ(info->permission_, "nihao"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(info->extraInfo_->GetParam(key))), value); + EXPECT_EQ(info->want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(info->want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(info->resultCode_, resultCode); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn b/kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn new file mode 100644 index 000000000..c3faf5baf --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_helper_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_helper_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + + sources = [ "want_agent_helper_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_helper_test" ] +} diff --git a/kits/native/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp b/kits/native/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp new file mode 100644 index 000000000..957123078 --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp @@ -0,0 +1,712 @@ +/* + * Copyright (c) 2021 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_constant.h" +#define private public +#define protected public +#include "want_agent_helper.h" +#include "want_agent_info.h" +#undef private +#undef protected +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class WantAgentHelperTest : public testing::Test { +public: + WantAgentHelperTest() + {} + ~WantAgentHelperTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + virtual void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentHelperTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentHelperTest::SetUpTestCase(void) +{} + +void WantAgentHelperTest::TearDownTestCase(void) +{} + +void WantAgentHelperTest::SetUp(void) +{} + +void WantAgentHelperTest::TearDown(void) +{} + +/* + * @tc.number : WantAgentHelper_0100 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::ONE_TIME_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::ONE_TIME_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x40000000)); +} + +/* + * @tc.number : WantAgentHelper_0200 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::NO_BUILD_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::NO_BUILD_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x20000000)); +} + +/* + * @tc.number : WantAgentHelper_0300 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CANCEL_PRESENT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CANCEL_PRESENT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x10000000)); +} + +/* + * @tc.number : WantAgentHelper_0400 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::UPDATE_PRESENT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x8000000)); +} + +/* + * @tc.number : WantAgentHelper_0500 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CONSTANT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x4000000)); +} + +/* + * @tc.number : WantAgentHelper_0600 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::REPLACE_BUNDLE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + EXPECT_EQ( + wantAgentHelper->FlagsTransformer(flags), static_cast(WantAgentConstant::Flags::ONE_TIME_FLAG)); +} + +/* + * @tc.number : WantAgentHelper_0700 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CONSTANT_FLAG | UPDATE_PRESENT_FLAG | REPLACE_BUNDLE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + flags.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + flags.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0xc000000)); +} + +/* + * @tc.number : WantAgentHelper_0800 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + WantAgentInfo wantAgentInfo; + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_0900 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * ` 2.wantAgentInfo.wants_ empty + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.clear(); + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1000 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() != wantAgentInfo.flags_.siez() + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + WantAgentInfo wantAgentInfo; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.clear(); + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1100 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return 0 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + WantAgentInfo wantAgentInfo; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1200 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_ABILITY + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_ABILITY; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1300 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_ABILITIES + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_ABILITIES; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1400 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_SERVICE; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1500 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_FOREGROUND_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1600 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_FOREGROUND_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::SEND_COMMON_EVENT; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1700 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is 100 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1800 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_.siez() == 0 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.clear(); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1900 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() != wantAgentInfo.flags_.siez() + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.clear(); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2000 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(nullptr); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2100 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is not nullptr + * 4.wantAgentInfo.extraInfo_ is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + wantAgentInfo.extraInfo_ = wParams; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2200 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is not nullptr + * 4.wantAgentInfo.extraInfo_ is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + wantAgentInfo.extraInfo_ = nullptr; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2300 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2400 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2500 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr,PendingWant is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2600 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + std::shared_ptr wantAgent2(nullptr); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, true); +} + +/* + * @tc.number : WantAgentHelper_2700 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2(nullptr); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, false); +} + +/* + * @tc.number : WantAgentHelper_2800 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2 = std::make_shared(pendingWant); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, true); +} + +/* + * @tc.number : WantAgentHelper_2900 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2 = std::make_shared(pendingWant2); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, false); +} + +/* + * @tc.number : WantAgentHelper_3000 + * @tc.name : WantAgentHelper GetHashCode + * @tc.desc : 1.GetHashCode WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto hashCode = wantAgentHelper->GetHashCode(wantAgent); + EXPECT_EQ(hashCode, 0); +} + +/* + * @tc.number : WantAgentHelper_3100 + * @tc.name : WantAgentHelper GetHashCode + * @tc.desc : 1.GetHashCode WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto hashCode = wantAgentHelper->GetHashCode(wantAgent); + EXPECT_EQ(hashCode, 0); +} + +/* + * @tc.number : WantAgentHelper_3200 + * @tc.name : WantAgentHelper GetBundleName + * @tc.desc : 1.GetBundleName WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto bundleName = wantAgentHelper->GetBundleName(wantAgent); + EXPECT_EQ(bundleName, ""); +} + +/* + * @tc.number : WantAgentHelper_3300 + * @tc.name : WantAgentHelper GetBundleName + * @tc.desc : 1.GetBundleName WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto bundleName = wantAgentHelper->GetBundleName(wantAgent); + EXPECT_EQ(bundleName, ""); +} + +/* + * @tc.number : WantAgentHelper_3400 + * @tc.name : WantAgentHelper GetUid + * @tc.desc : 1.GetUid WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto uid = wantAgentHelper->GetUid(wantAgent); + EXPECT_EQ(uid, -1); +} + +/* + * @tc.number : WantAgentHelper_3500 + * @tc.name : WantAgentHelper GetUid + * @tc.desc : 1.GetUid WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto uid = wantAgentHelper->GetUid(wantAgent); + EXPECT_EQ(uid, -1); +} + +/* + * @tc.number : WantAgentHelper_3600 + * @tc.name : WantAgentHelper GetWant + * @tc.desc : 1.GetWant WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto want = wantAgentHelper->GetWant(wantAgent); + EXPECT_EQ(want, nullptr); +} + +/* + * @tc.number : WantAgentHelper_3700 + * @tc.name : WantAgentHelper GetWant + * @tc.desc : 1.GetWant WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto want = wantAgentHelper->GetWant(wantAgent); + EXPECT_EQ(want, nullptr); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn b/kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn new file mode 100644 index 000000000..979db4d11 --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_info_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_info_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + + sources = [ "want_agent_info_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_info_test" ] +} diff --git a/kits/native/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp b/kits/native/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp new file mode 100644 index 000000000..bdf8d1384 --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2021 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_constant.h" +#include "want_agent_helper.h" +#define private public +#define protected public +#include "want_agent_info.h" +#undef private +#undef protected +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class WantAgentInfoTest : public testing::Test { +public: + WantAgentInfoTest() + {} + ~WantAgentInfoTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + virtual void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentInfoTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentInfoTest::SetUpTestCase(void) +{} + +void WantAgentInfoTest::TearDownTestCase(void) +{} + +void WantAgentInfoTest::SetUp(void) +{} + +void WantAgentInfoTest::TearDown(void) +{} + +/* + * @tc.number : WantAgentInfo_0100 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0100, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flag, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0200 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0200, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0300 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Copy Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0300, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); + + WantAgentInfo wantAgentInfo1(wantAgentInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), wantAgentInfo1.GetRequestCode()); + EXPECT_EQ(wantAgentInfo->GetOperationType(), wantAgentInfo1.GetOperationType()); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), wantAgentInfo1.GetFlags().at(0)); + EXPECT_NE(wantAgentInfo->GetWants().at(0), wantAgentInfo1.GetWants().at(0)); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), + wantAgentInfo1.GetWants().at(0)->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), + wantAgentInfo1.GetWants().at(0)->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), wantAgentInfo1.GetExtraInfo()); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(wantAgentInfo1.GetExtraInfo()->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0400 + * @tc.name : WantAgentInfo GetRequestCode + * @tc.desc : 1.GetRequestCode + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0400, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); +} + +/* + * @tc.number : WantAgentInfo_0500 + * @tc.name : WantAgentInfo GetOperationType + * @tc.desc : 1.GetOperationType + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0500, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); +} + +/* + * @tc.number : WantAgentInfo_0600 + * @tc.name : WantAgentInfo GetFlags + * @tc.desc : 1.GetFlags + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0600, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); +} + +/* + * @tc.number : WantAgentInfo_0700 + * @tc.name : WantAgentInfo GetWants + * @tc.desc : 1.GetWants + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0700, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); +} + +/* + * @tc.number : WantAgentInfo_0800 + * @tc.name : WantAgentInfo GetWants + * @tc.desc : 1.GetWants + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0800, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn b/kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn new file mode 100644 index 000000000..50feeea16 --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_test/BUILD.gn @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_test") { + module_out_path = module_output_path + include_dirs = [ + "${kits_path}/native/include", + "${kits_path}/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + ] + + sources = [ "want_agent_test.cpp" ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}:ans_innerkits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_test" ] +} diff --git a/kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp b/kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp new file mode 100644 index 000000000..5eab24b3b --- /dev/null +++ b/kits/native/wantagent/test/unittest/want_agent_test/want_agent_test.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#define private public +#define protected public +#include "want_agent.h" +#undef private +#undef protected +#include "want_agent_constant.h" +#include "want_agent_helper.h" +#include "want_agent_info.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Notification::WantAgent; +using vector_str = std::vector; + +namespace OHOS::Notification::WantAgent { +class WantAgentTest : public testing::Test { +public: + WantAgentTest() + {} + ~WantAgentTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + virtual void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentTest::SetUpTestCase(void) +{} + +void WantAgentTest::TearDownTestCase(void) +{} + +void WantAgentTest::SetUp(void) +{} + +void WantAgentTest::TearDown(void) +{} + +/* + * @tc.number : WantAgent_0100 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors and GetPendingWant + */ +HWTEST_F(WantAgentTest, WantAgent_0100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgent = std::make_shared(nullptr); + EXPECT_EQ(wantAgent->GetPendingWant(), nullptr); +} + +/* + * @tc.number : WantAgent_0200 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors and GetPendingWant + */ +HWTEST_F(WantAgentTest, WantAgent_0200, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + EXPECT_EQ(wantAgent->GetPendingWant(), pendingWant); +} +} // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/kits/wantAgent/BUILD.gn b/kits/wantAgent/BUILD.gn new file mode 100644 index 000000000..f492bb887 --- /dev/null +++ b/kits/wantAgent/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("wantagent") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//foundation/aafwk/standard/services/common/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//base/notification/ans_standard/kits/native/wantagent/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context", + "//third_party/libuv/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/services/common/include", + "./", + ] + + sources = [ + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp", + "napi_want_agent.cpp", + "native_module.cpp", + ] + + deps = [ + "//base/notification/ans_standard/kits/native:ans_kits", + "//base/notification/ans_standard/kits/native/wantagent:wantagent_kits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/kits/wantAgent/napi_want_agent.cpp b/kits/wantAgent/napi_want_agent.cpp new file mode 100644 index 000000000..fa5d3de14 --- /dev/null +++ b/kits/wantAgent/napi_want_agent.cpp @@ -0,0 +1,1742 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_want_agent.h" + +#include +#include +#include +#include +#include + +#include "hilog_wrapper.h" +#include "ohos/aafwk/base/base_interfaces.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/base_object.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" + +#include "want_wrapper.h" +#include "want_agent_helper.h" + +namespace OHOS { + +constexpr int32_t BUSINESS_ERROR_CODE_OK = 0; + +TriggerCompleteCallBack::TriggerCompleteCallBack() +{} + +TriggerCompleteCallBack::~TriggerCompleteCallBack() +{} + +void TriggerCompleteCallBack::SetCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + triggerCompleteInfo_.env = env; + triggerCompleteInfo_.ref = ref; +} + +void TriggerCompleteCallBack::SetWantAgentInstance(const std::shared_ptr &wantAgent) +{ + triggerCompleteInfo_.wantAgent = wantAgent; +} + +void TriggerCompleteCallBack::OnSendFinished( + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) +{ + HILOG_INFO("TriggerCompleteCallBack::OnSendFinished start"); + if (triggerCompleteInfo_.ref == nullptr) { + HILOG_INFO("triggerCompleteInfo_ CallBack is nullptr"); + return; + } + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(triggerCompleteInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_INFO("uv_work_t instance is nullptr"); + return; + } + TriggerReceiveDataWorker *dataWorker = new (std::nothrow) TriggerReceiveDataWorker(); + if (dataWorker == nullptr) { + HILOG_INFO("TriggerReceiveDataWorker instance is nullptr"); + return; + } + dataWorker->want = want; + dataWorker->resultCode = resultCode; + dataWorker->resultData = resultData; + dataWorker->resultExtras = resultExtras; + dataWorker->env = triggerCompleteInfo_.env; + dataWorker->ref = triggerCompleteInfo_.ref; + dataWorker->wantAgent = triggerCompleteInfo_.wantAgent; + work->data = (void *)dataWorker; + uv_queue_work(loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + TriggerReceiveDataWorker *dataWorkerData = (TriggerReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + HILOG_INFO("TriggerReceiveDataWorker instance(uv_work_t) is nullptr"); + return; + } + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(dataWorkerData->env, BUSINESS_ERROR_CODE_OK); + napi_create_object(dataWorkerData->env, &result[1]); + // wrap wantAgent + napi_value jsWantAgent = nullptr; + napi_wrap(dataWorkerData->env, + jsWantAgent, + (void *)dataWorkerData->wantAgent.get(), + [](napi_env env, void *data, void *hint) {}, + nullptr, + nullptr); + napi_set_named_property(dataWorkerData->env, result[1], "wantAgent", jsWantAgent); + // wrap want + napi_value jsWant; + jsWant = WrapWant(dataWorkerData->want, dataWorkerData->env); + napi_set_named_property(dataWorkerData->env, result[1], "want", jsWant); + // wrap finalCode + napi_value jsFinalCode; + napi_create_int32(dataWorkerData->env, dataWorkerData->resultCode, &jsFinalCode); + napi_set_named_property(dataWorkerData->env, result[1], "finalCode", jsFinalCode); + // wrap finalData + napi_value jsFinalData; + napi_create_string_utf8( + dataWorkerData->env, dataWorkerData->resultData.c_str(), NAPI_AUTO_LENGTH, &jsFinalData); + napi_set_named_property(dataWorkerData->env, result[1], "finalData", jsFinalCode); + // wrap extraInfo + napi_value jsExtraInfo; + jsExtraInfo = WrapWantParam(dataWorkerData->resultExtras, dataWorkerData->env); + napi_set_named_property(dataWorkerData->env, result[1], "extraInfo", jsExtraInfo); + + napi_get_undefined(dataWorkerData->env, &undefined); + napi_get_reference_value(dataWorkerData->env, dataWorkerData->ref, &callback); + napi_call_function(dataWorkerData->env, undefined, callback, 2, &result[0], &callResult); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; + }); + + HILOG_INFO("TriggerCompleteCallBack::OnSendFinished end"); +} +napi_value WantAgentInit(napi_env env, napi_value exports) +{ + HILOG_INFO("napi_moudule Init start..."); + napi_property_descriptor desc[] = {DECLARE_NAPI_FUNCTION("getBundleName", NAPI_GetBundleName), + DECLARE_NAPI_FUNCTION("getUid", NAPI_GetUid), + DECLARE_NAPI_FUNCTION("cancel", NAPI_Cancel), + DECLARE_NAPI_FUNCTION("trigger", NAPI_Trigger), + DECLARE_NAPI_FUNCTION("equal", NAPI_Equal), + DECLARE_NAPI_FUNCTION("getWant", NAPI_GetWant), + DECLARE_NAPI_FUNCTION("getWantAgent", NAPI_GetWantAgent)}; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + HILOG_INFO("napi_moudule Init end..."); + return exports; +} + +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName) +{ + napi_value prop = nullptr; + if (napi_create_int32(env, objName, &prop) == napi_ok) { + napi_set_named_property(env, dstObj, propName, prop); + } +} + +napi_value WantAgentFlagsInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, 0, "ONE_TIME_FLAG"); + SetNamedPropertyByInteger(env, obj, 1, "NO_BUILD_FLAG"); + SetNamedPropertyByInteger(env, obj, 2, "CANCEL_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, 3, "UPDATE_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, 4, "CONSTANT_FLAG"); + SetNamedPropertyByInteger(env, obj, 5, "REPLACE_ELEMENT"); + SetNamedPropertyByInteger(env, obj, 6, "REPLACE_ACTION"); + SetNamedPropertyByInteger(env, obj, 7, "REPLACE_URI"); + SetNamedPropertyByInteger(env, obj, 8, "REPLACE_ENTITIES"); + SetNamedPropertyByInteger(env, obj, 9, "REPLACE_BUNDLE"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("Flags", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value WantAgentOperationTypeInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, 0, "UNKNOWN_TYPE"); + SetNamedPropertyByInteger(env, obj, 1, "START_ABILITY"); + SetNamedPropertyByInteger(env, obj, 2, "START_ABILITIES"); + SetNamedPropertyByInteger(env, obj, 3, "START_SERVICE"); + SetNamedPropertyByInteger(env, obj, 4, "SEND_COMMON_EVENT"); + SetNamedPropertyByInteger(env, obj, 5, "START_FOREGROUND_SERVICE"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("OperationType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value NAPI_GetBundleNameWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetBundleNameCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetBundleNameWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetBundleNameCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetBundleName called(CallBack Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = (AsyncGetBundleNameCallbackInfo *)data; + asyncCallbackInfo->bundleName = WantAgentHelper::GetBundleName(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetBundleName compeleted(CallBack Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = (AsyncGetBundleNameCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetBundleNamePromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetBundleName called(Promise Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = (AsyncGetBundleNameCallbackInfo *)data; + asyncCallbackInfo->bundleName = WantAgentHelper::GetBundleName(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetBundleName compeleted(Promise Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = (AsyncGetBundleNameCallbackInfo *)data; + napi_value result; + napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + Notification::WantAgent::WantAgent *pWantAgent = nullptr; + if (argv[0] == nullptr) { + HILOG_INFO("argv[0] is nullptr"); + } + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + HILOG_INFO("Notification::WantAgent::WantAgent napi_unwrap error"); + return NapiGetNull(env); + } + std::shared_ptr wantAgent(pWantAgent); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncGetBundleNameCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = wantAgent; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetBundleNameWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value NAPI_GetUidWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetUidCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetUidWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetUidCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetUid called(CallBack Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = (AsyncGetUidCallbackInfo *)data; + asyncCallbackInfo->uid = WantAgentHelper::GetUid(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetUid compeleted(CallBack Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = (AsyncGetUidCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_create_int32(env, asyncCallbackInfo->uid, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetUidPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetUid called(Promise Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = (AsyncGetUidCallbackInfo *)data; + asyncCallbackInfo->uid = WantAgentHelper::GetUid(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetUid compeleted(Promise Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = (AsyncGetUidCallbackInfo *)data; + napi_value result; + napi_create_int32(env, asyncCallbackInfo->uid, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value NAPI_GetUid(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + Notification::WantAgent::WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgent(pWantAgent); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetUidCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncGetUidCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = wantAgent; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetUidWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value NAPI_GetWantWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetWantCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetWantWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetWantCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetWant called(CallBack Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; + asyncCallbackInfo->want = WantAgentHelper::GetWant(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWant compeleted(CallBack Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + result[1] = WrapWant(*(asyncCallbackInfo->want), env); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetWantPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetWant called(Promise Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; + asyncCallbackInfo->want = WantAgentHelper::GetWant(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWant compeleted(Promise Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = (AsyncGetWantCallbackInfo *)data; + napi_value result; + result = WrapWant(*(asyncCallbackInfo->want), env); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value NAPI_GetWant(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + Notification::WantAgent::WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgent(pWantAgent); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetWantCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncGetWantCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = wantAgent; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetWantWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value NAPI_CancelWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncCancelCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_CancelWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_CancelCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("Cancel called(CallBack Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; + WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Cancel compeleted(CallBack Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_get_null(env, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_CancelPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("Cancel called(Promise Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; + WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Cancel compeleted(Promise Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = (AsyncCancelCallbackInfo *)data; + napi_value result; + napi_get_null(env, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value NAPI_Cancel(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + Notification::WantAgent::WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgent(pWantAgent); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncCancelCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncCancelCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = wantAgent; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_CancelWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value NAPI_TriggerWrap(napi_env env, napi_callback_info info, AsyncTriggerCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_TriggerWrap called..."); + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_TriggerWrap", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("Trigger called ..."); + AsyncTriggerCallbackInfo *asyncCallbackInfo = (AsyncTriggerCallbackInfo *)data; + asyncCallbackInfo->triggerObj->SetCallbackInfo(env, asyncCallbackInfo->callback[0]); + asyncCallbackInfo->triggerObj->SetWantAgentInstance(asyncCallbackInfo->wantAgent); + WantAgentHelper::TriggerWantAgent(asyncCallbackInfo->context, + asyncCallbackInfo->wantAgent, + asyncCallbackInfo->triggerObj, + asyncCallbackInfo->triggerInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Trigger compeleted ..."); + AsyncTriggerCallbackInfo *asyncCallbackInfo = (AsyncTriggerCallbackInfo *)data; + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; +} + +napi_value NAPI_Trigger(napi_env env, napi_callback_info info) +{ + size_t argc = 3; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + Notification::WantAgent::WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgent(pWantAgent); + + // Get triggerInfo + napi_value jsTriggerInfo = argv[1]; + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, jsTriggerInfo, &valueType)); + NAPI_ASSERT(env, valueType == napi_object, "param type mismatch!"); + + // Get triggerInfo code + int32_t code = -1; + if (!GetInt32ByPropertyName(env, jsTriggerInfo, "code", code)) { + return NapiGetNull(env); + } + // Get triggerInfo want + napi_value jsWant = nullptr; + jsWant = GetObjectByPropertyName(env, jsTriggerInfo, "want"); + std::shared_ptr want = nullptr; + if (jsWant != nullptr) { + want = std::make_shared(); + WantAgentUnwrapWant(*want, env, jsWant); + } + // Get triggerInfo permission + std::string permission; + GetStringByPropertyName(env, jsTriggerInfo, "permission", permission); + // Get triggerInfo extraInfo + napi_value jsExtraInfo = nullptr; + jsExtraInfo = GetObjectByPropertyName(env, jsTriggerInfo, "extraInfo"); + std::shared_ptr extraInfo = nullptr; + if (jsExtraInfo != nullptr) { + extraInfo = std::make_shared(); + UnwrapWantParam(*extraInfo, env, jsExtraInfo); + } + // Get context + napi_value global = 0; + NAPI_CALL(env, napi_get_global(env, &global)); + napi_value abilityObj = 0; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + std::shared_ptr context = nullptr; + context = ability->GetContext(); + + bool callBackMode = false; + if (argc >= 3) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncTriggerCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncTriggerCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = wantAgent; + asyncCallbackInfo->context = context; + Notification::WantAgent::TriggerInfo triggerInfo(permission, extraInfo, want, code); + asyncCallbackInfo->triggerInfo = triggerInfo; + asyncCallbackInfo->triggerObj = nullptr; + if (callBackMode) { + asyncCallbackInfo->callBackMode = callBackMode; + asyncCallbackInfo->triggerObj = std::make_shared(); + napi_create_reference(env, argv[2], 1, &asyncCallbackInfo->callback[0]); + } + + napi_value ret = NAPI_TriggerWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return NapiGetNull(env); +} + +napi_value NAPI_EqualWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncEqualCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_EqualWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_EqualWrapCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("Equal called(CallBack Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = (AsyncEqualCallbackInfo *)data; + asyncCallbackInfo->result = WantAgentHelper::JudgeEquality( + asyncCallbackInfo->wantAgentFirst, asyncCallbackInfo->wantAgentSecond); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Equal compeleted(CallBack Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = (AsyncEqualCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_get_boolean(env, asyncCallbackInfo->result, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_EqualPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("Equal called(Promise Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = (AsyncEqualCallbackInfo *)data; + asyncCallbackInfo->result = WantAgentHelper::JudgeEquality( + asyncCallbackInfo->wantAgentFirst, asyncCallbackInfo->wantAgentSecond); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Equal compeleted(Promise Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = (AsyncEqualCallbackInfo *)data; + napi_value result; + napi_get_boolean(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value NAPI_Equal(napi_env env, napi_callback_info info) +{ + size_t argc = 3; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + Notification::WantAgent::WantAgent *pWantAgentFirst = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgentFirst)); + if (pWantAgentFirst == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgentFirst(pWantAgentFirst); + + Notification::WantAgent::WantAgent *pWantAgentSecond = nullptr; + napi_unwrap(env, argv[1], (void **)&(pWantAgentSecond)); + if (pWantAgentSecond == nullptr) { + return NapiGetNull(env); + } + std::shared_ptr wantAgentSecond(pWantAgentSecond); + + bool callBackMode = false; + if (argc >= 3) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncEqualCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncEqualCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgentFirst = wantAgentFirst; + asyncCallbackInfo->wantAgentSecond = wantAgentSecond; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_EqualWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +std::string NapiGetStringParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IString *ao = AAFwk::IString::Query(value); + if (ao != nullptr) { + return AAFwk::String::Unbox(ao); + } + return std::string(); +} + +bool NapiGetBoolParam(const AAFwk::WantParams &extraInfo, const std::string &key, bool defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IBoolean *bo = AAFwk::IBoolean::Query(value); + if (bo != nullptr) { + return AAFwk::Boolean::Unbox(bo); + } + return defaultValue; +} + +short NapiGetShortParam(const AAFwk::WantParams &extraInfo, const std::string &key, short defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IShort *ao = AAFwk::IShort::Query(value); + if (ao != nullptr) { + return AAFwk::Short::Unbox(ao); + } + return defaultValue; +} + +int NapiGetIntParam(const AAFwk::WantParams &extraInfo, const std::string &key, const int defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IInteger *ao = AAFwk::IInteger::Query(value); + if (ao != nullptr) { + return AAFwk::Integer::Unbox(ao); + } + return defaultValue; +} + +long NapiGetLongParam(const AAFwk::WantParams &extraInfo, const std::string &key, long defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::ILong *ao = AAFwk::ILong::Query(value); + if (ao != nullptr) { + return AAFwk::Long::Unbox(ao); + } + return defaultValue; +} + +float NapiGetFloatParam(const AAFwk::WantParams &extraInfo, const std::string &key, float defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IFloat *ao = AAFwk::IFloat::Query(value); + if (ao != nullptr) { + return AAFwk::Float::Unbox(ao); + } + return defaultValue; +} + +double NapiGetDoubleParam(const AAFwk::WantParams &extraInfo, const std::string &key, double defaultValue) +{ + auto value = extraInfo.GetParam(key); + AAFwk::IDouble *ao = AAFwk::IDouble::Query(value); + if (ao != nullptr) { + return AAFwk::Double::Unbox(ao); + } + return defaultValue; +} + +napi_value WrapWantParam(const AAFwk::WantParams &extraInfo, napi_env env) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_value jsParam = nullptr; + napi_value proValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsParam)); + const std::map> paramList = extraInfo.GetParams(); + for (auto iter = paramList.begin(); iter != paramList.end(); iter++) { + proValue = nullptr; + if (AAFwk::IString::Query(iter->second) != nullptr) { + std::string nativeValue = NapiGetStringParam(extraInfo, iter->first); + HILOG_INFO("%{public}s, %{public}s=%{public}s", __func__, iter->first.c_str(), nativeValue.c_str()); + if (napi_create_string_utf8(env, nativeValue.c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::IBoolean::Query(iter->second) != nullptr) { + bool natvieValue = NapiGetBoolParam(extraInfo, iter->first, false); + if (napi_get_boolean(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::IShort::Query(iter->second) != nullptr) { + short natvieValue = NapiGetShortParam(extraInfo, iter->first, 0); + if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::IInteger::Query(iter->second) != nullptr) { + int natvieValue = NapiGetIntParam(extraInfo, iter->first, 0); + if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::ILong::Query(iter->second) != nullptr) { + long natvieValue = NapiGetLongParam(extraInfo, iter->first, 0); + if (napi_create_int64(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::IFloat::Query(iter->second) != nullptr) { + float natvieValue = NapiGetFloatParam(extraInfo, iter->first, 0.0); + if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else if (AAFwk::IDouble::Query(iter->second) != nullptr) { + double natvieValue = NapiGetDoubleParam(extraInfo, iter->first, 0.0); + if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { + napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); + } + } else { + AAFwk::IArray *ao = AAFwk::IArray::Query(iter->second); + if (ao != nullptr) { + sptr array(ao); + WrapWantParamArray(extraInfo, env, iter->first, array, jsParam); + } + } + } + return jsParam; +} + +napi_value UnwrapWantParam(AAFwk::WantParams &extraInfo, napi_env env, napi_value JsExtraInfo) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_valuetype valueType = napi_undefined; + napi_value proNameList = 0; + uint32_t proCount = 0; + + NAPI_CALL(env, napi_get_property_names(env, JsExtraInfo, &proNameList)); + NAPI_CALL(env, napi_get_array_length(env, proNameList, &proCount)); + HILOG_INFO("UnwrapWantParam property size=%{public}d", proCount); + + napi_value proName = 0; + napi_value proValue = 0; + for (uint32_t index = 0; index < proCount; index++) { + NAPI_CALL(env, napi_get_element(env, proNameList, index, &proName)); + std::string strProName = NapiValueToStringUtf8(env, proName); + HILOG_INFO("UnwrapWantParam proName=%{public}s", strProName.c_str()); + NAPI_CALL(env, napi_get_named_property(env, JsExtraInfo, strProName.c_str(), &proValue)); + NAPI_CALL(env, napi_typeof(env, proValue, &valueType)); + switch (valueType) { + case napi_string: { + std::string str_pro_value = NapiValueToStringUtf8(env, proValue); + HILOG_INFO("UnwrapWantParam proValue=%{public}s", str_pro_value.c_str()); + extraInfo.SetParam(strProName, AAFwk::String::Box(str_pro_value)); + break; + } + case napi_boolean: { + bool c_pro_value = false; + NAPI_CALL(env, napi_get_value_bool(env, proValue, &c_pro_value)); + HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value); + extraInfo.SetParam(strProName, AAFwk::Boolean::Box(c_pro_value)); + break; + } + case napi_number: { + int32_t c_pro_value32 = 0; + double c_pro_value_double = 0.0; + + if (napi_get_value_int32(env, proValue, &c_pro_value32) == napi_ok) { + HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value32); + extraInfo.SetParam(strProName, AAFwk::Integer::Box(c_pro_value32)); + break; + } + if (napi_get_value_double(env, proValue, &c_pro_value_double) == napi_ok) { + HILOG_INFO("UnwrapWantParam proValue=%{public}lf", c_pro_value_double); + extraInfo.SetParam(strProName, AAFwk::Double::Box(c_pro_value_double)); + break; + } + HILOG_INFO("UnwrapWantParam unknown proValue of Number"); + break; + } + default: { + if (UnwrapWantParamArray(extraInfo, env, strProName, proValue) == nullptr) { + return nullptr; + } + } + } + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; +} + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IString); + if (ao == nullptr) { + return; + } + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::String::Box(value[i])); + } + extraInfo.SetParam(key, ao); +} + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IInteger); + if (ao == nullptr) { + return; + } + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Integer::Box(value[i])); + } + extraInfo.SetParam(key, ao); +} + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_ILong); + if (ao == nullptr) { + return; + } + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Long::Box(value[i])); + } + extraInfo.SetParam(key, ao); +} + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IBoolean); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Boolean::Box(value[i])); + } + extraInfo.SetParam(key, ao); + } +} + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IDouble); + if (ao == nullptr) { + return; + } + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Double::Box(value[i])); + } + extraInfo.SetParam(key, ao); +} + +napi_value UnwrapWantParamArray(AAFwk::WantParams &extraInfo, napi_env env, std::string strProName, napi_value proValue) +{ + HILOG_INFO("%{public}s,called", __func__); + bool isArray = false; + uint32_t arrayLength = 0; + napi_value valueAry = 0; + napi_valuetype valueAryType = napi_undefined; + + NAPI_CALL(env, napi_is_array(env, proValue, &isArray)); + NAPI_CALL(env, napi_get_array_length(env, proValue, &arrayLength)); + HILOG_INFO("UnwrapWantParam proValue is array, length=%{public}d", arrayLength); + + std::vector stringList; + std::vector intList; + std::vector longList; + std::vector boolList; + std::vector doubleList; + bool isDouble = false; + for (uint32_t j = 0; j < arrayLength; j++) { + NAPI_CALL(env, napi_get_element(env, proValue, j, &valueAry)); + NAPI_CALL(env, napi_typeof(env, valueAry, &valueAryType)); + switch (valueAryType) { + case napi_string: { + std::string str_ary_value = NapiValueToStringUtf8(env, valueAry); + HILOG_INFO("UnwrapWantParam string array proValue=%{public}s", str_ary_value.c_str()); + stringList.push_back(str_ary_value); + break; + } + case napi_boolean: { + bool c_ary_value = false; + NAPI_CALL(env, napi_get_value_bool(env, valueAry, &c_ary_value)); + HILOG_INFO("UnwrapWantParam bool array proValue=%{public}d", c_ary_value); + boolList.push_back(c_ary_value); + break; + } + case napi_number: { + int32_t c_ary_value32 = 0; + int64_t c_ary_value64 = 0; + double c_ary_value_double = 0.0; + if (isDouble) { + if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { + HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); + doubleList.push_back(c_ary_value_double); + } + break; + } else { + if (napi_get_value_int32(env, valueAry, &c_ary_value32) == napi_ok) { + HILOG_INFO("UnwrapWantParam int array proValue=%{public}d", c_ary_value32); + intList.push_back(c_ary_value32); + break; + } + } + + if (napi_get_value_int64(env, valueAry, &c_ary_value64) == napi_ok) { + HILOG_INFO("UnwrapWantParam int64 array proValue=%{public}lld", c_ary_value64); + longList.push_back(c_ary_value64); + break; + } + if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { + HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); + isDouble = true; + if (intList.size() > 0) { + for (int k = 0; k < (int)intList.size(); k++) { + doubleList.push_back(intList[k]); + } + intList.clear(); + } + doubleList.push_back(c_ary_value_double); + break; + } + HILOG_INFO("UnwrapWantParam array unkown Number"); + break; + } + default: + HILOG_INFO("UnwrapWantParam array unkown"); + break; + } + } + if (stringList.size() > 0) { + SetParam(extraInfo, strProName, stringList); + } + if (intList.size() > 0) { + SetParam(extraInfo, strProName, intList); + } + if (longList.size() > 0) { + SetParam(extraInfo, strProName, longList); + } + if (boolList.size() > 0) { + SetParam(extraInfo, strProName, boolList); + } + if (doubleList.size() > 0) { + SetParam(extraInfo, strProName, doubleList); + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; +} + +napi_value NAPI_GetWantAgentWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetWantAgentCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetWantAgentWrap called..."); + if (callBackMode) { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetWantAgentCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetWantAgent called(CallBack Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = (AsyncGetWantAgentCallbackInfo *)data; + Notification::WantAgent::WantAgentInfo wantAgentInfo(asyncCallbackInfo->requestCode, + asyncCallbackInfo->operationType, + asyncCallbackInfo->wantAgentFlags, + asyncCallbackInfo->wants, + asyncCallbackInfo->extraInfo); + asyncCallbackInfo->wantAgent = + Notification::WantAgent::WantAgentHelper::GetWantAgent(asyncCallbackInfo->context, wantAgentInfo); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantAgent compeleted(CallBack Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = (AsyncGetWantAgentCallbackInfo *)data; + napi_value result[2] = {0}; + napi_value callback; + napi_value undefined; + napi_value callResult = 0; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + + napi_value wantAgentClass = nullptr; + napi_define_class(env, + "WantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); + napi_new_instance(env, wantAgentClass, 0, nullptr, &result[1]); + napi_wrap(env, + result[1], + (void *)asyncCallbackInfo->wantAgent.get(), + [](napi_env env, void *data, void *hint) {}, + nullptr, + nullptr); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, 2, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + // create reutrn + napi_value ret = 0; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetWantAgentPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + HILOG_INFO("GetWantAgent called(Promise Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = (AsyncGetWantAgentCallbackInfo *)data; + HILOG_INFO("GetWantAgent wants.size = [%{public}d], wantAgentFlags.size = [%{public}d]", + asyncCallbackInfo->wants.size(), + asyncCallbackInfo->wantAgentFlags.size()); + + Notification::WantAgent::WantAgentInfo wantAgentInfo(asyncCallbackInfo->requestCode, + asyncCallbackInfo->operationType, + asyncCallbackInfo->wantAgentFlags, + asyncCallbackInfo->wants, + asyncCallbackInfo->extraInfo); + asyncCallbackInfo->wantAgent = + Notification::WantAgent::WantAgentHelper::GetWantAgent(asyncCallbackInfo->context, wantAgentInfo); + if (asyncCallbackInfo->wantAgent == nullptr) { + HILOG_INFO("GetWantAgent instance is nullptr..."); + } else { + HILOG_INFO("GetWantAgent instance is not nullptr..."); + } + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantAgent compeleted(Promise Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = (AsyncGetWantAgentCallbackInfo *)data; + napi_value wantAgentClass = nullptr; + napi_define_class(env, + "WantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); + napi_value result = nullptr; + napi_new_instance(env, wantAgentClass, 0, nullptr, &result); + napi_wrap(env, + result, + (void *)asyncCallbackInfo->wantAgent.get(), + [](napi_env env, void *data, void *hint) {}, + nullptr, + nullptr); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; + } +} + +napi_value WantAgentUnwrapWant(Want ¶m, napi_env env, napi_value jsWant) +{ + HILOG_INFO("%{public}s,called", __func__); + // unwrap the param + napi_valuetype valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, jsWant, &valueType)); + if (valueType != napi_object) { + return nullptr; + } + std::string strValue; + // get want action property + if (GetStringByPropertyName(env, jsWant, "action", strValue)) { + param.SetAction(strValue); + } + // get want entities property + std::vector nativeStringList; + GetStringArrayByPropertyName(env, jsWant, "entities", nativeStringList); + for (size_t i = 0; i < nativeStringList.size(); i++) { + param.AddEntity(nativeStringList[i]); + } + // get want type property + if (GetStringByPropertyName(env, jsWant, "type", strValue)) { + param.SetType(strValue); + } + // get want flags property(WantOptions in want.d.ts) + GetWantOptions(env, jsWant, "options", param); + // get want uri property + if (GetStringByPropertyName(env, jsWant, "uri", strValue)) { + param.SetUri(strValue); + } + // get elementName property + UnwrapElementName(param, env, jsWant); + // get want param (optional) + UnwrapWantParam(param, env, jsWant); + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; +} + +napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}d]", argc); + + napi_valuetype jsWantAgentInfoType; + napi_value jsWantAgentInfo = argv[0]; + NAPI_CALL(env, napi_typeof(env, jsWantAgentInfo, &jsWantAgentInfoType)); + NAPI_ASSERT(env, jsWantAgentInfoType == napi_object, "param type mismatch!"); + + napi_value jsWants = nullptr; + jsWants = GetObjectByPropertyName(env, jsWantAgentInfo, "wants"); + if (jsWants == nullptr) { + return NapiGetNull(env); + } + bool isArray = false; + if (napi_is_array(env, jsWants, &isArray) != napi_ok) { + return NapiGetNull(env); + } + if (isArray == false) { + return NapiGetNull(env); + } + uint32_t wantsLen = 0; + napi_get_array_length(env, jsWants, &wantsLen); + if (wantsLen < 0) { + return NapiGetNull(env); + } + std::vector> wants; + for (uint32_t i = 0; i < wantsLen; i++) { + std::shared_ptr want = std::make_shared(); + napi_value jsWant; + napi_get_element(env, jsWants, i, &jsWant); + WantAgentUnwrapWant(*want, env, jsWant); + HILOG_INFO("want type is [%{public}s]", want->GetType().c_str()); + wants.emplace_back(want); + } + // Get operationType + int32_t operationType = -1; + if (!GetInt32ByPropertyName(env, jsWantAgentInfo, "operationType", operationType)) { + return NapiGetNull(env); + } + // Get requestCode + int32_t requestCode = -1; + if (!GetInt32ByPropertyName(env, jsWantAgentInfo, "requestCode", requestCode)) { + return NapiGetNull(env); + } + // Get wantAgentFlags + napi_value JsWantAgentFlags = nullptr; + std::vector wantAgentFlags; + JsWantAgentFlags = GetObjectByPropertyName(env, jsWantAgentInfo, "wantAgentFlags"); + if (JsWantAgentFlags != nullptr) { + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, JsWantAgentFlags, &arrayLength)); + HILOG_INFO("property is array, length=%{public}d", arrayLength); + for (uint32_t i = 0; i < arrayLength; i++) { + napi_value napiWantAgentFlags; + napi_get_element(env, JsWantAgentFlags, i, &napiWantAgentFlags); + napi_valuetype valuetype0; + NAPI_CALL(env, napi_typeof(env, napiWantAgentFlags, &valuetype0)); + NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected."); + int32_t value0 = 0; + NAPI_CALL(env, napi_get_value_int32(env, napiWantAgentFlags, &value0)); + wantAgentFlags.emplace_back(static_cast(value0)); + } + } + // Get extraInfo + napi_value JsExtraInfo = nullptr; + JsExtraInfo = GetObjectByPropertyName(env, jsWantAgentInfo, "extraInfo"); + AAFwk::WantParams extraInfo; + if (JsExtraInfo != nullptr) { + UnwrapWantParam(extraInfo, env, JsExtraInfo); + } + // Get context + napi_value global = 0; + NAPI_CALL(env, napi_get_global(env, &global)); + napi_value abilityObj = 0; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + std::shared_ptr context = nullptr; + context = ability->GetContext(); + + bool callBackMode = false; + if (argc >= 2) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncGetWantAgentCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wants = wants; + asyncCallbackInfo->operationType = + static_cast(operationType); + asyncCallbackInfo->requestCode = requestCode; + asyncCallbackInfo->wantAgentFlags = wantAgentFlags; + asyncCallbackInfo->extraInfo.reset(new (std::nothrow) AAFwk::WantParams(extraInfo)); + asyncCallbackInfo->context = context; + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetWantAgentWrap(env, info, callBackMode, asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value GetCallbackErrorResult(napi_env env, int errCode) +{ + napi_value result = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); + return result; +} + +napi_value NapiGetNull(napi_env env) +{ + napi_value result = 0; + napi_get_null(env, &result); + return result; +} + +std::vector GetStringArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + std::vector array; + auto value = extraInfo.GetParam(key); + AAFwk::IArray *ao = AAFwk::IArray::Query(value); + if (ao != nullptr && AAFwk::Array::IsStringArray(ao)) { + auto func = [&](AAFwk::IInterface *object) { + if (object != nullptr) { + AAFwk::IString *value = AAFwk::IString::Query(object); + if (value != nullptr) { + array.push_back(AAFwk::String::Unbox(value)); + } + } + }; + AAFwk::Array::ForEach(ao, func); + } + return array; +} + +std::vector GetBoolArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + std::vector array; + auto value = extraInfo.GetParam(key); + AAFwk::IArray *ao = AAFwk::IArray::Query(value); + if (ao != nullptr && AAFwk::Array::IsBooleanArray(ao)) { + auto func = [&](AAFwk::IInterface *object) { + if (object != nullptr) { + AAFwk::IBoolean *value = AAFwk::IBoolean::Query(object); + if (value != nullptr) { + array.push_back(AAFwk::Boolean::Unbox(value)); + } + } + }; + + AAFwk::Array::ForEach(ao, func); + } + return array; +} + +std::vector GetIntArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + std::vector array; + auto value = extraInfo.GetParam(key); + AAFwk::IArray *ao = AAFwk::IArray::Query(value); + if (ao != nullptr && AAFwk::Array::IsIntegerArray(ao)) { + auto func = [&](AAFwk::IInterface *object) { + if (object != nullptr) { + AAFwk::IInteger *value = AAFwk::IInteger::Query(object); + if (value != nullptr) { + array.push_back(AAFwk::Integer::Unbox(value)); + } + } + }; + AAFwk::Array::ForEach(ao, func); + } + return array; +} + +std::vector GetLongArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + std::vector array; + auto value = extraInfo.GetParam(key); + AAFwk::IArray *ao = AAFwk::IArray::Query(value); + if (ao != nullptr && AAFwk::Array::IsLongArray(ao)) { + auto func = [&](AAFwk::IInterface *object) { + if (object != nullptr) { + AAFwk::ILong *value = AAFwk::ILong::Query(object); + if (value != nullptr) { + array.push_back(AAFwk::Long::Unbox(value)); + } + } + }; + AAFwk::Array::ForEach(ao, func); + } + return array; +} + +std::vector GetDoubleArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key) +{ + std::vector array; + auto value = extraInfo.GetParam(key); + AAFwk::IArray *ao = AAFwk::IArray::Query(value); + if (ao != nullptr && AAFwk::Array::IsDoubleArray(ao)) { + auto func = [&](AAFwk::IInterface *object) { + if (object != nullptr) { + AAFwk::IDouble *value = AAFwk::IDouble::Query(object); + if (value != nullptr) { + array.push_back(AAFwk::Double::Unbox(value)); + } + } + }; + AAFwk::Array::ForEach(ao, func); + } + return array; +} + +void WrapWantParamArray(const AAFwk::WantParams &extraInfo, napi_env env, const std::string &key, + sptr &ao, napi_value jsObject) +{ + napi_value jsArray = nullptr; + napi_value proValue = nullptr; + if (AAFwk::Array::IsStringArray(ao)) { + std::vector nativeValue = GetStringArrayParam(extraInfo, key); + if (napi_create_array(env, &jsArray) != napi_ok) { + return; + } + for (uint32_t i = 0; i < nativeValue.size(); i++) { + proValue = nullptr; + if (napi_create_string_utf8(env, nativeValue[i].c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { + napi_set_element(env, jsArray, i, proValue); + } + } + napi_set_named_property(env, jsObject, key.c_str(), jsArray); + } else if (AAFwk::Array::IsBooleanArray(ao)) { + std::vector nativeValue = GetBoolArrayParam(extraInfo, key); + if (napi_create_array(env, &jsArray) != napi_ok) { + return; + } + for (uint32_t i = 0; i < nativeValue.size(); i++) { + proValue = nullptr; + if (napi_get_boolean(env, nativeValue[i], &proValue) == napi_ok) { + napi_set_element(env, jsArray, i, proValue); + } + } + napi_set_named_property(env, jsObject, key.c_str(), jsArray); + } else if (AAFwk::Array::IsIntegerArray(ao)) { + std::vector nativeValue = GetIntArrayParam(extraInfo, key); + if (napi_create_array(env, &jsArray) != napi_ok) { + return; + } + for (uint32_t i = 0; i < nativeValue.size(); i++) { + proValue = nullptr; + if (napi_create_int32(env, nativeValue[i], &proValue) == napi_ok) { + napi_set_element(env, jsArray, i, proValue); + } + } + napi_set_named_property(env, jsObject, key.c_str(), jsArray); + } else if (AAFwk::Array::IsLongArray(ao)) { + std::vector nativeValue = GetLongArrayParam(extraInfo, key); + if (napi_create_array(env, &jsArray) != napi_ok) { + return; + } + for (uint32_t i = 0; i < nativeValue.size(); i++) { + proValue = nullptr; + if (napi_create_int64(env, nativeValue[i], &proValue) == napi_ok) { + napi_set_element(env, jsArray, i, proValue); + } + } + napi_set_named_property(env, jsObject, key.c_str(), jsArray); + } else if (AAFwk::Array::IsDoubleArray(ao)) { + std::vector nativeValue = GetDoubleArrayParam(extraInfo, key); + if (napi_create_array(env, &jsArray) != napi_ok) { + return; + } + for (uint32_t i = 0; i < nativeValue.size(); i++) { + proValue = nullptr; + if (napi_create_double(env, nativeValue[i], &proValue) == napi_ok) { + napi_set_element(env, jsArray, i, proValue); + } + } + napi_set_named_property(env, jsObject, key.c_str(), jsArray); + } +} + +} // namespace OHOS \ No newline at end of file diff --git a/kits/wantAgent/napi_want_agent.h b/kits/wantAgent/napi_want_agent.h new file mode 100644 index 000000000..1bc73ad7c --- /dev/null +++ b/kits/wantAgent/napi_want_agent.h @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2021 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 NAPI_WANT_AGENT_H +#define NAPI_WANT_AGENT_H + +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +#include "want_agent_constant.h" +#include "completed_callback.h" +#include "context.h" +#include "want.h" +#include "want_params.h" +#include "ability.h" +#include "want_agent.h" +#include "trigger_info.h" + +namespace OHOS { + +using namespace OHOS::AppExecFwk; +using namespace OHOS::Notification; +using namespace OHOS::Notification::WantAgent; + +class TriggerCompleteCallBack; + +struct AsyncGetWantAgentCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::vector> wants; + Notification::WantAgent::WantAgentConstant::OperationType operationType; + int32_t requestCode = -1; + std::vector wantAgentFlags; + std::shared_ptr extraInfo; + std::shared_ptr context; + std::shared_ptr wantAgent; +}; + +struct AsyncGetBundleNameCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + std::string bundleName; +}; + +struct AsyncGetUidCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + int32_t uid; +}; + +struct AsyncGetWantCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + std::shared_ptr want; +}; + +struct AsyncEqualCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgentFirst; + std::shared_ptr wantAgentSecond; + bool result; +}; + +struct AsyncCancelCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; +}; + +struct AsyncTriggerCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + bool callBackMode = false; + std::shared_ptr triggerObj; + std::shared_ptr context; + std::shared_ptr wantAgent; + Notification::WantAgent::TriggerInfo triggerInfo; +}; + +struct CallbackInfo { + std::shared_ptr wantAgent; + napi_env env; + napi_ref ref; +}; + +struct TriggerReceiveDataWorker { + napi_env env; + napi_ref ref = 0; + std::shared_ptr wantAgent; + AAFwk::Want want; + int resultCode; + std::string resultData; + AAFwk::WantParams resultExtras; +}; + +class TriggerCompleteCallBack : public CompletedCallback { +public: + TriggerCompleteCallBack(); + virtual ~TriggerCompleteCallBack(); + +public: + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override; + void SetCallbackInfo(const napi_env &env, const napi_ref &ref); + void SetWantAgentInstance(const std::shared_ptr &wantAgent); + +private: + CallbackInfo triggerCompleteInfo_; +}; + +napi_value WantAgentInit(napi_env env, napi_value exports); + +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const char *propName); +napi_value WantAgentFlagsInit(napi_env env, napi_value exports); +napi_value WantAgentOperationTypeInit(napi_env env, napi_value exports); + +napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info); +napi_value NAPI_GetUid(napi_env env, napi_callback_info info); +napi_value NAPI_GetWant(napi_env env, napi_callback_info info); +napi_value NAPI_Cancel(napi_env env, napi_callback_info info); +napi_value NAPI_Trigger(napi_env env, napi_callback_info info); +napi_value NAPI_Equal(napi_env env, napi_callback_info info); +napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info); + +napi_value GetCallbackErrorResult(napi_env env, int errCode); +napi_value WrapWantParam(const AAFwk::WantParams &extraInfo, napi_env env); +napi_value UnwrapWantParamArray( + AAFwk::WantParams &extraInfo, napi_env env, std::string strProName, napi_value proValue); +napi_value UnwrapWantParam(AAFwk::WantParams &extraInfo, napi_env env, napi_value JsExtraInfo); +napi_value NapiGetNull(napi_env env); +napi_value WantAgentUnwrapWant(Want ¶m, napi_env env, napi_value jsWant); + +std::string NapiGetStringParam(const AAFwk::WantParams &extraInfo, const std::string &key); +bool NapiGetBoolParam(const AAFwk::WantParams &extraInfo, const std::string &key, bool defaultValue); +short NapiGetShortParam(const AAFwk::WantParams &extraInfo, const std::string &key, short defaultValue); +int NapiGetIntParam(const AAFwk::WantParams &extraInfo, const std::string &key, const int defaultValue); +long NapiGetLongParam(const AAFwk::WantParams &extraInfo, const std::string &key, long defaultValue); +float NapiGetFloatParam(const AAFwk::WantParams &extraInfo, const std::string &key, float defaultValue); +double NapiGetDoubleParam(const AAFwk::WantParams &extraInfo, const std::string &key, double defaultValue); + +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); +void SetParam(AAFwk::WantParams &extraInfo, const std::string &key, const std::vector &value); +void WrapWantParamArray(const AAFwk::WantParams &extraInfo, napi_env env, const std::string &key, + sptr &ao, napi_value jsObject); +std::vector GetStringArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); +std::vector GetBoolArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); +std::vector GetIntArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); +std::vector GetLongArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); +std::vector GetDoubleArrayParam(const AAFwk::WantParams &extraInfo, const std::string &key); + +} // namespace OHOS +#endif // NAPI_WANT_AGENT_H diff --git a/kits/wantAgent/native_module.cpp b/kits/wantAgent/native_module.cpp new file mode 100644 index 000000000..11981d2a2 --- /dev/null +++ b/kits/wantAgent/native_module.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 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 +#include +#include +#include + +#include "napi_want_agent.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "hilog_wrapper.h" + +using namespace OHOS::Notification; +using namespace OHOS::Notification::WantAgent; + +namespace OHOS { +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + WantAgentInit(env, exports); + WantAgentFlagsInit(env, exports); + WantAgentOperationTypeInit(env, exports); + return exports; +} +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "wantagent", + .nm_priv = ((void *)0), + .reserved = {0}}; + +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS \ No newline at end of file diff --git a/notification.gni b/notification.gni new file mode 100644 index 000000000..27ba0928e --- /dev/null +++ b/notification.gni @@ -0,0 +1,37 @@ +# Copyright (c) 2021 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. + +ans_standard_path = "//base/notification/ans_standard" + +services_path = "${ans_standard_path}/services" + +kits_path = "${ans_standard_path}/kits" + +innerkits_path = "${ans_standard_path}/innerkits" + +test_path = "${ans_standard_path}/test" + +tools_path = "${ans_standard_path}/tools" + +ans_standard_external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", +] diff --git a/ohos.build b/ohos.build new file mode 100644 index 000000000..d9e509b7c --- /dev/null +++ b/ohos.build @@ -0,0 +1,21 @@ +{ + "parts": { + "ans_standard": { + "module_list": [ + "//base/notification/ans_standard/innerkits:innerkits_target", + "//base/notification/ans_standard/kits:kits_target", + "//base/notification/ans_standard/sa_profile:ans_sa_profile", + "//base/notification/ans_standard/services:services_target", + "//base/notification/ans_standard/tools:tools_target" + ], + "inner_kits": [ + ], + "test_list": [ + "//base/notification/ans_standard/services/ans/test/unittest:ans_unit_test", + "//base/notification/ans_standard/services/test/moduletest:ans_module_test", + "//base/notification/ans_standard/kits/native/wantagent/test/:unittest" + ] + } + }, + "subsystem": "notification" +} \ No newline at end of file diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml new file mode 100755 index 000000000..7f45c1fc0 --- /dev/null +++ b/sa_profile/3203.xml @@ -0,0 +1,24 @@ + + + + foundation + + 3203 + /system/lib/libans.z.so + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100644 index 000000000..cd42149ef --- /dev/null +++ b/sa_profile/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("ans_sa_profile") { + sources = [ "3203.xml" ] + + part_name = "ans_standard" +} diff --git a/services/BUILD.gn b/services/BUILD.gn new file mode 100644 index 000000000..14494d7b4 --- /dev/null +++ b/services/BUILD.gn @@ -0,0 +1,16 @@ +# Copyright (c) 2021 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. + +group("services_target") { + deps = [ "ans:ans_targets" ] +} diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn new file mode 100644 index 000000000..c91ddc50f --- /dev/null +++ b/services/ans/BUILD.gn @@ -0,0 +1,83 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") + +group("ans_targets") { + deps = [ ":libans" ] +} + +config("public_ans_config") { + include_dirs = [ + "${services_path}/ans/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + defines = [ + "APP_LOG_TAG = \"Ans\"", + "LOG_DOMAIN = 0xD002200", + ] +} + +config("json_config") { + cflags_cc = [ "-fexceptions" ] +} + +ohos_shared_library("libans") { + include_dirs = [ + "include", + "${innerkits_path}/base/include", + "${innerkits_path}/core/include", + "${kits_path}/native/include", + "//third_party/json/include", + ] + + sources = [ + "src/advanced_notification_service.cpp", + "src/advanced_notification_service_ability.cpp", + "src/bundle_manager_helper.cpp", + "src/disturb_filter.cpp", + "src/notification_preferences.cpp", + "src/notification_slot_filter.cpp", + "src/notification_subscriber_manager.cpp", + "src/permission_filter.cpp", + ] + + configs = [ + ":public_ans_config", + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ":json_config", + ] + + deps = [ + "${innerkits_path}:ans_innerkits", + "${kits_path}/native:ans_kits", + "${kits_path}/native/wantagent:wantagent_kits", + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//utils/native/base:utils", + ] + + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + external_deps = [] + external_deps += ans_standard_external_deps + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h new file mode 100644 index 000000000..123d5152c --- /dev/null +++ b/services/ans/include/advanced_notification_service.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H + +#include +#include +#include + +#include "event_handler.h" +#include "event_runner.h" +#include "refbase.h" + +#include "ans_manager_stub.h" +#include "notification.h" +#include "notification_sorting_map.h" + +namespace OHOS { +namespace Notification { + +class AdvancedNotificationService final : public AnsManagerStub { +public: + ~AdvancedNotificationService() override; + DISALLOW_COPY_AND_MOVE(AdvancedNotificationService); + + static sptr GetInstance(); + + ErrCode Publish(const std::string &label, const sptr &request) override; + ErrCode Cancel(int notificationId, const std::string &label) override; + ErrCode CancelAll() override; + ErrCode AddSlots(const std::vector> &slots) override; + ErrCode RemoveSlotByType(const NotificationConstant::SlotType slotType) override; + ErrCode AddSlotGroups(std::vector> groups) override; + ErrCode GetSlotByType(const NotificationConstant::SlotType slotType, sptr &slot) override; + ErrCode GetSlots(std::vector> &slots) override; + ErrCode GetSlotGroup(const std::string &groupId, sptr &group) override; + ErrCode GetSlotGroups(std::vector> &groups) override; + ErrCode RemoveSlotGroups(const std::vector &groupIds) override; + ErrCode GetActiveNotifications(std::vector> ¬ifications) override; + ErrCode GetActiveNotificationNums(int &num) override; + ErrCode GetAllActiveNotifications(std::vector> ¬ifications) override; + ErrCode GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) override; + ErrCode SetNotificationAgent(const std::string &agent) override; + ErrCode GetNotificationAgent(std::string &agent) override; + ErrCode CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) override; + ErrCode PublishAsBundle( + const sptr notification, const std::string &representativeBundle) override; + ErrCode SetNotificationBadgeNum(int num) override; + ErrCode GetBundleImportance(int &importance) override; + ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; + ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; + ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; + ErrCode SetPrivateNotificationsAllowed(bool allow) override; + ErrCode GetPrivateNotificationsAllowed(bool &allow) override; + ErrCode Delete(const std::string &key) override; + ErrCode DeleteByBundle(const std::string &bundle) override; + ErrCode DeleteAll() override; + ErrCode GetSlotsByBundle(const std::string &bundle, std::vector> &slots) override; + ErrCode UpdateSlots(const std::string &bundle, const std::vector> &slots) override; + ErrCode UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) override; + ErrCode SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) override; + ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) override; + ErrCode SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) override; + ErrCode SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) override; + ErrCode GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) override; + ErrCode Subscribe(const sptr &subscriber, const sptr &info) override; + ErrCode Unsubscribe(const sptr &subscriber, const sptr &info) override; + ErrCode IsAllowedNotify(bool &allowed) override; + ErrCode IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) override; + +private: + AdvancedNotificationService(); + + void StartFilters(); + void StopFilters(); + ErrCode Filter(const sptr ¬ification); + + void AddToNotificationList(const sptr ¬ification); + void UpdateInNotificationList(const sptr ¬ification); + ErrCode RemoveFromNotificationList( + const std::string &bundle, const std::string &label, int notificationId, sptr ¬ification); + ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification); + std::vector GetRemovableNotificationKeys(const std::string &bundle); + bool IsNotificationExists(const std::string &key); + void SortNotificationList(); + static bool NotificationCompare(const sptr &first, const sptr &second); + + sptr GenerateSortingMap(); + + std::string GetClientBundleName(); + bool IsSystemApp(); + +private: + static sptr instance_; + static std::mutex instanceMutex_; + + std::shared_ptr runner_ = nullptr; + std::shared_ptr handler_ = nullptr; + std::list> notificationList_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // ADVANCED_NOTIFICATION_SERVICE_H \ No newline at end of file diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h new file mode 100644 index 000000000..10f8ac311 --- /dev/null +++ b/services/ans/include/advanced_notification_service_ability.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_ABILITY_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_ABILITY_H + +#include "system_ability.h" + +#include "advanced_notification_service.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { + +class AdvancedNotificationServiceAbility final : public SystemAbility { +public: + AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate); + ~AdvancedNotificationServiceAbility() final; + DISALLOW_COPY_AND_MOVE(AdvancedNotificationServiceAbility); + DECLARE_SYSTEM_ABILITY(AdvancedNotificationServiceAbility); + +private: + void OnStart() final; + void OnStop() final; + +private: + sptr service_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_ABILITY_H \ No newline at end of file diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h new file mode 100644 index 000000000..0e8936727 --- /dev/null +++ b/services/ans/include/bundle_manager_helper.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H + +#include +#include +#include + +#include "bundle_mgr_interface.h" +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "refbase.h" +#include "remote_death_recipient.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { + +class BundleManagerHelper : public DelayedSingleton { +public: + std::string GetBundleNameByUid(uid_t uid); + bool IsSystemApp(uid_t uid); + +private: + void Connect(); + void Disconnect(); + + void OnRemoteDied(const wptr &object); + +private: + sptr bundleMgr_ = nullptr; + std::mutex connectionMutex_; + sptr deathRecipient_ = nullptr; + + DECLARE_DELAYED_SINGLETON(BundleManagerHelper) +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/ans/include/disturb_filter.h b/services/ans/include/disturb_filter.h new file mode 100644 index 000000000..a38dcfa1c --- /dev/null +++ b/services/ans/include/disturb_filter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H + +#include "notification_filter.h" + +namespace OHOS { +namespace Notification { + +class DisturbFilter : public INotificationFilter { +public: + DisturbFilter(){}; + ~DisturbFilter(){}; + + void OnStart() override; + void OnStop() override; + + ErrCode OnPublish(const sptr ¬ification) override; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H \ No newline at end of file diff --git a/services/ans/include/notification_filter.h b/services/ans/include/notification_filter.h new file mode 100644 index 000000000..2773c9205 --- /dev/null +++ b/services/ans/include/notification_filter.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_FILTER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_FILTER_H + +#include "errors.h" +#include "refbase.h" + +#include "notification.h" + +namespace OHOS { +namespace Notification { + +class INotificationFilter { +public: + INotificationFilter(){}; + virtual ~INotificationFilter(){}; + + virtual void OnStart() = 0; + virtual void OnStop() = 0; + + virtual ErrCode OnPublish(const sptr ¬ification) = 0; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_FILTER_H \ No newline at end of file diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h new file mode 100644 index 000000000..e0c673207 --- /dev/null +++ b/services/ans/include/notification_preferences.h @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2021 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 NOTIFICATION_PREFERENCES_H +#define NOTIFICATION_PREFERENCES_H + +#include +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "refbase.h" +#include "singleton.h" + +#include "ans_inner_errors.h" +#include "notification_slot.h" +#include "notification_slot_group.h" + +namespace OHOS { +namespace Notification { + +class NotificationPreferences final { +public: + DISALLOW_COPY_AND_MOVE(NotificationPreferences); + static NotificationPreferences &GetInstance(); + ErrCode AddNotificationSlots(const std::string &bundleName, const std::vector> &slots); + ErrCode AddNotificationSlotGroups( + const std::string &bundleName, const std::vector> &groups); + ErrCode RemoveNotificationSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType); + ErrCode RemoveNotificationSlotGroups(const std::string &bundleName, const std::vector &groupIds); + ErrCode RemoveNotificationForBundle(const std::string &bundleName); + ErrCode UpdateNotificationSlots(const std::string &bundleName, const std::vector> &slot); + ErrCode UpdateNotificationSlotGroups( + const std::string &bundleName, const std::vector> &groups); + ErrCode GetNotificationSlot( + const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot); + ErrCode GetNotificationAllSlots(const std::string &bundleName, std::vector> &slots); + ErrCode GetNotificationSlotGroup( + const std::string &bundleName, const std::string &groupId, sptr &group); + ErrCode GetNotificationAllSlotGroups( + const std::string &bundleName, std::vector> &groups); + ErrCode GetNotificationAllSlotInSlotGroup( + const std::string &bundleName, const std::string &groupId, std::vector> &slots); + ErrCode IsShowBadge(const std::string &bundleName, bool &enable); + ErrCode SetShowBadge(const std::string &bundleName, const bool enable); + ErrCode GetImportance(const std::string &bundleName, int &importance); + ErrCode SetImportance(const std::string &bundleName, const int importance); + ErrCode GetTotalBadgeNums(const std::string &bundleName, int &totalBadgeNum); + ErrCode SetTotalBadgeNums(const std::string &bundleName, const int num); + ErrCode GetPrivateNotificationsAllowed(const std::string &bundleName, bool &allow); + ErrCode SetPrivateNotificationsAllowed(const std::string &bundleName, const bool allow); + ErrCode GetNotificationsEnabledForBundle(const std::string &bundleName, bool &enabled); + ErrCode SetNotificationsEnabledForBundle(const std::string &bundleName, const bool enabled); + ErrCode GetNotificationsEnabled(bool &enabled); + ErrCode SetNotificationsEnabled(const bool &enabled); + ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode); + ErrCode SetDisturbMode(const NotificationConstant::DisturbMode &mode); + ErrCode ClearNotificationInRestoreFactorySettings(); + +private: + struct BundleInfo { + std::string bundleName {}; + int importance = NotificationSlot::NotificationLevel::LEVEL_DEFAULT; + bool isShowBadge = false; + int badgeTotalNum = 0; + bool isPrivateAllowed = false; + bool isEnabledNotification = true; + std::map> groups {}; + std::map> slots {}; + }; + struct PreferencesInfo { + bool isEnabledAllNotification = true; + NotificationConstant::DisturbMode disturbMode = NotificationConstant::DisturbMode::ALLOW_ALL; + std::map infos {}; + }; + enum class BundlePropertyType; + + ErrCode CreateSlot( + const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot); + ErrCode CheckSlotForCreateSlot(const std::string &bundleName, const sptr &slot, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + ErrCode CheckGroupForCreateSlotGroup(const std::string &bundleName, const sptr &group, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + ErrCode CheckSlotForRemoveSlot(const std::string &bundleName, const NotificationConstant::SlotType &slotType, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + ErrCode CheckGroupForRemoveSlotGroup(const std::string &bundleName, const std::string &groupId, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + ErrCode CheckSlotForUpdateSlot(const std::string &bundleName, const sptr &slot, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + ErrCode CheckGroupForUpdateSlotGroup(const std::string &bundleName, const sptr &group, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const; + template + void SetBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, const std::string &bundleName, + const BundlePropertyType &type, const T &value); + template + void CreateBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, + const std::string &bundleName, const BundlePropertyType &type, const T &value); + template + void UpdateBundleProperty(BundleInfo &bundleInfo, nlohmann::json ¶seJson, const std::string &bundleName, + const BundlePropertyType &type, const T &value); + template + ErrCode GetBundleProperty(const std::string &bundleName, const BundlePropertyType &type, T &value); + + void AddSlotToJson(nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; + void AddSlotGroupToJson( + nlohmann::json &json, const std::string &bundleName, const sptr &group) const; + void UpdateExsitSlotTypeInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; + void RemoveSlotInJson( + nlohmann::json &json, const std::string &bundleName, const NotificationConstant::SlotType &type) const; + void UpdateSlotInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; + void RemoveSlotGroupInJson(nlohmann::json &json, const std::string &bundleName, const std::string &groupId) const; + void UpdateSlotGroupInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const; + void RemoveBundleInJson(nlohmann::json &json, const std::string &bundleName); + void AddJson(nlohmann::json &json, const BundleInfo &info, const NotificationConstant::DisturbMode &mode, + const bool &enable) const; + void ParseFromJson(); + ErrCode ParseNotification(); + ErrCode StoreNotification(const nlohmann::json &json) const; + ErrCode CommitNotification(const nlohmann::json ¶seJson, const PreferencesInfo &preferencesInfo); + + template + void CheckInvalidPath(T &t) const; + void InitDir() const; + void InitFile() const; + bool IsEmptyInputFile(std::ifstream &inputFile) const; + bool IsExistDir(const std::string &path) const; + bool IsExistFile(const std::string &dirPath, const std::string &filePath) const; + bool CreateDirectory(const std::string &path) const; + bool CreateAndChangeFileAttr(const std::string &filePath) const; + + nlohmann::json BundlePropertyToJson(const BundleInfo &bundleInfo) const; + nlohmann::json GroupToJson(const sptr &group) const; + nlohmann::json SlotToJson(const sptr &slot) const; + void JsonToBundleProperty(nlohmann::json &json, BundleInfo &bundleInfo) const; + void JsonToGroup(nlohmann::json &json, sptr &group) const; + void JsonToSlot(nlohmann::json &json, sptr &slot) const; + +private: + PreferencesInfo preferencesInfo_ {}; + nlohmann::json paraseJson_ {}; + + DECLARE_DELAYED_REF_SINGLETON(NotificationPreferences); +}; + +} // namespace Notification +} // namespace OHOS + +#endif // NOTIFICATION_PREFERENCES_H diff --git a/services/ans/include/notification_slot_filter.h b/services/ans/include/notification_slot_filter.h new file mode 100644 index 000000000..238fed9ca --- /dev/null +++ b/services/ans/include/notification_slot_filter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_SLOT_FILTER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_SLOT_FILTER_H + +#include "notification_filter.h" + +namespace OHOS { +namespace Notification { + +class NotificationSlotFilter : public INotificationFilter { +public: + NotificationSlotFilter(){}; + ~NotificationSlotFilter(){}; + + void OnStart() override; + void OnStop() override; + + ErrCode OnPublish(const sptr ¬ification) override; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_NOTIFICATION_SLOT_FILTER_H \ No newline at end of file diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h new file mode 100644 index 000000000..0e1ff2c11 --- /dev/null +++ b/services/ans/include/notification_subscriber_manager.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_NOTIFICATIONMGR_INCLUDE_NOTIFICATION_SUBSCRIBER_MANAGER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATIONMGR_INCLUDE_NOTIFICATION_SUBSCRIBER_MANAGER_H + +#include +#include +#include + +#include "errors.h" +#include "event_handler.h" +#include "event_runner.h" +#include "nocopyable.h" +#include "refbase.h" +#include "singleton.h" + +#include "ans_subscriber_interface.h" +#include "notification_constant.h" +#include "notification_request.h" +#include "notification_sorting_map.h" +#include "notification_subscribe_info.h" + +namespace OHOS { +namespace Notification { +class NotificationSubscriberManager : public DelayedSingleton { +public: + ErrCode AddSubscriber(const sptr &subscriber, const sptr &subscribeInfo); + ErrCode RemoveSubscriber( + const sptr &subscriber, const sptr &subscribeInfo); + + void NotifyConsumed(const sptr ¬ification, const sptr ¬ificationMap); + void NotifyCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); + void NotifyUpdated(const sptr ¬ificationMap); + void NotifyDisturbModeChanged(const NotificationConstant::DisturbMode &mode); + void OnRemoteDied(const wptr &object); + +private: + struct SubscriberRecord; + + std::shared_ptr FindSubscriberRecord(const wptr &object); + std::shared_ptr FindSubscriberRecord(const sptr &subscriber); + std::shared_ptr CreateSubscriberRecord(const sptr &subscriber); + void AddRecordInfo(std::shared_ptr &record, const sptr &subscribeInfo); + void RemoveRecordInfo( + std::shared_ptr &record, const sptr &subscribeInfo); + void AddSubscriberInner( + const sptr &subscriber, const sptr &subscribeInfo); + void RemoveSubscriberInner( + const sptr &subscriber, const sptr &subscribeInfo); + + void NotifyConsumedInner( + const sptr ¬ification, const sptr ¬ificationMap); + void NotifyCanceledInner( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); + void NotifyUpdatedInner(const sptr ¬ificationMap); + void NotifyDisturbModeChangedInner(const NotificationConstant::DisturbMode &mode); + +private: + std::list> subscriberRecordList_ {}; + std::shared_ptr runner_ {}; + std::shared_ptr handler_ {}; + sptr ansSubscriberProxy_ {}; + sptr recipient_ {}; + + DECLARE_DELAYED_SINGLETON(NotificationSubscriberManager); + DISALLOW_COPY_AND_MOVE(NotificationSubscriberManager); +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATIONMGR_INCLUDE_NOTIFICATION_SUBSCRIBER_MANAGER_H \ No newline at end of file diff --git a/services/ans/include/permission_filter.h b/services/ans/include/permission_filter.h new file mode 100644 index 000000000..00af78530 --- /dev/null +++ b/services/ans/include/permission_filter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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_ANS_STANDARD_SERVICES_ANS_INCLUDE_PERMISSION_FILTER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_PERMISSION_FILTER_H + +#include "notification_filter.h" + +namespace OHOS { +namespace Notification { + +class PermissionFilter : public INotificationFilter { +public: + PermissionFilter(){}; + ~PermissionFilter(){}; + + void OnStart() override; + void OnStop() override; + + ErrCode OnPublish(const sptr ¬ification) override; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_PERMISSION_FILTER_H \ No newline at end of file diff --git a/services/ans/include/remote_death_recipient.h b/services/ans/include/remote_death_recipient.h new file mode 100644 index 000000000..400dfd58d --- /dev/null +++ b/services/ans/include/remote_death_recipient.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 + +#include "iremote_object.h" +#include "refbase.h" + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H + +namespace OHOS { +namespace Notification { + +class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { +public: + RemoteDeathRecipient(std::function &)> callback) + { + callback_ = callback; + } + ~RemoteDeathRecipient() + { + callback_ = nullptr; + } + + // IRemoteObject::DeathRecipient + void OnRemoteDied(const wptr &object) + { + if (callback_ != nullptr) { + callback_(object); + } + } + +private: + std::function &)> callback_; +}; + +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp new file mode 100644 index 000000000..6d2e05d7b --- /dev/null +++ b/services/ans/src/advanced_notification_service.cpp @@ -0,0 +1,886 @@ +/* + * Copyright (c) 2021 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 "advanced_notification_service.h" + +#include + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "bundle_manager_helper.h" +#include "disturb_filter.h" +#include "ipc_skeleton.h" +#include "notification_constant.h" +#include "notification_filter.h" +#include "notification_preferences.h" +#include "notification_slot.h" +#include "notification_slot_filter.h" +#include "notification_subscriber_manager.h" +#include "permission_filter.h" + +namespace OHOS { +namespace Notification { + +sptr AdvancedNotificationService::instance_; +std::mutex AdvancedNotificationService::instanceMutex_; + +static const std::shared_ptr NOTIFICATION_FILTERS[] = { + std::make_shared(), + std::make_shared(), + std::make_shared(), +}; + +sptr AdvancedNotificationService::GetInstance() +{ + std::lock_guard lock(instanceMutex_); + + if (instance_ == nullptr) { + instance_ = new AdvancedNotificationService(); + } + return instance_; +} + +AdvancedNotificationService::AdvancedNotificationService() +{ + runner_ = OHOS::AppExecFwk::EventRunner::Create(); + handler_ = std::make_shared(runner_); + + StartFilters(); +} + +AdvancedNotificationService::~AdvancedNotificationService() +{ + StopFilters(); +} + +ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) && !IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + + std::string bundle = GetClientBundleName(); + request->SetOwnerBundleName(bundle); + request->SetCreatorBundleName(bundle); + + int32_t uid = IPCSkeleton::GetCallingUid(); + int32_t pid = IPCSkeleton::GetCallingPid(); + request->SetCreatorUid(uid); + request->SetCreatorPid(pid); + + sptr notification = new Notification(request); + handler_->PostSyncTask(std::bind([this, &label, ¬ification, &result]() { + result = Filter(notification); + if (result != ERR_OK) { + return; + } + + if (!IsNotificationExists(notification->GetKey())) { + AddToNotificationList(notification); + } else { + if (notification->request_->IsAlertOneTime()) { + notification->request_->SetColorEnabled(false); + notification->SetSound(Uri(std::string())); + notification->SetVibrationStyle(std::vector()); + } + UpdateInNotificationList(notification); + } + + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(notification, sortingMap); + })); + + return result; +} + +bool AdvancedNotificationService::IsNotificationExists(const std::string &key) +{ + bool isExists = false; + + for (auto item : notificationList_) { + if (item->GetKey() == key) { + isExists = true; + break; + } + } + + return isExists; +} + +ErrCode AdvancedNotificationService::Filter(const sptr ¬ification) +{ + ErrCode result = ERR_OK; + + for (auto filter : NOTIFICATION_FILTERS) { + result = filter->OnPublish(notification); + if (result != ERR_OK) { + break; + } + } + + return result; +} + +void AdvancedNotificationService::AddToNotificationList(const sptr ¬ification) +{ + notificationList_.push_back(notification); + SortNotificationList(); +} + +void AdvancedNotificationService::UpdateInNotificationList(const sptr ¬ification) +{ + auto iter = notificationList_.begin(); + while (iter != notificationList_.end()) { + if ((*iter)->GetKey() == notification->GetKey()) { + *iter = notification; + break; + } + iter++; + } + + SortNotificationList(); +} + +void AdvancedNotificationService::SortNotificationList() +{ + notificationList_.sort(AdvancedNotificationService::NotificationCompare); +} + +bool AdvancedNotificationService::NotificationCompare(const sptr &first, const sptr &second) +{ + // sorting notifications by create time + return (first->request_->GetCreateTime() < second->request_->GetCreateTime()); +} + +sptr AdvancedNotificationService::GenerateSortingMap() +{ + std::vector sortingList; + for (auto notification : notificationList_) { + NotificationSorting sorting; + sorting.SetKey(notification->GetKey()); + sptr slot; + if (NotificationPreferences::GetInstance().GetNotificationSlot( + notification->GetBundleName(), notification->request_->GetSlotType(), slot) == ERR_OK) { + sorting.SetRanking((int32_t)sortingList.size()); + sorting.SetSlot(slot); + } + sortingList.push_back(sorting); + } + + sptr sortingMap = new NotificationSortingMap(sortingList); + + return sortingMap; +} + +void AdvancedNotificationService::StartFilters() +{ + for (auto filter : NOTIFICATION_FILTERS) { + filter->OnStart(); + } +} + +void AdvancedNotificationService::StopFilters() +{ + for (auto filter : NOTIFICATION_FILTERS) { + filter->OnStop(); + } +} + +ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::string &label) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &label, notificationId, &result]() { + sptr notification = nullptr; + result = RemoveFromNotificationList(bundle, label, notificationId, notification); + if (result != ERR_OK) { + return; + } + + if (notification != nullptr) { + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled( + notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + } + })); + return result; +} + +ErrCode AdvancedNotificationService::CancelAll() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &result]() { + sptr notification = nullptr; + + std::vector removableList = GetRemovableNotificationKeys(bundle); + for (auto key : removableList) { + result = RemoveFromNotificationList(key, notification); + if (result != ERR_OK) { + continue; + } + + if (notification != nullptr) { + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled( + notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + } + } + })); + return result; +} + +inline bool IsCustomSlotContained(const std::vector> &slots) +{ + bool isContained = false; + for (auto slot : slots) { + if (slot->GetType() == NotificationConstant::SlotType::CUSTOM) { + isContained = true; + break; + } + } + return isContained; +} + +ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (IsCustomSlotContained(slots) && !IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { + result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots); + })); + return result; +} + +ErrCode AdvancedNotificationService::AddSlotGroups(std::vector> groups) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &groups, &result]() { + result = NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundle, groups); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetSlots(std::vector> &slots) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetSlotGroup(const std::string &groupId, sptr &group) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &groupId, &group, &result]() { + result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundle, groupId, group); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetSlotGroups(std::vector> &groups) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &groups, &result]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundle, groups); + })); + return result; +} + +ErrCode AdvancedNotificationService::RemoveSlotGroups(const std::vector &groupIds) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &groupIds, &result]() { + result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundle, groupIds); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetActiveNotifications(std::vector> ¬ifications) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, ¬ifications, &result]() { + for (auto notification : notificationList_) { + if (notification->GetBundleName() == bundle) { + notifications.push_back(notification->request_); + } + } + })); + return result; +} + +ErrCode AdvancedNotificationService::GetActiveNotificationNums(int &num) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &num, &result]() { + int count = 0; + for (auto notification : notificationList_) { + if (notification->GetBundleName() == bundle) { + count += 1; + } + } + num = count; + })); + return result; +} + +ErrCode AdvancedNotificationService::SetNotificationAgent(const std::string &agent) +{ + return ERR_OK; +} +ErrCode AdvancedNotificationService::GetNotificationAgent(std::string &agent) +{ + return ERR_OK; +} +ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish) +{ + return ERR_OK; +} +ErrCode AdvancedNotificationService::PublishAsBundle( + const sptr notification, const std::string &representativeBundle) +{ + return ERR_OK; +} + +ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int num) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &num, &result]() { + result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundle, num); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetBundleImportance(int &importance) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &importance, &result]() { + result = NotificationPreferences::GetInstance().GetImportance(bundle, importance); + })); + return result; +} + +ErrCode AdvancedNotificationService::SetDisturbMode(NotificationConstant::DisturbMode mode) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind( + [this, &bundle, mode, &result]() { result = NotificationPreferences::GetInstance().SetDisturbMode(mode); })); + return result; +} +ErrCode AdvancedNotificationService::GetDisturbMode(NotificationConstant::DisturbMode &mode) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind( + [this, &bundle, &mode, &result]() { result = NotificationPreferences::GetInstance().GetDisturbMode(mode); })); + return result; +} +ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted) +{ + return ERR_OK; +} + +ErrCode AdvancedNotificationService::SetPrivateNotificationsAllowed(bool allow) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &allow, &result]() { + result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundle, allow); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetPrivateNotificationsAllowed(bool &allow) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &allow, &result]() { + result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundle, allow); + })); + return result; +} + +ErrCode AdvancedNotificationService::Delete(const std::string &key) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind([this, &key, &result]() { + sptr notification = nullptr; + result = RemoveFromNotificationList(key, notification); + if (result != ERR_OK) { + return; + } + + if (notification != nullptr) { + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled( + notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + } + })); + + return result; +} + +ErrCode AdvancedNotificationService::DeleteByBundle(const std::string &bundle) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind([this, &bundle, &result]() { + sptr notification = nullptr; + + std::vector removableList = GetRemovableNotificationKeys(bundle); + for (auto key : removableList) { + result = RemoveFromNotificationList(key, notification); + if (result != ERR_OK) { + continue; + } + + if (notification != nullptr) { + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled( + notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + } + } + })); + + return result; +} + +ErrCode AdvancedNotificationService::DeleteAll() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &result]() { + sptr notification = nullptr; + + std::vector removableList = GetRemovableNotificationKeys(std::string()); + for (auto key : removableList) { + result = RemoveFromNotificationList(key, notification); + if (result != ERR_OK) { + continue; + } + + if (notification != nullptr) { + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled( + notification, sortingMap, NotificationConstant::CANCEL_REASON_DELETE); + } + } + })); + + return result; +} + +std::vector AdvancedNotificationService::GetRemovableNotificationKeys(const std::string &bundle) +{ + std::vector keys; + + for (auto item : notificationList_) { + if (!bundle.empty() && (item->GetBundleName() != bundle)) { + continue; + } + if (!item->GetNotificationRequest().IsUnremovable()) { + keys.push_back(item->GetKey()); + } + } + + return keys; +} + +ErrCode AdvancedNotificationService::GetSlotsByBundle( + const std::string &bundle, std::vector> &slots) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); + })); + return result; +} + +ErrCode AdvancedNotificationService::UpdateSlots( + const std::string &bundle, const std::vector> &slots) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &slots, &result]() { + result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); + })); + return result; +} + +ErrCode AdvancedNotificationService::UpdateSlotGroups( + const std::string &bundle, const std::vector> &groups) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &groups, &result]() { + result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); + })); + return result; +} + +ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &bundle, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { + result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled); + })); + return result; +} + +ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(const std::string &bundle, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { + result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(const std::string &bundle, bool &enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &enabled, &result]() { + result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); + })); + return result; +} + +ErrCode AdvancedNotificationService::RemoveFromNotificationList( + const std::string &bundle, const std::string &label, int notificationId, sptr ¬ification) +{ + for (auto item : notificationList_) { + if (item->GetBundleName() == bundle && item->GetLabel() == label && item->GetId() == notificationId) { + if (item->GetNotificationRequest().IsUnremovable()) { + return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + } + notification = item; + notificationList_.remove(item); + return ERR_OK; + } + } + + return ERR_ANS_NOTIFICATION_NOT_EXISTS; +} + +ErrCode AdvancedNotificationService::RemoveFromNotificationList( + const std::string &key, sptr ¬ification) +{ + for (auto item : notificationList_) { + if (item->GetKey() == key) { + if (item->GetNotificationRequest().IsUnremovable()) { + return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + } + notification = item; + notificationList_.remove(item); + return ERR_OK; + } + } + + return ERR_ANS_NOTIFICATION_NOT_EXISTS; +} + +std::string AdvancedNotificationService::GetClientBundleName() +{ + std::string bundle; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + bundle = bundleManager->GetBundleNameByUid(callingUid); + } + + return bundle; +} + +bool AdvancedNotificationService::IsSystemApp() +{ + bool isSystemApp = false; + + uid_t callingUid = IPCSkeleton::GetCallingUid(); + + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + isSystemApp = bundleManager->IsSystemApp(callingUid); + } + + return isSystemApp; +} + +ErrCode AdvancedNotificationService::Subscribe( + const sptr &subscriber, const sptr &info) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (subscriber == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + if (!IsSystemApp()) { + ANS_LOGE("Client is not a system app"); + return ERR_ANS_NON_SYSTEM_APP; + } + + return NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info); +} + +ErrCode AdvancedNotificationService::Unsubscribe( + const sptr &subscriber, const sptr &info) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (subscriber == nullptr) { + ANS_LOGE("Client is not a system app"); + return ERR_ANS_INVALID_PARAM; + } + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + return NotificationSubscriberManager::GetInstance()->RemoveSubscriber(subscriber, info); +} + +ErrCode AdvancedNotificationService::GetSlotByType( + const NotificationConstant::SlotType slotType, sptr &slot) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &slotType, &slot, &result]() { + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot); + })); + return result; +} + +ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant::SlotType slotType) +{ + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &slotType, &result]() { + result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType); + })); + return result; +} + +ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vector> ¬ifications) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, ¬ifications, &result]() { + notifications.assign(notificationList_.begin(), notificationList_.end()); + })); + return result; +} + +inline bool IsContained(const std::vector &vec, const std::string &target) +{ + bool isContained = false; + + auto iter = vec.begin(); + while (iter != vec.end()) { + if (*iter == target) { + isContained = true; + break; + } + iter++; + } + + return isContained; +} + +ErrCode AdvancedNotificationService::GetSpecialActiveNotifications( + const std::vector &key, std::vector> ¬ifications) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &key, ¬ifications, &result]() { + for (auto notification : notificationList_) { + if (IsContained(key, notification->GetKey())) { + notifications.push_back(notification); + } + } + })); + return result; +} + +ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &deviceId, &enabled, &result]() { + if (deviceId.empty()) { + // Local device + result = NotificationPreferences::GetInstance().SetNotificationsEnabled(enabled); + } else { + // Remote device + } + })); + return result; +} + +ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const std::string &bundleName, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &deviceId, &bundleName, &enabled, &result]() { + if (deviceId.empty()) { + // Local device + result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, enabled); + } else { + // Remote revice + } + })); + return result; +} + +ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + std::string bundle = GetClientBundleName(); + handler_->PostSyncTask(std::bind([this, &bundle, &allowed, &result]() { + allowed = false; + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); + if (result == ERR_OK && allowed) { + result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundle, allowed); + } + })); + return result; +} + +ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(const std::string &bundle, bool &allowed) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([this, &bundle, &allowed, &result]() { + allowed = false; + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); + if (result == ERR_OK && allowed) { + result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundle, allowed); + } + })); + return result; +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp new file mode 100644 index 000000000..f361f3d16 --- /dev/null +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 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 "advanced_notification_service_ability.h" + +namespace OHOS { +namespace Notification { + +namespace { +REGISTER_SYSTEM_ABILITY_BY_ID(AdvancedNotificationServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); +} + +AdvancedNotificationServiceAbility::AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate) + : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) +{} + +AdvancedNotificationServiceAbility::~AdvancedNotificationServiceAbility() +{} + +void AdvancedNotificationServiceAbility::OnStart() +{ + if (service_ != nullptr) { + return; + } + + service_ = AdvancedNotificationService::GetInstance(); + if (!Publish(service_)) { + return; + } +} + +void AdvancedNotificationServiceAbility::OnStop() +{ + service_ = nullptr; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp new file mode 100644 index 000000000..fca92739b --- /dev/null +++ b/services/ans/src/bundle_manager_helper.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 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 "bundle_manager_helper.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { + +BundleManagerHelper::BundleManagerHelper() +{ + deathRecipient_ = + new RemoteDeathRecipient(std::bind(&BundleManagerHelper::OnRemoteDied, this, std::placeholders::_1)); +} + +BundleManagerHelper::~BundleManagerHelper() +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +{ + std::string bundle; + + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + bundleMgr_->GetBundleNameForUid(uid, bundle); + } + + return bundle; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + bool isSystemApp = false; + + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + isSystemApp = bundleMgr_->CheckIsSystemAppByUid(uid); + } + + return isSystemApp; +} + +void BundleManagerHelper::Connect() +{ + if (bundleMgr_ != nullptr) { + return; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + return; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + return; + } + + bundleMgr_ = iface_cast(remoteObject); + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->AddDeathRecipient(deathRecipient_); + } +} + +void BundleManagerHelper::Disconnect() +{ + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->RemoveDeathRecipient(deathRecipient_); + bundleMgr_ = nullptr; + } +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp new file mode 100644 index 000000000..7bfc34788 --- /dev/null +++ b/services/ans/src/disturb_filter.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 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 "disturb_filter.h" + +namespace OHOS { +namespace Notification { + +void DisturbFilter::OnStart() +{} + +void DisturbFilter::OnStop() +{} + +ErrCode DisturbFilter::OnPublish(const sptr ¬ification) +{ + return ERR_OK; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp new file mode 100644 index 000000000..f0e2b499c --- /dev/null +++ b/services/ans/src/notification_preferences.cpp @@ -0,0 +1,1204 @@ +/* + * Copyright (c) 2021 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 "notification_preferences.h" + +#include +#include +#include + +#include "directory_ex.h" +#include "uri.h" + +#include "ans_const_define.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + +namespace { +const static std::string kStorePath = "/data/ans"; +const static std::string kStoreFile = kStorePath + "/Notification.json"; +const static std::string kDisturbMode = "disturbMode"; +const static std::string kEnable = "enable"; +const static std::string kBundle = "bundle"; +const static std::string kBundleName = "bundleName"; +const static std::string kBundleImportance = "importance"; +const static std::string kBundleShowBadge = "isShowBadge"; +const static std::string kBundleBadgeTotalNum = "badgeTotalNum"; +const static std::string kBundlePrivateAllowed = "isPrivateAllowed"; +const static std::string kBundleEnableNotification = "isEnabledNotification"; + +const static std::string kGroup = "slotGroup"; +const static std::string kGroupId = "groupId"; +const static std::string kGroupName = "groupName"; +const static std::string kGroupDescription = "groupDescription"; +const static std::string kGroupDisable = "isDisable"; + +const static std::string kSlot = "slot"; +const static std::string kSlotGroupId = "groupId"; +const static std::string kSlotId = "slotId"; +const static std::string kSlotType = "slotType"; +const static std::string kSlotName = "slotName"; +const static std::string kSlotDescription = "slotDescription"; +const static std::string kSlotLevel = "slotLevel"; +const static std::string kSlotShowBadge = "isShowBadge"; +const static std::string kSlotEnableLight = "isEnableLight"; +const static std::string kSlotEnableVrbration = "isEnableVibration"; +const static std::string kSlotLedLightColor = "ledLightColor"; +const static std::string kSlotLockscreenVisibleness = "isLockscreenVisibleness"; +const static std::string kSlotSound = "sound"; +const static std::string kSlotVibrationSytle = "vibrationSytle"; +const static std::string kSlotEnableBypassDnd = "isEnableBypassDnd"; + +const static uint8_t kJsonDump = 4; + +} // namespace + +enum class NotificationPreferences::BundlePropertyType { + kBundleImportanceType = 1, + kBundleShowBadgeType, + kBundleBadgeTotalNumType, + kBundlePrivateAllowedType, + kBundleEnableNotificationType, +}; + +NotificationPreferences::NotificationPreferences() +{ + InitDir(); + InitFile(); + ParseNotification(); +} + +NotificationPreferences::~NotificationPreferences() +{ + StoreNotification(paraseJson_); +} + +NotificationPreferences &NotificationPreferences::GetInstance() +{ + return DelayedRefSingleton::GetInstance(); +} + +ErrCode NotificationPreferences::AddNotificationSlots( + const std::string &bundleName, const std::vector> &slots) +{ + if (bundleName.empty() || slots.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + for (auto slot : slots) { + result = CheckSlotForCreateSlot(bundleName, slot, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + } + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::AddNotificationSlotGroups( + const std::string &bundleName, const std::vector> &groups) +{ + if (bundleName.empty() || groups.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + for (auto group : groups) { + result = CheckGroupForCreateSlotGroup(bundleName, group, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + } + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::RemoveNotificationSlot( + const std::string &bundleName, const NotificationConstant::SlotType &slotType) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + result = CheckSlotForRemoveSlot(bundleName, slotType, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::RemoveNotificationSlotGroups( + const std::string &bundleName, const std::vector &groupIds) +{ + if (bundleName.empty() || groupIds.empty()) { + return ERR_ANS_INVALID_PARAM; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + for (auto groupId : groupIds) { + result = CheckGroupForRemoveSlotGroup(bundleName, groupId, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + } + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::RemoveNotificationForBundle(const std::string &bundleName) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + + ErrCode result = ERR_OK; + auto iter = preferencesInfo.infos.find(bundleName); + if (iter != preferencesInfo.infos.end()) { + preferencesInfo.infos.erase(iter); + RemoveBundleInJson(paraseJson, bundleName); + result = CommitNotification(paraseJson, preferencesInfo); + } else { + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::UpdateNotificationSlots( + const std::string &bundleName, const std::vector> &slots) +{ + if (bundleName.empty() || slots.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + for (auto slotIter : slots) { + result = CheckSlotForUpdateSlot(bundleName, slotIter, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + } + + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::UpdateNotificationSlotGroups( + const std::string &bundleName, const std::vector> &groups) +{ + if (bundleName.empty() || groups.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + ErrCode result = ERR_OK; + for (auto groupIter : groups) { + result = CheckGroupForUpdateSlotGroup(bundleName, groupIter, preferencesInfo, paraseJson); + if (result != ERR_OK) { + return result; + } + } + + result = CommitNotification(paraseJson, preferencesInfo); + return result; +} + +ErrCode NotificationPreferences::GetNotificationSlot( + const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo_.infos.find(bundleName); + if (preferencesIter != preferencesInfo_.infos.end()) { + auto slotIter = preferencesIter->second.slots.find(type); + if (slotIter != preferencesIter->second.slots.end()) { + slot = slotIter->second; + } else { + result = CreateSlot(bundleName, type, slot); + } + } else { + result = CreateSlot(bundleName, type, slot); + } + return result; +} + +ErrCode NotificationPreferences::GetNotificationAllSlots( + const std::string &bundleName, std::vector> &slots) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto iter = preferencesInfo_.infos.find(bundleName); + if (iter != preferencesInfo_.infos.end()) { + std::for_each(iter->second.slots.begin(), + iter->second.slots.end(), + [&](std::map>::reference slot) { + slots.emplace_back(slot.second); + }); + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + + return result; +} + +ErrCode NotificationPreferences::GetNotificationSlotGroup( + const std::string &bundleName, const std::string &groupId, sptr &group) +{ + if (bundleName.empty() || groupId.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo_.infos.find(bundleName); + if (preferencesIter != preferencesInfo_.infos.end()) { + auto groupIter = preferencesIter->second.groups.begin(); + while (groupIter != preferencesIter->second.groups.end()) { + if (!groupId.compare(groupIter->first)) { + group = groupIter->second; + break; + } + ++groupIter; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::GetNotificationAllSlotGroups( + const std::string &bundleName, std::vector> &groups) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo_.infos.find(bundleName); + if (preferencesIter != preferencesInfo_.infos.end()) { + std::for_each(preferencesIter->second.groups.begin(), + preferencesIter->second.groups.end(), + [&](std::map>::reference group) { + groups.emplace_back(group.second); + }); + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup( + const std::string &bundleName, const std::string &groupId, std::vector> &slots) +{ + if (bundleName.empty() || groupId.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo_.infos.find(bundleName); + if (preferencesIter != preferencesInfo_.infos.end()) { + auto slotIter = preferencesIter->second.slots.begin(); + while (slotIter != preferencesIter->second.slots.end()) { + if ((slotIter->second != nullptr) && (!groupId.compare(slotIter->second->GetSlotGroup()))) { + slots.emplace_back(slotIter->second); + } + ++slotIter; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::IsShowBadge(const std::string &bundleName, bool &enable) +{ + ErrCode result = ERR_ANS_INVALID_PARAM; + if (bundleName.empty()) { + return result; + } + result = GetBundleProperty(bundleName, BundlePropertyType::kBundleShowBadgeType, enable); + return result; +} + +ErrCode NotificationPreferences::SetShowBadge(const std::string &bundleName, const bool enable) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + + SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleShowBadgeType, enable); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetImportance(const std::string &bundleName, int &importance) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleImportanceType, importance); + return result; +} + +ErrCode NotificationPreferences::SetImportance(const std::string &bundleName, const int importance) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleImportanceType, importance); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetTotalBadgeNums(const std::string &bundleName, int &totalBadgeNum) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleBadgeTotalNumType, totalBadgeNum); + return result; +} + +ErrCode NotificationPreferences::SetTotalBadgeNums(const std::string &bundleName, const int num) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleBadgeTotalNumType, num); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetPrivateNotificationsAllowed(const std::string &bundleName, bool &allow) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundlePrivateAllowedType, allow); + return result; +} + +ErrCode NotificationPreferences::SetPrivateNotificationsAllowed(const std::string &bundleName, const bool allow) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + SetBundleProperty(preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundlePrivateAllowedType, allow); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(const std::string &bundleName, bool &enabled) +{ + if (bundleName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + ErrCode result = GetBundleProperty(bundleName, BundlePropertyType::kBundleEnableNotificationType, enabled); + return result; +} + +ErrCode NotificationPreferences::SetNotificationsEnabledForBundle(const std::string &bundleName, const bool enabled) +{ + if (bundleName.empty()) { + return ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + SetBundleProperty( + preferencesInfo, paraseJson, bundleName, BundlePropertyType::kBundleEnableNotificationType, enabled); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetNotificationsEnabled(bool &enabled) +{ + enabled = preferencesInfo_.isEnabledAllNotification; + return ERR_OK; +} + +ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) +{ + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + preferencesInfo.isEnabledAllNotification = enabled; + paraseJson[kEnable] = enabled; + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::GetDisturbMode(NotificationConstant::DisturbMode &mode) +{ + mode = preferencesInfo_.disturbMode; + return ERR_OK; +} + +ErrCode NotificationPreferences::SetDisturbMode(const NotificationConstant::DisturbMode &mode) +{ + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + preferencesInfo.disturbMode = mode; + paraseJson[kDisturbMode] = mode; + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() +{ + PreferencesInfo preferencesInfo = preferencesInfo_; + nlohmann::json paraseJson = paraseJson_; + preferencesInfo.disturbMode = NotificationConstant::DisturbMode::ALLOW_ALL; + preferencesInfo.isEnabledAllNotification = true; + preferencesInfo.infos.clear(); + paraseJson.clear(); + return CommitNotification(paraseJson, preferencesInfo); +} + +ErrCode NotificationPreferences::CreateSlot( + const std::string &bundleName, const NotificationConstant::SlotType &type, sptr &slot) +{ + sptr tmpSlot; + switch (type) { + case NotificationConstant::SlotType::SOCIAL_COMMUNICATION: + tmpSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + break; + case NotificationConstant::SlotType::SERVICE_REMINDER: + tmpSlot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); + break; + case NotificationConstant::SlotType::CONTENT_INFORMATION: + tmpSlot = new NotificationSlot(NotificationConstant::SlotType::CONTENT_INFORMATION); + break; + case NotificationConstant::SlotType::OTHER: + case NotificationConstant::SlotType::CUSTOM: + tmpSlot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + break; + default: + break; + } + std::vector> slots; + slots.push_back(tmpSlot); + ErrCode result = AddNotificationSlots(bundleName, slots); + if (result == ERR_OK) { + slot = tmpSlot; + } + return result; +} + +ErrCode NotificationPreferences::CheckSlotForCreateSlot(const std::string &bundleName, + const sptr &slot, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + if (slot == nullptr) { + ANS_LOGE("Notification slot is nullptr."); + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.slots.find(slot->GetType()) != preferencesIter->second.slots.end()) { + preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); + UpdateExsitSlotTypeInJson(paraseJson, bundleName, slot); + } else { + preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); + AddSlotToJson(paraseJson, bundleName, slot); + } + } else { + BundleInfo bundle; + bundle.bundleName = bundleName; + bundle.slots.insert_or_assign(slot->GetType(), slot); + preferencesInfo.infos.insert_or_assign(bundleName, bundle); + AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); + } + + return result; +} + +ErrCode NotificationPreferences::CheckGroupForCreateSlotGroup(const std::string &bundleName, + const sptr &group, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + if (group == nullptr) { + ANS_LOGE("Notification slot group is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + if (group->GetId().empty()) { + ANS_LOGE("Notification slot group id is invalid."); + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.groups.find(group->GetId()) != preferencesIter->second.groups.end()) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_HAS_EXISTED; + } else { + if (preferencesIter->second.groups.size() >= MAX_SLOT_GROUP_NUM) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM; + } else { + preferencesIter->second.groups.insert_or_assign(group->GetId(), group); + AddSlotGroupToJson(paraseJson, bundleName, group); + } + } + } else { + BundleInfo bundle; + bundle.bundleName = bundleName; + bundle.groups.insert_or_assign(group->GetId(), group); + preferencesInfo.infos.insert_or_assign(bundleName, bundle); + AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); + } + + return result; +} + +ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const std::string &bundleName, + const NotificationConstant::SlotType &slotType, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.slots.empty()) { + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; + } + auto slotIter = preferencesIter->second.slots.find(slotType); + if (slotIter != preferencesIter->second.slots.end()) { + preferencesIter->second.slots.erase(slotIter); + RemoveSlotInJson(paraseJson, bundleName, slotType); + } else { + ANS_LOGE("Notification slot id is invalid."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::CheckGroupForRemoveSlotGroup(const std::string &bundleName, const std::string &groupId, + PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.groups.empty()) { + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; + } + auto groupIter = preferencesIter->second.groups.find(groupId); + if (groupIter != preferencesIter->second.groups.end()) { + preferencesIter->second.groups.erase(groupIter); + RemoveSlotGroupInJson(paraseJson, bundleName, groupId); + } else { + ANS_LOGE("Notification slot id is invalid."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const std::string &bundleName, + const sptr &slot, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + if (slot == nullptr) { + ANS_LOGE("Notification slot is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.slots.empty()) { + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; + } + auto slotIter = preferencesIter->second.slots.find(slot->GetType()); + if (slotIter != preferencesIter->second.slots.end()) { + preferencesIter->second.slots.insert_or_assign(slot->GetType(), slot); + UpdateSlotInJson(paraseJson, bundleName, slot); + } else { + ANS_LOGE("Notification slot id is invalid."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +ErrCode NotificationPreferences::CheckGroupForUpdateSlotGroup(const std::string &bundleName, + const sptr &group, PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson) const +{ + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + if (preferencesIter->second.groups.empty()) { + return ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; + } + auto groupIter = preferencesIter->second.groups.find(group->GetId()); + if (groupIter != preferencesIter->second.groups.end()) { + preferencesIter->second.groups.insert_or_assign(group->GetId(), group); + UpdateSlotGroupInJson(paraseJson, bundleName, group); + } else { + ANS_LOGE("Notification slot group id is invalid."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +template +void NotificationPreferences::SetBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, + const std::string &bundleName, const BundlePropertyType &type, const T &value) +{ + auto preferencesIter = preferencesInfo.infos.find(bundleName); + if (preferencesIter != preferencesInfo.infos.end()) { + UpdateBundleProperty(preferencesIter->second, paraseJson, bundleName, type, value); + } else { + CreateBundleProperty(preferencesInfo, paraseJson, bundleName, type, value); + } +} + +template +void NotificationPreferences::CreateBundleProperty(PreferencesInfo &preferencesInfo, nlohmann::json ¶seJson, + const std::string &bundleName, const BundlePropertyType &type, const T &value) +{ + BundleInfo bundle; + bundle.bundleName = bundleName; + switch (type) { + case BundlePropertyType::kBundleImportanceType: + bundle.importance = value; + break; + case BundlePropertyType::kBundleBadgeTotalNumType: + bundle.badgeTotalNum = value; + break; + case BundlePropertyType::kBundleShowBadgeType: + bundle.isShowBadge = value; + break; + case BundlePropertyType::kBundlePrivateAllowedType: + bundle.isPrivateAllowed = value; + break; + case BundlePropertyType::kBundleEnableNotificationType: + bundle.isEnabledNotification = value; + break; + default: + break; + } + preferencesInfo.infos.emplace(bundleName, bundle); + AddJson(paraseJson, bundle, preferencesInfo.disturbMode, preferencesInfo.isEnabledAllNotification); +} + +template +void NotificationPreferences::UpdateBundleProperty(BundleInfo &bundleInfo, nlohmann::json ¶seJson, + const std::string &bundleName, const BundlePropertyType &type, const T &value) +{ + auto packageJsonIter = paraseJson[kBundle].begin(); + while (packageJsonIter != paraseJson[kBundle].end()) { + if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { + break; + } + ++packageJsonIter; + } + switch (type) { + case BundlePropertyType::kBundleImportanceType: + bundleInfo.importance = value; + packageJsonIter->at(kBundleImportance) = value; + break; + case BundlePropertyType::kBundleBadgeTotalNumType: + bundleInfo.badgeTotalNum = value; + packageJsonIter->at(kBundleBadgeTotalNum) = value; + break; + case BundlePropertyType::kBundleShowBadgeType: + bundleInfo.isShowBadge = value; + packageJsonIter->at(kBundleShowBadge) = value; + break; + case BundlePropertyType::kBundlePrivateAllowedType: + bundleInfo.isPrivateAllowed = value; + packageJsonIter->at(kBundlePrivateAllowed) = value; + break; + case BundlePropertyType::kBundleEnableNotificationType: + bundleInfo.isEnabledNotification = value; + packageJsonIter->at(kBundleEnableNotification) = value; + break; + default: + break; + } +} + +template +ErrCode NotificationPreferences::GetBundleProperty( + const std::string &bundleName, const BundlePropertyType &type, T &value) +{ + ErrCode result = ERR_OK; + auto preferencesIter = preferencesInfo_.infos.find(bundleName); + if (preferencesIter != preferencesInfo_.infos.end()) { + switch (type) { + case BundlePropertyType::kBundleImportanceType: + value = preferencesIter->second.importance; + break; + case BundlePropertyType::kBundleBadgeTotalNumType: + value = preferencesIter->second.badgeTotalNum; + break; + case BundlePropertyType::kBundleShowBadgeType: + value = preferencesIter->second.isShowBadge; + break; + case BundlePropertyType::kBundlePrivateAllowedType: + value = preferencesIter->second.isPrivateAllowed; + break; + case BundlePropertyType::kBundleEnableNotificationType: + value = preferencesIter->second.isEnabledNotification; + break; + default: + result = ERR_ANS_INVALID_PARAM; + break; + } + } else { + ANS_LOGE("Notification bundle does not exsit."); + result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + } + return result; +} + +void NotificationPreferences::AddSlotToJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const +{ + auto packageJsonIter = json[kBundle].begin(); + while (packageJsonIter != json[kBundle].end()) { + if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { + (*packageJsonIter)[kSlot].emplace_back(SlotToJson(slot)); + break; + } + ++packageJsonIter; + } +} + +void NotificationPreferences::AddSlotGroupToJson( + nlohmann::json &json, const std::string &bundleName, const sptr &group) const +{ + auto packageJsonIter = json[kBundle].begin(); + while (packageJsonIter != json[kBundle].end()) { + if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { + (*packageJsonIter)[kGroup].emplace_back(GroupToJson(group)); + break; + } + ++packageJsonIter; + } +} + +void NotificationPreferences::UpdateExsitSlotTypeInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const +{ + for (auto &packageJsonIter : json[kBundle]) { + if (bundleName.compare(packageJsonIter[kBundleName].get())) { + continue; + } + + for (auto &slotJsonIter : packageJsonIter[kSlot]) { + if (slot->GetType() == slotJsonIter[kSlotType].get()) { + slotJsonIter[kSlotId] = slot->GetId(); + slotJsonIter[kSlotName] = slot->GetName(); + slotJsonIter[kSlotDescription] = slot->GetDescription(); + break; + } + } + } +} + +void NotificationPreferences::RemoveSlotInJson( + nlohmann::json &json, const std::string &bundleName, const NotificationConstant::SlotType &type) const +{ + for (auto &packageJsonIter : json[kBundle]) { + if (bundleName.compare(packageJsonIter[kBundleName].get())) { + continue; + } + + auto slotJsonIter = packageJsonIter[kSlot].begin(); + while (slotJsonIter != packageJsonIter[kSlot].end()) { + if (type == (*slotJsonIter)[kSlotType].get()) { + packageJsonIter[kSlot].erase(slotJsonIter); + break; + } + ++slotJsonIter; + } + } +} + +void NotificationPreferences::UpdateSlotInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &slot) const +{ + for (auto &packageJsonIter : json[kBundle]) { + if (bundleName.compare(packageJsonIter[kBundleName].get())) { + continue; + } + + auto slotJsonIter = packageJsonIter[kSlot].begin(); + while (slotJsonIter != packageJsonIter[kSlot].end()) { + if (!slot->GetId().compare((*slotJsonIter)[kSlotId].get())) { + nlohmann::json tempSlotJson = SlotToJson(slot); + (*slotJsonIter).update(tempSlotJson.begin(), tempSlotJson.end()); + break; + } + ++slotJsonIter; + } + } +} + +void NotificationPreferences::RemoveSlotGroupInJson( + nlohmann::json &json, const std::string &bundleName, const std::string &groupId) const +{ + for (auto &packageJsonIter : json[kBundle]) { + if (bundleName.compare(packageJsonIter[kBundleName].get())) { + continue; + } + + auto groupJsonIter = packageJsonIter[kGroup].begin(); + while (groupJsonIter != packageJsonIter[kGroup].end()) { + if (!groupId.compare((*groupJsonIter)[kGroupId].get())) { + packageJsonIter[kGroup].erase(groupJsonIter); + break; + } + ++groupJsonIter; + } + } +} + +void NotificationPreferences::UpdateSlotGroupInJson( + nlohmann::json &json, const std::string &bundleName, const sptr &group) const +{ + for (auto &packageJsonIter : json[kBundle]) { + if (bundleName.compare(packageJsonIter[kBundleName].get())) { + continue; + } + + auto groupJsonIter = packageJsonIter[kGroup].begin(); + while (groupJsonIter != packageJsonIter[kGroup].end()) { + if (!group->GetId().compare((*groupJsonIter)[kGroupId].get())) { + nlohmann::json tempGroupJson = GroupToJson(group); + (*groupJsonIter).update(tempGroupJson.begin(), tempGroupJson.end()); + break; + } + ++groupJsonIter; + } + } +} + +void NotificationPreferences::RemoveBundleInJson(nlohmann::json &json, const std::string &bundleName) +{ + auto packageJsonIter = json[kBundle].begin(); + while (packageJsonIter != json[kBundle].end()) { + if (!bundleName.compare((*packageJsonIter)[kBundleName].get())) { + json[kBundle].erase(packageJsonIter); + break; + } + ++packageJsonIter; + } +} + +void NotificationPreferences::AddJson(nlohmann::json &json, const BundleInfo &info, + const NotificationConstant::DisturbMode &mode, const bool &enable) const +{ + nlohmann::json preferencesJson = BundlePropertyToJson(info); + if (!info.groups.empty()) { + for (auto groupIter : info.groups) { + preferencesJson[kGroup].emplace_back(GroupToJson(groupIter.second)); + } + } + + if (!info.slots.empty()) { + for (auto slotIter : info.slots) { + preferencesJson[kSlot].emplace_back(SlotToJson(slotIter.second)); + } + } + json[kBundle].emplace_back(preferencesJson); + + if (json[kDisturbMode].is_null()) { + json[kDisturbMode] = mode; + } + + if (json[kEnable].is_null()) { + json[kEnable] = enable; + } +} + +void NotificationPreferences::ParseFromJson() +{ + if (paraseJson_.empty() || !paraseJson_.contains(kBundle)) { + ANS_LOGE("Current file is empty."); + return; + } + preferencesInfo_.disturbMode = paraseJson_[kDisturbMode].get(); + preferencesInfo_.isEnabledAllNotification = paraseJson_[kEnable].get(); + for (auto packageIter : paraseJson_[kBundle]) { + BundleInfo bundleInfo; + JsonToBundleProperty(packageIter, bundleInfo); + preferencesInfo_.infos.emplace(std::make_pair(bundleInfo.bundleName, bundleInfo)); + for (auto groupIter : packageIter[kGroup]) { + sptr group = new NotificationSlotGroup( + groupIter[kGroupId].get(), groupIter[kGroupName].get()); + JsonToGroup(groupIter, group); + preferencesInfo_.infos.at(bundleInfo.bundleName).groups.emplace(std::make_pair(group->GetId(), group)); + } + + for (auto &slotIter : packageIter[kSlot]) { + sptr slot = + new NotificationSlot(slotIter[kSlotType].get()); + JsonToSlot(slotIter, slot); + preferencesInfo_.infos.at(bundleInfo.bundleName).slots.emplace(std::make_pair(slot->GetType(), slot)); + } + } +} + +ErrCode NotificationPreferences::ParseNotification() +{ + std::ifstream inputFile(kStoreFile, std::ifstream::in); + CheckInvalidPath(inputFile); + if (IsEmptyInputFile(inputFile)) { + return ERR_ANS_PREFERENCES_FILE_IS_NULL; + } + + ErrCode result = ERR_OK; + try { + paraseJson_ = nlohmann::json::parse(inputFile); + inputFile.close(); + } catch (const nlohmann::detail::exception &e) { + ANS_LOGE("Exception file error is: %{public}s", e.what()); + paraseJson_.clear(); + result = ERR_ANS_PREFERENCES_FILE_EXCEPTION; + } + if (result == ERR_OK) { + ParseFromJson(); + } + return result; +} + +ErrCode NotificationPreferences::StoreNotification(const nlohmann::json &json) const +{ + std::ofstream outFile(kStoreFile, std::ofstream::out); + CheckInvalidPath(outFile); + + outFile.exceptions(std::ofstream::failbit | std::ofstream::badbit); + ErrCode result = ERR_OK; + try { + outFile << json.dump(kJsonDump); + outFile.flush(); + outFile.close(); + } catch (std::ofstream::failure e) { + ANS_LOGE("Exception file error is: %{public}s", e.what()); + result = ERR_ANS_PREFERENCES_FILE_EXCEPTION; + } + return result; +} + +ErrCode NotificationPreferences::CommitNotification( + const nlohmann::json ¶seJson, const PreferencesInfo &preferencesInfo) +{ + ErrCode result = StoreNotification(paraseJson); + + if (result == ERR_OK) { + preferencesInfo_ = preferencesInfo; + paraseJson_ = paraseJson; + } + return result; +} + +template +void NotificationPreferences::CheckInvalidPath(T &t) const +{ + if (!t.is_open()) { + ANS_LOGI("File does not open, create a new dir"); + InitDir(); + InitFile(); + } +} + +bool NotificationPreferences::IsEmptyInputFile(std::ifstream &inputFile) const +{ + inputFile.seekg(0, inputFile.end); + if (0 == inputFile.tellg()) { + ANS_LOGI("InputFile is empty, does not parase json file."); + return true; + } + inputFile.seekg(0, inputFile.beg); + return false; +} + +void NotificationPreferences::InitDir() const +{ + if (IsExistDir(kStorePath)) { + ANS_LOGI("Path already exists."); + return; + } + + if (!CreateDirectory(kStorePath)) { + ANS_LOGE("create path failed %{public}s", strerror(errno)); + } +} + +void NotificationPreferences::InitFile() const +{ + if (IsExistFile(kStorePath, kStoreFile)) { + ANS_LOGI("File already exists."); + return; + } + + if (!CreateAndChangeFileAttr(kStoreFile)) { + ANS_LOGE("Change file attr failed %{public}s", strerror(errno)); + } +} + +bool NotificationPreferences::IsExistDir(const std::string &path) const +{ + struct stat buf = {}; + if (stat(path.c_str(), &buf) != 0) { + return false; + } + return S_ISDIR(buf.st_mode); +} + +bool NotificationPreferences::IsExistFile(const std::string &dirPath, const std::string &filePath) const +{ + std::vector files; + OHOS::GetDirFiles(dirPath, files); + auto iter = + std::find_if(files.begin(), files.end(), [&filePath](std::string &path) { return !path.compare(filePath); }); + + if (iter != files.end()) { + return true; + } + return false; +} + +bool NotificationPreferences::CreateDirectory(const std::string &path) const +{ + if (!OHOS::ForceCreateDirectory(path)) { + ANS_LOGE("mkdir failed"); + return false; + } + mode_t mode = S_IRWXU | S_IRGRP; + return OHOS::ChangeModeDirectory(path, mode); +} + +bool NotificationPreferences::CreateAndChangeFileAttr(const std::string &filePath) const +{ + std::ofstream outFile(filePath, std::ofstream::out); + if (outFile.is_open()) { + outFile.clear(); + outFile.close(); + ANS_LOGI("Create a json file."); + } + mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; + return OHOS::ChangeModeFile(filePath, mode); +} + +nlohmann::json NotificationPreferences::BundlePropertyToJson(const BundleInfo &bundleInfo) const +{ + return nlohmann::json{{kBundleName, bundleInfo.bundleName}, + {kBundleImportance, bundleInfo.importance}, + {kBundleShowBadge, bundleInfo.isShowBadge}, + {kBundleBadgeTotalNum, bundleInfo.badgeTotalNum}, + {kBundlePrivateAllowed, bundleInfo.isPrivateAllowed}, + {kBundleEnableNotification, bundleInfo.isEnabledNotification}}; +} + +nlohmann::json NotificationPreferences::GroupToJson(const sptr &group) const +{ + return nlohmann::json{{kGroupId, group->GetId()}, + {kGroupName, group->GetName()}, + {kGroupDescription, group->GetDescription()}, + {kGroupDisable, group->IsDisabled()}}; +} + +nlohmann::json NotificationPreferences::SlotToJson(const sptr &slot) const +{ + return nlohmann::json{{kSlotGroupId, slot->GetSlotGroup()}, + {kSlotId, slot->GetId()}, + {kSlotName, slot->GetName()}, + {kSlotDescription, slot->GetDescription()}, + {kSlotLevel, slot->GetLevel()}, + {kSlotShowBadge, slot->IsShowBadge()}, + {kSlotEnableLight, slot->CanEnableLight()}, + {kSlotEnableVrbration, slot->CanVibrate()}, + {kSlotLedLightColor, slot->GetLedLightColor()}, + {kSlotLockscreenVisibleness, slot->GetLockScreenVisibleness()}, + {kSlotSound, slot->GetSound().ToString()}, + {kSlotVibrationSytle, slot->GetVibrationStyle()}, + {kSlotEnableBypassDnd, slot->IsEnableBypassDnd()}, + {kSlotType, slot->GetType()}}; +} + +void NotificationPreferences::JsonToBundleProperty(nlohmann::json &json, BundleInfo &bundleInfo) const +{ + json.at(kBundleName).get_to(bundleInfo.bundleName); + json.at(kBundleImportance).get_to(bundleInfo.importance); + json.at(kBundleShowBadge).get_to(bundleInfo.isShowBadge); + json.at(kBundleBadgeTotalNum).get_to(bundleInfo.badgeTotalNum); + json.at(kBundlePrivateAllowed).get_to(bundleInfo.isPrivateAllowed); + json.at(kBundleEnableNotification).get_to(bundleInfo.isEnabledNotification); +} + +void NotificationPreferences::JsonToGroup(nlohmann::json &json, sptr &group) const +{ + group->SetDescription(json[kGroupDescription].get()); +} + +void NotificationPreferences::JsonToSlot(nlohmann::json &json, sptr &slot) const +{ + slot->SetSlotGroup(json[kSlotGroupId].get()); + slot->SetDescription(json[kSlotDescription].get()); + slot->SetLevel(json[kSlotLevel].get()); + slot->EnableBadge(json[kSlotShowBadge].get()); + slot->SetEnableLight(json[kSlotEnableLight].get()); + slot->SetLedLightColor(json[kSlotLedLightColor].get()); + slot->SetLockscreenVisibleness(json[kSlotLockscreenVisibleness].get()); + Uri uri(json[kSlotSound].get()); + slot->SetSound(uri); + slot->SetVibrationStyle(json[kSlotVibrationSytle].get>()); + slot->EnableBypassDnd(json[kSlotEnableBypassDnd].get()); + slot->SetType(json[kSlotType].get()); +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp new file mode 100644 index 000000000..931437b1d --- /dev/null +++ b/services/ans/src/notification_slot_filter.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 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 "notification_slot_filter.h" + +#include "notification_preferences.h" + +namespace OHOS { +namespace Notification { + +void NotificationSlotFilter::OnStart() +{} + +void NotificationSlotFilter::OnStop() +{} + +ErrCode NotificationSlotFilter::OnPublish(const sptr ¬ification) +{ + sptr slot; + ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot( + notification->GetBundleName(), notification->request_->GetSlotType(), slot); + if (result == ERR_OK && slot != nullptr) { + if (slot->CanEnableLight()) { + notification->SetLedLightColor(slot->GetLedLightColor()); + } + + if (slot->CanVibrate()) { + notification->SetVibrationStyle(slot->GetVibrationStyle()); + } + + notification->SetSound(slot->GetSound()); + + notification->request_->SetVisibleness(slot->GetLockScreenVisibleness()); + } + + return result; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp new file mode 100644 index 000000000..f39e953f5 --- /dev/null +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2021 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 "notification_subscriber_manager.h" + +#include +#include +#include + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "remote_death_recipient.h" + +namespace OHOS { +namespace Notification { + +struct NotificationSubscriberManager::SubscriberRecord { + sptr subscriber {nullptr}; + std::set bundleList_ {}; + bool subscribedAll {false}; +}; + +NotificationSubscriberManager::NotificationSubscriberManager() +{ + runner_ = OHOS::AppExecFwk::EventRunner::Create(); + handler_ = std::make_shared(runner_); + recipient_ = + new RemoteDeathRecipient(std::bind(&NotificationSubscriberManager::OnRemoteDied, this, std::placeholders::_1)); +} + +NotificationSubscriberManager::~NotificationSubscriberManager() +{ + subscriberRecordList_.clear(); +} + +ErrCode NotificationSubscriberManager::AddSubscriber( + const sptr &subscriber, const sptr &subscribeInfo) +{ + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null."); + return ERR_ANS_INVALID_PARAM; + } + + AppExecFwk::EventHandler::Callback addSubscriberFunc = + std::bind(&NotificationSubscriberManager::AddSubscriberInner, this, subscriber, subscribeInfo); + + if (!handler_->PostTask(addSubscriberFunc, AppExecFwk::EventQueue::Priority::HIGH)) { + return ERR_ANS_TASK_ERR; + } + return ERR_OK; +} + +ErrCode NotificationSubscriberManager::RemoveSubscriber( + const sptr &subscriber, const sptr &subscribeInfo) +{ + if (subscriber == nullptr) { + ANS_LOGE("subscriber is null."); + return ERR_ANS_INVALID_PARAM; + } + + AppExecFwk::EventHandler::Callback removeSubscriberFunc = + std::bind(&NotificationSubscriberManager::RemoveSubscriberInner, this, subscriber, subscribeInfo); + + if (!handler_->PostTask(removeSubscriberFunc, AppExecFwk::EventQueue::Priority::HIGH)) { + return ERR_ANS_TASK_ERR; + } + return ERR_OK; +} + +void NotificationSubscriberManager::NotifyConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{ + if (handler_ == nullptr) { + ANS_LOGE("handler is nullptr"); + return; + } + + AppExecFwk::EventHandler::Callback NotifyConsumedFunc = + std::bind(&NotificationSubscriberManager::NotifyConsumedInner, this, notification, notificationMap); + + handler_->PostTask(NotifyConsumedFunc); +} + +void NotificationSubscriberManager::NotifyCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) +{ + if (handler_ == nullptr) { + ANS_LOGE("handler is nullptr"); + return; + } + + AppExecFwk::EventHandler::Callback NotifyCanceledFunc = std::bind( + &NotificationSubscriberManager::NotifyCanceledInner, this, notification, notificationMap, deleteReason); + + handler_->PostTask(NotifyCanceledFunc); +} + +void NotificationSubscriberManager::NotifyUpdated(const sptr ¬ificationMap) +{ + if (handler_ == nullptr) { + ANS_LOGE("handler is nullptr"); + return; + } + + AppExecFwk::EventHandler::Callback NotifyUpdatedFunc = + std::bind(&NotificationSubscriberManager::NotifyUpdatedInner, this, notificationMap); + + handler_->PostTask(NotifyUpdatedFunc); +} + +void NotificationSubscriberManager::NotifyDisturbModeChanged(const NotificationConstant::DisturbMode &mode) +{ + if (handler_ == nullptr) { + ANS_LOGE("handler is nullptr"); + return; + } + + AppExecFwk::EventHandler::Callback NotifyDisturbModeChangedFunc = + std::bind(&NotificationSubscriberManager::NotifyDisturbModeChangedInner, this, mode); + + handler_->PostTask(NotifyDisturbModeChangedFunc); +} + +void NotificationSubscriberManager::OnRemoteDied(const wptr &object) +{ + ANS_LOGI("OnRemoteDied"); + handler_->PostSyncTask(std::bind([this, object]() { + std::shared_ptr record = FindSubscriberRecord(object); + if (record != nullptr) { + ANS_LOGW("subscriber removed."); + subscriberRecordList_.remove(record); + } + }), + AppExecFwk::EventQueue::Priority::HIGH); +} + +std::shared_ptr NotificationSubscriberManager::FindSubscriberRecord( + const wptr &object) +{ + auto iter = subscriberRecordList_.begin(); + + for (; iter != subscriberRecordList_.end(); iter++) { + if ((*iter)->subscriber->AsObject() == object) { + return (*iter); + } + } + return nullptr; +} + +std::shared_ptr NotificationSubscriberManager::FindSubscriberRecord( + const sptr &subscriber) +{ + auto iter = subscriberRecordList_.begin(); + + for (; iter != subscriberRecordList_.end(); iter++) { + if ((*iter)->subscriber->AsObject() == subscriber->AsObject()) { + return (*iter); + } + } + return nullptr; +} + +std::shared_ptr NotificationSubscriberManager::CreateSubscriberRecord( + const sptr &subscriber) +{ + std::shared_ptr record = std::make_shared(); + if (record != nullptr) { + record->subscriber = subscriber; + } + return record; +} + +void NotificationSubscriberManager::AddRecordInfo( + std::shared_ptr &record, const sptr &subscribeInfo) +{ + if (subscribeInfo != nullptr) { + record->bundleList_.clear(); + record->subscribedAll = false; + for (auto bundle : subscribeInfo->GetAppNames()) { + record->bundleList_.insert(bundle); + } + } else { + record->bundleList_.clear(); + record->subscribedAll = true; + } +} + +void NotificationSubscriberManager::RemoveRecordInfo( + std::shared_ptr &record, const sptr &subscribeInfo) +{ + if (subscribeInfo != nullptr) { + for (auto bundle : subscribeInfo->GetAppNames()) { + if (record->subscribedAll) { + record->bundleList_.insert(bundle); + } else { + record->bundleList_.erase(bundle); + } + } + } else { + record->bundleList_.clear(); + record->subscribedAll = false; + } +} + +void NotificationSubscriberManager::AddSubscriberInner( + const sptr &subscriber, const sptr &subscribeInfo) +{ + std::shared_ptr record = FindSubscriberRecord(subscriber); + + if (record == nullptr) { + record = CreateSubscriberRecord(subscriber); + if (record == nullptr) { + ANS_LOGE("CreateSubscriberRecord failed."); + subscriber->OnSubscribeResult(NotificationConstant::RESOURCES_FAIL); + return; + } + subscriberRecordList_.push_back(record); + + record->subscriber->AsObject()->AddDeathRecipient(recipient_); + + record->subscriber->OnSubscribeResult(NotificationConstant::SUCCESS); + ANS_LOGI("subscriber is connected."); + } + + AddRecordInfo(record, subscribeInfo); + + return; +} + +void NotificationSubscriberManager::RemoveSubscriberInner( + const sptr &subscriber, const sptr &subscribeInfo) +{ + std::shared_ptr record = FindSubscriberRecord(subscriber); + + if (record == nullptr) { + ANS_LOGE("subscriber not found."); + subscriber->OnUnsubscribeResult(NotificationConstant::SUCCESS); + return; + } + + RemoveRecordInfo(record, subscribeInfo); + + if (record->subscribedAll == false && record->bundleList_.empty()) { + record->subscriber->AsObject()->RemoveDeathRecipient(recipient_); + + subscriberRecordList_.remove(record); + + record->subscriber->OnUnsubscribeResult(NotificationConstant::SUCCESS); + ANS_LOGI("subscriber is disconnected."); + } + + return; +} + +void NotificationSubscriberManager::NotifyConsumedInner( + const sptr ¬ification, const sptr ¬ificationMap) +{ + for (auto record : subscriberRecordList_) { + auto BundleNames = notification->GetBundleName(); + + auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); + if (record->subscribedAll ^ (iter != record->bundleList_.end())) { + record->subscriber->OnConsumed(notification, notificationMap); + record->subscriber->OnConsumed(notification); + } + } +} + +void NotificationSubscriberManager::NotifyCanceledInner( + const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) +{ + for (auto record : subscriberRecordList_) { + auto BundleNames = notification->GetBundleName(); + + auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); + if (iter != record->bundleList_.end() ^ record->subscribedAll) { + record->subscriber->OnCanceled(notification, notificationMap, deleteReason); + record->subscriber->OnCanceled(notification); + } + } +} + +void NotificationSubscriberManager::NotifyUpdatedInner(const sptr ¬ificationMap) +{ + for (auto record : subscriberRecordList_) { + record->subscriber->OnUpdated(notificationMap); + } +} + +void NotificationSubscriberManager::NotifyDisturbModeChangedInner(const NotificationConstant::DisturbMode &mode) +{ + for (auto record : subscriberRecordList_) { + + record->subscriber->OnDisturbModeChanged(mode); + } +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp new file mode 100644 index 000000000..794d7bd4a --- /dev/null +++ b/services/ans/src/permission_filter.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 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 "permission_filter.h" + +#include "notification_preferences.h" + +namespace OHOS { +namespace Notification { + +void PermissionFilter::OnStart() +{} + +void PermissionFilter::OnStop() +{} + +ErrCode PermissionFilter::OnPublish(const sptr ¬ification) +{ + bool enable = false; + ErrCode result = + NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(notification->GetBundleName(), enable); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + enable = true; + } + if (result == ERR_OK) { + if (!enable) { + result = ERR_ANS_NOT_ALLOWED; + } + + if (notification->GetBundleName() != notification->GetCreateBundle()) { + // Publish as bundle + } + } + return result; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn new file mode 100644 index 000000000..75a29c4d2 --- /dev/null +++ b/services/ans/test/unittest/BUILD.gn @@ -0,0 +1,113 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/unittest" + +config("test_ans_config") { + include_dirs = [ + "${services_path}/ans/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "${kits_path}/native/include", + ] +} + +config("json_config") { + cflags_cc = [ "-fexceptions" ] +} + +ohos_unittest("ans_unit_test") { + module_out_path = module_output_path + include_dirs = [ + "include", + "${innerkits_path}/base/include", + "${innerkits_path}/core/include", + "${kits_path}/native/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/libs/libeventhandler/src", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//base/notification/ans_standard/services/ans/include", + "//third_party/json/include", + "//base/notification/ans_standard/services/ans/test/unittest/mock/include", + ] + + sources = [ + "//base/notification/ans_standard/innerkits/core/src/ans_manager_stub.cpp", + "//base/notification/ans_standard/kits/native/src/notification.cpp", + "//base/notification/ans_standard/services/ans/src/advanced_notification_service.cpp", + "//base/notification/ans_standard/services/ans/src/advanced_notification_service_ability.cpp", + "//base/notification/ans_standard/services/ans/src/bundle_manager_helper.cpp", + "//base/notification/ans_standard/services/ans/src/disturb_filter.cpp", + "//base/notification/ans_standard/services/ans/src/notification_preferences.cpp", + "//base/notification/ans_standard/services/ans/src/notification_slot_filter.cpp", + "//base/notification/ans_standard/services/ans/src/notification_subscriber_manager.cpp", + "//base/notification/ans_standard/services/ans/src/permission_filter.cpp", + "advanced_notification_service_ability_test.cpp", + "advanced_notification_service_test.cpp", + "bundle_manager_helper_test.cpp", + "disturb_filter_test.cpp", + "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "notification_preferences_test.cpp", + "notification_slot_filter_test.cpp", + "notification_subscriber_manager_test.cpp", + "permission_filter_test.cpp", + ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ":test_ans_config", + ":json_config", + ] + + deps = [ + "${innerkits_path}:ans_innerkits", + "${kits_path}/native:ans_kits", + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("unittest") { + testonly = true + deps = [] + + deps += [ ":ans_unit_test" ] +} diff --git a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp new file mode 100644 index 000000000..b1518c831 --- /dev/null +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 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 "advanced_notification_service_ability.h" +#include +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class AdvancedNotificationServiceAbilityTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AdvancedNotificationServiceAbilityTest::SetUpTestCase() +{} + +void AdvancedNotificationServiceAbilityTest::TearDownTestCase() +{} + +void AdvancedNotificationServiceAbilityTest::SetUp() +{} + +void AdvancedNotificationServiceAbilityTest::TearDown() +{} + +/** + * @tc.number : AdvancedNotificationServiceAbilityTest_00100 + * @tc.name : AMS_ANS_AdvancedNotificationServiceAbility_0100 + * @tc.desc : structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + */ +HWTEST_F( + AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00100, Function | SmallTest | Level1) +{ + int32_t systemAbilityId = 1; + bool runOnCreate = true; + AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp new file mode 100644 index 000000000..c3cbc03a8 --- /dev/null +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -0,0 +1,872 @@ +/* + * Copyright (c) 2021 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 "advanced_notification_service.h" +#include "notification_preferences.h" +#include +#include +#define private public +#include "notification_subscriber.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class AdvancedNotificationServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +sptr g_advancedNotificationService; +void AdvancedNotificationServiceTest::SetUpTestCase() +{ + g_advancedNotificationService = AdvancedNotificationService::GetInstance(); +} + +void AdvancedNotificationServiceTest::TearDownTestCase() +{ + sptr g_advancedNotificationService = nullptr; +} + +void AdvancedNotificationServiceTest::SetUp() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void AdvancedNotificationServiceTest::TearDown() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +class TestAnsSubscriber : public NotificationSubscriber { +public: + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnDied() override + {} + virtual void OnUpdate(const std::shared_ptr &sortingMap) override + {} + virtual void OnDisturbModeChanged(int disturbMode) override + {} + virtual void OnCanceled(const std::shared_ptr &request) override + {} + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + virtual void OnConsumed(const std::shared_ptr &request) override + {} + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} +}; + +void TestAddSlots() +{ + std::vector> slots; + sptr slotOther = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slotOther); + g_advancedNotificationService->AddSlots(slots); +} + +void TestAddSlotGroups() +{ + std::vector> groups; + sptr group = new NotificationSlotGroup("id0", "name0"); + groups.push_back(group); + g_advancedNotificationService->AddSlotGroups(groups); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00100 + * @tc.name : AMS_ANS_Publish_0100 + * @tc.desc : Test the branch if notification not exists + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::OTHER); + TestAddSlots(); + EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00200 + * @tc.name : AMS_ANS_Publish_0200 + * @tc.desc : Test the branch if notification is exists + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00200, Function | SmallTest | Level1) +{ + int32_t notificationId = 1; + sptr req = new NotificationRequest(notificationId); + req->SetSlotType(NotificationConstant::OTHER); + req->SetAlertOneTime(true); + TestAddSlots(); + g_advancedNotificationService->Publish(std::string(), req); + EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00300 + * @tc.name : AMS_ANS_Publish_0300 + * @tc.desc : Publish notification when no slot is set + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00300, Function | SmallTest | Level1) +{ + int32_t notificationId = 1; + sptr req = new NotificationRequest(NULL, notificationId); + req->SetSlotType(NotificationConstant::OTHER); + EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00400 + * @tc.name : AMS_ANS_Publish_0400 + * @tc.desc : Test Publish function when no slotType + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00400, Function | SmallTest | Level1) +{ + int32_t notificationId = 1; + sptr req = new NotificationRequest(notificationId); + req->SetSlotType(NotificationConstant::CUSTOM); + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00500 + * @tc.name : AMS_ANS_Publish_0500 + * @tc.desc : publish function when NotificationsEnabled is false + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00500, Function | SmallTest | Level1) +{ + int32_t notificationId = 1; + sptr req = new NotificationRequest(notificationId); + req->SetSlotType(NotificationConstant::OTHER); + TestAddSlots(); + g_advancedNotificationService->SetNotificationsEnabledForBundle("bundleName", false); + EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_ANS_NOT_ALLOWED); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00600 + * @tc.name : AMS_ANS_Cancel_0100 + * @tc.desc : public two notification to cancel one of them + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00600, Function | SmallTest | Level1) +{ + int32_t notificationId = 2; + std::string label = "testLabel"; + sptr req = new NotificationRequest(NULL, notificationId); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + TestAddSlots(); + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00700 + * @tc.name : AMS_ANS_Cancel_0200 + * @tc.desc : Test Cancel function when notification no exists + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00700, Function | SmallTest | Level1) +{ + int32_t notificationId = 0; + std::string label = "testLabel"; + EXPECT_EQ((int)g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00800 + * @tc.name : AMS_ANS_CancelAll_0100 + * @tc.desc : Test CancelAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00800, Function | SmallTest | Level1) +{ + EXPECT_EQ(g_advancedNotificationService->CancelAll(), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00900 + * @tc.name : AMS_ANS_Cancel_0100 + * @tc.desc : Test Cancel function when unremovable is true + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00900, Function | SmallTest | Level1) +{ + int32_t notificationId = 2; + std::string label = "testLabel"; + sptr req = new NotificationRequest(notificationId); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + req->SetUnremovable(true); + TestAddSlots(); + g_advancedNotificationService->Publish(label, req); + g_advancedNotificationService->Publish(label, req); + EXPECT_EQ(g_advancedNotificationService->Cancel(notificationId, label), (int)ERR_ANS_NOTIFICATION_IS_UNREMOVABLE); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01000 + * @tc.name : AMS_ANS_AddSlots_0100 + * @tc.desc : Test AddSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01000, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01100 + * @tc.name : AMS_ANS_RemoveSlotByType_0100 + * @tc.desc : Test RemoveSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01100, Function | SmallTest | Level1) +{ + TestAddSlots(); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotByType(NotificationConstant::OTHER), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01200 + * @tc.name : AMS_ANS_RemoveSlotByType_0200 + * @tc.desc : Test RemoveSlotByType function when no type + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, Function | SmallTest | Level1) +{ + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->RemoveSlotByType(NotificationConstant::CUSTOM), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01300 + * @tc.name : AMS_ANS_AddSlotGroups_0100 + * @tc.desc : Test AddSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01300, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group0 = new NotificationSlotGroup("id0", "name0"); + sptr group1 = new NotificationSlotGroup("id1", "name1"); + groups.push_back(group0); + groups.push_back(group1); + EXPECT_EQ(g_advancedNotificationService->AddSlotGroups(groups), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01400 + * @tc.name : AMS_ANS_RemoveSlotGroups_0100 + * @tc.desc : Test RemoveSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01400, Function | SmallTest | Level1) +{ + TestAddSlotGroups(); + std::vector groupIds; + groupIds.push_back("id0"); + EXPECT_EQ(g_advancedNotificationService->RemoveSlotGroups(groupIds), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01500 + * @tc.name : AMS_ANS_GetSlot_0100 + * @tc.desc : Test GetSlot function for data + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01500, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + EXPECT_EQ((int)g_advancedNotificationService->GetSlot("id0", slot), ERR_OK); + EXPECT_EQ(slot->GetName(), slot0->GetName()); + EXPECT_EQ(slot->GetId(), slot0->GetId()); + EXPECT_EQ(slot->GetLevel(), slot0->GetLevel()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01600 + * @tc.name : AMS_ANS_GetSlot_0200 + * @tc.desc : Test GetSlots function when add two identical data + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + std::vector> slotsResult; + g_advancedNotificationService->AddSlots(slots); + g_advancedNotificationService->GetSlots(slotsResult); + EXPECT_EQ((int)slots.size(), 2); + EXPECT_EQ((int)slotsResult.size(), 1); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01700 + * @tc.name : AMS_ANS_GetSlotGroup_0100 + * @tc.desc : Test GetSlotGroup function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + group2->SetDescription("Description"); + groups.push_back(group2); + g_advancedNotificationService->AddSlotGroups(groups); + sptr group = new NotificationSlotGroup(); + EXPECT_EQ(g_advancedNotificationService->GetSlotGroup("id2", group), ERR_OK); + EXPECT_EQ(group2->GetId(), group->GetId()); + EXPECT_EQ(group2->GetName(), group->GetName()); + EXPECT_EQ(group2->GetDescription(), group->GetDescription()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01800 + * @tc.name : AMS_ANS_SetNotificationBadgeNum_0100 + * @tc.desc : Test SetNotificationBadgeNum function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) +{ + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->SetNotificationBadgeNum(2), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01900 + * @tc.name : AMS_ANS_GetBundleImportance_0100 + * @tc.desc : Test GetBundleImportance function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) +{ + TestAddSlots(); + int importance; + EXPECT_EQ((int)g_advancedNotificationService->GetBundleImportance(importance), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02000 + * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0100 + * @tc.desc : Test SetPrivateNotificationsAllowed function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, Function | SmallTest | Level1) +{ + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->SetPrivateNotificationsAllowed(true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02100 + * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 + * @tc.desc : Test GetPrivateNotificationsAllowed function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, Function | SmallTest | Level1) +{ + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->SetPrivateNotificationsAllowed(true), (int)ERR_OK); + bool allow; + EXPECT_EQ((int)g_advancedNotificationService->GetPrivateNotificationsAllowed(allow), (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02200 + * @tc.name : AMS_ANS_UpdateSlots_0100 + * @tc.desc : Test UpdateSlots function when no slot + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + EXPECT_EQ((int)g_advancedNotificationService->UpdateSlots(bundle, slots), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02300 + * @tc.name : AMS_ANS_UpdateSlots_0200 + * @tc.desc : Test UpdateSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + std::vector> slots; + TestAddSlots(); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + EXPECT_EQ((int)g_advancedNotificationService->UpdateSlots(bundle, slots), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02400 + * @tc.name : AMS_ANS_UpdateSlotGroups_0100 + * @tc.desc : Test UpdateSlotGroups function when no group + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02400, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + groups.push_back(group2); + EXPECT_EQ( + (int)g_advancedNotificationService->UpdateSlotGroups(bundle, groups), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02500 + * @tc.name : AMS_ANS_UpdateSlotGroups_0200 + * @tc.desc : Test UpdateSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02500, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id0", "name2"); + groups.push_back(group2); + TestAddSlotGroups(); + EXPECT_EQ((int)g_advancedNotificationService->UpdateSlotGroups(bundle, groups), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02600 + * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0100 + * @tc.desc : Test SetNotificationsEnabledForBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02600, Function | SmallTest | Level1) +{ + std::string bundle = ""; + EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForBundle(bundle, true), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02700 + * @tc.name : AMS_ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, Function | SmallTest | Level1) +{ + std::string bundle = ""; + EXPECT_EQ(g_advancedNotificationService->SetShowBadgeEnabledForBundle(bundle, true), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02800 + * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + bool allow; + EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02900 + * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.desc : Test GetActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ((int)g_advancedNotificationService->GetActiveNotifications(notifications), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03000 + * @tc.name : AMS_ANS_SetNotificationAgent_0100 + * @tc.desc : Test SetNotificationAgent function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03000, Function | SmallTest | Level1) +{ + std::string agent = "agent"; + g_advancedNotificationService->SetNotificationAgent(agent); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03100 + * @tc.name : AMS_ANS_GetNotificationAgent_0100 + * @tc.desc : Test GetNotificationAgent function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, Function | SmallTest | Level1) +{ + std::string agent; + g_advancedNotificationService->GetNotificationAgent(agent); +} + +/** + * @tc.number : NotificationPreferencesTest_03200 + * @tc.name : AMS_ANS_CanPublishAsBundle_0100 + * @tc.desc : Test CanPublishAsBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, Function | SmallTest | Level1) +{ + std::string representativeBundle = "representativeBundle"; + bool canPublish = true; + g_advancedNotificationService->CanPublishAsBundle(representativeBundle, canPublish); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03300 + * @tc.name : AMS_ANS_PublishAsBundle_0100 + * @tc.desc : Test PublishAsBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03300, Function | SmallTest | Level1) +{ + std::string representativeBundle = "representativeBundle"; + sptr notification = new NotificationRequest(); + g_advancedNotificationService->PublishAsBundle(notification, representativeBundle); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03400 + * @tc.name : AMS_ANS_SetDisturbMode_0100 + * @tc.desc : Test SetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_PRIORITY), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03500 + * @tc.name : AMS_ANS_GetDisturbMode_0100 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) +{ + TestAddSlots(); + NotificationConstant::DisturbMode mode; + EXPECT_EQ((int)g_advancedNotificationService->GetDisturbMode(mode), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03600 + * @tc.name : AMS_ANS_HasNotificationPolicyAccessPermission_0100 + * @tc.desc : Test HasNotificationPolicyAccessPermission function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03600, Function | SmallTest | Level1) +{ + bool granted; + g_advancedNotificationService->HasNotificationPolicyAccessPermission(granted); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03700 + * @tc.name : AMS_ANS_Delete_0100 + * @tc.desc : Test Delete function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, Function | SmallTest | Level1) +{ + const std::string key = "key"; + EXPECT_EQ((int)g_advancedNotificationService->Delete(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03800 + * @tc.name : AMS_ANS_DeleteByBundle_0100 + * @tc.desc : Test DeleteByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, Function | SmallTest | Level1) +{ + const std::string bundle = "bundleName"; + EXPECT_EQ(g_advancedNotificationService->DeleteByBundle(bundle), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03900 + * @tc.name : AMS_ANS_DeleteAll_0100 + * @tc.desc : Test DeleteAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, Function | SmallTest | Level1) +{ + EXPECT_EQ(g_advancedNotificationService->DeleteAll(), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04000 + * @tc.name : AMS_ANS_GetSlotsByBundle_0100 + * @tc.desc : Test GetSlotsByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::string bundle = "bundleName"; + std::vector> slots; + EXPECT_EQ(g_advancedNotificationService->GetSlotsByBundle(bundle, slots), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04100 + * @tc.name : AMS_ANS_GetSpecialActiveNotifications_0100 + * @tc.desc : Test GetSpecialActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04100, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(); + req->SetSlotType(NotificationConstant::OTHER); + TestAddSlots(); + g_advancedNotificationService->Publish(std::string(), req); + EXPECT_EQ(g_advancedNotificationService->Publish(std::string(), req), (int)ERR_OK); + sptr notification = new Notification(req); + std::vector> notifications; + std::string key1 = notification->GetKey(); + std::string key2 = "key2"; + std::vector keys; + keys.push_back(key1); + keys.push_back(key2); + EXPECT_EQ(g_advancedNotificationService->GetSpecialActiveNotifications(keys, notifications), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04200 + * @tc.name : AMS_ANS_Subscribe_0100 + * @tc.desc : Test Subscribe function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04200, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ((int)g_advancedNotificationService->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04300 + * @tc.name : AMS_ANS_Unsubscribe_0100 + * @tc.desc : Test Unsubscribe function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ((int)g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), info), (int)ERR_OK); + ; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04400 + * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0200 + * @tc.desc : Test SetNotificationsEnabledForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04400, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForBundle(bundle, true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04500 + * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0200 + * @tc.desc : Test GetShowBadgeEnabledForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04500, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + TestAddSlots(); + EXPECT_EQ((int)g_advancedNotificationService->SetShowBadgeEnabledForBundle(bundle, true), (int)ERR_OK); + bool allow; + EXPECT_EQ((int)g_advancedNotificationService->GetShowBadgeEnabledForBundle(bundle, allow), (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04600 + * @tc.name : AMS_ANS_GetSlotByType_0100 + * @tc.desc : Test GetSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04600, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + TestAddSlots(); + sptr slot; + EXPECT_EQ((int)g_advancedNotificationService->GetSlotByType(NotificationConstant::OTHER, slot), (int)ERR_OK); + EXPECT_EQ(slot->GetId(), "OTHER"); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04700 + * @tc.name : AMS_ANS_GetSlotByType_0200 + * @tc.desc : Test the CreateSlot branch of the GetSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04700, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + sptr slot; + g_advancedNotificationService->GetSlotByType(NotificationConstant::SOCIAL_COMMUNICATION, slot); + g_advancedNotificationService->GetSlotByType(NotificationConstant::SERVICE_REMINDER, slot); + g_advancedNotificationService->GetSlotByType(NotificationConstant::CONTENT_INFORMATION, slot); + g_advancedNotificationService->GetSlotByType(NotificationConstant::OTHER, slot); + EXPECT_EQ((int)g_advancedNotificationService->GetSlotByType(NotificationConstant::CUSTOM, slot), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04800 + * @tc.name : AMS_ANS_GetSlotGroups_0100 + * @tc.desc : Test GetSlotGroups function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04800, Function | SmallTest | Level1) +{ + std::vector> groups; + sptr group2 = new NotificationSlotGroup("id2", "name2"); + group2->SetDescription("Description"); + groups.push_back(group2); + g_advancedNotificationService->AddSlotGroups(groups); + std::vector> group; + EXPECT_EQ(g_advancedNotificationService->GetSlotGroups(group), ERR_OK); + EXPECT_EQ(groups.size(), group.size()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04900 + * @tc.name : AMS_ANS_GetAllActiveNotifications_0100 + * @tc.desc : Test GetAllActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04900, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ(g_advancedNotificationService->GetAllActiveNotifications(notifications), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05000 + * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0100 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function for else + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05000, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForAllBundles("test", true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05100 + * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0200 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function for if + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::vector> notifications; + EXPECT_EQ( + (int)g_advancedNotificationService->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05200 + * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0100 + * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function for if + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::vector> notifications; + EXPECT_EQ( + (int)g_advancedNotificationService->SetNotificationsEnabledForSpecialBundle(std::string(), "bundleName", true), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05300 + * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0200 + * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function for else + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) +{ + std::vector> notifications; + EXPECT_EQ((int)g_advancedNotificationService->SetNotificationsEnabledForSpecialBundle("test", "bundleName", true), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05400 + * @tc.name : AMS_ANS_IsAllowedNotify_0100 + * @tc.desc : Test IsAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05400, Function | SmallTest | Level1) +{ + bool allowed = true; + EXPECT_EQ((int)g_advancedNotificationService->IsAllowedNotify(allowed), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05500 + * @tc.name : AMS_ANS_IsAllowedNotify_0200 + * @tc.desc : Test IsAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05500, Function | SmallTest | Level1) +{ + TestAddSlots(); + bool allowed = true; + EXPECT_EQ((int)g_advancedNotificationService->IsAllowedNotify(allowed), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05600 + * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0100 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::vector> notifications; + bool allowed = true; + std::string bundle = "bundleName"; + EXPECT_EQ((int)g_advancedNotificationService->IsSpecialBundleAllowedNotify(bundle, allowed), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05700 + * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0200 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05700, Function | SmallTest | Level1) +{ + std::vector> notifications; + bool allowed = true; + std::string bundle = "bundleName"; + EXPECT_EQ((int)g_advancedNotificationService->IsSpecialBundleAllowedNotify(bundle, allowed), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05800 + * @tc.name : AMS_ANS_GetSlotsByBundle_0200 + * @tc.desc : Test GetSlotsByBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05800, Function | SmallTest | Level1) +{ + std::string bundle = "bundleName"; + std::vector> slots; + EXPECT_EQ( + (int)g_advancedNotificationService->GetSlotsByBundle(bundle, slots), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp new file mode 100644 index 000000000..aa20d3bec --- /dev/null +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 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 "bundle_manager_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class BundleManagerHelperTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void BundleManagerHelperTest::SetUpTestCase() +{} + +void BundleManagerHelperTest::TearDownTestCase() +{} + +void BundleManagerHelperTest::SetUp() +{} + +void BundleManagerHelperTest::TearDown() +{} + +/** + * @tc.number : BundleManagerHelperTest_00100 + * @tc.name : AMS_ANS_GetBundleNameByUid_0100 + * @tc.desc : Test GetBundleNameByUid function + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) +{ + uid_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + EXPECT_EQ(bundleManager->GetBundleNameByUid(callingUid), "bundleName"); +} + +/** + * @tc.number : BundleManagerHelperTest_00200 + * @tc.name : AMS_ANS_IsSystemApp_0100 + * @tc.desc : Test IsSystemApp function + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) +{ + uid_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + EXPECT_TRUE(bundleManager->IsSystemApp(callingUid)); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/disturb_filter_test.cpp b/services/ans/test/unittest/disturb_filter_test.cpp new file mode 100644 index 000000000..5621b5268 --- /dev/null +++ b/services/ans/test/unittest/disturb_filter_test.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 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 "disturb_filter.h" +#include +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class DisturbFilterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DisturbFilterTest::SetUpTestCase() +{} + +void DisturbFilterTest::TearDownTestCase() +{} + +void DisturbFilterTest::SetUp() +{} + +void DisturbFilterTest::TearDown() +{} + +/** + * @tc.number : DisturbFilterTest_00100 + * @tc.name : AMS_ANS_OnStart_0100 + * @tc.desc : Test OnStart function + */ +HWTEST_F(DisturbFilterTest, DisturbFilterTest_00100, Function | SmallTest | Level1) +{ + DisturbFilter disturbFilter; + disturbFilter.OnStart(); +} + +/** + * @tc.number : DisturbFilterTest_00200 + * @tc.name : AMS_ANS_OnStop_0100 + * @tc.desc : Test OnStop function for data + */ +HWTEST_F(DisturbFilterTest, DisturbFilterTest_00200, Function | SmallTest | Level1) +{ + DisturbFilter disturbFilter; + disturbFilter.OnStop(); +} + +/** + * @tc.number : DisturbFilterTest_00300 + * @tc.name : AMS_ANS_OnPublish_0100 + * @tc.desc : Test OnPublish function for data + */ +HWTEST_F(DisturbFilterTest, DisturbFilterTest_00300, Function | SmallTest | Level1) +{ + DisturbFilter disturbFilter; + sptr request = new NotificationRequest(); + auto objptr = new Notification(request); + disturbFilter.OnPublish(objptr); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/include/mock_bundle_manager.h b/services/ans/test/unittest/mock/include/mock_bundle_manager.h new file mode 100644 index 000000000..4b7875b33 --- /dev/null +++ b/services/ans/test/unittest/mock/include/mock_bundle_manager.h @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H +#define FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H + +#include + +#include "ability_info.h" +#include "application_info.h" +#include "bundle_mgr_host.h" +#include "bundle_mgr_interface.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace AppExecFwk { +class MockBundleMgrService : public BundleMgrHost { +public: + MockBundleMgrService() + {} + + ~MockBundleMgrService() + {} + + /** + * @brief Obtains the ApplicationInfo based on a given bundle name. + * @param appName Indicates the application bundle name to be queried. + * @param flag Indicates the flag used to specify information contained + * in the ApplicationInfo object that will be returned. + * @param userId Indicates the user ID. + * @param appInfo Indicates the obtained ApplicationInfo object. + * @return Returns true if the application is successfully obtained; returns false otherwise. + */ + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override + { + return true; + } + /** + * @brief Obtains information about all installed applications of a specified user. + * @param flag Indicates the flag used to specify information contained + * in the ApplicationInfo objects that will be returned. + * @param userId Indicates the user ID. + * @param appInfos Indicates all of the obtained ApplicationInfo objects. + * @return Returns true if the application is successfully obtained; returns false otherwise. + */ + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + } + /** + * @brief Obtains the BundleInfo based on a given bundle name. + * @param bundleName Indicates the application bundle name to be queried. + * @param flag Indicates the information contained in the BundleInfo object to be returned. + * @param bundleInfo Indicates the obtained BundleInfo object. + * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + /** + * @brief Obtains BundleInfo of all bundles available in the system. + * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + }; + /** + * @brief Obtains the application UID based on the given bundle name and user ID. + * @param bundleName Indicates the bundle name of the application. + * @param userId Indicates the user ID. + * @return Returns the uid if successfully obtained; returns -1 otherwise. + */ + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + return 0; + } + /** + * @brief Obtains the bundle name of a specified application based on the given UID. + * @param uid Indicates the uid. + * @param bundleName Indicates the obtained bundle name. + * @return Returns true if the bundle name is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "hello"; + return true; + } + /** + * @brief Obtains an array of all group IDs associated with a specified bundle. + * @param bundleName Indicates the bundle name. + * @param gids Indicates the group IDs associated with the specified bundle. + * @return Returns true if the gids is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + } + /** + * @brief Obtains the type of a specified application based on the given bundle name. + * @param bundleName Indicates the bundle name. + * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. + */ + virtual std::string GetAppType(const std::string &bundleName) override + { + return ""; + } + /** + * @brief Check whether the app is system app by it's UID. + * @param uid Indicates the uid. + * @return Returns true if the bundle is a system application; returns false otherwise. + */ + virtual bool CheckIsSystemAppByUid(const int uid) override; + + /** + * @brief Obtains the BundleInfo of application bundles based on the specified metaData. + * @param metaData Indicates the metadata to get in the bundle. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + } + /** + * @brief Query the AbilityInfo by the given Want. + * @param want Indicates the infomation of the ability. + * @param abilityInfo Indicates the obtained AbilityInfo object. + * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Query the AbilityInfo by ability.uri in config.json. + * @param abilityUri Indicates the uri of the ability. + * @param abilityInfo Indicates the obtained AbilityInfo object. + * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Obtains the BundleInfo of all keep-alive applications in the system. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + }; + /** + * @brief Obtains the label of a specified ability. + * @param bundleName Indicates the bundle name. + * @param className Indicates the ability class name. + * @return Returns the label of the ability if exist; returns empty string otherwise. + */ + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + } + /** + * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). + * @param hapFilePath Indicates the absolute file path of the HAP. + * @param flag Indicates the information contained in the BundleInfo object to be returned. + * @param bundleInfo Indicates the obtained BundleInfo object. + * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + /** + * @brief Obtain the HAP module info of a specific ability. + * @param abilityInfo Indicates the ability. + * @param hapModuleInfo Indicates the obtained HapModuleInfo object. + * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + /** + * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. + * @param bundleName Indicates the bundle name. + * @param want Indicates the obtained launch Want object. + * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. + */ + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + } + /** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting + * a certain permission. + * @param bundleName Indicates the name of the bundle to check. + * @param permission Indicates the permission to check. + * @param userId Indicates the user id. + * @return Returns true if the current application does not have the permission and the user does not turn off + * further requests; returns false if the current application already has the permission, the permission is rejected + * by the system, or the permission is denied by the user and the user has turned off further requests. + */ + virtual bool CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) override + { + return true; + } + /** + * @brief Checks whether the publickeys of two bundles are the same. + * @param firstBundleName Indicates the first bundle name. + * @param secondBundleName Indicates the second bundle name. + * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; + * returns SIGNATURE_NOT_MATCHED if their publickeys are different; + * returns SIGNATURE_MATCHED if their publickeys are the same. + */ + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + } + /** + * @brief Checks whether a specified bundle has been granted a specific permission. + * @param bundleName Indicates the name of the bundle to check. + * @param permission Indicates the permission to check. + * @return Returns 0 if the bundle has the permission; returns -1 otherwise. + */ + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override; + /** + * @brief Obtains detailed information about a specified permission. + * @param permissionName Indicates the name of the ohos permission. + * @param permissionDef Indicates the object containing detailed information about the given ohos permission. + * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. + */ + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + } + /** + * @brief Obtains all known permission groups in the system. + * @param permissionDefs Indicates the list of objects containing the permission group information. + * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. + */ + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + } + /** + * @brief Obtains all known permission groups in the system. + * @param permissions Indicates the permission array. + * @param appNames Indicates the list of application names that have the specified permissions. + * @return Returns true if the application names is successfully obtained; returns false otherwise. + */ + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + } + /** + * @brief Requests a certain permission from user. + * @param bundleName Indicates the name of the bundle to request permission. + * @param permission Indicates the permission to request permission. + * @param userId Indicates the user id. + * @return Returns true if the permission request successfully; returns false otherwise. + */ + virtual bool RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) override + { + return true; + } + /** + * @brief Checks whether the system has a specified capability. + * @param capName Indicates the name of the system feature to check. + * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. + */ + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + } + /** + * @brief Obtains the capabilities that are available in the system. + * @param systemCaps Indicates the list of capabilities available in the system. + * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. + */ + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + } + /** + * @brief Checks whether the current device has been started in safe mode. + * @return Returns true if the device is in safe mode; returns false otherwise. + */ + virtual bool IsSafeMode() override + { + return true; + } + /** + * @brief Clears cache data of a specified application. + * @param bundleName Indicates the bundle name of the application whose cache data is to be cleared. + * @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } + /** + * @brief Clears application running data of a specified application. + * @param bundleName Indicates the bundle name of the application whose data is to be cleared. + * @return Returns true if the data cleared successfully; returns false otherwise. + */ + virtual bool CleanBundleDataFiles(const std::string &bundleName) override + { + return true; + } + /** + * @brief Register the specific bundle status callback. + * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + /** + * @brief Clear the specific bundle status callback. + * @param bundleStatusCallback Indicates the callback to be cleared. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + /** + * @brief Unregister all the callbacks of status changed. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool UnregisterBundleStatusCallback() override + { + return true; + } + /** + * @brief Dump the bundle informations with specifc flags. + * @param flag Indicates the information contained in the dump result. + * @param bundleName Indicates the bundle name if needed. + * @param result Indicates the dump infomation result. + * @return Returns true if the dump result is successfully obtained; returns false otherwise. + */ + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + } + /** + * @brief Checks whether a specified application is enabled. + * @param bundleName Indicates the bundle name of the application. + * @return Returns true if the application is enabled; returns false otherwise. + */ + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + } + /** + * @brief Sets whether to enable a specified application. + * @param bundleName Indicates the bundle name of the application. + * @param isEnable Specifies whether to enable the application. + * The value true means to enable it, and the value false means to disable it. + * @return Returns true if the application is enabled; returns false otherwise. + */ + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } + /** + * @brief Obtains the interface used to install and uninstall bundles. + * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. + */ + virtual sptr GetBundleInstaller() override + { + return nullptr; + } + + void MockSetIsSystemApp(bool isSystemApp); + +private: + bool isSystemApp_ = false; + bool isSystemAppMock_ = false; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_bundle_manager.cpp b/services/ans/test/unittest/mock/mock_bundle_manager.cpp new file mode 100644 index 000000000..d026341ec --- /dev/null +++ b/services/ans/test/unittest/mock/mock_bundle_manager.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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 "mock_bundle_manager.h" +#include "ability_info.h" +#include "application_info.h" + +namespace OHOS { +namespace AppExecFwk { +void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) +{ + isSystemAppMock_ = true; + isSystemApp_ = isSystemApp; +} + +bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) +{ + if (isSystemAppMock_) { + return isSystemApp_; + } + return (uid < 1000) ? false : true; +} + +int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + if (!bundleName.compare("bundleName")) { + return 0; + } else { + return -1; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 000000000..adde06e33 --- /dev/null +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 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 "bundle_manager_helper.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { + +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} + +std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +{ + return "bundleName"; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + return true; +} + +void BundleManagerHelper::Connect() +{} + +void BundleManagerHelper::Disconnect() +{} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp b/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp new file mode 100644 index 000000000..6c9526322 --- /dev/null +++ b/services/ans/test/unittest/mock/mock_bundle_mgr_proxy.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2021 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 "bundle_mgr_proxy.h" + +#include "ipc_types.h" +#include "parcel.h" +#include "string_ex.h" + +#include "appexecfwk_errors.h" +#include "bundle_constants.h" + +namespace OHOS { +namespace AppExecFwk { + +BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} + +BundleMgrProxy::~BundleMgrProxy() +{} + +bool BundleMgrProxy::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + return true; +} + +bool BundleMgrProxy::GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) +{ + return true; +} + +int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + return 1; +} + +std::string BundleMgrProxy::GetAppIdByBundleName(const std::string &bundleName, const int userId) +{ + return "appId"; +} + +bool BundleMgrProxy::GetBundleNameForUid(const int uid, std::string &bundleName) +{ + bundleName = "bundleName"; + return true; +} + +bool BundleMgrProxy::GetBundlesForUid(const int uid, std::vector &bundleNames) +{ + return true; +} + +bool BundleMgrProxy::GetNameForUid(const int uid, std::string &name) +{ + return true; +} + +bool BundleMgrProxy::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + return true; +} + +std::string BundleMgrProxy::GetAppType(const std::string &bundleName) +{ + return "Constants::EMPTY_STRING"; +} + +bool BundleMgrProxy::CheckIsSystemAppByUid(const int uid) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) +{ + return true; +} + +bool BundleMgrProxy::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::QueryKeepAliveBundleInfos(std::vector &bundleInfos) +{ + return true; +} + +std::string BundleMgrProxy::GetAbilityLabel(const std::string &bundleName, const std::string &className) +{ + return "reply.ReadString()"; +} + +bool BundleMgrProxy::GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetLaunchWantForBundle(const std::string &bundleName, Want &want) +{ + return true; +} + +int BundleMgrProxy::CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) +{ + return 1; +} + +int BundleMgrProxy::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + return 1; +} + +bool BundleMgrProxy::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) +{ + return true; +} + +bool BundleMgrProxy::GetAllPermissionGroupDefs(std::vector &permissionDefs) +{ + return true; +} + +bool BundleMgrProxy::GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) +{ + return true; +} + +bool BundleMgrProxy::HasSystemCapability(const std::string &capName) +{ + return true; +} + +bool BundleMgrProxy::GetSystemAvailableCapabilities(std::vector &systemCaps) +{ + return true; +} + +bool BundleMgrProxy::IsSafeMode() +{ + return true; +} + +bool BundleMgrProxy::CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) +{ + return true; +} + +bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName) +{ + return true; +} + +bool BundleMgrProxy::RegisterBundleStatusCallback(const sptr &bundleStatusCallback) +{ + return true; +} + +bool BundleMgrProxy::ClearBundleStatusCallback(const sptr &bundleStatusCallback) +{ + return true; +} + +bool BundleMgrProxy::UnregisterBundleStatusCallback() +{ + return true; +} + +bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) +{ + return true; +} + +bool BundleMgrProxy::IsApplicationEnabled(const std::string &bundleName) +{ + return true; +} + +bool BundleMgrProxy::SetApplicationEnabled(const std::string &bundleName, bool isEnable) +{ + return true; +} + +bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) +{ + return true; +} + +std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) +{ + return "AbilityIcon"; +} + +bool BundleMgrProxy::CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) +{ + return true; +} + +bool BundleMgrProxy::RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) +{ + return true; +} + +bool BundleMgrProxy::RegisterAllPermissionsChanged(const sptr &callback) +{ + return true; +} + +bool BundleMgrProxy::RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) +{ + return true; +} + +bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr &callback) +{ + return true; +} + +template +bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) +{ + return true; +} + +template +bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) +{ + return true; +} + +bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_event_handler.cpp b/services/ans/test/unittest/mock/mock_event_handler.cpp new file mode 100644 index 000000000..12a7f65b9 --- /dev/null +++ b/services/ans/test/unittest/mock/mock_event_handler.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 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 "event_handler.h" +#include "event_handler_utils.h" +#include + +namespace OHOS { +namespace AppExecFwk { + +std::shared_ptr EventHandler::Current() +{ + const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); + return wp.lock(); +} + +EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) +{} + +EventHandler::~EventHandler() +{} + +bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) +{ + return true; +} + +bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) +{ + std::function callback = event->GetTaskCallback(); + callback(); + return true; +} + +void EventHandler::RemoveAllEvents() +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId) +{} + +void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) +{} + +void EventHandler::RemoveTask(const std::string &name) +{} + +ErrCode EventHandler::AddFileDescriptorListener( + int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) +{ + return EVENT_HANDLER_ERR_INVALID_PARAM; +} + +void EventHandler::RemoveAllFileDescriptorListeners() +{} + +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) +{} + +void EventHandler::SetEventRunner(const std::shared_ptr &runner) +{} + +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) +{} + +void EventHandler::Dump(Dumper &dumper) +{} + +bool EventHandler::HasInnerEvent(uint32_t innerEventId) +{ + return true; +} + +bool EventHandler::HasInnerEvent(int64_t param) +{ + return true; +} + +std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) +{ + return "132123"; +} + +bool EventHandler::IsIdle() +{ + return true; +} + +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) +{} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_ipc.cpp b/services/ans/test/unittest/mock/mock_ipc.cpp new file mode 100644 index 000000000..117032cd1 --- /dev/null +++ b/services/ans/test/unittest/mock/mock_ipc.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2021 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 "ipc_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif +pid_t IPCSkeleton::GetCallingUid() +{ + pid_t uid = 1; + return uid; +} + +pid_t IPCSkeleton::GetCallingPid() +{ + pid_t uid = 1; + return uid; +} +} // namespace OHOS diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp new file mode 100644 index 000000000..efa4894c6 --- /dev/null +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -0,0 +1,830 @@ +/* + * Copyright (c) 2021 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 "notification_preferences.h" +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class NotificationPreferencesTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void NotificationPreferencesTest::SetUpTestCase() +{} + +void NotificationPreferencesTest::TearDownTestCase() +{} + +void NotificationPreferencesTest::SetUp() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void NotificationPreferencesTest::TearDown() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void TestAddNotificationSlot() +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); +} + +void TestAddNotificationSlotGroup() +{ + std::string bundleName = "bundleName"; + sptr spGroup = new NotificationSlotGroup("id", "name"); + std::vector> groups; + groups.push_back(spGroup); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); +} + +/** + * @tc.number : NotificationPreferencesTest_00100 + * @tc.name : AMS_ANS_AddNotificationSlots_0100 + * @tc.desc : Test AddNotificationSlots function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_00200 + * @tc.name : AMS_ANS_AddNotificationSlots_0200 + * @tc.desc : Test AddNotificationSlots function when add two identical data + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName1"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + spSlot->SetSlotGroup("test"); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_00300 + * @tc.name : AMS_ANS_AddNotificationSlots_0300 + * @tc.desc : Test AddNotificationSlots function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00300, Function | SmallTest | Level1) +{ + std::vector> spSlots; + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlots(std::string(), spSlots), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_00400 + * @tc.name : AMS_ANS_AddNotificationSlots_0100 + * @tc.desc : Test AddNotificationSlotGroups function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00400, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlotGroup = new NotificationSlotGroup("id", "name"); + std::vector> spSlotGroups; + spSlotGroups.push_back(spSlotGroup); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_00500 + * @tc.name : AMS_ANS_AddNotificationSlotGroups_0200 + * @tc.desc : Test AddNotificationSlotGroups function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00500, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlotGroup = new NotificationSlotGroup("", "name"); + std::vector> spSlotGroups; + spSlotGroups.push_back(spSlotGroup); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); +} + +/** + * @tc.number : NotificationPreferencesTest_00600 + * @tc.name : AMS_ANS_AddNotificationSlotGroups_0300 + * @tc.desc : Test AddNotificationSlotGroups function when bundleName is not set + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00600, Function | SmallTest | Level1) +{ + std::vector> spSlotGroups; + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(std::string(), spSlotGroups), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_00700 + * @tc.name : AMS_ANS_RemoveNotificationSlot_0100 + * @tc.desc : Test RemoveNotificationSlot function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00700, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + std::vector slotIds; + slotIds.push_back(spSlot->GetId()); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), + (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_00800 + * @tc.name : AMS_ANS_RemoveNotificationSlot_0200 + * @tc.desc : Test RemoveNotificationSlot function when bundleName is not set + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00800, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + std::vector slotIds; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_00900 + * @tc.name : AMS_ANS_RemoveNotificationSlot_0300 + * @tc.desc : Test RemoveNotificationSlot function when slot not exist + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_00900, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string slotId = "id"; + std::vector slotIds; + slotIds.push_back(slotId); + TestAddNotificationSlot(); + NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_01000 + * @tc.name : AMS_ANS_RemoveNotificationSlot_0400 + * @tc.desc : Test RemoveNotificationSlot function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01000, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + std::vector slotIds; + slotIds.push_back(spSlot->GetId()); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleName, NotificationConstant::OTHER), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_01100 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0100 + * @tc.desc : Test RemoveNotificationSlotGroups function when bundle not exist + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName1"; + sptr spSlotGroup = new NotificationSlotGroup("id1", "name"); + std::vector> spSlotGroups; + spSlotGroups.push_back(spSlotGroup); + NotificationPreferences::GetInstance().AddNotificationSlotGroups("bundleName", spSlotGroups); + std::string groupId = "id1"; + std::vector groupIds; + groupIds.push_back(groupId); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_01200 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 + * @tc.desc : Test RemoveNotificationSlotGroups function the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::vector groupIds; + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_01300 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0300 + * @tc.desc : Test RemoveNotificationSlotGroups function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01300, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string groupId = "id"; + std::vector groupIds; + groupIds.push_back(groupId); + TestAddNotificationSlotGroup(); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_01400 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0400 + * @tc.desc : Test RemoveNotificationSlotGroups function when slotid invalid + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01400, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string groupId = ""; + std::vector groupIds; + groupIds.push_back(groupId); + TestAddNotificationSlotGroup(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ID_INVALID); +} + +/** + * @tc.number : NotificationPreferencesTest_01500 + * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0100 + * @tc.desc : Test UpdateNotificationSlotGroups function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01500, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlotGroup = new NotificationSlotGroup("id1", "name"); + std::vector> spSlotGroups; + spSlotGroups.push_back(spSlotGroup); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, spSlotGroups); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, spSlotGroups), + (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_01600 + * @tc.name : AMS_ANS_GetNotificationSlot_0100 + * @tc.desc : Test GetNotificationSlot function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01600, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr notificationSlot; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationSlot( + bundleName, NotificationConstant::OTHER, notificationSlot), + (int)ERR_OK); + EXPECT_EQ(spSlot->GetName(), notificationSlot->GetName()); +} + +/** + * @tc.number : NotificationPreferencesTest_01700 + * @tc.name : AMS_ANS_GetNotificationAllSlots_0100 + * @tc.desc : Test GetNotificationAllSlots function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01700, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + std::vector> slotsResult; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleName, slotsResult), (int)ERR_OK); + EXPECT_EQ((int)slotsResult.size(), 1); +} + +/** + * @tc.number : NotificationPreferencesTest_01800 + * @tc.name : AMS_ANS_GetNotificationSlotGroup_0100 + * @tc.desc : Test GetNotificationSlotGroup function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01800, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spGroup = new NotificationSlotGroup("id", "name"); + spGroup->SetDescription("Description"); + std::vector> groups; + groups.push_back(spGroup); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); + sptr groupResult; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundleName, spGroup->GetId(), groupResult), + (int)ERR_OK); + EXPECT_EQ(groupResult->GetDescription(), spGroup->GetDescription()); +} + +/** + * @tc.number : NotificationPreferencesTest_01900 + * @tc.name : AMS_ANS_GetNotificationAllSlotGroups_0100 + * @tc.desc : Test GetNotificationAllSlotGroups function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_01900, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlotGroup(); + std::vector> groups; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleName, groups), (int)ERR_OK); + EXPECT_EQ((int)groups.size(), 1); +} + +/** + * @tc.number : NotificationPreferencesTest_02000 + * @tc.name : AMS_ANS_GetNotificationAllSlotInSlotGroup_0100 + * @tc.desc : Test GetNotificationAllSlotInSlotGroup function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02000, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string groupId = "groupId"; + sptr spGroup = new NotificationSlotGroup("groupId", "name"); + std::vector> groups; + groups.push_back(spGroup); + NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups); + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + spSlot->SetSlotGroup(groupId); + std::vector> spSlots; + spSlots.push_back(spSlot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, spSlots); + std::vector> slotsReuslt; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().GetNotificationAllSlotInSlotGroup(bundleName, groupId, slotsReuslt), + (int)ERR_OK); + EXPECT_EQ((int)slotsReuslt.size(), 1); +} + +/** + * @tc.number : NotificationPreferencesTest_02100 + * @tc.name : AMS_ANS_IsShowBadge_0100 + * @tc.desc : Test IsShowBadge function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02100, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + bool enable; + TestAddNotificationSlot(); + NotificationPreferences::GetInstance().SetShowBadge(bundleName, true); + EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleName, enable), (int)ERR_OK); + EXPECT_TRUE(enable); +} + +/** + * @tc.number : NotificationPreferencesTest_02200 + * @tc.name : AMS_ANS_SetShowBadge_0100 + * @tc.desc : Test SetShowBadge function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetShowBadge(bundleName, false), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_02300 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 + * @tc.desc : Test RemoveNotificationSlotGroups function when bundle not exist + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02300, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + std::string groupId = "id1"; + std::vector groupIds; + groupIds.push_back(groupId); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_02400 + * @tc.name : AMS_ANS_IsShowBadge_0200 + * @tc.desc : Test IsShowBadge function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02400, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + bool enable; + EXPECT_EQ((int)NotificationPreferences::GetInstance().IsShowBadge(bundleName, enable), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_02600 + * @tc.name : AMS_ANS_GetImportance_0200 + * @tc.desc : Test GetImportance function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02600, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + const int importance = 1; + NotificationPreferences::GetInstance().SetImportance(bundleName, importance); + int importanceResult; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleName, importanceResult), (int)ERR_OK); + EXPECT_EQ(importanceResult, importance); +} + +/** + * @tc.number : NotificationPreferencesTest_02700 + * @tc.name : AMS_ANS_GetTotalBadgeNums_0100 + * @tc.desc : Test GetTotalBadgeNums function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02700, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + int num = 1; + TestAddNotificationSlot(); + NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleName, num); + int totalBadgeNum; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleName, totalBadgeNum), (int)ERR_OK); + EXPECT_EQ(totalBadgeNum, num); +} + +/** + * @tc.number : NotificationPreferencesTest_02800 + * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 + * @tc.desc : Test GetPrivateNotificationsAllowed function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02800, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleName, true); + bool allow; + NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow); + EXPECT_EQ(allow, true); +} + +/** + * @tc.number : NotificationPreferencesTest_02900 + * @tc.name : AMS_ANS_GetNotificationsEnabledForBundle_0100 + * @tc.desc : Test GetNotificationsEnabledForBundle function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false); + bool enabled; + NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled); + EXPECT_FALSE(enabled); +} + +/** + * @tc.number : NotificationPreferencesTest_03000 + * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0200 + * @tc.desc : Test UpdateNotificationSlotGroups function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03000, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spGroup = new NotificationSlotGroup("groupId", "name"); + std::vector> groups; + groups.push_back(spGroup); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, groups), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_03100 + * @tc.name : AMS_ANS_RemoveNotificationForBundle_0100 + * @tc.desc : Test RemoveNotificationForBundle function when bundleName is not set + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03100, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleName), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_03200 + * @tc.name : AMS_ANS_ClearNotificationInRestoreFactorySettings_0100 + * @tc.desc : Test ClearNotificationInRestoreFactorySettings function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03200, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_03300 + * @tc.name : AMS_ANS_RemoveNotificationSlotGroups_0200 + * @tc.desc : Test RemoveNotificationSlotGroups function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03300, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlotGroup(); + std::string groupId = "id"; + std::vector groupIds; + groupIds.push_back(groupId); + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleName, groupIds), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_03400 + * @tc.name : AMS_ANS_UpdateNotificationSlots_0200 + * @tc.desc : Test UpdateNotificationSlots function when bundleName not exist + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03400, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName1"; + TestAddNotificationSlot(); + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_03500 + * @tc.name : AMS_ANS_GetNotificationSlot_0200 + * @tc.desc : Test UpdateNotificationSlots function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03500, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + spSlot->SetLevel(NotificationSlot::NotificationLevel::LEVEL_HIGH); + std::vector> spSlots; + spSlots.push_back(spSlot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), (int)ERR_OK); + sptr updateSpSlot; + NotificationPreferences::GetInstance().GetNotificationSlot(bundleName, NotificationConstant::OTHER, updateSpSlot); + EXPECT_EQ(updateSpSlot->GetLevel(), spSlot->GetLevel()); +} + +/** + * @tc.number : NotificationPreferencesTest_03600 + * @tc.name : AMS_ANS_UpdateNotificationSlots_0300 + * @tc.desc : Test UpdateNotificationSlots function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03600, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + std::vector> spSlots; + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_03700 + * @tc.name : AMS_ANS_UpdateNotificationSlotGroups_0300 + * @tc.desc : Test UpdateNotificationSlotGroups function when groupid invalid + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03700, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlotGroup(); + sptr spGroup = new NotificationSlotGroup("", "name"); + std::vector> groups; + groups.push_back(spGroup); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundleName, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID); +} + +/** + * @tc.number : NotificationPreferencesTest_03800 + * @tc.name : AMS_ANS_SetImportance_0200 + * @tc.desc : Test SetImportance function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03800, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + int importance = 1; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().SetImportance(bundleName, importance), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_03900 + * @tc.name : AMS_ANS_SetImportance_0300 + * @tc.desc : Test SetImportance function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_03900, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + int importance = 1; + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetImportance(bundleName, importance), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_04000 + * @tc.name : AMS_ANS_GetImportance_0300 + * @tc.desc : Test GetImportance function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04000, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + int importanceResult; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetImportance(bundleName, importanceResult), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_04100 + * @tc.name : AMS_ANS_SetTotalBadgeNums_0200 + * @tc.desc : Test SetTotalBadgeNums function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04100, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + int num = 1; + EXPECT_EQ( + (int)NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleName, num), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_04200 + * @tc.name : AMS_ANS_GetTotalBadgeNums_0300 + * @tc.desc : Test GetTotalBadgeNums function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04200, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + int totalBadgeNum; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetTotalBadgeNums(bundleName, totalBadgeNum), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_04300 + * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0200 + * @tc.desc : Test SetPrivateNotificationsAllowed function when the parameter is wrong + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04300, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleName, false), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : NotificationPreferencesTest_04400 + * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0200 + * @tc.desc : Test GetPrivateNotificationsAllowed function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04400, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + bool allow; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleName, allow), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_04500 + * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0200 + * @tc.desc : Test SetNotificationsEnabledForBundle function when bundleName not exist + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04500, Function | SmallTest | Level1) +{ + std::string bundleName = ""; + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_04600 + * @tc.name : AMS_ANS_SetNotificationsEnabledForBundle_0300 + * @tc.desc : Test GetNotificationsEnabledForBundle function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04600, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + bool enabled; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleName, enabled), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); +} + +/** + * @tc.number : NotificationPreferencesTest_04700 + * @tc.name : AMS_ANS_RemoveNotificationForBundle_0200 + * @tc.desc : Test RemoveNotificationForBundle function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04700, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleName), (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_04800 + * @tc.name : AMS_ANS_AddNotificationSlotGroups_0400 + * @tc.desc : Test AddNotificationSlotGroups function when group size more than the max + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04800, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spGroup0 = new NotificationSlotGroup("id1", "name1"); + sptr spGroup1 = new NotificationSlotGroup("id2", "name2"); + sptr spGroup2 = new NotificationSlotGroup("id3", "name3"); + sptr spGroup3 = new NotificationSlotGroup("id4", "name4"); + sptr spGroup4 = new NotificationSlotGroup("id5", "name5"); + std::vector> groups; + groups.push_back(spGroup0); + groups.push_back(spGroup1); + groups.push_back(spGroup2); + groups.push_back(spGroup3); + groups.push_back(spGroup4); + EXPECT_EQ((int)NotificationPreferences::GetInstance().AddNotificationSlotGroups(bundleName, groups), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM); +} + +/** + * @tc.number : NotificationPreferencesTest_04900 + * @tc.name : AMS_ANS_UpdateNotificationSlots_0400 + * @tc.desc : Test UpdateNotificationSlots function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_04900, Function | SmallTest | Level1) +{ + std::string bundleName = "bundleName"; + sptr spSlot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> spSlots; + spSlots.push_back(spSlot); + EXPECT_EQ((int)NotificationPreferences::GetInstance().UpdateNotificationSlots(bundleName, spSlots), + (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_05000 + * @tc.name : AMS_ANS_SetDisturbMode_0100 + * @tc.desc : Test SetDisturbMode function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05000, Function | SmallTest | Level1) +{ + TestAddNotificationSlot(); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_ALL), + (int)ERR_OK); +} + +/** + * @tc.number : NotificationPreferencesTest_05100 + * @tc.name : AMS_ANS_GetDisturbMode_0100 + * @tc.desc : Test GetDisturbMode function when file is null + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05100, Function | SmallTest | Level1) +{ + NotificationConstant::DisturbMode mode; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDisturbMode(mode), (int)ERR_ANS_PREFERENCES_FILE_IS_NULL); +} + +/** + * @tc.number : NotificationPreferencesTest_05200 + * @tc.name : AMS_ANS_GetDisturbMode_0200 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_05200, Function | SmallTest | Level1) +{ + TestAddNotificationSlot(); + NotificationConstant::DisturbMode mode; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDisturbMode(mode), (int)ERR_OK); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/test/unittest/notification_slot_filter_test.cpp b/services/ans/test/unittest/notification_slot_filter_test.cpp new file mode 100644 index 000000000..c7f9c283b --- /dev/null +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 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 "notification_slot_filter.h" +#include +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class NotificationSlotFilterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void NotificationSlotFilterTest::SetUpTestCase() +{} + +void NotificationSlotFilterTest::TearDownTestCase() +{} + +void NotificationSlotFilterTest::SetUp() +{} + +void NotificationSlotFilterTest::TearDown() +{} + +/** + * @tc.number : NotificationSlotFilterTest_00100 + * @tc.name : AMS_ANS_OnStart_0100 + * @tc.desc : Test OnStart function + */ +HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00100, Function | SmallTest | Level1) +{ + NotificationSlotFilter notificationSlotFilter; + notificationSlotFilter.OnStart(); +} + +/** + * @tc.number : NotificationSlotFilterTest_00200 + * @tc.name : AMS_ANS_OnStop_0100 + * @tc.desc : Test OnStop function + */ +HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00200, Function | SmallTest | Level1) +{ + NotificationSlotFilter notificationSlotFilter; + notificationSlotFilter.OnStop(); +} + +/** + * @tc.number : NotificationSlotFilterTest_00300 + * @tc.name : AMS_ANS_OnPublish_0100 + * @tc.desc : Test OnPublish function + */ +HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00300, Function | SmallTest | Level1) +{ + NotificationSlotFilter notificationSlotFilter; + sptr request = new NotificationRequest(); + auto objptr = new Notification(request); + notificationSlotFilter.OnPublish(objptr); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp new file mode 100644 index 000000000..33d5f5006 --- /dev/null +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 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 "notification_subscriber_manager.h" +#include +#include +#define private public +#include "notification_subscriber.h" +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +std::shared_ptr g_notificationSubscriberManager; +class NotificationSubscriberManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void NotificationSubscriberManagerTest::SetUpTestCase() +{ + g_notificationSubscriberManager = NotificationSubscriberManager::GetInstance(); +} + +void NotificationSubscriberManagerTest::TearDownTestCase() +{ + g_notificationSubscriberManager = nullptr; +} + +void NotificationSubscriberManagerTest::SetUp() +{} + +void NotificationSubscriberManagerTest::TearDown() +{} +class TestAnsSubscriber : public NotificationSubscriber { +public: + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + {} + virtual void OnDied() override + {} + virtual void OnUpdate(const std::shared_ptr &sortingMap) override + {} + virtual void OnDisturbModeChanged(int disturbMode) override + {} + virtual void OnCanceled(const std::shared_ptr &request) override + {} + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + virtual void OnConsumed(const std::shared_ptr &request) override + {} + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} +}; + +/** + * @tc.number : NotificationSubscriberManagerTest_001 + * @tc.name : AMS_ANS_NotifyUpdated_0100 + * @tc.desc : Test NotifyUpdated function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_001, Function | SmallTest | Level1) +{ + const std::vector sortingList; + sptr map = new NotificationSortingMap(sortingList); + g_notificationSubscriberManager->NotifyUpdated(map); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_002 + * @tc.name : AMS_ANS_NotifyDisturbModeChanged_0100 + * @tc.desc : Test NotifyDisturbModeChanged function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_002, Function | SmallTest | Level1) +{ + NotificationConstant::DisturbMode mode; + g_notificationSubscriberManager->NotifyDisturbModeChanged(mode); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_003 + * @tc.name : AMS_ANS_NotifyConsumed_0100 + * @tc.desc : Test NotifyConsumed function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_003, Function | SmallTest | Level1) +{ + std::vector sortingList; + sptr request = new NotificationRequest(); + sptr notification = new Notification(request); + sptr notificationMap = new NotificationSortingMap(sortingList); + g_notificationSubscriberManager->NotifyConsumed(notification, notificationMap); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_004 + * @tc.name : AMS_ANS_NotifyCanceled_0100 + * @tc.desc : Test NotifyCanceled function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_004, Function | SmallTest | Level1) +{ + std::vector sortingList; + sptr request = new NotificationRequest(); + sptr notification = new Notification(request); + sptr notificationMap = new NotificationSortingMap(sortingList); + int deleteReason = 0; + g_notificationSubscriberManager->NotifyCanceled(notification, notificationMap, deleteReason); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_005 + * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.desc : Test AddSubscriber function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_005, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ(g_notificationSubscriberManager->AddSubscriber(subscriber->GetImpl(), info), (int)ERR_OK); +} + +/** + * @tc.number : NotificationSubscriberManagerTest_006 + * @tc.name : AMS_ANS_RemoveSubscriber_0100 + * @tc.desc : Test RemoveSubscriber function + */ +HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_006, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_EQ(g_notificationSubscriberManager->RemoveSubscriber(subscriber->GetImpl(), info), (int)ERR_OK); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/permission_filter_test.cpp b/services/ans/test/unittest/permission_filter_test.cpp new file mode 100644 index 000000000..cf9885c22 --- /dev/null +++ b/services/ans/test/unittest/permission_filter_test.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2021 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 "permission_filter.h" +#include +#include + +#include "ans_inner_errors.h" +#include "notification_preferences.h" +#include "notification_slot.h" +#include "string_ex.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +class PermissionFilterTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void PermissionFilterTest::SetUpTestCase() +{} + +void PermissionFilterTest::TearDownTestCase() +{} + +void PermissionFilterTest::SetUp() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void PermissionFilterTest::TearDown() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +/** + * @tc.number : PermissionFilterTest_00100 + * @tc.name : AMS_ANS_OnStop_0100 + * @tc.desc : Test OnStart function + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00100, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + permissionFilter.OnStart(); +} + +/** + * @tc.number : PermissionFilterTest_00200 + * @tc.name : AMS_ANS_OnStop_0100 + * @tc.desc : Test OnStop function + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00200, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + permissionFilter.OnStop(); +} + +/** + * @tc.number : PermissionFilterTest_00300 + * @tc.name : AMS_ANS_OnPublish_0100 + * @tc.desc : Test OnPublish function when the param is wrong + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00300, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + sptr request = new NotificationRequest(); + auto objptr = new Notification(request); + EXPECT_EQ(permissionFilter.OnPublish(objptr), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : PermissionFilterTest_00400 + * @tc.name : AMS_ANS_OnPublish_0200 + * @tc.desc : Test OnPublish function + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00400, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + std::string bundleName = "bundleName"; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> slots; + slots.push_back(slot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); + sptr request = new NotificationRequest(); + request->SetOwnerBundleName(bundleName); + sptr notification = new Notification(request); + EXPECT_EQ(permissionFilter.OnPublish(notification), ERR_OK); +} + +/** + * @tc.number : PermissionFilterTest_00500 + * @tc.name : AMS_ANS_OnPublish_0300 + * @tc.desc : Test OnPublish function when file is null + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00500, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + std::string bundleName = "bundleName"; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> slots; + slots.push_back(slot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); + sptr request = new NotificationRequest(); + request->SetOwnerBundleName("bundleName1"); + sptr notification = new Notification(request); + EXPECT_EQ((int)permissionFilter.OnPublish(notification), (int)ERR_OK); +} + +/** + * @tc.number : PermissionFilterTest_00600 + * @tc.name : AMS_ANS_OnPublish_0400 + * @tc.desc : Test OnPublish function when NotificationsEnabled is false + */ +HWTEST_F(PermissionFilterTest, PermissionFilterTest_00600, Function | SmallTest | Level1) +{ + PermissionFilter permissionFilter; + std::string bundleName = "bundleName"; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + std::vector> slots; + slots.push_back(slot); + NotificationPreferences::GetInstance().AddNotificationSlots(bundleName, slots); + NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleName, false); + sptr request = new NotificationRequest(); + request->SetOwnerBundleName(bundleName); + sptr notification = new Notification(request); + EXPECT_EQ((int)permissionFilter.OnPublish(notification), (int)ERR_ANS_NOT_ALLOWED); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn new file mode 100644 index 000000000..c8bbdcf5f --- /dev/null +++ b/services/test/moduletest/BUILD.gn @@ -0,0 +1,112 @@ +# Copyright (c) 2021 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/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/moduletest" + +config("public_ans_config") { + include_dirs = [ + "${services_path}/ans/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "${kits_path}/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", + ] +} + +config("json_config") { + cflags_cc = [ "-fexceptions" ] +} + +ohos_moduletest("ans_module_test") { + module_out_path = module_output_path + include_dirs = [ + "include", + "${innerkits_path}/base/include", + "${innerkits_path}/core/include", + "${kits_path}/native/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/libs/libeventhandler/src", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "//base/notification/ans_standard/services/ans/include", + "//third_party/json/include", + "//base/notification/ans_standard/services/test/moduletest/mock/include", + ] + + sources = [ + "//base/notification/ans_standard/innerkits/core/src/ans_manager_stub.cpp", + "//base/notification/ans_standard/kits/native/src/notification.cpp", + "//base/notification/ans_standard/services/ans/src/advanced_notification_service.cpp", + "//base/notification/ans_standard/services/ans/src/advanced_notification_service_ability.cpp", + "//base/notification/ans_standard/services/ans/src/bundle_manager_helper.cpp", + "//base/notification/ans_standard/services/ans/src/disturb_filter.cpp", + "//base/notification/ans_standard/services/ans/src/notification_preferences.cpp", + "//base/notification/ans_standard/services/ans/src/notification_slot_filter.cpp", + "//base/notification/ans_standard/services/ans/src/notification_subscriber_manager.cpp", + "//base/notification/ans_standard/services/ans/src/permission_filter.cpp", + "ans_module_test.cpp", + "mock/mock_bundle_manager.cpp", + "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + ] + + configs = [ + "//utils/native/base:utils_config", + "${innerkits_path}:public_ans_innerkits_config", + ":json_config", + ] + + deps = [ + "${innerkits_path}:ans_innerkits", + "${kits_path}/native:ans_kits", + "${kits_path}/native/wantagent:wantagent_kits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("moduletest") { + testonly = true + deps = [] + + deps += [ ":ans_module_test" ] +} diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp new file mode 100644 index 000000000..723314355 --- /dev/null +++ b/services/test/moduletest/ans_module_test.cpp @@ -0,0 +1,132 @@ +#include +#include "advanced_notification_service.h" +#include "notification_preferences.h" +#include +#define private public +#include "notification_subscriber.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { + +const int32_t USLEEP_TIME = 300; +sptr g_advancedNotificationService; +bool passed = false; +class TestAnsSubscriber : public NotificationSubscriber +{ +public: + virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override {} + virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override {} + virtual void OnDied() override {} + virtual void OnUpdate(const std::shared_ptr &sortingMap) override {} + virtual void OnDisturbModeChanged(int disturbMode) override {} + virtual void OnCanceled(const std::shared_ptr &request) override {} + virtual void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override {} + virtual void OnConsumed(const std::shared_ptr &request) override + { + passed = true; + } + virtual void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + { + passed = true; + } +}; + +class AnsModuleTest : public testing::Test +{ +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AnsModuleTest::SetUpTestCase() +{ + g_advancedNotificationService = AdvancedNotificationService::GetInstance(); +} + +void AnsModuleTest::TearDownTestCase() +{ + sptr g_advancedNotificationService = nullptr; +} + +void AnsModuleTest::SetUp() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void AnsModuleTest::TearDown() +{ + NotificationPreferences::GetInstance().ClearNotificationInRestoreFactorySettings(); +} + +void TestAddSlots() +{ + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); +} + +/** + * @tc.number : AnsModuleTest_001 + * @tc.name : AMS_ANS_Subscribe_Publish_0100 + * @tc.desc : Test the functions of subscribing, publishing, and canceling + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::string label = "testLabel"; + auto subscriber = new TestAnsSubscriber(); + sptr req = new NotificationRequest(2); + sptr req1 = new NotificationRequest(1); + req1->SetLabel(label); + sptr info = new NotificationSubscribeInfo(); + info->AddAppName("bundleName"); + EXPECT_EQ((int)g_advancedNotificationService->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req1), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->Cancel(1, label), (int)ERR_OK); + usleep(USLEEP_TIME); + EXPECT_TRUE(passed); + g_advancedNotificationService->CancelAll(); + EXPECT_EQ((int)g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), info), (int)ERR_OK); + passed = false; +} + +/** + * @tc.number : AnsModuleTest_002 + * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.desc : Test the function of getting notifications and getting all notifications + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) +{ + TestAddSlots(); + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + sptr req1 = new NotificationRequest(1); + req1->SetLabel(label); + sptr req2 = new NotificationRequest(2); + req2->SetLabel("testLabel1"); + sptr info = new NotificationSubscribeInfo(); + info->AddAppName("bundleName"); + std::vector> notificationsReqs; + std::vector> notifications; + EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->Publish(label, req1), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->Publish("testLabel1", req2), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->GetActiveNotifications(notificationsReqs), (int)ERR_OK); + int num; + g_advancedNotificationService->GetActiveNotificationNums(num); + EXPECT_EQ((int)num, (int)3); + EXPECT_EQ((int)g_advancedNotificationService->Cancel(2, "testLabel1"), (int)ERR_OK); + EXPECT_EQ((int)g_advancedNotificationService->GetAllActiveNotifications(notifications), (int)ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)2); + EXPECT_EQ((int)g_advancedNotificationService->CancelAll(), (int)ERR_OK); +} +} +} \ No newline at end of file diff --git a/services/test/moduletest/mock/include/mock_bundle_manager.h b/services/test/moduletest/mock/include/mock_bundle_manager.h new file mode 100644 index 000000000..960b2aa7b --- /dev/null +++ b/services/test/moduletest/mock/include/mock_bundle_manager.h @@ -0,0 +1,413 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H +#define FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H + +#include + +#include "ability_info.h" +#include "application_info.h" +#include "bundle_mgr_host.h" +#include "bundle_mgr_interface.h" +#include "ohos/aafwk/content/want.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +class MockBundleMgrService : public BundleMgrHost { +public: + MockBundleMgrService() + { + } + + ~MockBundleMgrService() + {} + + /** + * @brief Obtains the ApplicationInfo based on a given bundle name. + * @param appName Indicates the application bundle name to be queried. + * @param flag Indicates the flag used to specify information contained + * in the ApplicationInfo object that will be returned. + * @param userId Indicates the user ID. + * @param appInfo Indicates the obtained ApplicationInfo object. + * @return Returns true if the application is successfully obtained; returns false otherwise. + */ + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override + { + return true; + } + /** + * @brief Obtains information about all installed applications of a specified user. + * @param flag Indicates the flag used to specify information contained + * in the ApplicationInfo objects that will be returned. + * @param userId Indicates the user ID. + * @param appInfos Indicates all of the obtained ApplicationInfo objects. + * @return Returns true if the application is successfully obtained; returns false otherwise. + */ + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + } + /** + * @brief Obtains the BundleInfo based on a given bundle name. + * @param bundleName Indicates the application bundle name to be queried. + * @param flag Indicates the information contained in the BundleInfo object to be returned. + * @param bundleInfo Indicates the obtained BundleInfo object. + * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + /** + * @brief Obtains BundleInfo of all bundles available in the system. + * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + }; + /** + * @brief Obtains the application UID based on the given bundle name and user ID. + * @param bundleName Indicates the bundle name of the application. + * @param userId Indicates the user ID. + * @return Returns the uid if successfully obtained; returns -1 otherwise. + */ + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + return 0; + } + /** + * @brief Obtains the bundle name of a specified application based on the given UID. + * @param uid Indicates the uid. + * @param bundleName Indicates the obtained bundle name. + * @return Returns true if the bundle name is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "hello"; + return true; + } + /** + * @brief Obtains an array of all group IDs associated with a specified bundle. + * @param bundleName Indicates the bundle name. + * @param gids Indicates the group IDs associated with the specified bundle. + * @return Returns true if the gids is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + } + /** + * @brief Obtains the type of a specified application based on the given bundle name. + * @param bundleName Indicates the bundle name. + * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. + */ + virtual std::string GetAppType(const std::string &bundleName) override + { + return ""; + } + /** + * @brief Check whether the app is system app by it's UID. + * @param uid Indicates the uid. + * @return Returns true if the bundle is a system application; returns false otherwise. + */ + virtual bool CheckIsSystemAppByUid(const int uid) override; + + /** + * @brief Obtains the BundleInfo of application bundles based on the specified metaData. + * @param metaData Indicates the metadata to get in the bundle. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + } + /** + * @brief Query the AbilityInfo by the given Want. + * @param want Indicates the infomation of the ability. + * @param abilityInfo Indicates the obtained AbilityInfo object. + * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Query the AbilityInfo by ability.uri in config.json. + * @param abilityUri Indicates the uri of the ability. + * @param abilityInfo Indicates the obtained AbilityInfo object. + * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) override + { + return true; + } + /** + * @brief Obtains the BundleInfo of all keep-alive applications in the system. + * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. + */ + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + }; + /** + * @brief Obtains the label of a specified ability. + * @param bundleName Indicates the bundle name. + * @param className Indicates the ability class name. + * @return Returns the label of the ability if exist; returns empty string otherwise. + */ + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + } + /** + * @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP). + * @param hapFilePath Indicates the absolute file path of the HAP. + * @param flag Indicates the information contained in the BundleInfo object to be returned. + * @param bundleInfo Indicates the obtained BundleInfo object. + * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + /** + * @brief Obtain the HAP module info of a specific ability. + * @param abilityInfo Indicates the ability. + * @param hapModuleInfo Indicates the obtained HapModuleInfo object. + * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + /** + * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. + * @param bundleName Indicates the bundle name. + * @param want Indicates the obtained launch Want object. + * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. + */ + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + } + /** + * @brief Confirms with the permission management module to check whether a request prompt is required for granting + * a certain permission. + * @param bundleName Indicates the name of the bundle to check. + * @param permission Indicates the permission to check. + * @param userId Indicates the user id. + * @return Returns true if the current application does not have the permission and the user does not turn off + * further requests; returns false if the current application already has the permission, the permission is rejected + * by the system, or the permission is denied by the user and the user has turned off further requests. + */ + virtual bool CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) override + { + return true; + } + /** + * @brief Checks whether the publickeys of two bundles are the same. + * @param firstBundleName Indicates the first bundle name. + * @param secondBundleName Indicates the second bundle name. + * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; + * returns SIGNATURE_NOT_MATCHED if their publickeys are different; + * returns SIGNATURE_MATCHED if their publickeys are the same. + */ + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + } + /** + * @brief Checks whether a specified bundle has been granted a specific permission. + * @param bundleName Indicates the name of the bundle to check. + * @param permission Indicates the permission to check. + * @return Returns 0 if the bundle has the permission; returns -1 otherwise. + */ + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override; + /** + * @brief Obtains detailed information about a specified permission. + * @param permissionName Indicates the name of the ohos permission. + * @param permissionDef Indicates the object containing detailed information about the given ohos permission. + * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. + */ + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + } + /** + * @brief Obtains all known permission groups in the system. + * @param permissionDefs Indicates the list of objects containing the permission group information. + * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. + */ + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + } + /** + * @brief Obtains all known permission groups in the system. + * @param permissions Indicates the permission array. + * @param appNames Indicates the list of application names that have the specified permissions. + * @return Returns true if the application names is successfully obtained; returns false otherwise. + */ + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + } + /** + * @brief Requests a certain permission from user. + * @param bundleName Indicates the name of the bundle to request permission. + * @param permission Indicates the permission to request permission. + * @param userId Indicates the user id. + * @return Returns true if the permission request successfully; returns false otherwise. + */ + virtual bool RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) override + { + return true; + } + /** + * @brief Checks whether the system has a specified capability. + * @param capName Indicates the name of the system feature to check. + * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. + */ + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + } + /** + * @brief Obtains the capabilities that are available in the system. + * @param systemCaps Indicates the list of capabilities available in the system. + * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. + */ + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + } + /** + * @brief Checks whether the current device has been started in safe mode. + * @return Returns true if the device is in safe mode; returns false otherwise. + */ + virtual bool IsSafeMode() override + { + return true; + } + /** + * @brief Clears cache data of a specified application. + * @param bundleName Indicates the bundle name of the application whose cache data is to be cleared. + * @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } + /** + * @brief Clears application running data of a specified application. + * @param bundleName Indicates the bundle name of the application whose data is to be cleared. + * @return Returns true if the data cleared successfully; returns false otherwise. + */ + virtual bool CleanBundleDataFiles(const std::string &bundleName) override + { + return true; + } + /** + * @brief Register the specific bundle status callback. + * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + /** + * @brief Clear the specific bundle status callback. + * @param bundleStatusCallback Indicates the callback to be cleared. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + /** + * @brief Unregister all the callbacks of status changed. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool UnregisterBundleStatusCallback() override + { + return true; + } + /** + * @brief Dump the bundle informations with specifc flags. + * @param flag Indicates the information contained in the dump result. + * @param bundleName Indicates the bundle name if needed. + * @param result Indicates the dump infomation result. + * @return Returns true if the dump result is successfully obtained; returns false otherwise. + */ + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + } + /** + * @brief Checks whether a specified application is enabled. + * @param bundleName Indicates the bundle name of the application. + * @return Returns true if the application is enabled; returns false otherwise. + */ + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + } + /** + * @brief Sets whether to enable a specified application. + * @param bundleName Indicates the bundle name of the application. + * @param isEnable Specifies whether to enable the application. + * The value true means to enable it, and the value false means to disable it. + * @return Returns true if the application is enabled; returns false otherwise. + */ + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } + /** + * @brief Obtains the interface used to install and uninstall bundles. + * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. + */ + virtual sptr GetBundleInstaller() override + { + return nullptr; + } + + void MockSetIsSystemApp(bool isSystemApp); + +private: + bool isSystemApp_ = false; + bool isSystemAppMock_ = false; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_bundle_manager.cpp b/services/test/moduletest/mock/mock_bundle_manager.cpp new file mode 100644 index 000000000..340c592c3 --- /dev/null +++ b/services/test/moduletest/mock/mock_bundle_manager.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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 "ability_info.h" +#include "application_info.h" +#include "mock_bundle_manager.h" + +namespace OHOS { +namespace AppExecFwk { +void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) +{ + isSystemAppMock_ = true; + isSystemApp_ = isSystemApp; +} + +bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid) +{ + if (isSystemAppMock_) { + return isSystemApp_; + } + return (uid < 1000) ? false : true; +} + +int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + if (!bundleName.compare("hello")) { + return 0; + } else { + return -1; + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 000000000..afaa94b2b --- /dev/null +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 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 "bundle_manager_helper.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { + +BundleManagerHelper::BundleManagerHelper() +{ +} + +BundleManagerHelper::~BundleManagerHelper() +{ +} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{ +} + +std::string BundleManagerHelper::GetBundleNameByUid(uid_t uid) +{ + return "bundleName"; +} + +bool BundleManagerHelper::IsSystemApp(uid_t uid) +{ + return true; +} + +void BundleManagerHelper::Connect() +{ +} + +void BundleManagerHelper::Disconnect() +{ +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp new file mode 100644 index 000000000..cd58a4838 --- /dev/null +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2021 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 "bundle_mgr_proxy.h" + +#include "ipc_types.h" +#include "parcel.h" +#include "string_ex.h" + +#include "appexecfwk_errors.h" +#include "bundle_constants.h" + +namespace OHOS { +namespace AppExecFwk { + +BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{ +} + +BundleMgrProxy::~BundleMgrProxy() +{ +} + +bool BundleMgrProxy::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + return true; +} + +bool BundleMgrProxy::GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) +{ + return true; +} + +int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + return 1; +} + +std::string BundleMgrProxy::GetAppIdByBundleName(const std::string &bundleName, const int userId) +{ + return "appId"; +} + +bool BundleMgrProxy::GetBundleNameForUid(const int uid, std::string &bundleName) +{ + bundleName = "bundleName"; + return true; +} + +bool BundleMgrProxy::GetBundlesForUid(const int uid, std::vector &bundleNames) +{ + return true; +} + +bool BundleMgrProxy::GetNameForUid(const int uid, std::string &name) +{ + return true; +} + +bool BundleMgrProxy::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + return true; +} + +std::string BundleMgrProxy::GetAppType(const std::string &bundleName) +{ + return "Constants::EMPTY_STRING"; +} + +bool BundleMgrProxy::CheckIsSystemAppByUid(const int uid) +{ + return true; +} + +bool BundleMgrProxy::GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) +{ + return true; +} + +bool BundleMgrProxy::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::QueryKeepAliveBundleInfos(std::vector &bundleInfos) +{ + return true; +} + +std::string BundleMgrProxy::GetAbilityLabel(const std::string &bundleName, const std::string &className) +{ + return "reply.ReadString()"; +} + +bool BundleMgrProxy::GetBundleArchiveInfo(const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) +{ + return true; +} + +bool BundleMgrProxy::GetLaunchWantForBundle(const std::string &bundleName, Want &want) +{ + return true; +} + +int BundleMgrProxy::CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) +{ + return 1; +} + +int BundleMgrProxy::CheckPermission(const std::string &bundleName, const std::string &permission) +{ + return 1; +} + +bool BundleMgrProxy::GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) +{ + return true; +} + +bool BundleMgrProxy::GetAllPermissionGroupDefs(std::vector &permissionDefs) +{ + return true; +} + +bool BundleMgrProxy::GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) +{ + return true; +} + +bool BundleMgrProxy::HasSystemCapability(const std::string &capName) +{ + return true; +} + +bool BundleMgrProxy::GetSystemAvailableCapabilities(std::vector &systemCaps) +{ + return true; +} + +bool BundleMgrProxy::IsSafeMode() +{ + return true; +} + +bool BundleMgrProxy::CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) +{ + return true; +} + +bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName) +{ + return true; +} + +bool BundleMgrProxy::RegisterBundleStatusCallback(const sptr &bundleStatusCallback) +{ + return true; +} + +bool BundleMgrProxy::ClearBundleStatusCallback(const sptr &bundleStatusCallback) +{ + return true; +} + +bool BundleMgrProxy::UnregisterBundleStatusCallback() +{ + return true; +} + +bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) +{ + return true; +} + +bool BundleMgrProxy::IsApplicationEnabled(const std::string &bundleName) +{ + return true; +} + +bool BundleMgrProxy::SetApplicationEnabled(const std::string &bundleName, bool isEnable) +{ + return true; +} + +bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrProxy::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) +{ + return true; +} + +std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) +{ + return "AbilityIcon"; +} + +bool BundleMgrProxy::CanRequestPermission( + const std::string &bundleName, const std::string &permissionName, const int userId) +{ + return true; +} + +bool BundleMgrProxy::RequestPermissionFromUser( + const std::string &bundleName, const std::string &permission, const int userId) +{ + return true; +} + +bool BundleMgrProxy::RegisterAllPermissionsChanged(const sptr &callback) +{ + return true; +} + +bool BundleMgrProxy::RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) +{ + return true; +} + +bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr &callback) +{ + return true; +} + +template +bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) +{ + return true; +} + +template +bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) +{ + return true; +} + +bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/test/moduletest/mock/mock_event_handler.cpp b/services/test/moduletest/mock/mock_event_handler.cpp new file mode 100644 index 000000000..4fcdd4a2c --- /dev/null +++ b/services/test/moduletest/mock/mock_event_handler.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 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 "event_handler.h" +#include "event_handler_utils.h" +#include + +namespace OHOS +{ + namespace AppExecFwk + { + + std::shared_ptr EventHandler::Current() + { + const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); + return wp.lock(); + } + + EventHandler::EventHandler(const std::shared_ptr &runner) : eventRunner_(runner) + { + } + + EventHandler::~EventHandler() + { + } + + bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Priority priority) + { + std::function callback = event->GetTaskCallback(); + callback(); + return true; + } + + bool EventHandler::SendTimingEvent(InnerEvent::Pointer &event, int64_t taskTime, Priority priority) + { + return true; + } + + bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) + { + std::function callback = event->GetTaskCallback(); + callback(); + return true; + } + + void EventHandler::RemoveAllEvents() + { + } + + void EventHandler::RemoveEvent(uint32_t innerEventId) + { + } + + void EventHandler::RemoveEvent(uint32_t innerEventId, int64_t param) + { + } + + void EventHandler::RemoveTask(const std::string &name) + { + } + + ErrCode EventHandler::AddFileDescriptorListener( + int32_t fileDescriptor, uint32_t events, const std::shared_ptr &listener) + { + return EVENT_HANDLER_ERR_INVALID_PARAM; + } + + void EventHandler::RemoveAllFileDescriptorListeners() + { + } + + void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) + { + } + + void EventHandler::SetEventRunner(const std::shared_ptr &runner) + { + } + + void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) + { + } + + void EventHandler::Dump(Dumper &dumper) + { + } + + bool EventHandler::HasInnerEvent(uint32_t innerEventId) + { + return true; + } + + bool EventHandler::HasInnerEvent(int64_t param) + { + return true; + } + + std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) + { + return "132123"; + } + + bool EventHandler::IsIdle() + { + return true; + } + + void EventHandler::ProcessEvent(const InnerEvent::Pointer &) + { + } + } // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_ipc.cpp b/services/test/moduletest/mock/mock_ipc.cpp new file mode 100644 index 000000000..1acbe4a3f --- /dev/null +++ b/services/test/moduletest/mock/mock_ipc.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2021 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 "ipc_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif +pid_t IPCSkeleton::GetCallingUid() +{ + pid_t uid = 1; + return uid; +} +} // namespace OHOS diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 000000000..e69de29bb diff --git a/tools/BUILD.gn b/tools/BUILD.gn new file mode 100644 index 000000000..adb8ad2ba --- /dev/null +++ b/tools/BUILD.gn @@ -0,0 +1,16 @@ +# Copyright (c) 2021 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. + +group("tools_target") { + deps = [] +} -- Gitee