From c113d1fd3ab294230a628bc1e70b0f0f1b5807b8 Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Sun, 27 Apr 2025 20:00:23 +0800 Subject: [PATCH 1/9] =?UTF-8?q?feat:notification=20=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3ani=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- bundle.json | 4 +- frameworks/ani/BUILD.gn | 22 ++ frameworks/ani/notification_manager/BUILD.gn | 83 +++++ .../notification_manager/ets/@ohos.base.ets | 49 +++ .../ets/@ohos.notificationManager.ets | 322 ++++++++++++++++++ .../notification/NotificationCommonDef.ets | 24 ++ .../include/sts_bundle_option.h | 28 ++ .../include/sts_common_util.h | 102 ++++++ .../include/sts_enum_slot_type.h | 45 +++ .../include/sts_notification_manager.h | 24 ++ .../src/sts_bundle_option.cpp | 73 ++++ .../src/sts_common_util.cpp | 41 +++ .../src/sts_enum_slot_type.cpp | 101 ++++++ .../src/sts_notification_manager.cpp | 266 +++++++++++++++ 14 files changed, 1183 insertions(+), 1 deletion(-) create mode 100644 frameworks/ani/BUILD.gn create mode 100644 frameworks/ani/notification_manager/BUILD.gn create mode 100644 frameworks/ani/notification_manager/ets/@ohos.base.ets create mode 100644 frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets create mode 100644 frameworks/ani/notification_manager/include/sts_bundle_option.h create mode 100644 frameworks/ani/notification_manager/include/sts_common_util.h create mode 100644 frameworks/ani/notification_manager/include/sts_enum_slot_type.h create mode 100644 frameworks/ani/notification_manager/include/sts_notification_manager.h create mode 100644 frameworks/ani/notification_manager/src/sts_bundle_option.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_common_util.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_manager.cpp diff --git a/bundle.json b/bundle.json index de58f375c..b6e84f467 100644 --- a/bundle.json +++ b/bundle.json @@ -90,6 +90,7 @@ "init", "eventhandler", "c_utils", + "runtime_core", "i18n", "device_manager", "kv_store", @@ -120,7 +121,8 @@ "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification", - "//base/notification/distributed_notification_service/frameworks/reminder:reminder_client" + "//base/notification/distributed_notification_service/frameworks/reminder:reminder_client", + "//base/notification/distributed_notification_service/frameworks/ani:ani_packages" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", diff --git a/frameworks/ani/BUILD.gn b/frameworks/ani/BUILD.gn new file mode 100644 index 000000000..071a0da8d --- /dev/null +++ b/frameworks/ani/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +group("ani_packages") { + deps = [ + "notification_manager:notification_manager_ani_kit", + "notification_manager:notification_manager_abc_etc" + ] +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/BUILD.gn b/frameworks/ani/notification_manager/BUILD.gn new file mode 100644 index 000000000..d88ba8fe7 --- /dev/null +++ b/frameworks/ani/notification_manager/BUILD.gn @@ -0,0 +1,83 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//base/notification/distributed_notification_service/notification.gni") + +ohos_shared_library("notification_manager_ani_kit") { + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + + include_dirs = [ + "./include", + "${core_path}/common/include", + "${inner_api_path}", + ] + + sources = [ + "./src/sts_notification_manager.cpp", + "./src/sts_common_util.cpp", + "./src/sts_bundle_option.cpp", + "./src/sts_enum_slot_type.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "runtime_core:ani", + "ipc:ipc_core", + "ability_base:zuri", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +generate_static_abc("notification_manager_abc") { + base_url = "./ets" + files = [ + "./ets/notification/NotificationCommonDef.ets", + "./ets/@ohos.notificationManager.ets", + "./ets/@ohos.base.ets", + ] + + dst_file = "$target_out_dir/notification_manager.abc" + out_puts = [ "$target_out_dir/notification_manager.abc" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/notification_manager.abc" +} + +ohos_prebuilt_etc("notification_manager_abc_etc") { + source = "$target_out_dir/notification_manager.abc" + module_install_dir = "framework" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + deps = [ ":notification_manager_abc" ] +} diff --git a/frameworks/ani/notification_manager/ets/@ohos.base.ets b/frameworks/ani/notification_manager/ets/@ohos.base.ets new file mode 100644 index 000000000..f7b23f6b1 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/@ohos.base.ets @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type Callback = (data: T) => void; + +export type ErrorCallback = (err: T)=> void; + + +export type AsyncCallback = (err: BusinessError, data: T)=> void; + +export class BusinessError extends Error { + + // 构造函数重载1:无参数 + constructor() { + super(); // 调用父类 Error 的构造函数 + this.code = 0; // 默认错误代码 + this.data = undefined; // 默认数据为 undefined + } + + // 构造函数重载2:带有错误代码和 Error 对象 + constructor(code: number, error: Error) { + // constructor(name: String, message: String | undefined, options: ErrorOptions | undefined) + super(error.name, error.message, undefined); // 调用父类 Error 的构造函数,并传递错误信息 + this.code = code; + this.data = undefined; // 默认数据为 undefined + } + + constructor(code: number, data: T, error: Error) { + super(error.name, error.message, undefined); // 调用父类 Error 的构造函数,并传递错误信息 + this.code = code; + this.data = data; // 默认数据为 undefined + } + + public code: number; + + public data?: T; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets new file mode 100644 index 000000000..e77aa75a8 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BundleOption } from 'notification.NotificationCommonDef'; +import { BusinessError, AsyncCallback } from '@ohos.base'; + +type ResolveCallback = (data: T) => void; +type RejectCallback = (err: Object) => void; +export namespace notificationManager { + export enum SlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + LIVE_VIEW = 4, + CUSTOMER_SERVICE = 5, + EMERGENCY_INFORMATION = 10, + OTHER_TYPES = 0xFFFF + } + export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; + export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; + export native function nativeGetActiveNotificationCount(): number; + export native function nativeIsNotificationEnabled(userId?: int, bundleOption?: BundleOption): boolean; + export native function nativegetSlotFlagsByBundle(bundle: BundleOption): int; + export native function nativesetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; + export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; + export native function nativeisNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; + export native function nativeCancelWithId(id: number): void; + export native function nativeCancelWithIdLabel(id: number, label: string): void; + export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; + export native function nativeCancelAll(): void; + + export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); + p.then((e: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function displayBadge(bundle: BundleOption, enable: boolean): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void { + let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function isBadgeDisplayed(bundle: BundleOption): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getActiveNotificationCount(): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback):void => { + let p = taskpool.execute((): number => { return nativeGetActiveNotificationCount(); }); + p.then((data :NullishType): void => { + let ret : number = data as number; + resolve(ret); + }, (err:Object): void => { + reject(err); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(userId: int, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function isNotificationEnabled(userId: int): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(bundleOption: BundleOption, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function isNotificationEnabled(bundleOption: BundleOption): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationEnabled(callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function isNotificationEnabled(): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function getSlotFlagsByBundle(bundle: BundleOption): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): number => { return nativegetSlotFlagsByBundle(bundle); }); + p.then((data: NullishType): void => { + let ret : Double = data as Double; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativesetSlotFlagsByBundle(bundle, slotFlags); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void + { + let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function cancel(id: number, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function cancel(id: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label: string): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancel(id: number, label: string, callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function cancel(bundle: BundleOption, id: number): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelWithBundle(bundle, id); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAll(): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function cancelAll(callback: AsyncCallback): void { + let p = taskpool.execute((): void => { return nativeCancelAll(); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } +} diff --git a/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets new file mode 100644 index 000000000..a434e6b75 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface BundleOption { + bundle: string; + uid?: number; +} + +class BundleOptionInner implements BundleOption { + public bundle: string = ''; + public uid?: number = 0; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_bundle_option.h b/frameworks/ani/notification_manager/include/sts_bundle_option.h new file mode 100644 index 000000000..72cc23e34 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_bundle_option.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_BUNDLE_OPTION_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_BUNDLE_OPTION_H + +#include "ani.h" +#include "notification_bundle_option.h" + +namespace OHOS { +namespace NotificationSts { + bool UnwrapBundleOption(ani_env *env, ani_object param, Notification::NotificationBundleOption& option); +} +} + +#endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h new file mode 100644 index 000000000..13f3da97e --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_UTIL_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_UTIL_H +#include "ani.h" +#include "notification_bundle_option.h" +#include +#include + +namespace OHOS { +namespace AniCommom { + +bool GetStdString(ani_env *env, ani_string str, std::string &res); + +inline bool AniBooleanToBool(ani_boolean value) +{ + return value == ANI_TRUE; +} + +inline ani_boolean BoolToAniBoolean(bool value) +{ + return value ? ANI_TRUE : ANI_FALSE; +} + +template +static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &result) +{ + ani_status status = ANI_ERROR; + if constexpr (std::is_enum::value || std::is_integral::value) { + ani_int intValue{}; + status = env->EnumItem_GetValue_Int(enumItem, &intValue); + if (ANI_OK != status) { + ANS_LOGD("EnumConvert_StsToNative failed, status : %{public}d", status); + return false; + } + result = static_cast(intValue); + return true; + } else if constexpr (std::is_same::value) { + ani_string strValue{}; + status = env->EnumItem_GetValue_String(enumItem, &strValue); + if (ANI_OK != status) { + ANS_LOGD("EnumItem_GetValue_String failed, status : %{public}d", status); + return false; + } + return GetStdString(env, strValue, result); + } else { + ANS_LOGD("Enum convert failed: type not supported"); + return false; + } +} + +template +static bool EnumConvertAniToNative(ani_env *env, ani_object enumItem, T &result) +{ + return EnumConvertAniToNative(env, static_cast(enumItem), result); +} + +template +static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T enumValue, ani_enum_item &result) +{ + ani_enum aniEnum{}; + ani_status status = env->FindEnum(enumName, &aniEnum); + if (ANI_OK != status) { + ANS_LOGD("Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); + return false; + } + constexpr int32_t loopMaxNum = 1000; + for (int32_t index = 0U; index < loopMaxNum; index++) { + ani_enum_item enumItem{}; + status = env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem); + if (ANI_OK != status) { + ANS_LOGD("Enum convert Enum_GetEnumItemByIndex failed: enumName:%{public}s index:%{public}d,\ + status:%{public}d", enumName, index, status); + return false; + } + // compare value + T tmpValue{}; + if (EnumConvertAniToNative(env, enumItem, tmpValue) && tmpValue == enumValue) { + result = enumItem; + return true; + } + } + ANS_LOGD("EnumConvert_NativeToSts failed enumName: %{public}s", enumName); + return false; +} + +} // namespace AniCommom +} // namespace OHOS +#endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_enum_slot_type.h b/frameworks/ani/notification_manager/include/sts_enum_slot_type.h new file mode 100644 index 000000000..91a8aa4f9 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_enum_slot_type.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H +#include "sts_common_util.h" +#include "notification_constant.h" + +using SlotType = OHOS::Notification::NotificationConstant::SlotType; +namespace OHOS { +namespace NotificationSts { +enum STSSlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + LIVE_VIEW = 4, + CUSTOMER_SERVICE = 5, + EMERGENCY_INFORMATION = 10, + OTHER_TYPES = 0xFFFF, +}; + +class StsSlotTypeUtils { +public: +static bool StsToC(const STSSlotType inType, SlotType &outType); +static bool CToSts(const SlotType inType, STSSlotType &outType); +}; + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType); +[[maybe_unused]]bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem); +} +} +#endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_manager.h b/frameworks/ani/notification_manager/include/sts_notification_manager.h new file mode 100644 index 000000000..e24fdb058 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_notification_manager.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_NOTIFICATION_MANAGER_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_NOTIFICATION_MANAGER_H +#include "ani.h" +namespace OHOS { +namespace NotificationManagerSts { +void StsNotificationManagerRegistryInit(ani_env *env); +} +} +#endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp new file mode 100644 index 000000000..503bba6f6 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "sts_common_util.h" +#include "ans_log_wrapper.h" + +using namespace OHOS::AniCommom; +namespace OHOS { +namespace NotificationSts { + +bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::NotificationBundleOption& option) +{ + ANS_LOGD("WrapBundleOption call"); + ani_ref bundleNameRef; + ani_status status = env->Object_GetPropertyByName_Ref(obj, "bundle", &bundleNameRef); + if (ANI_OK != status) { + ANS_LOGD("WrapBundleOption Object_GetField_Ref bundle fail, status: %{public}d", status); + return false; + } + + std::string bundleName; + if (!GetStdString(env, reinterpret_cast(bundleNameRef), bundleName)) { + ANS_LOGD("WrapBundleOption GetStdString failed"); + return false; + } + option.SetBundleName(bundleName); + ANS_LOGD("WrapBundleOption bundleName: %{public}s", bundleName.c_str()); + + ani_ref uidRef; + status = env->Object_GetPropertyByName_Ref(obj, "uid", &uidRef); + if (ANI_OK != status) { + ANS_LOGD("WrapBundleOption Object_GetPropertyByName_Ref uid fail, status: %{public}d", status); + return true; + } + ani_boolean isUndefined = true; + if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { + ANS_LOGD("WrapBundleOption Object_GetPropertyByName_Ref status : %{public}d", status); + return true; + } + if (isUndefined) { + ANS_LOGD("WrapBundleOption uid is undefined"); + return true; + } + ani_double result = 0.0; + status = env->Object_CallMethodByName_Double(static_cast(uidRef), "doubleValue", nullptr, &result); + if (ANI_OK != status) { + ANS_LOGD("WrapBundleOption Object_CallMethodByName_Double uid fail, status: %{public}d", status); + return true; + } + + int32_t uid = static_cast(result); + + ANS_LOGD("WrapBundleOption bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), uid); + + option.SetUid(uid); + + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_common_util.cpp b/frameworks/ani/notification_manager/src/sts_common_util.cpp new file mode 100644 index 000000000..dc4ad565c --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_common_util.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "sts_common_util.h" +#include "ans_log_wrapper.h" +#include "securec.h" + +namespace OHOS { +namespace AniCommom { + +bool GetStdString(ani_env *env, ani_string str, std::string &res) +{ + ani_size sz {}; + ani_status status = ANI_ERROR; + if ((status = env->String_GetUTF8Size(str, &sz)) != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + res.resize(sz + 1); + if ((status = env->String_GetUTF8SubString(str, 0, sz, res.data(), res.size(), &sz)) != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + res.resize(sz); + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp b/frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp new file mode 100644 index 000000000..0b02741ec --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sts_enum_slot_type.h" +namespace OHOS { +namespace NotificationSts { +bool StsSlotTypeUtils::StsToC(const STSSlotType inType, SlotType &outType) +{ + switch (inType) { + case STSSlotType::SOCIAL_COMMUNICATION: + outType = SlotType::SOCIAL_COMMUNICATION; + break; + case STSSlotType::SERVICE_INFORMATION: + outType = SlotType::SERVICE_REMINDER; + break; + case STSSlotType::CONTENT_INFORMATION: + outType = SlotType::CONTENT_INFORMATION; + break; + case STSSlotType::LIVE_VIEW: + outType = SlotType::LIVE_VIEW; + break; + case STSSlotType::CUSTOMER_SERVICE: + outType = SlotType::CUSTOMER_SERVICE; + break; + case STSSlotType::EMERGENCY_INFORMATION: + outType = SlotType::EMERGENCY_INFORMATION; + break; + case STSSlotType::UNKNOWN_TYPE: + case STSSlotType::OTHER_TYPES: + outType = SlotType::OTHER; + break; + default: + ANS_LOGE("SlotType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsSlotTypeUtils::CToSts(const SlotType inType, STSSlotType &outType) +{ + switch (inType) { + case SlotType::CUSTOM: + outType = STSSlotType::UNKNOWN_TYPE; + break; + case SlotType::SOCIAL_COMMUNICATION: + outType = STSSlotType::SOCIAL_COMMUNICATION; + break; + case SlotType::SERVICE_REMINDER: + outType = STSSlotType::SERVICE_INFORMATION; + break; + case SlotType::CONTENT_INFORMATION: + outType = STSSlotType::CONTENT_INFORMATION; + break; + case SlotType::LIVE_VIEW: + outType = STSSlotType::LIVE_VIEW; + break; + case SlotType::CUSTOMER_SERVICE: + outType = STSSlotType::CUSTOMER_SERVICE; + break; + case SlotType::EMERGENCY_INFORMATION: + outType = STSSlotType::EMERGENCY_INFORMATION; + break; + case SlotType::OTHER: + outType = STSSlotType::OTHER_TYPES; + break; + default: + ANS_LOGE("SlotType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType) +{ + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + AniCommom::EnumConvertAniToNative(env, enumItem, stsSlotType); + StsSlotTypeUtils::StsToC(stsSlotType, slotType); + return true; +} + +bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem) +{ + STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; + StsSlotTypeUtils::CToSts(slotType, stsSlotType); + AniCommom::EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/#SlotType", stsSlotType, enumItem); + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp new file mode 100644 index 000000000..76b14a800 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "sts_notification_manager.h" +#include "sts_common_util.h" +#include "sts_bundle_option.h" +#include "notification_bundle_option.h" +#include "notification_helper.h" +#include "sts_enum_slot_type.h" + +using namespace OHOS::AniCommom; +using namespace OHOS::NotificationSts; +namespace OHOS { +namespace NotificationManagerSts { + +static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) +{ + ANS_LOGD("sts DisplayBadge call"); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, obj, option); + int ret = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, AniBooleanToBool(enable)); + ANS_LOGD("sts DisplayBadge end, ret: %{public}d", ret); +} + +static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts IsBadgeDisplayed call"); + Notification::NotificationBundleOption option; + bool ret = UnwrapBundleOption(env, obj, option); + bool isDisplayed = false; + int returncode = 0; + if (ret) { + returncode = Notification::NotificationHelper::GetShowBadgeEnabledForBundle(option, isDisplayed); + } else { + returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); + } + ANS_LOGD("sts IsBadgeDisplayed end, isDisplayed: %{public}d, returncode: %{public}d", isDisplayed, returncode); + return BoolToAniBoolean(isDisplayed); +} + +static ani_double GetActiveNotificationCount(ani_env *env) +{ + ANS_LOGD("sts GetActiveNotificationCount call"); + uint64_t num = 0; + OHOS::Notification::NotificationHelper::GetActiveNotificationNums(num); + ANS_LOGD("sts GetActiveNotificationCount end, num: %{public}llu", num); + ani_double retNum = static_cast(num); + return retNum; +} + +static ani_boolean isNotificationEnabled([[maybe_unused]]ani_env *env, ani_object jsUserId, ani_object jsBundleOption) +{ + ani_int userId = 0; + bool allowed = false; + int32_t ret = 0; + ani_boolean isUserIdUndefined = ANI_FALSE; + ani_boolean isBundleUndefined = ANI_FALSE; + + ANS_LOGD("sts DisplayBadge call"); + + env->Reference_IsUndefined(jsUserId, &isUserIdUndefined); + env->Reference_IsUndefined(jsBundleOption, &isBundleUndefined); + + ANS_LOGD("isNotificationEnabled isUserIdUndefined = %{public}d isBundleUndefined = %{public}d", + isUserIdUndefined, isBundleUndefined); + + // 3. 解析 userId + if (!isUserIdUndefined) { + ANS_LOGD("isNotificationEnabled ==>> isUserIdUndefined"); + if (ANI_OK !=env->Object_CallMethodByName_Int(jsUserId, "intValue", nullptr, &userId)) { + ANS_LOGD("isNotificationEnabled Object_CallMethodByName_Int Fail"); + userId = 0; + return ANI_FALSE; + } + ret = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); + ANS_LOGD("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); + } else if (!isBundleUndefined) { + ANS_LOGD("isNotificationEnabled ==>> isBundleUndefined"); + + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, jsBundleOption, option); + ret = Notification::NotificationHelper::IsAllowedNotify(option, allowed); + } else { + ANS_LOGD("isNotificationEnabled ==>> no parameter"); + ret = Notification::NotificationHelper::IsAllowedNotify(allowed); + ANS_LOGD("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); + } + + if (ret != ANI_OK) { + return ANI_FALSE; + } else { + return allowed ? ANI_TRUE : ANI_FALSE; + } +} + +static ani_int getSlotFlagsByBundle(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts getSlotFlagsByBundle call"); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, obj, option); + uint32_t slotFlags = 0; + Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); + return slotFlags; +} + +static void setSlotFlagsByBundle(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts setSlotFlagsByBundle call"); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, obj, option); + uint32_t slotFlags = 0; + Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); + return; +} + +static void SetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean enable) +{ + ANS_LOGD("SetNotificationEnable enter "); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, bundleOption, option); + std::string deviceId {""}; + Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(option, deviceId, + AniBooleanToBool(enable)); +} + +static ani_boolean IsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type) +{ + ANS_LOGD("isNotificationSlotEnabledSync enter"); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, bundleOption, option); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + NotificationSts::SlotTypeEtsToC(env, type, slotType); + bool isEnable = false; + Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); + return isEnable ? ANI_TRUE : ANI_FALSE; +} + +static void CancelWithId(ani_env* env, ani_int id) +{ + ANS_LOGD("Cancel by ID callback id:%{public}d", id); + int32_t ret = Notification::NotificationHelper::CancelNotification(id); + if (ret != ERR_OK) { + ANS_LOGE("Cancel failed! Error:%{public}d", ret); + } +} + +static void CancelWithIdLabel(ani_env* env, ani_int id, ani_string label) +{ + std::string labelStr; + if (!AniCommom::GetStdString(env, label, labelStr)) { + ANS_LOGE("Label parse failed!"); + return; + } + + ANS_LOGD("Cancel by label id:%{public}d label:%{public}s", id, labelStr.c_str()); + int32_t ret = Notification::NotificationHelper::CancelNotification(labelStr, id); + if (ret != ERR_OK) { + ANS_LOGE("Cancel failed! Error:%{public}d", ret); + } +} + +static void CancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id) +{ + Notification::NotificationBundleOption option; + if (!NotificationSts::UnwrapBundleOption(env, bundleObj, option)) { + ANS_LOGE("Invalid BundleOption!"); + return; + } + + ANS_LOGD("Cancel by bundle:%{public}s id:%{public}d", + option.GetBundleName().c_str(), id); + int32_t ret = Notification::NotificationHelper::CancelAsBundle(option, id); + if (ret != ERR_OK) { + ANS_LOGE("Cancel failed! Error:%{public}d", ret); + } +} + +static void CancelAll(ani_env* env) +{ + ANS_LOGD("Cancel all notifications"); + int32_t ret = Notification::NotificationHelper::CancelAllNotifications(); + if (ret != ERR_OK) { + ANS_LOGE("CancelAll failed! Error:%{public}d", ret); + } +} + +void StsNotificationManagerRegistryInit(ani_env *env) +{ + ANS_LOGD("StsNotificationManagerRegistryInit call"); + ani_status status = ANI_ERROR; + if (env->ResetError() != ANI_OK) { + ANS_LOGD("ResetError failed"); + } + + ani_namespace ns; + status = env->FindNamespace("L@ohos/notificationManager/notificationManager;", &ns); + if (status != ANI_OK) { + ANS_LOGD("FindNamespace notificationManager failed status : %{public}d", status); + return; + } + + std::array kitFunctions = { + ani_native_function {"nativeDisplayBadge", nullptr, reinterpret_cast(DisplayBadge)}, + ani_native_function {"nativeIsBadgeDisplayed", nullptr, reinterpret_cast(IsBadgeDisplayed)}, + ani_native_function {"nativeGetActiveNotificationCount", ":D", + reinterpret_cast(GetActiveNotificationCount)}, + ani_native_function {"nativeIsNotificationEnabled", nullptr, reinterpret_cast(isNotificationEnabled)}, + ani_native_function {"nativegetSlotFlagsByBundle", nullptr, reinterpret_cast(getSlotFlagsByBundle)}, + ani_native_function {"nativesetSlotFlagsByBundle", nullptr, reinterpret_cast(setSlotFlagsByBundle)}, + ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(SetNotificationEnable)}, + ani_native_function {"nativeisNotificationSlotEnabled", nullptr, + reinterpret_cast(IsNotificationSlotEnabled)}, + ani_native_function {"nativeCancelWithId", nullptr, reinterpret_cast(CancelWithId)}, + ani_native_function {"nativeCancelWithIdLabel", nullptr, reinterpret_cast(CancelWithIdLabel)}, + ani_native_function {"nativeCancelWithBundle", nullptr, reinterpret_cast(CancelWithBundle)}, + ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(CancelAll)}, + + }; + + status = env->Namespace_BindNativeFunctions(ns, kitFunctions.data(), kitFunctions.size()); + if (status != ANI_OK) { + ANS_LOGD("Namespace_BindNativeFunctions failed status : %{public}d", status); + } + + if (env->ResetError() != ANI_OK) { + ANS_LOGD("ResetError failed"); + } + + ANS_LOGD("StsNotificationManagerRegistryInit end"); +} + +} +} + + +extern "C" { +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + ANS_LOGD("ANI_Constructor"); + ani_env *env = nullptr; + ani_status status = ANI_ERROR; + status = vm->GetEnv(ANI_VERSION_1, &env); + if (status != ANI_OK) { + ANS_LOGD("GetEnv failed status : %{public}d", status); + return ANI_NOT_FOUND; + } + + OHOS::NotificationManagerSts::StsNotificationManagerRegistryInit(env); + *result = ANI_VERSION_1; + ANS_LOGD("ANI_Constructor finish"); + return ANI_OK; +} +} \ No newline at end of file -- Gitee From b981f2a03f42b7ea4e296fbe69bc1e426df9fa88 Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Tue, 6 May 2025 14:29:16 +0800 Subject: [PATCH 2/9] =?UTF-8?q?feat:=20notificationmanager=20ani=E5=8C=96?= =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- frameworks/ani/notification_manager/BUILD.gn | 28 +- .../ets/@ohos.notificationManager.ets | 135 ++++ .../notification/notificationActionButton.ets | 28 + .../ets/notification/notificationContent.ets | 181 +++++ .../ets/notification/notificationFlags.ets | 41 ++ .../ets/notification/notificationRequest.ets | 98 +++ .../ets/notification/notificationTemplate.ets | 19 + .../notification/notificationUserInput.ets | 18 + .../include/sts_bundle_option.h | 1 + .../include/sts_common_util.h | 101 +-- .../include/sts_do_not_disturb_profile.h | 32 + .../include/sts_notification_action_button.h | 45 ++ .../include/sts_notification_enum_type.h | 156 +++++ ...slot_type.h => sts_notification_request.h} | 32 +- .../include/sts_notification_slot.h | 30 + .../include/sts_notification_utils.h | 96 +++ .../src/sts_bundle_option.cpp | 35 +- .../src/sts_common_util.cpp | 385 +++++++++- .../src/sts_do_not_disturb_profile.cpp | 101 +++ .../src/sts_notification_action_button.cpp | 86 +++ .../src/sts_notification_content.cpp | 559 +++++++++++++++ ...ype.cpp => sts_notification_enum_type.cpp} | 170 ++++- .../src/sts_notification_flags.cpp | 54 ++ .../src/sts_notification_manager.cpp | 95 ++- .../src/sts_notification_request.cpp | 661 ++++++++++++++++++ .../src/sts_notification_slot.cpp | 119 ++++ .../sts_notification_template.cpp} | 63 +- .../src/sts_notification_user_input.cpp | 32 + .../src/sts_notification_utils.cpp | 87 +++ 29 files changed, 3353 insertions(+), 135 deletions(-) create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationContent.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationFlags.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationRequest.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets create mode 100644 frameworks/ani/notification_manager/include/sts_do_not_disturb_profile.h create mode 100644 frameworks/ani/notification_manager/include/sts_notification_action_button.h create mode 100644 frameworks/ani/notification_manager/include/sts_notification_enum_type.h rename frameworks/ani/notification_manager/include/{sts_enum_slot_type.h => sts_notification_request.h} (46%) create mode 100644 frameworks/ani/notification_manager/include/sts_notification_slot.h create mode 100644 frameworks/ani/notification_manager/include/sts_notification_utils.h create mode 100644 frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_action_button.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_content.cpp rename frameworks/ani/notification_manager/src/{sts_enum_slot_type.cpp => sts_notification_enum_type.cpp} (34%) create mode 100644 frameworks/ani/notification_manager/src/sts_notification_flags.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_request.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_slot.cpp rename frameworks/ani/notification_manager/{ets/@ohos.base.ets => src/sts_notification_template.cpp} (34%) create mode 100644 frameworks/ani/notification_manager/src/sts_notification_user_input.cpp create mode 100644 frameworks/ani/notification_manager/src/sts_notification_utils.cpp diff --git a/frameworks/ani/notification_manager/BUILD.gn b/frameworks/ani/notification_manager/BUILD.gn index d88ba8fe7..2956dc5bd 100644 --- a/frameworks/ani/notification_manager/BUILD.gn +++ b/frameworks/ani/notification_manager/BUILD.gn @@ -28,13 +28,23 @@ ohos_shared_library("notification_manager_ani_kit") { "./include", "${core_path}/common/include", "${inner_api_path}", + "${frameworks_path}/cj/ffi/include", ] sources = [ "./src/sts_notification_manager.cpp", "./src/sts_common_util.cpp", "./src/sts_bundle_option.cpp", - "./src/sts_enum_slot_type.cpp", + "./src/sts_notification_enum_type.cpp", + "./src/sts_notification_slot.cpp", + "./src/sts_do_not_disturb_profile.cpp", + "./src/sts_notification_utils.cpp", + "./src/sts_notification_flags.cpp", + "./src/sts_notification_template.cpp", + "./src/sts_notification_user_input.cpp", + "./src/sts_notification_action_button.cpp", + "./src/sts_notification_content.cpp", + "./src/sts_notification_request.cpp", ] cflags = [] @@ -44,6 +54,7 @@ ohos_shared_library("notification_manager_ani_kit") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_path}/cj/ffi:cj_notification_manager_ffi", ] external_deps = [ @@ -52,6 +63,14 @@ ohos_shared_library("notification_manager_ani_kit") { "runtime_core:ani", "ipc:ipc_core", "ability_base:zuri", + "ability_runtime:ani_common", + "ability_runtime:aniwantagent", + "ability_runtime:wantagent_innerkits", + "ability_runtime:runtime", + "napi:ace_napi", + "image_framework:image_native", + "image_framework:image_ani", + "resource_management:global_resmgr", ] innerapi_tags = [ "platformsdk" ] @@ -64,7 +83,12 @@ generate_static_abc("notification_manager_abc") { files = [ "./ets/notification/NotificationCommonDef.ets", "./ets/@ohos.notificationManager.ets", - "./ets/@ohos.base.ets", + "./ets/notification/notificationContent.ets", + "./ets/notification/notificationFlags.ets", + "./ets/notification/notificationRequest.ets", + "./ets/notification/notificationTemplate.ets", + "./ets/notification/notificationUserInput.ets", + "./ets/notification/notificationActionButton.ets", ] dst_file = "$target_out_dir/notification_manager.abc" diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index e77aa75a8..9acc08017 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -18,7 +18,43 @@ import { BusinessError, AsyncCallback } from '@ohos.base'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; + +export interface NotificationSlot { + notificationType?: notificationManager.SlotType; + //level?: notification.SlotLevel; + desc?: string; + badgeFlag?: boolean; + bypassDnd?: boolean; + lockscreenVisibility?: number; + vibrationEnabled?: boolean; + sound?: string; + lightEnabled?: boolean; + lightColor?: number; + vibrationValues?: Array; + readonly enabled?: boolean; + readonly reminderMode?: number; + readonly authorizedStatus?: number; +} + +class NotificationSlotInner implements NotificationSlot { + notificationType?: notificationManager.SlotType; + //level?: notification.SlotLevel; + desc?: string; + badgeFlag?: boolean; + bypassDnd?: boolean; + lockscreenVisibility?: number; + vibrationEnabled?: boolean; + sound?: string; + lightEnabled?: boolean; + lightColor?: number; + vibrationValues?: Array; + readonly enabled?: boolean; + readonly reminderMode?: number; + readonly authorizedStatus?: number; +} + export namespace notificationManager { + loadLibrary("notification_manager_ani_kit.z") export enum SlotType { UNKNOWN_TYPE = 0, SOCIAL_COMMUNICATION = 1, @@ -29,6 +65,19 @@ export namespace notificationManager { EMERGENCY_INFORMATION = 10, OTHER_TYPES = 0xFFFF } + + export interface DoNotDisturbProfile { + id: number; + name: string; + trustlist?: Array; + } + + class DoNotDisturbProfileInner implements DoNotDisturbProfile { + id: number = -1; + name: string = ""; + trustlist?: Array = new Array(); + } + export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; export native function nativeGetActiveNotificationCount(): number; @@ -41,6 +90,11 @@ export namespace notificationManager { export native function nativeCancelWithIdLabel(id: number, label: string): void; export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; export native function nativeCancelAll(): void; + export native function nativeGetSlotsByBundle(bundle: BundleOption): Array; + export native function nativeaddDoNotDisturbProfile(templates: Array): void; + export native function nativeremoveDoNotDisturbProfile(templates: Array): void; + export native function nativeSetNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): void; + export native function nativeSetNotificationEnableSlotByOld(bundle: BundleOption, type: SlotType, enable: boolean): void; export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); @@ -319,4 +373,85 @@ export namespace notificationManager { }, (error: Object): void => { }) } + + export function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void { + let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); + p.then((data: NullishType): void => { + let slots : Array = data as Array; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, slots); + }, (error: Object): void => { + console.log("getSlotsByBundle error", error) + }) + } + + export function getSlotsByBundle(bundle: BundleOption): Promise> { + let pPromise = new Promise>((resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); + p.then((data: NullishType): void => { + let slots : Array = data as Array; + resolve(slots); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function addDoNotDisturbProfile(templates: Array): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeaddDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function removeDoNotDisturbProfile(templates: Array): Promise { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeremoveDoNotDisturbProfile(templates); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void + { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotByOld(bundle, type, enable); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void + { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); + p.then((data: NullishType): void => { + let err: BusinessError = {code: 1, data: undefined}; + callback(err, undefined); + }, (error: Object): void => { + }) + } + + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise + { + let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { + let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); + p.then((data: NullishType): void => { + resolve(undefined); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } } diff --git a/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets b/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets new file mode 100644 index 000000000..857960052 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NotificationUserInput } from './notificationUserInput'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; + +export interface NotificationActionButton { + + title: string; + + wantAgent: WantAgent; + + extras?: Record; + + userInput?: NotificationUserInput; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets new file mode 100644 index 000000000..e0d67e5bc --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import image from '@ohos.multimedia.image'; +import { Resource } from 'global.resource'; +import type notificationManager from '@ohos.notificationManager'; + +type IconType = Resource | image.PixelMap; + + +export interface NotificationBasicContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; +} + +export interface NotificationLongTextContent extends NotificationBasicContent { + + longText: string; + + briefText: string; + + expandedTitle: string; +} + +export enum LiveViewStatus { + + LIVE_VIEW_CREATE = 0, + + LIVE_VIEW_INCREMENTAL_UPDATE = 1, + + LIVE_VIEW_END = 2, + + LIVE_VIEW_FULL_UPDATE = 3 +} + +export enum LiveViewTypes { + + LIVE_VIEW_ACTIVITY = 0, + + LIVE_VIEW_INSTANT = 1, + + LIVE_VIEW_LONG_TERM = 2 +} + +export interface NotificationLiveViewContent extends NotificationBasicContent { + + status: LiveViewStatus; + + version?: number; + + extraInfo?: Record; + + pictureInfo?: Record>; + + isLocalUpdateOnly?: boolean; +} + +export interface NotificationMultiLineContent extends NotificationBasicContent { + + briefText: string; + + longTitle: string; + + lines: Array; +} + +export interface NotificationPictureContent extends NotificationBasicContent { + + briefText: string; + + expandedTitle: string; + + picture: image.PixelMap; +} + +export interface NotificationSystemLiveViewContent extends NotificationBasicContent { + + typeCode: number; + + capsule?: NotificationCapsule; + + button?: NotificationButton; + + cardButtons?: Array; + + time?: NotificationTime; + + progress?: NotificationProgress; + + liveViewType?: LiveViewTypes; +} + +export interface NotificationCapsule { + + title?: string; + + icon?: image.PixelMap; + + backgroundColor?: string; + + content?: string; + + time?: number; + + capsuleButtons?: Array; +} + +export interface NotificationIconButton { + + name: string; + + iconResource: IconType; + + text?: string; + + hidePanel?: boolean; +} + +export interface NotificationButton { + + names?: Array; + + icons?: Array; + + iconsResource?: Array; +} + +export interface NotificationTime { + + initialTime?: number; + + isCountDown?: boolean; + + isPaused?: boolean; + + isInTitle?: boolean; +} + +export interface NotificationProgress { + + maxValue?: number; + + currentValue?: number; + + isPercentage?: boolean; +} + +export interface NotificationContent { + + notificationContentType?: notificationManager.ContentType; + + normal?: NotificationBasicContent; + + longText?: NotificationLongTextContent; + + multiLine?: NotificationMultiLineContent; + + picture?: NotificationPictureContent; + + systemLiveView?: NotificationSystemLiveViewContent; + + liveView?: NotificationLiveViewContent; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets b/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets new file mode 100644 index 000000000..e5404faed --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + export enum NotificationFlagStatus { + + TYPE_NONE = 0, + + TYPE_OPEN = 1, + + TYPE_CLOSE = 2 +} + +export interface NotificationFlags { + + readonly soundEnabled?: NotificationFlagStatus; + + readonly vibrationEnabled?: NotificationFlagStatus; + + readonly reminderFlags?: number; +} + +class NotificationFlagsInner implements NotificationFlags { + + soundEnabled?: NotificationFlagStatus | undefined; + + vibrationEnabled?: NotificationFlagStatus| undefined; + + reminderFlags?: number = -1; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets new file mode 100644 index 000000000..c928d8edb --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import image from '@ohos.multimedia.image'; +import type notificationManager from '@ohos.notificationManager'; +import type notificationSubscribe from '@ohos.notificationSubscribe'; +import { NotificationContent } from 'notification.notificationContent'; +import { NotificationActionButton } from 'notification.notificationActionButton'; +import { NotificationTemplate } from 'notification.notificationTemplate'; +import { NotificationFlags } from 'notification.notificationFlags'; +import { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BundleOption } from 'notification.NotificationCommonDef'; + +export interface NotificationRequest { + content: NotificationContent; + id?: number; + appMessageId?: string; + notificationSlotType?: notificationManager.SlotType; + isOngoing?: boolean; + isUnremovable?: boolean; + updateOnly?: boolean; + deliveryTime?: number; + tapDismissed?: boolean; + autoDeletedTime?: number; + wantAgent?: WantAgent; + extraInfo?: Record; + color?: number; + colorEnabled?: boolean; + isAlertOnce?: boolean; + isStopwatch?: boolean; + isCountDown?: boolean; + isFloatingIcon?: boolean; + label?: string; + badgeIconStyle?: number; + showDeliveryTime?: boolean; + actionButtons?: Array; + smallIcon?: image.PixelMap; + largeIcon?: image.PixelMap; + overlayIcon?: image.PixelMap; + groupName?: string; + readonly creatorBundleName?: string; + readonly creatorUid?: number; + readonly creatorPid?: number; + readonly creatorUserId?: number; + readonly creatorInstanceKey?: number; + sound?: string; + classification?: string; + readonly hashCode?: string; + isRemoveAllowed?: boolean; + readonly source?: number; + template?: NotificationTemplate; + distributedOption?: DistributedOptions; + readonly deviceId?: string; + readonly notificationFlags?: NotificationFlags; + removalWantAgent?: WantAgent; + badgeNumber?: number; + representativeBundle?: BundleOption; + readonly agentBundle?: BundleOption; + unifiedGroupInfo?: UnifiedGroupInfo; + notificationControlFlags?: number; + readonly appInstanceKey?: string; + forceDistributed?: boolean; + notDistributed?: boolean; +} +export interface DistributedOptions { + isDistributed?: boolean; + supportDisplayDevices?: Array; + supportOperateDevices?: Array; + readonly remindType?: number; +} +export interface NotificationFilter { + bundle: BundleOption; + notificationKey: notificationSubscribe.NotificationKey; + extraInfoKeys?: Array; +} +export interface NotificationCheckRequest { + contentType: notificationManager.ContentType; + slotType: notificationManager.SlotType; + extraInfoKeys: Array; +} +export interface UnifiedGroupInfo { + key?: string; + title?: string; + content?: string; + sceneName?: string; + extraInfo?: Record; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets b/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets new file mode 100644 index 000000000..1c0a07e43 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + export interface NotificationTemplate { + name: string; + data: Record; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets b/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets new file mode 100644 index 000000000..eef5e12cc --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface NotificationUserInput { + inputKey: string; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_bundle_option.h b/frameworks/ani/notification_manager/include/sts_bundle_option.h index 72cc23e34..c67cc05d3 100644 --- a/frameworks/ani/notification_manager/include/sts_bundle_option.h +++ b/frameworks/ani/notification_manager/include/sts_bundle_option.h @@ -22,6 +22,7 @@ namespace OHOS { namespace NotificationSts { bool UnwrapBundleOption(ani_env *env, ani_object param, Notification::NotificationBundleOption& option); + bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector& options); } } diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index 13f3da97e..72e3ef1c5 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -17,13 +17,37 @@ #define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_COMMON_UTIL_H #include "ani.h" #include "notification_bundle_option.h" +#include "notification_constant.h" #include #include namespace OHOS { -namespace AniCommom { +namespace NotificationSts { +static const char *NotificationSlotClassName = "L@ohos/notificationManager/NotificationSlotInner;"; -bool GetStdString(ani_env *env, ani_string str, std::string &res); +ani_status GetStdString(ani_env *env, ani_string str, std::string &res); +ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_ref &ref, ani_boolean &isUndefined); +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, std::string &outStr); +ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, std::vector &res); +ani_status GetPropertyBooleanOrUndefined(ani_env *env, ani_object aniObj, const char *name, + ani_boolean isUndefined, bool outvalue); +ani_status GetPropertyDoubleOrUndefined(ani_env *env, ani_object obj, const char *name, + ani_boolean isUndefined, ani_double outvalue); +bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj); + +bool SetFieldString(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, const std::string &value); +bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, bool value); +bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, double value); +bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const std::vector &values); +bool SetOptionalFieldSlotType(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const Notification::NotificationConstant::SlotType& value); + + +ani_object newArrayClass(ani_env *env, int length); + +ani_object createBoolean(ani_env *env, ani_boolean value); +ani_object createDouble(ani_env *env, ani_double value); inline bool AniBooleanToBool(ani_boolean value) { @@ -35,68 +59,17 @@ inline ani_boolean BoolToAniBoolean(bool value) return value ? ANI_TRUE : ANI_FALSE; } -template -static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &result) -{ - ani_status status = ANI_ERROR; - if constexpr (std::is_enum::value || std::is_integral::value) { - ani_int intValue{}; - status = env->EnumItem_GetValue_Int(enumItem, &intValue); - if (ANI_OK != status) { - ANS_LOGD("EnumConvert_StsToNative failed, status : %{public}d", status); - return false; - } - result = static_cast(intValue); - return true; - } else if constexpr (std::is_same::value) { - ani_string strValue{}; - status = env->EnumItem_GetValue_String(enumItem, &strValue); - if (ANI_OK != status) { - ANS_LOGD("EnumItem_GetValue_String failed, status : %{public}d", status); - return false; - } - return GetStdString(env, strValue, result); - } else { - ANS_LOGD("Enum convert failed: type not supported"); - return false; - } -} - -template -static bool EnumConvertAniToNative(ani_env *env, ani_object enumItem, T &result) -{ - return EnumConvertAniToNative(env, static_cast(enumItem), result); -} - -template -static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T enumValue, ani_enum_item &result) -{ - ani_enum aniEnum{}; - ani_status status = env->FindEnum(enumName, &aniEnum); - if (ANI_OK != status) { - ANS_LOGD("Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); - return false; - } - constexpr int32_t loopMaxNum = 1000; - for (int32_t index = 0U; index < loopMaxNum; index++) { - ani_enum_item enumItem{}; - status = env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem); - if (ANI_OK != status) { - ANS_LOGD("Enum convert Enum_GetEnumItemByIndex failed: enumName:%{public}s index:%{public}d,\ - status:%{public}d", enumName, index, status); - return false; - } - // compare value - T tmpValue{}; - if (EnumConvertAniToNative(env, enumItem, tmpValue) && tmpValue == enumValue) { - result = enumItem; - return true; - } - } - ANS_LOGD("EnumConvert_NativeToSts failed enumName: %{public}s", enumName); - return false; -} +#define ANI_FAILED_AND_RETURN(status) \ +do \ +{ \ + ani_status const local_status = (status); \ + if (ani_status::ANI_OK != local_status) \ + { \ + ANS_LOGE("check status error: %{public}d", (int)local_status); \ + return false; \ + } \ +} while (0) -} // namespace AniCommom +} // namespace NotificationSts } // namespace OHOS #endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_do_not_disturb_profile.h b/frameworks/ani/notification_manager/include/sts_do_not_disturb_profile.h new file mode 100644 index 000000000..d172231f6 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_do_not_disturb_profile.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DO_NOT_DISTURB_PROFILE_H + #define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DO_NOT_DISTURB_PROFILE_H + + #include "ani.h" + #include "notification_do_not_disturb_profile.h" + + namespace OHOS { + namespace NotificationSts { + using namespace OHOS::Notification; + + bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, sptr &profile); + [[maybe_unused]]bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, + std::vector> &profiles); + } + } + + #endif // OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_DO_NOT_DISTURB_PROFILE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_action_button.h b/frameworks/ani/notification_manager/include/sts_notification_action_button.h new file mode 100644 index 000000000..46f78387e --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_notification_action_button.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_ACTION_BUTTON_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_ACTION_BUTTON_H +#include "pixel_map.h" +#include "want_params.h" +#include "want_agent.h" +#include "notification_constant.h" +#include "notification_user_input.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using SemanticActionButton = OHOS::Notification::NotificationConstant::SemanticActionButton; +using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; +using NotificationUserInput = OHOS::Notification::NotificationUserInput; + +struct StsActionButton { + std::shared_ptr icon; + std::string title; + std::shared_ptr wantAgent; + std::shared_ptr extras = {}; + SemanticActionButton semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + bool autoCreatedReplies = true; + std::vector> mimeTypeOnlyInputs = {}; + std::shared_ptr userInput = {}; + bool isContextual = false; +}; +} +} +#endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_enum_type.h b/frameworks/ani/notification_manager/include/sts_notification_enum_type.h new file mode 100644 index 000000000..abe137581 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_notification_enum_type.h @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H +#include "sts_common_util.h" +#include "notification_constant.h" +#include "notification_local_live_view_content.h" +#include "notification_live_view_content.h" +#include "notification_content.h" + +using SlotType = OHOS::Notification::NotificationConstant::SlotType; +using LiveViewTypes = OHOS::Notification::NotificationLocalLiveViewContent::LiveViewTypes; +using LiveViewStatus = OHOS::Notification::NotificationLiveViewContent::LiveViewStatus; +using ContentType = OHOS::Notification::NotificationContent::Type; +namespace OHOS { +namespace NotificationSts { +enum STSSlotType { + UNKNOWN_TYPE = 0, + SOCIAL_COMMUNICATION = 1, + SERVICE_INFORMATION = 2, + CONTENT_INFORMATION = 3, + LIVE_VIEW = 4, + CUSTOMER_SERVICE = 5, + EMERGENCY_INFORMATION = 10, + OTHER_TYPES = 0xFFFF, +}; + +enum STSLiveViewStatus { + LIVE_VIEW_CREATE = 0, + LIVE_VIEW_INCREMENTAL_UPDATE = 1, + LIVE_VIEW_END = 2, + LIVE_VIEW_FULL_UPDATE = 3 +}; + +enum STSContentType { + NOTIFICATION_CONTENT_BASIC_TEXT, + NOTIFICATION_CONTENT_LONG_TEXT, + NOTIFICATION_CONTENT_PICTURE, + NOTIFICATION_CONTENT_CONVERSATION, + NOTIFICATION_CONTENT_MULTILINE, + NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW, + NOTIFICATION_CONTENT_LIVE_VIEW, +}; + +class StsSlotTypeUtils { +public: +static bool StsToC(const STSSlotType inType, SlotType &outType); +static bool CToSts(const SlotType inType, STSSlotType &outType); +}; + +class StsLiveViewStatusUtils { +public: +static bool StsToC(const STSLiveViewStatus inType, LiveViewStatus &outType); +static bool CToSts(const LiveViewStatus inType, STSLiveViewStatus &outType); +}; + +class StsContentTypeUtils { +public: +static bool StsToC(const STSContentType inType, ContentType &outType); +static bool CToSts(const ContentType inType, STSContentType &outType); +}; + +bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType); +bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem); + +bool LiveViewTypesEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewTypes &liveViewTypes); +bool LiveViewTypesCToEts(ani_env *env, LiveViewTypes liveViewTypes, ani_enum_item &enumItem); + +bool LiveViewStatusEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewStatus &liveViewStatus); +bool LiveViewStatusCToEts(ani_env *env, LiveViewStatus liveViewStatus, ani_enum_item &enumItem); + +bool ContentTypeEtsToC(ani_env *env, ani_enum_item enumItem, ContentType &contentType); +bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enumItem); + +template +static bool EnumConvertAniToNative(ani_env *env, ani_enum_item enumItem, T &result) +{ + ani_status status = ANI_ERROR; + if constexpr (std::is_enum::value || std::is_integral::value) { + ani_int intValue{}; + status = env->EnumItem_GetValue_Int(enumItem, &intValue); + if (ANI_OK != status) { + ANS_LOGD("EnumConvert_StsToNative failed, status : %{public}d", status); + return false; + } + result = static_cast(intValue); + return true; + } else if constexpr (std::is_same::value) { + ani_string strValue{}; + status = env->EnumItem_GetValue_String(enumItem, &strValue); + if (ANI_OK != status) { + ANS_LOGD("EnumItem_GetValue_String failed, status : %{public}d", status); + return false; + } + status = GetStdString(env, strValue, result); + if (ANI_OK != status) { + ANS_LOGD("EnumConvertAniToNative GetStdString failed, status : %{public}d", status); + return false; + } + } else { + ANS_LOGD("Enum convert failed: type not supported"); + return false; + } +} + +template +static bool EnumConvertAniToNative(ani_env *env, ani_object enumItem, T &result) +{ + return EnumConvertAniToNative(env, static_cast(enumItem), result); +} + +template +static bool EnumConvertNativeToAni(ani_env *env, const char *enumName, const T enumValue, ani_enum_item &result) +{ + ani_enum aniEnum{}; + ani_status status = env->FindEnum(enumName, &aniEnum); + if (ANI_OK != status) { + ANS_LOGD("Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); + return false; + } + constexpr int32_t loopMaxNum = 1000; + for (int32_t index = 0U; index < loopMaxNum; index++) { + ani_enum_item enumItem{}; + status = env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem); + if (ANI_OK != status) { + ANS_LOGD( + "Enum_GetEnumItemByIndex failed: enumName:%{public}s index:%{public}d, status:%{public}d", + enumName, index, status); + return false; + } + // compare value + T tmpValue{}; + if (EnumConvertAniToNative(env, enumItem, tmpValue) && tmpValue == enumValue) { + result = enumItem; + return true; + } + } + ANS_LOGD("EnumConvert_NativeToSts failed enumName: %{public}s", enumName); + return false; +} +} +} +#endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_enum_slot_type.h b/frameworks/ani/notification_manager/include/sts_notification_request.h similarity index 46% rename from frameworks/ani/notification_manager/include/sts_enum_slot_type.h rename to frameworks/ani/notification_manager/include/sts_notification_request.h index 91a8aa4f9..7148054bb 100644 --- a/frameworks/ani/notification_manager/include/sts_enum_slot_type.h +++ b/frameworks/ani/notification_manager/include/sts_notification_request.h @@ -13,33 +13,21 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H -#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H -#include "sts_common_util.h" -#include "notification_constant.h" +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_REQUEST_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_REQUEST_H +#include "ani.h" + -using SlotType = OHOS::Notification::NotificationConstant::SlotType; namespace OHOS { namespace NotificationSts { -enum STSSlotType { - UNKNOWN_TYPE = 0, - SOCIAL_COMMUNICATION = 1, - SERVICE_INFORMATION = 2, - CONTENT_INFORMATION = 3, - LIVE_VIEW = 4, - CUSTOMER_SERVICE = 5, - EMERGENCY_INFORMATION = 10, - OTHER_TYPES = 0xFFFF, -}; - -class StsSlotTypeUtils { -public: -static bool StsToC(const STSSlotType inType, SlotType &outType); -static bool CToSts(const SlotType inType, STSSlotType &outType); +struct StsDistributedOptions { + bool isDistributed = false; + std::vector supportDisplayDevices = {}; + std::vector supportOperateDevices = {}; + int32_t remindType = -1; }; -bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType); -[[maybe_unused]]bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem); +void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions); } } #endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_slot.h b/frameworks/ani/notification_manager/include/sts_notification_slot.h new file mode 100644 index 000000000..f5c454836 --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_notification_slot.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_SLOT_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_SLOT_H + +#include "ani.h" +#include "notification_slot.h" + +namespace OHOS { +namespace NotificationSts { + bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj); + + bool WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, ani_object &outAniObj); +} +} + +#endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_utils.h b/frameworks/ani/notification_manager/include/sts_notification_utils.h new file mode 100644 index 000000000..b41a3ca3c --- /dev/null +++ b/frameworks/ani/notification_manager/include/sts_notification_utils.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H +#define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H + +#include "ani.h" +#include "notification_action_button.h" +#include "notification_bundle_option.h" +#include "notification_constant.h" +#include "notification_flags.h" +#include "notification_template.h" +#include "notification_user_input.h" +#include "notification_action_button.h" +#include "notification_basic_content.h" +#include "notification_normal_content.h" +#include "notification_long_text_content.h" +#include "notification_multiline_content.h" +#include "notification_picture_content.h" +#include "notification_live_view_content.h" +#include "notification_progress.h" +#include "notification_time.h" +#include "notification_icon_button.h" +#include "notification_local_live_view_button.h" +#include "notification_capsule.h" +#include "notification_local_live_view_content.h" +#include "notification_content.h" +#include "notification_request.h" +#include "notification_unified_group_Info.h" +#include "sts_notification_action_button.h" + +#include "pixel_map.h" + +namespace OHOS { +using namespace Global::Resource; +namespace NotificationSts { +using namespace OHOS::Notification; +using namespace OHOS::Media; + +void UnwrapWantAgent(ani_env *env, ani_object agent, void** result); +std::shared_ptr GetPixelMapFromEnvSp([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object obj); +ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource); + +ani_status UnwrapNotificationTemplate(ani_env *env, + ani_object aniObj, Notification::NotificationTemplate& tmplate); +void UnwrapNotificationFlags(ani_env *env, ani_object aniObj, NotificationFlags& flags); +ani_status UnwrapBundleOption(ani_env *env, ani_object param, NotificationBundleOption& option); +ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, + std::shared_ptr &userInput); +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, StsActionButton &actionButton); +ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, + std::shared_ptr basicContent); +ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, + std::shared_ptr &normalContent); +ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, + std::shared_ptr &longTextContent); +ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, + std::shared_ptr &multiLineContent); +ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, + std::shared_ptr &pictureContent); +ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent); +void UnWarpNotificationProgress(ani_env *env, ani_object obj, + NotificationProgress ¬ificationProgress); +void UnWarpNotificationTime(ani_env *env, ani_object obj, + NotificationTime ¬ificationTime); +ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, + NotificationIconButton &iconButton); +void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, + NotificationLocalLiveViewButton &iconButton); +void UnWarpNotificationCapsule(ani_env *env, ani_object obj, + NotificationCapsule &iconButton); +ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent); +ani_status UnWarpNotificationContent(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationContent); +/* NotificationRequest */ +void UnWarpNotificationRequest(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest); +ani_status UnWarpNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, + std::shared_ptr &unifiedGroupInfo); +} +} +#endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp index 503bba6f6..b6bcb3f8e 100644 --- a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp +++ b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp @@ -17,7 +17,7 @@ #include "sts_common_util.h" #include "ans_log_wrapper.h" -using namespace OHOS::AniCommom; +using namespace OHOS::NotificationSts; namespace OHOS { namespace NotificationSts { @@ -32,7 +32,7 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification } std::string bundleName; - if (!GetStdString(env, reinterpret_cast(bundleNameRef), bundleName)) { + if (ANI_OK != (status = GetStdString(env, reinterpret_cast(bundleNameRef), bundleName))) { ANS_LOGD("WrapBundleOption GetStdString failed"); return false; } @@ -69,5 +69,36 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification return true; } + +bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector& options) +{ + ani_status status; + ani_double length; + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + + Notification::NotificationBundleOption option; + for (int i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + return false; + } + + if (!UnwrapBundleOption(env, reinterpret_cast(optionRef), option)) { + ANS_LOGD("Get oprion failed, index: %{public}d", i); + return false; + } + options.push_back(option); + ANS_LOGD("GetOptions index: %{public}d", i); + } + return true; +} + } } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_common_util.cpp b/frameworks/ani/notification_manager/src/sts_common_util.cpp index dc4ad565c..b87f92b73 100644 --- a/frameworks/ani/notification_manager/src/sts_common_util.cpp +++ b/frameworks/ani/notification_manager/src/sts_common_util.cpp @@ -16,26 +16,401 @@ #include "sts_common_util.h" #include "ans_log_wrapper.h" #include "securec.h" +#include "sts_notification_enum_type.h" namespace OHOS { -namespace AniCommom { +namespace NotificationSts { -bool GetStdString(ani_env *env, ani_string str, std::string &res) +constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; +constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; + +ani_status GetStdString(ani_env *env, ani_string str, std::string &res) { ani_size sz {}; ani_status status = ANI_ERROR; if ((status = env->String_GetUTF8Size(str, &sz)) != ANI_OK) { ANS_LOGD("status : %{public}d", status); - return false; + return status; } res.resize(sz + 1); if ((status = env->String_GetUTF8SubString(str, 0, sz, res.data(), res.size(), &sz)) != ANI_OK) { ANS_LOGD("status : %{public}d", status); - return false; + return status; } res.resize(sz); + return status; +} + +ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_ref &ref, ani_boolean &isUndefined) +{ + ani_status status = env->Object_GetPropertyByName_Ref(obj, name, &ref); + if (status != ANI_OK) { + ANS_LOGI("Failed to get property '%{public}s', status: %{public}d", name, status); + return status; + } + status = env->Reference_IsUndefined(ref, &isUndefined); + if (status != ANI_OK) { + ANS_LOGI("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + } + return status; +} + +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, std::string &outStr) +{ + ani_status status = ANI_ERROR; + ani_ref strRef; + if ((status =env->Object_GetPropertyByName_Ref(obj, name, &strRef)) != ANI_OK) { + ANS_LOGD("Object_GetField_Ref bundle fail, status: %{public}d", status); + return status; + } + std::string result = ""; + if ((status = GetStdString(env, reinterpret_cast(strRef), result)) != ANI_OK) { + ANS_LOGD("WrapBundleOption GetStdString failed"); + return status; + } + outStr = result; + return status; +} + +ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, std::vector &res) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + std::string str; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return status; + } + + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref stringEntryRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + str = ""; + status = GetStdString(env, reinterpret_cast(stringEntryRef), str); + if (status != ANI_OK) { + ANS_LOGI("GetStdString failed, index: %{public}d", i); + return status; + } + + res.push_back(str); + ANS_LOGI("GetStdString index: %{public}d %{public}s", i, str.c_str()); + } + return status; +} + +ani_status GetPropertyBooleanOrUndefined(ani_env *env, ani_object aniObj, const char *name, + ani_boolean isUndefined, bool outvalue) +{ + ani_ref refObj = nullptr; + ani_status status = ANI_ERROR; + ani_boolean res = ANI_FALSE; + if (((status = GetPropertyRef(env, aniObj, name, refObj, isUndefined)) != ANI_OK) && (isUndefined == ANI_TRUE)) { + ANS_LOGI("GetPropertyRef failed or %{public}s : undefined", name); + return ANI_INVALID_ARGS; + } + if ((status = env->Object_CallMethodByName_Boolean(reinterpret_cast(refObj), + "unboxed", ":Z", &res)) != ANI_OK) { + ANS_LOGI("Object_CallMethodByName_Boolean failed, status : %{public}d", status); + return status; + } + outvalue = (res == ANI_TRUE); + return status; +} + +ani_status GetPropertyDoubleOrUndefined(ani_env *env, ani_object obj, const char *name, + ani_boolean isUndefined, ani_double outvalue) +{ + ani_status status = ANI_ERROR; + ani_ref uidRef; + if ((status = env->Object_GetPropertyByName_Ref(obj, name, &uidRef)) != ANI_OK) { + ANS_LOGI("Object_GetPropertyByName_Ref uid fail, status: %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) == ANI_OK) { + ANS_LOGI("Object_GetPropertyByName_Ref status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s is undefined", name); + return ANI_INVALID_ARGS; + } + ani_double result = 0.0; + status = env->Object_CallMethodByName_Double(static_cast(uidRef), "doubleValue", nullptr, &result); + if (ANI_OK != status) { + ANS_LOGI("Object_CallMethodByName_Double uid fail, status: %{public}d", status); + return status; + } + outvalue = result; + return status; +} + +bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj) +{ + ANI_FAILED_AND_RETURN(env->FindClass(className, &cls)); + ani_method ctor; + ANI_FAILED_AND_RETURN(env->Class_FindMethod(cls, "", nullptr, &ctor)); + outAniObj = {}; + ANI_FAILED_AND_RETURN(env->Object_New(cls, ctor, &outAniObj)); + return true; +} + +bool SetFieldString(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, const std::string &value) +{ + ani_field field = nullptr; + ani_string string = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + + ANS_LOGD("SetFieldString fieldName : %{public}s", fieldName.c_str()); + + if (status != ANI_OK) { + ANS_LOGE("SetFieldString status : %{public}d", status); + return false; + } + + if (value.empty()) { + ani_ref nullRef = nullptr; + if ((status = env->GetNull(&nullRef)) != ANI_OK) { + ANS_LOGE("SetFieldString GetNull fail status : %{public}d", status); + return false; + } + if ((status = env->Object_SetField_Ref(object, field, nullRef)) != ANI_OK) { + ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + return false; + } + return true; + } + + if ((status = env->String_NewUTF8(value.c_str(), value.size(), &string)) != ANI_OK) { + ANS_LOGE("SetFieldString String_NewUTF8 fail status : %{public}d", status); + return false; + } + + if ((status = env->Object_SetField_Ref(object, field, string)) != ANI_OK) { + ANS_LOGE("SetFieldString Object_SetField_Ref fail status : %{public}d", status); + return false; + } + return true; +} + +ani_object newArrayClass(ani_env *env, int length) +{ + ANS_LOGD("newArrayClass call"); + ani_class arrayCls = nullptr; + if (ANI_OK != env->FindClass("Lescompat/Array;", &arrayCls)){ + ANS_LOGE("FindClass Lescompat/Array; Failed"); + return nullptr; + } + ani_method arrayCtor; + if(ANI_OK != env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor)){ + ANS_LOGE("Class_FindMethod Failed"); + return nullptr; + } + ani_object arrayObj = nullptr; + if(ANI_OK != env->Object_New(arrayCls, arrayCtor, &arrayObj, length)){ + ANS_LOGE("Object_New Array Faild"); + return arrayObj; + } + ANS_LOGD("newArrayClass end"); + return arrayObj; +} + +ani_object createBoolean(ani_env *env, ani_boolean value) +{ + ani_class persion_cls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_BOOLEAN, &persion_cls)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_method personInfoCtor; + if ((status = env->Class_FindMethod(persion_cls, "", "Z:V", &personInfoCtor)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_object personInfoObj; + if ((status = env->Object_New(persion_cls, personInfoCtor, &personInfoObj, value)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + return personInfoObj; +} + +ani_object createDouble(ani_env *env, ani_double value) +{ + ani_class persion_cls; + ani_status status = ANI_ERROR; + if ((status = env->FindClass(CLASSNAME_DOUBLE, &persion_cls)) != ANI_OK) { + ANS_LOGE( "status : %{public}d", status); + return nullptr; + } + ani_method personInfoCtor; + if ((status = env->Class_FindMethod(persion_cls, "", "D:V", &personInfoCtor)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_object personInfoObj; + if ((status = env->Object_New(persion_cls, personInfoCtor, &personInfoObj, value)) != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + return personInfoObj; +} + +bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, bool value) +{ + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_object intObj = createBoolean(env, BoolToAniBoolean(value)); + if (intObj == nullptr) { + ANS_LOGE("null intObj"); + return false; + } + status = env->Object_SetField_Ref(object, field, intObj); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, double value) +{ + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_object intObj = createDouble(env, value); + if (intObj == nullptr) { + ANS_LOGE("null intObj"); + return false; + } + status = env->Object_SetField_Ref(object, field, intObj); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } return true; } -} // namespace AppExecFwk +bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const std::vector &values) +{ + ani_field field = nullptr; + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + + status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, values.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + + for (size_t i = 0; i < values.size(); i++) { + ani_field field_1 = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field_1); + if (status != ANI_OK || field_1 == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_object intObj = createDouble(env, static_cast(values[i])); + if (intObj == nullptr) { + ANS_LOGE("null intObj"); + return false; + } + status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, intObj); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + } + status = env->Object_SetField_Ref(object, field, arrayObj); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return false; + } + + return true; +} + +bool SetOptionalFieldSlotType(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const Notification::NotificationConstant::SlotType& value) +{ + ani_field field = nullptr; + ani_status status = env->Class_FindField(cls, fieldName.c_str(), &field); + if (status != ANI_OK || field == nullptr) { + ANS_LOGE("Class_FindField failed or null field, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + ani_enum_item enumItem = nullptr; + NotificationSts::SlotTypeCToEts(env, value, enumItem); + if (enumItem == nullptr) + { + ANS_LOGE("null enumItem"); + return false; + } + + status = env->Object_SetField_Ref(object, field, enumItem); + if (status != ANI_OK) { + ANS_LOGE("Object_SetField_Ref failed, status=%{public}d, fieldName=%{public}s", + status, fieldName.c_str()); + return false; + } + return true; +} + +} } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp b/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp new file mode 100644 index 000000000..7986c6f53 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sts_do_not_disturb_profile.h" +#include "sts_bundle_option.h" +#include "sts_common_util.h" +#include "ans_log_wrapper.h" + +using namespace OHOS::NotificationSts; +namespace OHOS { +namespace NotificationSts { +bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, sptr &profile) +{ + ANS_LOGD("UnwrapDoNotDisturbProfile call"); + ani_long idRef; + ani_status status = env->Object_GetPropertyByName_Long(param, "id", &idRef); + if (ANI_OK != status) { + ANS_LOGD("WrapBundleOption Object_GetField_Ref bundle fail, status: %{public}d", status); + return false; + } + ani_ref nameRef; + status = env->Object_GetPropertyByName_Ref(param, "name", &nameRef); + if (ANI_OK != status) { + ANS_LOGD("WrapBundleOption Object_GetField_Ref bundle fail, status: %{public}d", status); + return false; + } + std::string name; + if (ANI_OK != (status = GetStdString(env, reinterpret_cast(nameRef), name))) { + ANS_LOGD("WrapBundleOption GetStdString failed"); + return false; + } + profile->SetProfileId(static_cast(idRef)); + profile->SetProfileName(name); + + ani_ref trustlistRef; + status = env->Object_GetPropertyByName_Ref(param, "trustlist", &trustlistRef); + if (ANI_OK != status) { + ANS_LOGD("UnwrapDoNotDisturbProfile Object_GetPropertyByName_Ref trustlist fail, status: %{public}d", status); + return true; + } + ani_boolean isUndefined = true; + if ((status = env->Reference_IsUndefined(trustlistRef, &isUndefined)) != ANI_OK) { + ANS_LOGD("UnwrapDoNotDisturbProfile Object_GetPropertyByName_Ref status : %{public}d", status); + return true; + } + if (isUndefined) { + ANS_LOGD("UnwrapDoNotDisturbProfile trustlist is undefined"); + return true; + } + std::vector trustlist = {}; + UnwrapArrayBundleOption(env, reinterpret_cast(trustlistRef), trustlist); + if (trustlist.size() > 0) { + profile->SetProfileTrustList(trustlist); + } + return true; +} + +bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, + std::vector> &profiles) +{ + ani_status status; + ani_double length; + + status = env->Object_GetPropertyByName_Double(arrayObj, "length", &length); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d", status); + return false; + } + + sptr profile; + for (int i = 0; i < static_cast(length); i++) { + ani_ref optionRef; + status = env->Object_CallMethodByName_Ref(arrayObj, "$_get", + "I:L@ohos/notificationManager/notificationManager/DoNotDisturbProfile;", &optionRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGD("status : %{public}d, index: %{public}d", status, i); + return false; + } + + if (!UnwrapDoNotDisturbProfile(env, reinterpret_cast(optionRef), profile)) { + ANS_LOGD("Get profile failed, index: %{public}d", i); + return false; + } + profiles.push_back(profile); + ANS_LOGD("GetProfiles index: %{public}d", i); + } + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp b/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp new file mode 100644 index 000000000..0ab4a0aa6 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sts_notification_utils.h" +#include "sts_notification_action_button.h" +#include "sts_common_util.h" +#include "ani_common_want.h" +#include "want_params.h" +#include "want_agent.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; + +ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, + StsActionButton &actionButton) +{ + ani_status status = ANI_ERROR; + std::string title; + if((status = GetPropertyString(env, param, "title", title)) != ANI_OK) { + return status; + } + ani_ref wantAgentRef; + if ((status = env->Object_GetPropertyByName_Ref(param, "wantAgent", &wantAgentRef)) != ANI_OK) { + return status; + } + WantAgent* pWantAgent = nullptr; + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + if (pWantAgent == nullptr) { + return ANI_INVALID_ARGS; + } + + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + + ani_ref extrasRef; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(param, "extras", &extrasRef))) { + return status; + } + ani_boolean isUndefind = ANI_TRUE; + WantParams wantParams = {}; + if ((status = env->Reference_IsUndefined(extrasRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + UnwrapWantParams(env, extrasRef, wantParams); + } + std::shared_ptr extras = std::make_shared(wantParams); + + std::shared_ptr userInput = nullptr; + ani_ref userInputRef; + if (ANI_OK == env->Object_GetPropertyByName_Ref(param, "userInput", &userInputRef)) + { + isUndefind = ANI_TRUE; + if (env->Reference_IsUndefined(userInputRef, &isUndefind) == ANI_OK && isUndefind == ANI_FALSE) + { + UnwrapNotificationUserInput(env, static_cast(userInputRef), userInput); + } + if (userInput == nullptr) + { + userInput = {}; + } + } + actionButton.icon = nullptr; + actionButton.title = title; + actionButton.wantAgent = wantAgent; + actionButton.extras = extras; + actionButton.semanticActionButton = SemanticActionButton::NONE_ACTION_BUTTON; + actionButton.autoCreatedReplies = true; + actionButton.mimeTypeOnlyInputs = {}; + actionButton.userInput = userInput; + actionButton.isContextual = false; + return status; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_content.cpp b/frameworks/ani/notification_manager/src/sts_notification_content.cpp new file mode 100644 index 000000000..020fea735 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_content.cpp @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sts_notification_utils.h" +#include "sts_common_util.h" +#include "ans_log_wrapper.h" +#include "pixel_map_ani.h" +#include "sts_notification_enum_type.h" +#include "ani_common_want.h" +#include "want_params.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using LiveViewStatus = OHOS::Notification::NotificationLiveViewContent::LiveViewStatus; + +void UnWarpNotificationProgress(ani_env *env, ani_object obj, + NotificationProgress ¬ificationProgress) +{ + ani_double maxValueAni = 0.0; + if(env->Object_GetPropertyByName_Double(obj, "maxValue", &maxValueAni) == ANI_OK) { + notificationProgress.SetMaxValue(static_cast(maxValueAni)); + } + ani_double currentValueAni = 0.0; + if(env->Object_GetPropertyByName_Double(obj, "currentValue", ¤tValueAni) == ANI_OK) { + notificationProgress.SetCurrentValue(static_cast(currentValueAni)); + } + + bool isPercentage = true; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isPercentage", isUndefined, isPercentage) + && isUndefined == ANI_FALSE) { + notificationProgress.SetIsPercentage(isPercentage); + } +} + +void UnWarpNotificationTime(ani_env *env, ani_object obj, + NotificationTime ¬ificationTime) +{ + ani_boolean isUndefined = ANI_TRUE; + ani_double initialTime = 0.0; + if (GetPropertyDoubleOrUndefined(env, obj, "version", isUndefined, initialTime) == ANI_OK + && isUndefined == ANI_FALSE) { + notificationTime.SetInitialTime(static_cast(initialTime)); + } + + bool isCountDown = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isCountDown", isUndefined, isCountDown) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsCountDown(isCountDown); + } + + bool isPaused = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isPaused", isUndefined, isPaused) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsPaused(isPaused); + } + + bool isInTitle = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isInTitle", isUndefined, isInTitle) + && isUndefined == ANI_FALSE) { + notificationTime.SetIsInTitle(isInTitle); + } +} + +ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, + NotificationIconButton &iconButton) +{ + ani_status status = ANI_ERROR; + std::string name = ""; + if((status = GetPropertyString(env, obj, "name", name)) != ANI_OK) { + return status; + } + iconButton.SetName(name); + + ani_ref iconRef = {}; + if ((status = env->Object_GetPropertyByName_Ref(obj, "iconResource", &iconRef)) != ANI_OK) { + return status; + } + + ResourceManager::Resource resource; + if(ANI_OK == UnwrapResource(env, static_cast(iconRef), resource)) { + iconButton.SetIconResource(std::make_shared(resource)); + } else { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap != nullptr) { + iconButton.SetIconImage(pixelMap); + } + } + + std::string text = ""; + if(GetPropertyString(env, obj, "text", text) == ANI_OK) { + iconButton.SetName(text); + } + + bool hidePanel = true; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "hidePanel", isUndefined, hidePanel) + && isUndefined == ANI_FALSE) { + iconButton.SetHidePanel(hidePanel); + } + + return status; +} + +ani_status GetIconButtonArrayOrUndefined(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return status; + } + + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref buttonRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + NotificationIconButton button; + if(UnWarpNotificationIconButton(env, static_cast(buttonRef), button) == ANI_OK) { + res.push_back(button); + } + } + return status; +} + +ani_status GetPixelMapArrayOrUndefined(ani_env *env, + ani_object param, const char *name, std::vector> &res) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return status; + } + + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref pixelMapRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &pixelMapRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pixelMapRef)); + if (pixelMap == nullptr) { + return ANI_INVALID_ARGS; + } + res.push_back(pixelMap); + } + return status; +} + +ani_status GetResourceArrayOrUndefined(ani_env *env, + ani_object param, const char *name, std::vector &res) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return status; + } + + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref iconRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &iconRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + + ResourceManager::Resource resource; + if(ANI_OK != UnwrapResource(env, static_cast(iconRef), resource)) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + res.push_back(resource); + } + return status; +} + +void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, + NotificationLocalLiveViewButton &button) +{ + std::vector names = {}; + if(GetStringArrayOrUndefined(env, obj, "names", names) == ANI_OK) { + for(auto name: names) { + button.addSingleButtonName(name); + } + } + + std::vector> icons = {}; + if(ANI_OK == GetPixelMapArrayOrUndefined(env, obj, "icons", icons)) { + for(auto icon: icons) { + button.addSingleButtonIcon(icon); + } + } + std::vector resources = {}; + if(ANI_OK == GetResourceArrayOrUndefined(env, obj, "iconsResource", resources)) { + for(auto res: resources) { + std::shared_ptr pRes = std::make_shared(res); + button.addSingleButtonIconResource(pRes); + } + } +} + +void UnWarpNotificationCapsule(ani_env *env, ani_object obj, + NotificationCapsule &capsule) +{ + std::string title = ""; + if(GetPropertyString(env, obj, "title", title) == ANI_OK) { + capsule.SetTitle(title); + } + + std::string backgroundColor = ""; + if(GetPropertyString(env, obj, "backgroundColor", backgroundColor) == ANI_OK) { + capsule.SetBackgroundColor(backgroundColor); + } + + std::string content = ""; + if(GetPropertyString(env, obj, "content", content) == ANI_OK) { + capsule.SetContent(content); + } + + ani_double time = 0.0; + if(env->Object_GetPropertyByName_Double(obj, "time", &time) == ANI_OK) { + capsule.SetTime(static_cast(time)); + } + + ani_ref iconRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "icon", &iconRef) == ANI_OK) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(iconRef)); + if (pixelMap != nullptr) { + capsule.SetIcon(pixelMap); + } + } + + std::vector iconButtons = {}; + + if (GetIconButtonArrayOrUndefined(env, obj, "capsuleButtons", iconButtons) == ANI_OK) { + capsule.SetCapsuleButton(iconButtons); + } +} + +ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, + std::shared_ptr basicContent) +{ + ANS_LOGI("UnWarpNotificationBasicContent call"); + ani_status status = ANI_ERROR; + std::string title; + if((status = GetPropertyString(env, obj, "title", title)) != ANI_OK) { + return status; + } + basicContent->SetTitle(title); + + std::string text; + if((status = GetPropertyString(env, obj, "text", text)) != ANI_OK) { + return status; + } + basicContent->SetText(text); + + std::string additionalText; + if(GetPropertyString(env, obj, "additionalText", additionalText) == ANI_OK) { + basicContent->SetAdditionalText(additionalText); + } + + ani_ref lockscreenPictureRef = {}; + if (env->Object_GetPropertyByName_Ref(obj, "lockscreenPicture", &lockscreenPictureRef)) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(lockscreenPictureRef)); + if (pixelMap != nullptr) { + basicContent->SetLockScreenPicture(pixelMap); + } + } + return status; +} + +ani_status UnWarpNotificationNormalContent(ani_env *env, ani_object obj, + std::shared_ptr &normalContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, normalContent)) != ANI_OK) { + return status; + } + return status; +} + +ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, + std::shared_ptr &longTextContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, longTextContent)) != ANI_OK) { + return status; + } + + std::string longText; + if((status = GetPropertyString(env, obj, "longText", longText)) != ANI_OK) { + return status; + } + longTextContent->SetLongText(longText); + + std::string briefText; + if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { + return status; + } + longTextContent->SetBriefText(briefText); + + std::string expandedTitle; + if((status = GetPropertyString(env, obj, "expandedTitle", expandedTitle)) != ANI_OK) { + return status; + } + longTextContent->SetExpandedTitle(expandedTitle); + + return status; +} + +ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, + std::shared_ptr &multiLineContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, multiLineContent)) != ANI_OK) { + return status; + } + + std::string longTitle; + if((status = GetPropertyString(env, obj, "longTitle", longTitle)) != ANI_OK) { + return status; + } + multiLineContent->SetExpandedTitle(longTitle); + + std::string briefText; + if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { + return status; + } + multiLineContent->SetBriefText(briefText); + + std::vector lines = {}; + if((status = GetStringArrayOrUndefined(env, obj, "lines", lines)) != ANI_OK) { + return status; + } + for(auto line : lines) { + multiLineContent->AddSingleLine(line); + } + return status; +} + +ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, + std::shared_ptr &pictureContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, pictureContent)) != ANI_OK) { + return status; + } + + std::string expandedTitle; + if((status = GetPropertyString(env, obj, "expandedTitle", expandedTitle)) != ANI_OK) { + return status; + } + pictureContent->SetExpandedTitle(expandedTitle); + + std::string briefText; + if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { + return status; + } + pictureContent->SetBriefText(briefText); + + ani_ref pictureRef = {}; + if ((status = env->Object_GetPropertyByName_Ref(obj, "picture", &pictureRef)) != ANI_OK) { + return status; + } + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(pictureRef)); + if (pixelMap == nullptr) { + return ANI_INVALID_ARGS; + } + pictureContent->SetBigPicture(pixelMap); + + return status; +} + +ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &liveViewContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, liveViewContent)) != ANI_OK) { + return status; + } + + ani_ref statusRef; + if((status = env->Object_GetPropertyByName_Ref(obj, "status", &statusRef)) != ANI_OK) { + return status; + } + LiveViewStatus liveViewStatus = LiveViewStatus::LIVE_VIEW_CREATE; + if(!EnumConvertAniToNative(env, static_cast(statusRef), liveViewStatus)) { + return ANI_INVALID_ARGS; + } + liveViewContent->SetLiveViewStatus(liveViewStatus); + + ani_double versionAni = 0.0; + ani_boolean isUndefined = ANI_TRUE; + if (GetPropertyDoubleOrUndefined(env, obj, "version", isUndefined, versionAni) == ANI_OK && isUndefined == ANI_FALSE) { + liveViewContent->SetVersion(static_cast(versionAni)); + } + + ani_ref extraInfoRef; + isUndefined = ANI_TRUE; + if (ANI_OK == (status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef)) + && env->Reference_IsUndefined(extraInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + WantParams wantParams = {}; + if(UnwrapWantParams(env, extraInfoRef, wantParams)) { + std::shared_ptr extraInfo = std::make_shared(wantParams); + liveViewContent->SetExtraInfo(extraInfo); + } + } + + //pictureInfo?: Record> + // need to add + + bool isLocalUpdateOnly = true; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isLocalUpdateOnly", isUndefined, isLocalUpdateOnly) + && isUndefined == ANI_FALSE) { + liveViewContent->SetIsOnlyLocalUpdate(isLocalUpdateOnly); + } + return status; +} + +ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, + std::shared_ptr &localLiveViewContent) +{ + ani_status status =ANI_ERROR; + if((status = UnWarpNotificationBasicContent(env, obj, localLiveViewContent)) != ANI_OK) { + return status; + } + + ani_double typeCode = 0.0; + if((status = env->Object_GetPropertyByName_Double(obj, "typeCode", &typeCode)) != ANI_OK) { + return status; + } + localLiveViewContent->SetType(static_cast(typeCode)); + + ani_ref capsuleRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "capsule", &capsuleRef) == ANI_OK) { + NotificationCapsule capsule; + UnWarpNotificationCapsule(env, static_cast(capsuleRef), capsule); + localLiveViewContent->SetCapsule(capsule); + } + + ani_ref buttonRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "button", &buttonRef) == ANI_OK) { + NotificationLocalLiveViewButton button; + UnWarpNotificationLocalLiveViewButton(env, static_cast(buttonRef), button); + localLiveViewContent->SetButton(button); + } + + std::vector buttons = {}; + if(GetIconButtonArrayOrUndefined(env, obj, "cardButtons", buttons) == ANI_OK) { + localLiveViewContent->SetCardButton(buttons); + } + + ani_ref timeRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "time", &timeRef) == ANI_OK) { + NotificationTime notificationTime; + UnWarpNotificationTime(env, static_cast(timeRef), notificationTime); + localLiveViewContent->SetTime(notificationTime); + } + + ani_ref progressRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "progress", &progressRef) == ANI_OK) { + NotificationProgress notificationProgress; + UnWarpNotificationProgress(env, static_cast(progressRef), notificationProgress); + localLiveViewContent->SetProgress(notificationProgress); + } + + ani_ref liveViewTypeRef = {}; + if(env->Object_GetPropertyByName_Ref(obj, "liveViewType", &liveViewTypeRef) == ANI_OK) { + LiveViewTypes liveViewTypes = LiveViewTypes::LIVE_VIEW_ACTIVITY; + if(LiveViewTypesEtsToC(env, static_cast(liveViewTypeRef), liveViewTypes)) { + localLiveViewContent->SetLiveViewType(liveViewTypes); + } + } + + return status; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp b/frameworks/ani/notification_manager/src/sts_notification_enum_type.cpp similarity index 34% rename from frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp rename to frameworks/ani/notification_manager/src/sts_notification_enum_type.cpp index 0b02741ec..fb68d2bd7 100644 --- a/frameworks/ani/notification_manager/src/sts_enum_slot_type.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_enum_type.cpp @@ -12,7 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "sts_enum_slot_type.h" +#include "sts_notification_enum_type.h" + +#include "sts_notification_utils.h" namespace OHOS { namespace NotificationSts { bool StsSlotTypeUtils::StsToC(const STSSlotType inType, SlotType &outType) @@ -81,10 +83,54 @@ bool StsSlotTypeUtils::CToSts(const SlotType inType, STSSlotType &outType) return true; } +bool StsLiveViewStatusUtils::StsToC(const STSLiveViewStatus inType, LiveViewStatus &outType) +{ + switch (inType) { + case STSLiveViewStatus::LIVE_VIEW_CREATE: + outType = LiveViewStatus::LIVE_VIEW_CREATE; + break; + case STSLiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE: + outType = LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; + break; + case STSLiveViewStatus::LIVE_VIEW_END: + outType = LiveViewStatus::LIVE_VIEW_END; + break; + case STSLiveViewStatus::LIVE_VIEW_FULL_UPDATE: + outType = LiveViewStatus::LIVE_VIEW_FULL_UPDATE; + break; + default: + ANS_LOGE("LiveViewStatus %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsLiveViewStatusUtils::CToSts(const LiveViewStatus inType, STSLiveViewStatus &outType) +{ + switch (inType) { + case LiveViewStatus::LIVE_VIEW_CREATE: + outType = STSLiveViewStatus::LIVE_VIEW_CREATE; + break; + case LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE: + outType = STSLiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; + break; + case LiveViewStatus::LIVE_VIEW_END: + outType = STSLiveViewStatus::LIVE_VIEW_END; + break; + case LiveViewStatus::LIVE_VIEW_FULL_UPDATE: + outType = STSLiveViewStatus::LIVE_VIEW_FULL_UPDATE; + break; + default: + ANS_LOGE("LiveViewStatus %{public}d is an invalid value", inType); + return false; + } + return true; +} + bool SlotTypeEtsToC(ani_env *env, ani_enum_item enumItem, SlotType &slotType) { STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; - AniCommom::EnumConvertAniToNative(env, enumItem, stsSlotType); + EnumConvertAniToNative(env, enumItem, stsSlotType); StsSlotTypeUtils::StsToC(stsSlotType, slotType); return true; } @@ -93,9 +139,125 @@ bool SlotTypeCToEts(ani_env *env, SlotType slotType, ani_enum_item &enumItem) { STSSlotType stsSlotType = STSSlotType::UNKNOWN_TYPE; StsSlotTypeUtils::CToSts(slotType, stsSlotType); - AniCommom::EnumConvertNativeToAni(env, - "L@ohos/notificationManager/notificationManager/#SlotType", stsSlotType, enumItem); + EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/SlotType;", stsSlotType, enumItem); + return true; +} + + +bool StsContentTypeUtils::StsToC(const STSContentType inType, ContentType &outType) +{ + switch (inType) { + case STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT: + outType = ContentType::BASIC_TEXT; + break; + case STSContentType::NOTIFICATION_CONTENT_LONG_TEXT: + outType = ContentType::LONG_TEXT; + break; + case STSContentType::NOTIFICATION_CONTENT_MULTILINE: + outType = ContentType::MULTILINE; + break; + case STSContentType::NOTIFICATION_CONTENT_PICTURE: + outType = ContentType::PICTURE; + break; + case STSContentType::NOTIFICATION_CONTENT_CONVERSATION: + outType = ContentType::CONVERSATION; + break; + case STSContentType::NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW: + outType = ContentType::LOCAL_LIVE_VIEW; + break; + case STSContentType::NOTIFICATION_CONTENT_LIVE_VIEW: + outType = ContentType::LIVE_VIEW; + break; + default: + ANS_LOGE("ContentType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool StsContentTypeUtils::CToSts(const ContentType inType, STSContentType &outType) +{ + switch (inType) { + case ContentType::BASIC_TEXT: + outType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + break; + case ContentType::LONG_TEXT: + outType = STSContentType::NOTIFICATION_CONTENT_LONG_TEXT; + break; + case ContentType::MULTILINE: + outType = STSContentType::NOTIFICATION_CONTENT_MULTILINE; + break; + case ContentType::PICTURE: + outType = STSContentType::NOTIFICATION_CONTENT_PICTURE; + break; + case ContentType::CONVERSATION: + outType = STSContentType::NOTIFICATION_CONTENT_CONVERSATION; + break; + case ContentType::LOCAL_LIVE_VIEW: + outType = STSContentType::NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW; + break; + case ContentType::LIVE_VIEW: + outType = STSContentType::NOTIFICATION_CONTENT_LIVE_VIEW; + break; + default: + ANS_LOGE("ContentType %{public}d is an invalid value", inType); + return false; + } return true; } + +bool LiveViewTypesEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewTypes &liveViewTypes) +{ + return EnumConvertAniToNative(env, enumItem, liveViewTypes); +} + +bool LiveViewTypesCToEts(ani_env *env, LiveViewTypes liveViewTypes, ani_enum_item &enumItem) +{ + return EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewTypes", liveViewTypes, enumItem); +} + +bool LiveViewStatusEtsToC(ani_env *env, ani_enum_item enumItem, LiveViewStatus &liveViewStatus) +{ + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + if(EnumConvertAniToNative(env, enumItem, stsLiveViewStatus)) { + StsLiveViewStatusUtils::StsToC(stsLiveViewStatus, liveViewStatus); + return true; + } + return false; +} + +bool LiveViewStatusCToEts(ani_env *env, LiveViewStatus liveViewStatus, ani_enum_item &enumItem) +{ + STSLiveViewStatus stsLiveViewStatus = STSLiveViewStatus::LIVE_VIEW_CREATE; + StsLiveViewStatusUtils::CToSts(liveViewStatus, stsLiveViewStatus); + if(EnumConvertNativeToAni(env, + "Lnotification/notificationContent/#LiveViewStatus", stsLiveViewStatus, enumItem)) { + return true; + } + return false; +} + +bool ContentTypeEtsToC(ani_env *env, ani_enum_item enumItem, ContentType &contentType) +{ + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + if(EnumConvertAniToNative(env, enumItem, stsContentType)) { + StsContentTypeUtils::StsToC(stsContentType, contentType); + return true; + } + return false; +} + +bool ContentTypeCToEts(ani_env *env, ContentType contentType, ani_enum_item &enumItem) +{ + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + StsContentTypeUtils::CToSts(contentType, stsContentType); + if(EnumConvertNativeToAni(env, + "L@ohos/notificationManager/notificationManager/#ContentType", stsContentType, enumItem)) { + return true; + } + return false; +} } } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_flags.cpp b/frameworks/ani/notification_manager/src/sts_notification_flags.cpp new file mode 100644 index 000000000..cb4be48b1 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_flags.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification_constant.h" +#include "sts_notification_enum_type.h" +#include "ans_log_wrapper.h" +#include "sts_notification_utils.h" + +namespace OHOS { +namespace NotificationSts { +using FlagStatus = OHOS::Notification::NotificationConstant::FlagStatus; +void UnwrapNotificationFlags(ani_env *env, ani_object aniObj, NotificationFlags& flags) +{ + ani_ref soundEnabledRef; + FlagStatus soundEnabled {FlagStatus::NONE}; + if (ANI_OK == env->Object_CallMethodByName_Ref(aniObj, + "soundEnabled", + ":L@ohos/notification/notificationFlags/NotificationFlagStatus;", + &soundEnabledRef)) { + if (EnumConvertAniToNative(env, static_cast(soundEnabledRef), soundEnabled)) { + flags.SetSoundEnabled(soundEnabled); + } + } + + ani_ref vibrationEnabledRef; + FlagStatus vibrationEnabled {FlagStatus::NONE}; + if (ANI_OK == env->Object_CallMethodByName_Ref(aniObj, + "vibrationEnabled", + ":L@ohos/notification/notificationFlags/NotificationFlagStatus;", + &vibrationEnabledRef)) { + if (EnumConvertAniToNative(env, static_cast(vibrationEnabledRef), vibrationEnabled)) { + flags.SetVibrationEnabled(vibrationEnabled); + } + } + + ani_int reminderFlagsRef; + if (ANI_OK == env->Object_CallMethodByName_Int(aniObj, "reminderFlags", nullptr, &reminderFlagsRef)) { + flags.SetReminderFlags(reminderFlagsRef); + } +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index 76b14a800..2d4cdeff0 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -19,9 +19,14 @@ #include "sts_bundle_option.h" #include "notification_bundle_option.h" #include "notification_helper.h" -#include "sts_enum_slot_type.h" +#include "sts_notification_enum_type.h" +#include "sts_notification_slot.h" +#include "notification_slot.h" +#include "notification_constant.h" +#include "uri.h" +#include "inner_errors.h" +#include "sts_do_not_disturb_profile.h" -using namespace OHOS::AniCommom; using namespace OHOS::NotificationSts; namespace OHOS { namespace NotificationManagerSts { @@ -31,8 +36,10 @@ static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) ANS_LOGD("sts DisplayBadge call"); Notification::NotificationBundleOption option; UnwrapBundleOption(env, obj, option); + ANS_LOGD("sts DisplayBadge option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), + option.GetUid()); int ret = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, AniBooleanToBool(enable)); - ANS_LOGD("sts DisplayBadge end, ret: %{public}d", ret); + ANS_LOGD("sts DisplayBadge end, ret: %{public}d", CJSystemapi::Notification::ErrorToExternal(ret)); } static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) @@ -40,6 +47,8 @@ static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) ANS_LOGD("sts IsBadgeDisplayed call"); Notification::NotificationBundleOption option; bool ret = UnwrapBundleOption(env, obj, option); + ANS_LOGD("sts IsBadgeDisplayed option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), + option.GetUid()); bool isDisplayed = false; int returncode = 0; if (ret) { @@ -47,7 +56,8 @@ static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) } else { returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); } - ANS_LOGD("sts IsBadgeDisplayed end, isDisplayed: %{public}d, returncode: %{public}d", isDisplayed, returncode); + ANS_LOGD("sts IsBadgeDisplayed end, isDisplayed: %{public}d, returncode: %{public}d", isDisplayed, + CJSystemapi::Notification::ErrorToExternal(returncode)); return BoolToAniBoolean(isDisplayed); } @@ -160,7 +170,7 @@ static void CancelWithId(ani_env* env, ani_int id) static void CancelWithIdLabel(ani_env* env, ani_int id, ani_string label) { std::string labelStr; - if (!AniCommom::GetStdString(env, label, labelStr)) { + if (ANI_OK != GetStdString(env, label, labelStr)) { ANS_LOGE("Label parse failed!"); return; } @@ -197,6 +207,75 @@ static void CancelAll(ani_env* env) } } +static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) +{ + ANS_LOGD("sts GetSlotsByBundle enter"); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, bundleOption, option); + ANS_LOGD("sts GetSlotsByBundle option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), + option.GetUid()); + std::vector> slots; + auto ret = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); + ani_object outAniObj; + WrapNotificationSlotArray(env, slots, outAniObj); + ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", CJSystemapi::Notification::ErrorToExternal(ret)); + return outAniObj; +} + +static void addDoNotDisturbProfile(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts addDoNotDisturbProfile call"); + std::vector> profiles; + UnwrapArrayDoNotDisturbProfile(env, obj, profiles); + Notification::NotificationHelper::AddDoNotDisturbProfiles(profiles); + return; +} + +static void removeDoNotDisturbProfile(ani_env *env, ani_object obj) +{ + ANS_LOGD("sts removeDoNotDisturbProfile call"); + std::vector> profiles; + UnwrapArrayDoNotDisturbProfile(env, obj, profiles); + Notification::NotificationHelper::RemoveDoNotDisturbProfiles(profiles); + return; +} + +static void SetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, + ani_object isForceControl) +{ + ANS_LOGD("SetNotificationEnableSlot enter "); + ani_boolean isUndefined = false; + ani_boolean res = 0.0; + Notification::NotificationBundleOption option; + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + NotificationSts::SlotTypeEtsToC(env, type, slotType); + UnwrapBundleOption(env, bundleOption, option); + env->Reference_IsUndefined(isForceControl, &isUndefined); + if(isUndefined) { + bool forceControl = false; + Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + forceControl); + } else { + if (ANI_OK !=env->Object_CallMethodByName_Boolean(isForceControl, "booleanValue", nullptr, &res)){ + ANS_LOGD("SetNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); + } + } + Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + AniBooleanToBool(res)); +} + +static void SetNotificationEnableSlotByOld(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) +{ + ANS_LOGD("SetNotificationEnableSlotByOld enter "); + Notification::NotificationBundleOption option; + UnwrapBundleOption(env, bundleOption, option); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; + NotificationSts::SlotTypeEtsToC(env, type, slotType); + bool isForceControl = false; + Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + isForceControl); +} + void StsNotificationManagerRegistryInit(ani_env *env) { ANS_LOGD("StsNotificationManagerRegistryInit call"); @@ -227,6 +306,12 @@ void StsNotificationManagerRegistryInit(ani_env *env) ani_native_function {"nativeCancelWithIdLabel", nullptr, reinterpret_cast(CancelWithIdLabel)}, ani_native_function {"nativeCancelWithBundle", nullptr, reinterpret_cast(CancelWithBundle)}, ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(CancelAll)}, + ani_native_function {"nativeGetSlotsByBundle", nullptr, reinterpret_cast(GetSlotsByBundle)}, + ani_native_function {"nativeaddDoNotDisturbProfile", nullptr, reinterpret_cast(addDoNotDisturbProfile)}, + ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, reinterpret_cast(removeDoNotDisturbProfile)}, + ani_native_function {"nativeSetNotificationEnableSlot", nullptr, reinterpret_cast(SetNotificationEnableSlot)}, + ani_native_function {"nativeSetNotificationEnableSlotByOld", nullptr, + reinterpret_cast(SetNotificationEnableSlotByOld)}, }; diff --git a/frameworks/ani/notification_manager/src/sts_notification_request.cpp b/frameworks/ani/notification_manager/src/sts_notification_request.cpp new file mode 100644 index 000000000..e3b1030f4 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_request.cpp @@ -0,0 +1,661 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sts_notification_utils.h" +#include "sts_common_util.h" +#include "sts_notification_enum_type.h" +#include "ani_common_want.h" +#include "want_params.h" +#include "want_agent.h" +#include "sts_notification_request.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; + +void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions) +{ + bool isDistributed = false; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isDistributed", isUndefined, isDistributed) + && isUndefined == ANI_FALSE) { + distributedOptions.isDistributed = isDistributed; + } + + std::vector supportDisplayDevices = {}; + if(GetStringArrayOrUndefined(env, obj, "supportDisplayDevices", supportDisplayDevices) == ANI_OK) { + distributedOptions.supportDisplayDevices = supportDisplayDevices; + } + + std::vector supportOperateDevices = {}; + if(GetStringArrayOrUndefined(env, obj, "supportOperateDevices", supportOperateDevices) == ANI_OK) { + distributedOptions.supportOperateDevices = supportOperateDevices; + } + + ani_double remindType = 0.0; + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "remindType", isUndefined, remindType) + && isUndefined == ANI_FALSE) { + distributedOptions.remindType = static_cast(remindType); + } +} + +void GetNotificationRequestByBooleanOne(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isOngoing", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetInProgress(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isUnremovable", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUnremovable(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "updateOnly", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetUpdateOnly(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "tapDismissed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetTapDismissed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "colorEnabled", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetColorEnabled(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isAlertOnce", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetAlertOneTime(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isStopwatch", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowStopwatch(mbool); + } +} + +void GetNotificationRequestByBooleanTwo(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + bool mbool = false; + ani_boolean isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isCountDown", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetCountdownTimer(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isFloatingIcon", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetFloatingIcon(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "showDeliveryTime", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetShowDeliveryTime(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isRemoveAllowed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetRemoveAllowed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "forceDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetForceDistributed(mbool); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "notDistributed", isUndefined, mbool) + && isUndefined == ANI_FALSE) { + request->SetNotDistributed(mbool); + } +} + +void GetNotificationRequestByBoolean(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + GetNotificationRequestByBooleanOne(env, obj, request); + GetNotificationRequestByBooleanTwo(env, obj, request); +} + +void GetNotificationRequestByString(ani_env *env, ani_object obj, + std::shared_ptr &request) { + std::string mString = ""; + + if (ANI_OK == GetPropertyString(env, obj, "classification", mString)) { + request->SetClassification(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "appMessageId", mString)) { + request->SetAppMessageId(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "label", mString)) { + request->SetLabel(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "groupName", mString)) { + request->SetGroupName(mString); + } + + if (ANI_OK == GetPropertyString(env, obj, "sound", mString)) { + request->SetSound(mString); + } +} + +void GetNotificationRequestByNumber(ani_env *env, ani_object obj, + std::shared_ptr &request) { + ani_double mDouble = 0.0; + ani_boolean isUndefined = ANI_TRUE; + + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "id", isUndefined, mDouble) && isUndefined == ANI_FALSE) { + request->SetNotificationId(static_cast(mDouble)); + } else { + request->SetNotificationId(0); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "deliveryTime", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetDeliveryTime(static_cast(mDouble)); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "autoDeletedTime", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetAutoDeletedTime(static_cast(mDouble)); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "color", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetColor(static_cast(mDouble)); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "badgeIconStyle", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + int32_t style = static_cast(mDouble); + request->SetBadgeIconStyle(static_cast(style)); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "badgeNumber", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetBadgeNumber(static_cast(mDouble)); + } + + isUndefined = ANI_TRUE; + if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "notificationControlFlags", isUndefined, mDouble) + && isUndefined == ANI_FALSE) { + request->SetNotificationControlFlags(static_cast(mDouble)); + } +} + +bool GetNotificationContent(ani_env *env, ani_object obj, ContentType outType, + std::shared_ptr &request) +{ + ani_ref contentRef = {}; + switch (outType) { + case ContentType::BASIC_TEXT: + { + if(env->Object_GetPropertyByName_Ref(obj, "normal", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr normalContent = std::make_shared(); + UnWarpNotificationNormalContent(env, static_cast(contentRef), normalContent); + request->SetContent(std::make_shared(normalContent)); + break; + } + case ContentType::LONG_TEXT: + { + if(env->Object_GetPropertyByName_Ref(obj, "longText", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr longTextContent + = std::make_shared(); + UnWarpNotificationLongTextContent(env, static_cast(contentRef), longTextContent); + request->SetContent(std::make_shared(longTextContent)); + break; + } + case ContentType::PICTURE: + { + if(env->Object_GetPropertyByName_Ref(obj, "picture", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr pictureContent + = std::make_shared(); + UnWarpNotificationPictureContent(env, static_cast(contentRef), pictureContent); + request->SetContent(std::make_shared(pictureContent)); + break; + } + case ContentType::MULTILINE: + { + if(env->Object_GetPropertyByName_Ref(obj, "multiLine", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr multiLineContent + = std::make_shared(); + UnWarpNotificationMultiLineContent(env, static_cast(contentRef), multiLineContent); + request->SetContent(std::make_shared(multiLineContent)); + break; + } + case ContentType::LOCAL_LIVE_VIEW: + { + if(env->Object_GetPropertyByName_Ref(obj, "systemLiveView", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr localLiveView + = std::make_shared(); + UnWarpNotificationLocalLiveViewContent(env, static_cast(contentRef), localLiveView); + request->SetContent(std::make_shared(localLiveView)); + break; + } + case ContentType::LIVE_VIEW: + { + if(env->Object_GetPropertyByName_Ref(obj, "liveView", &contentRef) != ANI_OK) { + return false; + } + std::shared_ptr liveViewContent + = std::make_shared(); + UnWarpNotificationLiveViewContent(env, static_cast(contentRef), liveViewContent); + request->SetContent(std::make_shared(liveViewContent)); + break; + } + case ContentType::CONVERSATION: + // need to add + break; + default: + break; + } + return true; +} + +ani_status GetNotificationContent(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref notificationContentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "content", ¬ificationContentRef))!= ANI_OK) { + return status; + } + ani_ref contentTypeRef; + if((status = env->Object_GetPropertyByName_Ref(static_cast(notificationContentRef), + "notificationContentType", &contentTypeRef)) != ANI_OK) { + return status; + } + ani_boolean isUndefined = ANI_TRUE; + if ((status = env->Reference_IsUndefined(contentTypeRef, &isUndefined)) != ANI_OK) { + return status; + } + if (isUndefined == ANI_TRUE) { + return ANI_INCORRECT_REF; + } + ContentType type; + if(!ContentTypeEtsToC(env, static_cast(contentTypeRef), type)) { + return ANI_INVALID_ARGS; + } + + if(!GetNotificationContent(env, static_cast(notificationContentRef), type, request)) { + return ANI_INVALID_ARGS; + } + return status; +} + +void GetNotificationSlotType(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref slotTypeRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "notificationSlotType", &slotTypeRef))!= ANI_OK) { + return; + } + SlotType type = SlotType::OTHER; + if(!SlotTypeEtsToC(env, static_cast(slotTypeRef), type)) { + return; + } + request->SetSlotType(type); +} + +void GetNotificationRemovalWantAgent(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref wantAgentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "removalWantAgent", &wantAgentRef))!= ANI_OK) { + return; + } + WantAgent* pWantAgent = nullptr; + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + if (pWantAgent == nullptr) { + return; + } + + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + request->SetRemovalWantAgent(wantAgent); +} + +void GetNotificationWantAgent(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref wantAgentRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "wantAgent", &wantAgentRef))!= ANI_OK) { + return; + } + WantAgent* pWantAgent = nullptr; + UnwrapWantAgent(env, static_cast(wantAgentRef), reinterpret_cast(&pWantAgent)); + if (pWantAgent == nullptr) { + return; + } + + std::shared_ptr wantAgent = std::make_shared(*pWantAgent); + request->SetWantAgent(wantAgent); +} + +void GetNotificationExtraInfo(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref extraInfoRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "extraInfo", &extraInfoRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + WantParams wantParams = {}; + if ((status = env->Reference_IsUndefined(extraInfoRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + UnwrapWantParams(env, extraInfoRef, wantParams); + std::shared_ptr extras = std::make_shared(wantParams); + request->SetAdditionalData(extras); + } +} + +ani_status GetNotificationActionButtonArrayOrUndefined(ani_env *env, ani_object param, + const char *name, std::vector> &res) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + ani_double length; + StsActionButton actionButton; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return ANI_INVALID_ARGS; + } + + status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + + for (int i = 0; i < static_cast(length); i++) { + ani_ref buttonRef; + status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, i); + return status; + } + status = UnwrapNotificationActionButton(env, static_cast(buttonRef), actionButton); + if (status != ANI_OK) { + ANS_LOGI("ActionButton failed, index: %{public}d", i); + return status; + } + std::shared_ptr button + = NotificationActionButton::Create(actionButton.icon, + actionButton.title, actionButton.wantAgent, actionButton.extras, + actionButton.semanticActionButton, actionButton.autoCreatedReplies, actionButton.mimeTypeOnlyInputs, + actionButton.userInput, actionButton.isContextual); + res.push_back(button); + } + return status; +} + +void GetNotificationActionButtons(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + std::vector> buttons = {}; + ani_status status = GetNotificationActionButtonArrayOrUndefined(env, obj, "actionButtons", buttons); + if (status == ANI_OK) { + for(auto button: buttons) { + request->AddActionButton(button); + } + } +} + +void GetNotificationSmallIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref smallIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "smallIcon", &smallIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(smallIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(smallIconRef)); + if (pixelMap != nullptr) { + request->SetLittleIcon(pixelMap); + } + } +} + +void GetNotificationLargeIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref largeIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "largeIcon", &largeIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(largeIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(largeIconRef)); + if (pixelMap != nullptr) { + request->SetBigIcon(pixelMap); + } + } +} + +void GetNotificationOverlayIcon(ani_env *env, ani_object obj, std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref overlayIconRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "overlayIcon", &overlayIconRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(overlayIconRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + std::shared_ptr pixelMap = GetPixelMapFromEnvSp(env, static_cast(overlayIconRef)); + if (pixelMap != nullptr) { + request->SetOverlayIcon(pixelMap); + } + } +} + +void GetNotificationRequestDistributedOptions(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref optionRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "distributedOptionRef", &optionRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(optionRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + StsDistributedOptions options; + UnWarpDistributedOptions(env, static_cast(optionRef), options); + request->SetDistributed(options.isDistributed); + request->SetDevicesSupportDisplay(options.supportDisplayDevices); + request->SetDevicesSupportOperate(options.supportOperateDevices); + } +} + +void GetNotificationTemplate(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref templateRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "template", &templateRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(templateRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + Notification::NotificationTemplate tmplate; + UnwrapNotificationTemplate(env, static_cast(templateRef), tmplate); + request->SetTemplate(std::make_shared(tmplate)); + } +} + +void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref infoRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "template", &infoRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(infoRef, &isUndefind)) != ANI_OK || isUndefind == ANI_TRUE) { + return; + } + + std::shared_ptr unifiedGroupInfo = std::make_shared(); + std::string mString = ""; + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "key", mString)) { + unifiedGroupInfo->SetKey(mString); + } + + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "title", mString)) { + unifiedGroupInfo->SetTitle(mString); + } + + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "content", mString)) { + unifiedGroupInfo->SetContent(mString); + } + + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "sceneName", mString)) { + unifiedGroupInfo->SetSceneName(mString); + } + + ani_ref extraInfoRef = {}; + if((status = env->Object_GetPropertyByName_Ref(static_cast(infoRef), "extraInfo", &extraInfoRef)) + != ANI_OK) { + return; + } + isUndefind = ANI_TRUE; + WantParams wantParams = {}; + if ((status = env->Reference_IsUndefined(extraInfoRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + UnwrapWantParams(env, extraInfoRef, wantParams); + std::shared_ptr extras = std::make_shared(wantParams); + unifiedGroupInfo->SetExtraInfo(extras); + } + request->SetUnifiedGroupInfo(unifiedGroupInfo); +} + +void GetNotificationBundleOption(ani_env *env, ani_object obj, + std::shared_ptr &request) +{ + ani_status status = ANI_ERROR; + ani_ref optionRef = {}; + if((status = env->Object_GetPropertyByName_Ref(obj, "representativeBundle", &optionRef))!= ANI_OK) { + return; + } + ani_boolean isUndefind = ANI_TRUE; + if ((status = env->Reference_IsUndefined(optionRef, &isUndefind)) != ANI_OK || isUndefind == ANI_TRUE) { + return; + } + Notification::NotificationBundleOption option; + if(ANI_OK == UnwrapBundleOption(env, static_cast(optionRef), option)) { + request->SetBundleOption(std::make_shared(option)); + } +} + +ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest) +{ + ani_status status = ANI_ERROR; + if((status = GetNotificationContent(env, obj, notificationRequest)) != ANI_OK) { + return status; + } + + GetNotificationSlotType(env, obj, notificationRequest); + GetNotificationWantAgent(env, obj, notificationRequest); + GetNotificationExtraInfo(env, obj, notificationRequest); + GetNotificationRemovalWantAgent(env, obj, notificationRequest); + GetNotificationActionButtons(env, obj, notificationRequest); + GetNotificationSmallIcon(env, obj, notificationRequest); + GetNotificationLargeIcon(env, obj, notificationRequest); + GetNotificationOverlayIcon(env, obj, notificationRequest); + GetNotificationRequestDistributedOptions(env, obj, notificationRequest); + GetNotificationTemplate(env, obj, notificationRequest); + GetNotificationUnifiedGroupInfo(env, obj, notificationRequest); + GetNotificationBundleOption(env, obj, notificationRequest); + + /* + // maxScreenWantAgent?: WantAgent + if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { + return nullptr; + } + // template?: NotificationTemplate + if (GetNotificationTemplate(env, value, request) == nullptr) { + return nullptr; + } + // unifiedGroupInfo?: NotificationUnifiedGroupInfo + if (GetNotificationUnifiedGroupInfo(env, value, request) == nullptr) { + return nullptr; + } + // representativeBundle?: BundleOption + if (GetNotificationBundleOption(env, value, request) == nullptr) { + return nullptr; + } + */ + + return status; +} + +void UnWarpNotificationRequest(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest) +{ + GetNotificationRequestByNumber(env, obj, notificationRequest); + GetNotificationRequestByString(env, obj, notificationRequest); + GetNotificationRequestByBoolean(env, obj, notificationRequest); + GetNotificationRequestByCustom(env, obj, notificationRequest); +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_slot.cpp b/frameworks/ani/notification_manager/src/sts_notification_slot.cpp new file mode 100644 index 000000000..de9507455 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_slot.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "sts_common_util.h" +#include "ans_log_wrapper.h" +#include "sts_notification_slot.h" + +//using namespace OHOS::NotificationSts; +namespace OHOS { +namespace NotificationSts { + +bool WrapNotificationSlot(ani_env *env, sptr slot, ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlot call"); + if (slot == nullptr) { + ANS_LOGE("WrapNotificationSlot slot is null"); + return false; + } + ani_class cls; + if (!CreateClassObjByClassName(env, NotificationSlotClassName, cls, outAniObj)) { + ANS_LOGE("WrapNotificationSlot CreateClassObjByClassName fail"); + return false; + } + if (!SetOptionalFieldSlotType(env, cls, outAniObj, "notificationType", slot->GetType())) { + ANS_LOGE("WrapNotificationSlot Set notificationType fail"); + return false; + } + if (!SetFieldString(env, cls, outAniObj, "desc", slot->GetDescription())) { + ANS_LOGE("WrapNotificationSlot Set desc fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "badgeFlag", slot->IsShowBadge())) { + ANS_LOGE("WrapNotificationSlot Set badgeFlag fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "bypassDnd", slot->IsEnableBypassDnd())) { + ANS_LOGE("WrapNotificationSlot Set bypassDnd fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "lockscreenVisibility", static_cast(slot->GetLockScreenVisibleness()))) { + ANS_LOGE("WrapNotificationSlot Set lockscreenVisibility fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "vibrationEnabled", slot->CanVibrate())) { + ANS_LOGE("WrapNotificationSlot Set vibrationEnabled fail"); + return false; + } + if (!SetFieldString(env, cls, outAniObj, "sound", slot->GetSound().ToString().c_str())) { + ANS_LOGE("WrapNotificationSlot Set sound fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "lightEnabled", slot->CanEnableLight())) { + ANS_LOGE("WrapNotificationSlot Set lightEnabled fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "lightColor", static_cast(slot->GetLedLightColor()))) { + ANS_LOGE("WrapNotificationSlot Set lightColor fail"); + return false; + } + if (!SetOptionalFieldArrayDouble(env, cls, outAniObj, "vibrationValues", slot->GetVibrationStyle())) + { + ANS_LOGE("WrapNotificationSlot Set vibrationValues fail"); + return false; + } + if (!SetOptionalFieldBoolean(env, cls, outAniObj, "enabled", slot->GetEnable())) { + ANS_LOGE("WrapNotificationSlot Set enabled fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "reminderMode", static_cast(slot->GetReminderMode()))) { + ANS_LOGE("WrapNotificationSlot Set reminderMode fail"); + return false; + } + if (!SetOptionalFieldDouble(env, cls, outAniObj, "authorizedStatus", static_cast(slot->GetAuthorizedStatus()))) { + ANS_LOGE("WrapNotificationSlot Set authorizedStatus fail"); + return false; + } + ANS_LOGD("WrapNotificationSlot end"); + return true; +} + +bool WrapNotificationSlotArray(ani_env *env, const std::vector>& slots, ani_object &outAniObj) +{ + ANS_LOGD("WrapNotificationSlotArray call"); + outAniObj = newArrayClass(env, slots.size()); + if (outAniObj == nullptr) { + ANS_LOGE("WrapNotificationSlotArray outAniObj is null, newArrayClass Faild"); + return false; + } + int index = 0; + for (auto &it : slots) { + ani_object infoObj; + if (!WrapNotificationSlot(env, it, infoObj)) { + ANS_LOGE("WrapNotificationSlotArray WrapNotificationSlot Faild"); + return false; + } + ANI_FAILED_AND_RETURN(env->Object_CallMethodByName_Void(outAniObj, + "$_set", "ILstd/core/Object;:V", index, infoObj)); + index++; + } + + ANS_LOGD("WrapNotificationSlotArray end"); + return true; +} + +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/@ohos.base.ets b/frameworks/ani/notification_manager/src/sts_notification_template.cpp similarity index 34% rename from frameworks/ani/notification_manager/ets/@ohos.base.ets rename to frameworks/ani/notification_manager/src/sts_notification_template.cpp index f7b23f6b1..9abf544df 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.base.ets +++ b/frameworks/ani/notification_manager/src/sts_notification_template.cpp @@ -13,37 +13,38 @@ * limitations under the License. */ -export type Callback = (data: T) => void; - -export type ErrorCallback = (err: T)=> void; - - -export type AsyncCallback = (err: BusinessError, data: T)=> void; - -export class BusinessError extends Error { - - // 构造函数重载1:无参数 - constructor() { - super(); // 调用父类 Error 的构造函数 - this.code = 0; // 默认错误代码 - this.data = undefined; // 默认数据为 undefined +#include "sts_notification_utils.h" + +#include "sts_common_util.h" +#include "ani_common_want.h" +#include "want_params.h" + +namespace OHOS { +namespace NotificationSts { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, Notification::NotificationTemplate& tmplate) +{ + ani_status status = ANI_ERROR; + ani_ref nameRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(aniObj, "name",":Lstd/core/String;", &nameRef))) { + return status; } - - // 构造函数重载2:带有错误代码和 Error 对象 - constructor(code: number, error: Error) { - // constructor(name: String, message: String | undefined, options: ErrorOptions | undefined) - super(error.name, error.message, undefined); // 调用父类 Error 的构造函数,并传递错误信息 - this.code = code; - this.data = undefined; // 默认数据为 undefined + std::string nameStr = ""; + if (ANI_OK != (status = GetStdString(env, static_cast(nameRef), nameStr))) { + return status; } - - constructor(code: number, data: T, error: Error) { - super(error.name, error.message, undefined); // 调用父类 Error 的构造函数,并传递错误信息 - this.code = code; - this.data = data; // 默认数据为 undefined + ani_ref dataRef; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(aniObj, "data", &dataRef))) { + return status; } - - public code: number; - - public data?: T; -} \ No newline at end of file + WantParams wantParams; + if(!UnwrapWantParams(env, dataRef, wantParams)) { + return ANI_ERROR; + } + tmplate.SetTemplateName(nameStr); + tmplate.SetTemplateData(std::make_shared(wantParams)); + return status; +} +} +} diff --git a/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp b/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp new file mode 100644 index 000000000..05ad41512 --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sts_notification_utils.h" +#include "sts_common_util.h" + +namespace OHOS { +namespace NotificationSts { +ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, std::shared_ptr &userInput) +{ + ani_status status = ANI_ERROR; + std::string inputKey; + if((status = GetPropertyString(env, param, "inputKey", inputKey)) != ANI_OK) { + return status; + } + userInput = NotificationUserInput::Create(inputKey); + return status; +} +} +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_utils.cpp b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp new file mode 100644 index 000000000..8f51be64b --- /dev/null +++ b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sts_notification_utils.h" +#include "sts_common_util.h" +#include "pixel_map_ani.h" + +namespace OHOS { +namespace NotificationSts { + +void UnwrapWantAgent(ani_env *env, ani_object agent, void** result) +{ + ANS_LOGI("called"); + if (agent == nullptr) { + ANS_LOGI("agent null"); + return; + } + ani_long param_value; + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + ani_method method {}; + if ((status = env->FindClass("Lstd/core/Long;", &cls)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + if ((status = env->Class_FindMethod(cls, "unboxed", nullptr, &method)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + if ((status = env->Object_CallMethod_Long(agent, method, ¶m_value)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return; + } + *result = reinterpret_cast(param_value); +} + +std::shared_ptr GetPixelMapFromEnvSp([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object obj) +{ + ani_status ret; + ani_long nativeObj {}; + if ((ret = env->Object_GetFieldByName_Long(obj, "nativeObj", &nativeObj)) != ANI_OK) { + ANS_LOGI("[GetPixelMapFromEnv] Object_GetField_Long fetch failed"); + return nullptr; + } + PixelMapAni* pixelmapAni = reinterpret_cast(nativeObj); + if (!pixelmapAni) { + ANS_LOGI("[GetPixelMapFromEnv] pixelmapAni nullptr"); + return nullptr; + } + return pixelmapAni->nativePixelMap_; +} + +ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource) +{ + ani_status status = ANI_ERROR; + std::string bundleName = ""; + if((status = GetPropertyString(env, obj, "bundleName", bundleName)) != ANI_OK) { + return status; + } + resource.bundleName = bundleName; + + std::string moduleName = ""; + if((status = GetPropertyString(env, obj, "moduleName", moduleName)) != ANI_OK) { + return status; + } + resource.moduleName = moduleName; + + ani_double idAni = 0.0; + if((status = env->Object_GetPropertyByName_Double(obj, "id", &idAni)) != ANI_OK) { + return status; + } + resource.id = static_cast(idAni); + return status; +} +} +} \ No newline at end of file -- Gitee From b2a10e5844687aec8a4ebe56a98823ddf9490a9e Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Tue, 6 May 2025 17:10:33 +0800 Subject: [PATCH 3/9] =?UTF-8?q?feat:notificationManager=20ani=E5=8C=96?= =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- frameworks/ani/notification_manager/BUILD.gn | 1 + .../ets/@ohos.notificationManager.ets | 35 +------------------ .../ets/notification/notificationSlot.ets | 35 +++++++++++++++++++ .../include/sts_common_util.h | 2 +- 4 files changed, 38 insertions(+), 35 deletions(-) create mode 100644 frameworks/ani/notification_manager/ets/notification/notificationSlot.ets diff --git a/frameworks/ani/notification_manager/BUILD.gn b/frameworks/ani/notification_manager/BUILD.gn index 2956dc5bd..daac4373f 100644 --- a/frameworks/ani/notification_manager/BUILD.gn +++ b/frameworks/ani/notification_manager/BUILD.gn @@ -89,6 +89,7 @@ generate_static_abc("notification_manager_abc") { "./ets/notification/notificationTemplate.ets", "./ets/notification/notificationUserInput.ets", "./ets/notification/notificationActionButton.ets", + "./ets/notification/notificationSlot.ets", ] dst_file = "$target_out_dir/notification_manager.abc" diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index 9acc08017..fa087fb98 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -15,44 +15,11 @@ import { BundleOption } from 'notification.NotificationCommonDef'; import { BusinessError, AsyncCallback } from '@ohos.base'; +import { NotificationSlot } from 'notification.notificationSlot'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; -export interface NotificationSlot { - notificationType?: notificationManager.SlotType; - //level?: notification.SlotLevel; - desc?: string; - badgeFlag?: boolean; - bypassDnd?: boolean; - lockscreenVisibility?: number; - vibrationEnabled?: boolean; - sound?: string; - lightEnabled?: boolean; - lightColor?: number; - vibrationValues?: Array; - readonly enabled?: boolean; - readonly reminderMode?: number; - readonly authorizedStatus?: number; -} - -class NotificationSlotInner implements NotificationSlot { - notificationType?: notificationManager.SlotType; - //level?: notification.SlotLevel; - desc?: string; - badgeFlag?: boolean; - bypassDnd?: boolean; - lockscreenVisibility?: number; - vibrationEnabled?: boolean; - sound?: string; - lightEnabled?: boolean; - lightColor?: number; - vibrationValues?: Array; - readonly enabled?: boolean; - readonly reminderMode?: number; - readonly authorizedStatus?: number; -} - export namespace notificationManager { loadLibrary("notification_manager_ani_kit.z") export enum SlotType { diff --git a/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets b/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets new file mode 100644 index 000000000..e69b84515 --- /dev/null +++ b/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets @@ -0,0 +1,35 @@ +import type notificationManager from '@ohos.notificationManager'; + +export interface NotificationSlot { + notificationType?: notificationManager.SlotType; + //level?: notification.SlotLevel; + desc?: string; + badgeFlag?: boolean; + bypassDnd?: boolean; + lockscreenVisibility?: number; + vibrationEnabled?: boolean; + sound?: string; + lightEnabled?: boolean; + lightColor?: number; + vibrationValues?: Array; + readonly enabled?: boolean; + readonly reminderMode?: number; + readonly authorizedStatus?: number; +} + +class NotificationSlotInner implements NotificationSlot { + notificationType?: notificationManager.SlotType; + //level?: notification.SlotLevel; + desc?: string; + badgeFlag?: boolean; + bypassDnd?: boolean; + lockscreenVisibility?: number; + vibrationEnabled?: boolean; + sound?: string; + lightEnabled?: boolean; + lightColor?: number; + vibrationValues?: Array; + readonly enabled?: boolean; + readonly reminderMode?: number; + readonly authorizedStatus?: number; +} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index 72e3ef1c5..5a384213a 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -23,7 +23,7 @@ namespace OHOS { namespace NotificationSts { -static const char *NotificationSlotClassName = "L@ohos/notificationManager/NotificationSlotInner;"; +static const char *NotificationSlotClassName = "Lnotification/notificationSlot/NotificationSlotInner;"; ani_status GetStdString(ani_env *env, ani_string str, std::string &res); ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_ref &ref, ani_boolean &isUndefined); -- Gitee From 310083d9d110c5174cb233425f80a5a82534e616 Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Wed, 7 May 2025 10:37:41 +0800 Subject: [PATCH 4/9] =?UTF-8?q?feat:=20notificationmanager=20ani=E5=8C=96?= =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- .../ets/@ohos.notificationManager.ets | 2 +- .../ets/notification/notificationContent.ets | 10 + .../include/sts_common_util.h | 11 +- .../include/sts_notification_utils.h | 4 - .../src/sts_bundle_option.cpp | 6 +- .../src/sts_common_util.cpp | 27 +- .../src/sts_do_not_disturb_profile.cpp | 4 +- .../src/sts_notification_action_button.cpp | 7 +- .../src/sts_notification_content.cpp | 265 +++++++++++++----- .../src/sts_notification_manager.cpp | 1 + .../src/sts_notification_request.cpp | 38 ++- .../src/sts_notification_user_input.cpp | 6 +- .../src/sts_notification_utils.cpp | 16 +- 13 files changed, 281 insertions(+), 116 deletions(-) diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index fa087fb98..f9f7ca3fa 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -20,7 +20,7 @@ import { NotificationSlot } from 'notification.notificationSlot'; type ResolveCallback = (data: T) => void; type RejectCallback = (err: Object) => void; -export namespace notificationManager { +export default namespace notificationManager { loadLibrary("notification_manager_ani_kit.z") export enum SlotType { UNKNOWN_TYPE = 0, diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets index e0d67e5bc..712e66d63 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -19,6 +19,16 @@ import type notificationManager from '@ohos.notificationManager'; type IconType = Resource | image.PixelMap; +export class RecordTools { + public static GetKeys(obj: Record): Array { + try { + let keys: Array = Object.keys(record); + return keys; + } catch (err) { + return {}; + } + } +} export interface NotificationBasicContent { diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index 5a384213a..f2c3fb265 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -27,15 +27,18 @@ static const char *NotificationSlotClassName = "Lnotification/notificationSlot/N ani_status GetStdString(ani_env *env, ani_string str, std::string &res); ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_ref &ref, ani_boolean &isUndefined); -ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, std::string &outStr); -ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, std::vector &res); +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, std::string &outStr); +ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res); ani_status GetPropertyBooleanOrUndefined(ani_env *env, ani_object aniObj, const char *name, ani_boolean isUndefined, bool outvalue); ani_status GetPropertyDoubleOrUndefined(ani_env *env, ani_object obj, const char *name, - ani_boolean isUndefined, ani_double outvalue); + ani_boolean &isUndefined, ani_double &outvalue); bool CreateClassObjByClassName(ani_env *env, const char *className, ani_class &cls, ani_object &outAniObj); -bool SetFieldString(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, const std::string &value); +bool SetFieldString(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, + const std::string &value); bool SetOptionalFieldBoolean(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, bool value); bool SetOptionalFieldDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, double value); bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, diff --git a/frameworks/ani/notification_manager/include/sts_notification_utils.h b/frameworks/ani/notification_manager/include/sts_notification_utils.h index b41a3ca3c..c6d08ebe9 100644 --- a/frameworks/ani/notification_manager/include/sts_notification_utils.h +++ b/frameworks/ani/notification_manager/include/sts_notification_utils.h @@ -84,13 +84,9 @@ void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule &iconButton); ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &localLiveViewContent); -ani_status UnWarpNotificationContent(ani_env *env, ani_object obj, - std::shared_ptr ¬ificationContent); /* NotificationRequest */ void UnWarpNotificationRequest(ani_env *env, ani_object obj, std::shared_ptr ¬ificationRequest); -ani_status UnWarpNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, - std::shared_ptr &unifiedGroupInfo); } } #endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp index b6bcb3f8e..cb5dafbc9 100644 --- a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp +++ b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp @@ -74,7 +74,7 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vectorObject_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGD("status : %{public}d", status); return false; @@ -83,14 +83,14 @@ bool UnwrapArrayBundleOption(ani_env *env, ani_ref arrayObj, std::vector(length); i++) { ani_ref optionRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lnotification/NotificationCommonDef/BundleOption;", &optionRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGD("status : %{public}d, index: %{public}d", status, i); return false; } - if (!UnwrapBundleOption(env, reinterpret_cast(optionRef), option)) { + if (!UnwrapBundleOption(env, static_cast(optionRef), option)) { ANS_LOGD("Get oprion failed, index: %{public}d", i); return false; } diff --git a/frameworks/ani/notification_manager/src/sts_common_util.cpp b/frameworks/ani/notification_manager/src/sts_common_util.cpp index b87f92b73..97395e10a 100644 --- a/frameworks/ani/notification_manager/src/sts_common_util.cpp +++ b/frameworks/ani/notification_manager/src/sts_common_util.cpp @@ -55,7 +55,8 @@ ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_re return status; } -ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, std::string &outStr) +ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, + ani_boolean &isUndefined, std::string &outStr) { ani_status status = ANI_ERROR; ani_ref strRef; @@ -63,19 +64,27 @@ ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, std ANS_LOGD("Object_GetField_Ref bundle fail, status: %{public}d", status); return status; } + status = env->Reference_IsUndefined(strRef, &isUndefined); + if (status != ANI_OK) { + ANS_LOGI("Failed to check undefined for '%{public}s', status: %{public}d", name, status); + return status; + } + if(isUndefined == ANI_TRUE) { + return status; + } std::string result = ""; if ((status = GetStdString(env, reinterpret_cast(strRef), result)) != ANI_OK) { - ANS_LOGD("WrapBundleOption GetStdString failed"); + ANS_LOGD("GetStdString failed"); return status; } outStr = result; return status; } -ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, std::vector &res) +ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char *name, + ani_boolean &isUndefined, std::vector &res) { ani_ref arrayObj = nullptr; - ani_boolean isUndefined = true; ani_status status; ani_double length; std::string str; @@ -93,7 +102,7 @@ ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char return status; } - status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); return status; @@ -101,7 +110,7 @@ ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char for (int i = 0; i < static_cast(length); i++) { ani_ref stringEntryRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGI("status : %{public}d, index: %{public}d", status, i); @@ -109,7 +118,7 @@ ani_status GetStringArrayOrUndefined(ani_env *env, ani_object param, const char } str = ""; - status = GetStdString(env, reinterpret_cast(stringEntryRef), str); + status = GetStdString(env, static_cast(stringEntryRef), str); if (status != ANI_OK) { ANS_LOGI("GetStdString failed, index: %{public}d", i); return status; @@ -131,7 +140,7 @@ ani_status GetPropertyBooleanOrUndefined(ani_env *env, ani_object aniObj, const ANS_LOGI("GetPropertyRef failed or %{public}s : undefined", name); return ANI_INVALID_ARGS; } - if ((status = env->Object_CallMethodByName_Boolean(reinterpret_cast(refObj), + if ((status = env->Object_CallMethodByName_Boolean(static_cast(refObj), "unboxed", ":Z", &res)) != ANI_OK) { ANS_LOGI("Object_CallMethodByName_Boolean failed, status : %{public}d", status); return status; @@ -141,7 +150,7 @@ ani_status GetPropertyBooleanOrUndefined(ani_env *env, ani_object aniObj, const } ani_status GetPropertyDoubleOrUndefined(ani_env *env, ani_object obj, const char *name, - ani_boolean isUndefined, ani_double outvalue) + ani_boolean &isUndefined, ani_double &outvalue) { ani_status status = ANI_ERROR; ani_ref uidRef; diff --git a/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp b/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp index 7986c6f53..52472b816 100644 --- a/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp +++ b/frameworks/ani/notification_manager/src/sts_do_not_disturb_profile.cpp @@ -59,7 +59,7 @@ bool UnwrapDoNotDisturbProfile(ani_env *env, ani_object param, sptr trustlist = {}; - UnwrapArrayBundleOption(env, reinterpret_cast(trustlistRef), trustlist); + UnwrapArrayBundleOption(env, static_cast(trustlistRef), trustlist); if (trustlist.size() > 0) { profile->SetProfileTrustList(trustlist); } @@ -88,7 +88,7 @@ bool UnwrapArrayDoNotDisturbProfile(ani_env *env, ani_object arrayObj, return false; } - if (!UnwrapDoNotDisturbProfile(env, reinterpret_cast(optionRef), profile)) { + if (!UnwrapDoNotDisturbProfile(env, static_cast(optionRef), profile)) { ANS_LOGD("Get profile failed, index: %{public}d", i); return false; } diff --git a/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp b/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp index 0ab4a0aa6..2242deeeb 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_action_button.cpp @@ -30,9 +30,10 @@ ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, StsActionButton &actionButton) { ani_status status = ANI_ERROR; + ani_boolean isUndefind = ANI_TRUE; std::string title; - if((status = GetPropertyString(env, param, "title", title)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, param, "title", isUndefind, title)) != ANI_OK || isUndefind == ANI_TRUE) { + return ANI_INVALID_ARGS; } ani_ref wantAgentRef; if ((status = env->Object_GetPropertyByName_Ref(param, "wantAgent", &wantAgentRef)) != ANI_OK) { @@ -50,7 +51,7 @@ ani_status UnwrapNotificationActionButton(ani_env *env, ani_object param, if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(param, "extras", &extrasRef))) { return status; } - ani_boolean isUndefind = ANI_TRUE; + isUndefind = ANI_TRUE; WantParams wantParams = {}; if ((status = env->Reference_IsUndefined(extrasRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { UnwrapWantParams(env, extrasRef, wantParams); diff --git a/frameworks/ani/notification_manager/src/sts_notification_content.cpp b/frameworks/ani/notification_manager/src/sts_notification_content.cpp index 020fea735..2cc668a8a 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_content.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_content.cpp @@ -31,16 +31,19 @@ void UnWarpNotificationProgress(ani_env *env, ani_object obj, NotificationProgress ¬ificationProgress) { ani_double maxValueAni = 0.0; - if(env->Object_GetPropertyByName_Double(obj, "maxValue", &maxValueAni) == ANI_OK) { + ani_boolean isUndefined = ANI_TRUE; + if(GetPropertyDoubleOrUndefined(env, obj, "maxValue", isUndefined, maxValueAni) == ANI_OK + && isUndefined == ANI_FALSE) { notificationProgress.SetMaxValue(static_cast(maxValueAni)); } ani_double currentValueAni = 0.0; - if(env->Object_GetPropertyByName_Double(obj, "currentValue", ¤tValueAni) == ANI_OK) { + if(GetPropertyDoubleOrUndefined(env, obj, "currentValue", isUndefined, currentValueAni) == ANI_OK + && isUndefined == ANI_FALSE) { notificationProgress.SetCurrentValue(static_cast(currentValueAni)); } bool isPercentage = true; - ani_boolean isUndefined = ANI_TRUE; + isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "isPercentage", isUndefined, isPercentage) && isUndefined == ANI_FALSE) { notificationProgress.SetIsPercentage(isPercentage); @@ -83,9 +86,10 @@ ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, NotificationIconButton &iconButton) { ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; std::string name = ""; - if((status = GetPropertyString(env, obj, "name", name)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, obj, "name", isUndefined, name)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } iconButton.SetName(name); @@ -105,12 +109,13 @@ ani_status UnWarpNotificationIconButton(ani_env *env, ani_object obj, } std::string text = ""; - if(GetPropertyString(env, obj, "text", text) == ANI_OK) { + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "text", isUndefined, text) == ANI_OK && isUndefined == ANI_FALSE) { iconButton.SetName(text); } bool hidePanel = true; - ani_boolean isUndefined = ANI_TRUE; + isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyBooleanOrUndefined(env, obj, "hidePanel", isUndefined, hidePanel) && isUndefined == ANI_FALSE) { iconButton.SetHidePanel(hidePanel); @@ -140,7 +145,7 @@ ani_status GetIconButtonArrayOrUndefined(ani_env *env, return status; } - status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); return status; @@ -148,7 +153,7 @@ ani_status GetIconButtonArrayOrUndefined(ani_env *env, for (int i = 0; i < static_cast(length); i++) { ani_ref buttonRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGI("status : %{public}d, index: %{public}d", status, i); @@ -163,28 +168,11 @@ ani_status GetIconButtonArrayOrUndefined(ani_env *env, return status; } -ani_status GetPixelMapArrayOrUndefined(ani_env *env, - ani_object param, const char *name, std::vector> &res) +ani_status GetPixelMapArrayByRef(ani_env *env, ani_ref param, std::vector> &pixelMaps) { - ani_ref arrayObj = nullptr; - ani_boolean isUndefined = true; - ani_status status; + ani_status status = ANI_ERROR; ani_double length; - - if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { - ANS_LOGI("status : %{public}d", status); - return status; - } - if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { - ANS_LOGI("status : %{public}d", status); - return status; - } - if (isUndefined) { - ANS_LOGI("%{public}s : undefined", name); - return status; - } - - status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(param), "length", &length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); return status; @@ -192,7 +180,7 @@ ani_status GetPixelMapArrayOrUndefined(ani_env *env, for (int i = 0; i < static_cast(length); i++) { ani_ref pixelMapRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(param), "$_get", "I:Lstd/core/Object;", &pixelMapRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGI("status : %{public}d, index: %{public}d", status, i); @@ -203,7 +191,32 @@ ani_status GetPixelMapArrayOrUndefined(ani_env *env, if (pixelMap == nullptr) { return ANI_INVALID_ARGS; } - res.push_back(pixelMap); + pixelMaps.push_back(pixelMap); + } + return status; +} + +ani_status GetPixelMapArrayOrUndefined(ani_env *env, + ani_object param, const char *name, std::vector> &pixelMaps) +{ + ani_ref arrayObj = nullptr; + ani_boolean isUndefined = true; + ani_status status; + + if ((status = env->Object_GetFieldByName_Ref(param, name, &arrayObj)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if ((status = env->Reference_IsUndefined(arrayObj, &isUndefined)) != ANI_OK) { + ANS_LOGI("status : %{public}d", status); + return status; + } + if (isUndefined) { + ANS_LOGI("%{public}s : undefined", name); + return status; + } + if((status = GetPixelMapArrayByRef(env, arrayObj, pixelMaps)) != ANI_OK) { + return status; } return status; } @@ -229,7 +242,7 @@ ani_status GetResourceArrayOrUndefined(ani_env *env, return status; } - status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); return status; @@ -237,7 +250,7 @@ ani_status GetResourceArrayOrUndefined(ani_env *env, for (int i = 0; i < static_cast(length); i++) { ani_ref iconRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &iconRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGI("status : %{public}d, index: %{public}d", status, i); @@ -258,7 +271,8 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, NotificationLocalLiveViewButton &button) { std::vector names = {}; - if(GetStringArrayOrUndefined(env, obj, "names", names) == ANI_OK) { + ani_boolean isUndefined = ANI_TRUE; + if(GetStringArrayOrUndefined(env, obj, "names", isUndefined, names) == ANI_OK && isUndefined == ANI_FALSE) { for(auto name: names) { button.addSingleButtonName(name); } @@ -282,23 +296,27 @@ void UnWarpNotificationLocalLiveViewButton(ani_env *env, ani_object obj, void UnWarpNotificationCapsule(ani_env *env, ani_object obj, NotificationCapsule &capsule) { + ani_boolean isUndefined = ANI_TRUE; std::string title = ""; - if(GetPropertyString(env, obj, "title", title) == ANI_OK) { - capsule.SetTitle(title); + if(GetPropertyString(env, obj, "title", isUndefined, title) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetTitle(title); } std::string backgroundColor = ""; - if(GetPropertyString(env, obj, "backgroundColor", backgroundColor) == ANI_OK) { - capsule.SetBackgroundColor(backgroundColor); + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "backgroundColor", isUndefined, backgroundColor) == ANI_OK + && isUndefined == ANI_FALSE) { + capsule.SetBackgroundColor(backgroundColor); } std::string content = ""; - if(GetPropertyString(env, obj, "content", content) == ANI_OK) { - capsule.SetContent(content); + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "content", isUndefined, content) == ANI_OK && isUndefined == ANI_FALSE) { + capsule.SetContent(content); } ani_double time = 0.0; - if(env->Object_GetPropertyByName_Double(obj, "time", &time) == ANI_OK) { + if(GetPropertyDoubleOrUndefined(env, obj, "time", isUndefined,time) == ANI_OK && isUndefined == ANI_FALSE) { capsule.SetTime(static_cast(time)); } @@ -322,20 +340,24 @@ ani_status UnWarpNotificationBasicContent(ani_env *env, ani_object obj, { ANS_LOGI("UnWarpNotificationBasicContent call"); ani_status status = ANI_ERROR; + ani_boolean isUndefined = ANI_TRUE; std::string title; - if((status = GetPropertyString(env, obj, "title", title)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, obj, "title", isUndefined, title)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } basicContent->SetTitle(title); std::string text; - if((status = GetPropertyString(env, obj, "text", text)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "text", isUndefined, text)) != ANI_OK || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } basicContent->SetText(text); std::string additionalText; - if(GetPropertyString(env, obj, "additionalText", additionalText) == ANI_OK) { + isUndefined = ANI_TRUE; + if(GetPropertyString(env, obj, "additionalText", isUndefined, additionalText) == ANI_OK + && isUndefined == ANI_FALSE) { basicContent->SetAdditionalText(additionalText); } @@ -367,21 +389,27 @@ ani_status UnWarpNotificationLongTextContent(ani_env *env, ani_object obj, return status; } + ani_boolean isUndefined = ANI_TRUE; std::string longText; - if((status = GetPropertyString(env, obj, "longText", longText)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, obj, "longText", isUndefined, longText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } longTextContent->SetLongText(longText); std::string briefText; - if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } longTextContent->SetBriefText(briefText); std::string expandedTitle; - if((status = GetPropertyString(env, obj, "expandedTitle", expandedTitle)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } longTextContent->SetExpandedTitle(expandedTitle); @@ -396,21 +424,27 @@ ani_status UnWarpNotificationMultiLineContent(ani_env *env, ani_object obj, return status; } + ani_boolean isUndefined = ANI_TRUE; std::string longTitle; - if((status = GetPropertyString(env, obj, "longTitle", longTitle)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, obj, "longTitle", isUndefined, longTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } multiLineContent->SetExpandedTitle(longTitle); std::string briefText; - if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } multiLineContent->SetBriefText(briefText); std::vector lines = {}; - if((status = GetStringArrayOrUndefined(env, obj, "lines", lines)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetStringArrayOrUndefined(env, obj, "lines", isUndefined, lines)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } for(auto line : lines) { multiLineContent->AddSingleLine(line); @@ -427,14 +461,18 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, } std::string expandedTitle; - if((status = GetPropertyString(env, obj, "expandedTitle", expandedTitle)) != ANI_OK) { - return status; + ani_boolean isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "expandedTitle", isUndefined, expandedTitle)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } pictureContent->SetExpandedTitle(expandedTitle); std::string briefText; - if((status = GetPropertyString(env, obj, "briefText", briefText)) != ANI_OK) { - return status; + isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "briefText", isUndefined, briefText)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } pictureContent->SetBriefText(briefText); @@ -451,6 +489,87 @@ ani_status UnWarpNotificationPictureContent(ani_env *env, ani_object obj, return status; } +ani_status GetKeyString(ani_env *env, ani_object obj, int index, ani_string &str) +{ + ani_status status = ANI_ERROR; + ani_ref stringEntryRef; + status = env->Object_CallMethodByName_Ref(obj, + "$_get", "I:Lstd/core/Object;", &stringEntryRef, (ani_int)index); + if (status != ANI_OK) { + ANS_LOGI("status : %{public}d, index: %{public}d", status, index); + return status; + } + str = static_cast(stringEntryRef); + return status; +} + +ani_status GetMapByKeys(ani_env *env, ani_object obj, std::vector keys, + std::map>> &pictureMap) +{ + ani_status status = ANI_ERROR; + for(auto anikey : keys) { + ani_ref picturesArrayRef; + if (ANI_OK != (status = env->Object_CallMethodByName_Ref(obj, "$_get", nullptr, &picturesArrayRef, anikey))) { + return status; + } + std::vector> pixelMaps = {}; + if((status = GetPixelMapArrayByRef(env, picturesArrayRef, pixelMaps)) != ANI_OK) { + return status; + } + std::string str = ""; + if((status = GetStdString(env, anikey, str)) != ANI_OK) { + return status; + } + pictureMap[str] = pixelMaps; + } + return status; +} + +ani_status GetPictureInfoMap(ani_env *env, ani_object obj, + std::map>> pictureMap) +{ + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + if ((status = env->FindClass("Lnotification/notificationContent/RecordTools;", &cls)) != ANI_OK) { + return status; + } + if (cls == nullptr) { + return ANI_INVALID_TYPE; + } + ani_static_method keysMethod = nullptr; + status = env->Class_FindStaticMethod(cls, "GetKeys", nullptr, &keysMethod); + if (status != ANI_OK) { + return status; + } + ani_ref keysStrArrayRef = nullptr; + status = env->Class_CallStaticMethod_Ref(cls, keysMethod, &keysStrArrayRef, obj); + if (status != ANI_OK) { + return status; + } + ani_boolean isUndefined = ANI_TRUE; + if ((status = env->Reference_IsUndefined(keysStrArrayRef, &isUndefined)) != ANI_OK) { + return status; + } + if (isUndefined) { + return ANI_INVALID_ARGS; + } + ani_double length; + status = env->Object_GetPropertyByName_Double(static_cast(keysStrArrayRef), "length", &length); + if (status != ANI_OK) { + return status; + } + ani_string strAni = {}; + std::vector keys = {}; + for (int i = 0; i < static_cast(length); i++) { + if((status = GetKeyString(env, static_cast(keysStrArrayRef), i, strAni)) != ANI_OK) { + return status; + } + keys.push_back(strAni); + } + status = GetMapByKeys(env, obj, keys, pictureMap); + return status; +} + ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &liveViewContent) { @@ -471,7 +590,8 @@ ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, ani_double versionAni = 0.0; ani_boolean isUndefined = ANI_TRUE; - if (GetPropertyDoubleOrUndefined(env, obj, "version", isUndefined, versionAni) == ANI_OK && isUndefined == ANI_FALSE) { + if (GetPropertyDoubleOrUndefined(env, obj, "version", isUndefined, versionAni) == ANI_OK + && isUndefined == ANI_FALSE) { liveViewContent->SetVersion(static_cast(versionAni)); } @@ -485,9 +605,16 @@ ani_status UnWarpNotificationLiveViewContent(ani_env *env, ani_object obj, liveViewContent->SetExtraInfo(extraInfo); } } - - //pictureInfo?: Record> - // need to add + + ani_ref pictureInfoRef; + isUndefined = ANI_TRUE; + if (ANI_OK == env->Object_GetPropertyByName_Ref(obj, "pictureInfo", &pictureInfoRef) + && env->Reference_IsUndefined(pictureInfoRef, &isUndefined) == ANI_OK && isUndefined == ANI_FALSE) { + std::map>> pictureMap; + if(GetPictureInfoMap(env, static_cast(pictureInfoRef), pictureMap) == ANI_OK) { + liveViewContent->SetPicture(pictureMap); + } + } bool isLocalUpdateOnly = true; isUndefined = ANI_TRUE; @@ -507,8 +634,10 @@ ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, } ani_double typeCode = 0.0; - if((status = env->Object_GetPropertyByName_Double(obj, "typeCode", &typeCode)) != ANI_OK) { - return status; + ani_boolean isUndefined = ANI_TRUE; + if((status = GetPropertyDoubleOrUndefined(env, obj, "typeCode", isUndefined, typeCode)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } localLiveViewContent->SetType(static_cast(typeCode)); diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index 2d4cdeff0..f0ebcf930 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -255,6 +255,7 @@ static void SetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani bool forceControl = false; Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), forceControl); + return; } else { if (ANI_OK !=env->Object_CallMethodByName_Boolean(isForceControl, "booleanValue", nullptr, &res)){ ANS_LOGD("SetNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); diff --git a/frameworks/ani/notification_manager/src/sts_notification_request.cpp b/frameworks/ani/notification_manager/src/sts_notification_request.cpp index e3b1030f4..f4924e5c4 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_request.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_request.cpp @@ -36,12 +36,16 @@ void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOption } std::vector supportDisplayDevices = {}; - if(GetStringArrayOrUndefined(env, obj, "supportDisplayDevices", supportDisplayDevices) == ANI_OK) { + isUndefined = ANI_TRUE; + if(GetStringArrayOrUndefined(env, obj, "supportDisplayDevices", isUndefined, supportDisplayDevices) == ANI_OK + && isUndefined == ANI_FALSE) { distributedOptions.supportDisplayDevices = supportDisplayDevices; } std::vector supportOperateDevices = {}; - if(GetStringArrayOrUndefined(env, obj, "supportOperateDevices", supportOperateDevices) == ANI_OK) { + isUndefined = ANI_TRUE; + if(GetStringArrayOrUndefined(env, obj, "supportOperateDevices", isUndefined, supportOperateDevices) == ANI_OK + && isUndefined == ANI_FALSE) { distributedOptions.supportOperateDevices = supportOperateDevices; } @@ -152,24 +156,25 @@ void GetNotificationRequestByBoolean(ani_env *env, ani_object obj, void GetNotificationRequestByString(ani_env *env, ani_object obj, std::shared_ptr &request) { std::string mString = ""; + ani_boolean isUndefined = ANI_TRUE; - if (ANI_OK == GetPropertyString(env, obj, "classification", mString)) { + if (ANI_OK == GetPropertyString(env, obj, "classification", isUndefined, mString) && isUndefined == ANI_FALSE) { request->SetClassification(mString); } - if (ANI_OK == GetPropertyString(env, obj, "appMessageId", mString)) { + if (ANI_OK == GetPropertyString(env, obj, "appMessageId", isUndefined, mString) && isUndefined == ANI_FALSE) { request->SetAppMessageId(mString); } - if (ANI_OK == GetPropertyString(env, obj, "label", mString)) { + if (ANI_OK == GetPropertyString(env, obj, "label", isUndefined, mString) && isUndefined == ANI_FALSE) { request->SetLabel(mString); } - if (ANI_OK == GetPropertyString(env, obj, "groupName", mString)) { + if (ANI_OK == GetPropertyString(env, obj, "groupName", isUndefined, mString) && isUndefined == ANI_FALSE) { request->SetGroupName(mString); } - if (ANI_OK == GetPropertyString(env, obj, "sound", mString)) { + if (ANI_OK == GetPropertyString(env, obj, "sound", isUndefined, mString) && isUndefined == ANI_FALSE) { request->SetSound(mString); } } @@ -420,7 +425,7 @@ ani_status GetNotificationActionButtonArrayOrUndefined(ani_env *env, ani_object return ANI_INVALID_ARGS; } - status = env->Object_GetPropertyByName_Double(reinterpret_cast(arrayObj), "length", &length); + status = env->Object_GetPropertyByName_Double(static_cast(arrayObj), "length", &length); if (status != ANI_OK) { ANS_LOGI("status : %{public}d", status); return status; @@ -428,7 +433,7 @@ ani_status GetNotificationActionButtonArrayOrUndefined(ani_env *env, ani_object for (int i = 0; i < static_cast(length); i++) { ani_ref buttonRef; - status = env->Object_CallMethodByName_Ref(reinterpret_cast(arrayObj), + status = env->Object_CallMethodByName_Ref(static_cast(arrayObj), "$_get", "I:Lstd/core/Object;", &buttonRef, (ani_int)i); if (status != ANI_OK) { ANS_LOGI("status : %{public}d, index: %{public}d", status, i); @@ -557,19 +562,24 @@ void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, std::shared_ptr unifiedGroupInfo = std::make_shared(); std::string mString = ""; - if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "key", mString)) { + isUndefind = ANI_TRUE; + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "key", isUndefind, mString) + && isUndefind == ANI_FALSE) { unifiedGroupInfo->SetKey(mString); } - if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "title", mString)) { + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "title", isUndefind, mString) + && isUndefind == ANI_FALSE) { unifiedGroupInfo->SetTitle(mString); } - if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "content", mString)) { + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "content", isUndefind, mString) + && isUndefind == ANI_FALSE) { unifiedGroupInfo->SetContent(mString); } - if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "sceneName", mString)) { + if (ANI_OK == GetPropertyString(env, static_cast(infoRef), "sceneName", isUndefind, mString) + && isUndefind == ANI_FALSE) { unifiedGroupInfo->SetSceneName(mString); } @@ -579,8 +589,8 @@ void GetNotificationUnifiedGroupInfo(ani_env *env, ani_object obj, return; } isUndefind = ANI_TRUE; - WantParams wantParams = {}; if ((status = env->Reference_IsUndefined(extraInfoRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { + WantParams wantParams = {}; UnwrapWantParams(env, extraInfoRef, wantParams); std::shared_ptr extras = std::make_shared(wantParams); unifiedGroupInfo->SetExtraInfo(extras); diff --git a/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp b/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp index 05ad41512..da67cd5d7 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_user_input.cpp @@ -22,8 +22,10 @@ ani_status UnwrapNotificationUserInput(ani_env *env, ani_object param, std::shar { ani_status status = ANI_ERROR; std::string inputKey; - if((status = GetPropertyString(env, param, "inputKey", inputKey)) != ANI_OK) { - return status; + ani_boolean isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, param, "inputKey", isUndefined, inputKey)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } userInput = NotificationUserInput::Create(inputKey); return status; diff --git a/frameworks/ani/notification_manager/src/sts_notification_utils.cpp b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp index 8f51be64b..1a7d6cf86 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_utils.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp @@ -65,20 +65,24 @@ ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resourc { ani_status status = ANI_ERROR; std::string bundleName = ""; - if((status = GetPropertyString(env, obj, "bundleName", bundleName)) != ANI_OK) { - return status; + ani_boolean isUndefined = ANI_TRUE; + if((status = GetPropertyString(env, obj, "bundleName", isUndefined, bundleName)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } resource.bundleName = bundleName; std::string moduleName = ""; - if((status = GetPropertyString(env, obj, "moduleName", moduleName)) != ANI_OK) { - return status; + if((status = GetPropertyString(env, obj, "moduleName", isUndefined, moduleName)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } resource.moduleName = moduleName; ani_double idAni = 0.0; - if((status = env->Object_GetPropertyByName_Double(obj, "id", &idAni)) != ANI_OK) { - return status; + if((status = GetPropertyDoubleOrUndefined(env, obj, "id", isUndefined, idAni)) != ANI_OK + || isUndefined == ANI_TRUE) { + return ANI_INVALID_ARGS; } resource.id = static_cast(idAni); return status; -- Gitee From afc18ce9703bdfc13ce743acc445dc5768f1648a Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Wed, 7 May 2025 16:12:06 +0800 Subject: [PATCH 5/9] =?UTF-8?q?feat:notificationmanager=20ani=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- .../ets/@ohos.notificationManager.ets | 15 +++++-- .../ets/notification/notificationContent.ets | 2 +- .../include/sts_common_util.h | 2 +- .../src/sts_common_util.cpp | 43 +++++++++++++++++++ .../src/sts_notification_manager.cpp | 27 ++++++++++-- 5 files changed, 80 insertions(+), 9 deletions(-) diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index f9f7ca3fa..01c774f45 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -66,9 +66,11 @@ export default namespace notificationManager { export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); p.then((e: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } @@ -88,9 +90,12 @@ export default namespace notificationManager { let p = taskpool.execute((): boolean => { return nativeIsBadgeDisplayed(bundle); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); }) } @@ -345,10 +350,12 @@ export default namespace notificationManager { let p = taskpool.execute((): Array => { return nativeGetSlotsByBundle(bundle); }); p.then((data: NullishType): void => { let slots : Array = data as Array; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, slots); }, (error: Object): void => { - console.log("getSlotsByBundle error", error) + let slots : Array = []; + let err: BusinessError = error as BusinessError; + callback(err, slots); }) } diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets index 712e66d63..bb93f984a 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -22,7 +22,7 @@ type IconType = Resource | image.PixelMap; export class RecordTools { public static GetKeys(obj: Record): Array { try { - let keys: Array = Object.keys(record); + let keys: Array = Object.keys(obj); return keys; } catch (err) { return {}; diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index f2c3fb265..fd6081b97 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -46,7 +46,7 @@ bool SetOptionalFieldArrayDouble(ani_env *env, ani_class cls, ani_object object, bool SetOptionalFieldSlotType(ani_env *env, ani_class cls, ani_object object, const std::string &fieldName, const Notification::NotificationConstant::SlotType& value); - +std::string FindAnsErrMsg(const int32_t errCode); ani_object newArrayClass(ani_env *env, int length); ani_object createBoolean(ani_env *env, ani_boolean value); diff --git a/frameworks/ani/notification_manager/src/sts_common_util.cpp b/frameworks/ani/notification_manager/src/sts_common_util.cpp index 97395e10a..c55b0890d 100644 --- a/frameworks/ani/notification_manager/src/sts_common_util.cpp +++ b/frameworks/ani/notification_manager/src/sts_common_util.cpp @@ -17,10 +17,43 @@ #include "ans_log_wrapper.h" #include "securec.h" #include "sts_notification_enum_type.h" +#include "ans_inner_errors.h" +using namespace OHOS::Notification; namespace OHOS { namespace NotificationSts { +static const std::unordered_map ERROR_CODE_TO_MESSAGE { + {ERROR_PERMISSION_DENIED, "Permission denied"}, + {ERROR_NOT_SYSTEM_APP, "The application isn't system application"}, + {ERROR_PARAM_INVALID, "Invalid parameter"}, + {ERROR_SYSTEM_CAP_ERROR, "SystemCapability not found"}, + {ERROR_INTERNAL_ERROR, "Internal error"}, + {ERROR_IPC_ERROR, "Marshalling or unmarshalling error"}, + {ERROR_SERVICE_CONNECT_ERROR, "Failed to connect to the service"}, + {ERROR_NOTIFICATION_CLOSED, "Notification disabled"}, + {ERROR_SLOT_CLOSED, "Notification slot disabled"}, + {ERROR_NOTIFICATION_UNREMOVABLE, "Notification deletion disabled"}, + {ERROR_NOTIFICATION_NOT_EXIST, "The notification does not exist"}, + {ERROR_USER_NOT_EXIST, "The user does not exist"}, + {ERROR_OVER_MAX_NUM_PER_SECOND, "The notification sending frequency reaches the upper limit"}, + {ERROR_DISTRIBUTED_OPERATION_FAILED, "Distributed operation failed"}, + {ERROR_READ_TEMPLATE_CONFIG_FAILED, "Failed to read the template configuration"}, + {ERROR_NO_MEMORY, "No memory space"}, + {ERROR_BUNDLE_NOT_FOUND, "The specified bundle name was not found"}, + {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, + {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, + {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, + {ERROR_NO_PROFILE_TEMPLATE, "Not exit noNotDisturb profile template"}, + {ERROR_REPEAT_SET, "Repeat create or end"}, + {ERROR_NO_RIGHT, "No permission"}, + {ERROR_EXPIRED_NOTIFICATION, "Low update version"}, + {ERROR_NETWORK_UNREACHABLE, "Network unreachable"}, + {ERROR_REJECTED_WITH_DISABLE_NOTIFICATION, + "The application is not allowed to publish notifications due to permission control settings"}, + {ERROR_DISTRIBUTED_OPERATION_TIMEOUT, "Distributed operation timeout"}, +}; + constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; @@ -421,5 +454,15 @@ bool SetOptionalFieldSlotType(ani_env *env, ani_class cls, ani_object object, co return true; } +std::string FindAnsErrMsg(const int32_t errCode) +{ + auto findMsg = ERROR_CODE_TO_MESSAGE.find(errCode); + if (findMsg == ERROR_CODE_TO_MESSAGE.end()) { + ANSR_LOGI("FindAnsErrMsg Inner error."); + return "Inner error."; + } + return findMsg->second; +} + } } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index f0ebcf930..d74a040c2 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -39,7 +39,14 @@ static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) ANS_LOGD("sts DisplayBadge option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), option.GetUid()); int ret = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, AniBooleanToBool(enable)); - ANS_LOGD("sts DisplayBadge end, ret: %{public}d", CJSystemapi::Notification::ErrorToExternal(ret)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != 0) + { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts DisplayBadge error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts DisplayBadge end, ret: %{public}d", externalCode); } static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) @@ -56,8 +63,15 @@ static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) } else { returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); } + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != 0) + { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts IsBadgeDisplayed error, errorCode: %{public}d", externalCode); + return BoolToAniBoolean(false); + } ANS_LOGD("sts IsBadgeDisplayed end, isDisplayed: %{public}d, returncode: %{public}d", isDisplayed, - CJSystemapi::Notification::ErrorToExternal(returncode)); + externalCode); return BoolToAniBoolean(isDisplayed); } @@ -216,9 +230,16 @@ static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) option.GetUid()); std::vector> slots; auto ret = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != 0) + { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts GetSlotsByBundle error, errorCode: %{public}d", externalCode); + return nullptr; + } ani_object outAniObj; WrapNotificationSlotArray(env, slots, outAniObj); - ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", CJSystemapi::Notification::ErrorToExternal(ret)); + ANS_LOGD("sts GetSlotsByBundle end, ret: %{public}d", externalCode); return outAniObj; } -- Gitee From a2680d196fbf205b26b6a9eed3e8af0ac4ff108a Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Thu, 8 May 2025 15:34:16 +0800 Subject: [PATCH 6/9] =?UTF-8?q?feat:notification=20ani=E5=8C=96Notificatio?= =?UTF-8?q?nRequest=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- .../ets/@ohos.notificationManager.ets | 21 +- .../ets/notification/notificationContent.ets | 190 ++++- .../ets/notification/notificationRequest.ets | 53 ++ .../include/sts_common_util.h | 174 +++++ .../include/sts_notification_utils.h | 7 +- .../src/sts_common_util.cpp | 21 + .../src/sts_notification_content.cpp | 657 +++++++++++++++++- .../src/sts_notification_manager.cpp | 39 +- .../src/sts_notification_request.cpp | 389 ++++++++++- .../src/sts_notification_utils.cpp | 25 + 10 files changed, 1525 insertions(+), 51 deletions(-) diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index 01c774f45..483ffb517 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -48,7 +48,7 @@ export default namespace notificationManager { export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; export native function nativeGetActiveNotificationCount(): number; - export native function nativeIsNotificationEnabled(userId?: int, bundleOption?: BundleOption): boolean; + export native function nativeIsNotificationEnabled(userId?: number, bundleOption?: BundleOption): boolean; export native function nativegetSlotFlagsByBundle(bundle: BundleOption): int; export native function nativesetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; @@ -125,18 +125,21 @@ export default namespace notificationManager { return pPromise; } - export function isNotificationEnabled(userId: int, callback: AsyncCallback): void + export function isNotificationEnabled(userId: number, callback: AsyncCallback): void { let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); }) } - export function isNotificationEnabled(userId: int): Promise + export function isNotificationEnabled(userId: number): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); @@ -155,9 +158,12 @@ export default namespace notificationManager { let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); }) } @@ -180,9 +186,12 @@ export default namespace notificationManager { let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); }) } diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets index bb93f984a..94e5e2a89 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -20,9 +20,9 @@ import type notificationManager from '@ohos.notificationManager'; type IconType = Resource | image.PixelMap; export class RecordTools { - public static GetKeys(obj: Record): Array { + public static GetKeys(record: Record): Array { try { - let keys: Array = Object.keys(obj); + let keys: Array = Object.keys(record); return keys; } catch (err) { return {}; @@ -41,6 +41,17 @@ export interface NotificationBasicContent { lockscreenPicture?: image.PixelMap; } +class NotificationBasicContentInner implements NotificationBasicContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; +} + export interface NotificationLongTextContent extends NotificationBasicContent { longText: string; @@ -50,6 +61,23 @@ export interface NotificationLongTextContent extends NotificationBasicContent { expandedTitle: string; } +class NotificationLongTextContentInner implements NotificationLongTextContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; + + longText: string; + + briefText: string; + + expandedTitle: string; +} + export enum LiveViewStatus { LIVE_VIEW_CREATE = 0, @@ -83,6 +111,27 @@ export interface NotificationLiveViewContent extends NotificationBasicContent { isLocalUpdateOnly?: boolean; } +class NotificationLiveViewContentInner implements NotificationLiveViewContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; + + status: LiveViewStatus; + + version?: number; + + extraInfo?: Record; + + pictureInfo?: Record>; + + isLocalUpdateOnly?: boolean; +} + export interface NotificationMultiLineContent extends NotificationBasicContent { briefText: string; @@ -92,6 +141,23 @@ export interface NotificationMultiLineContent extends NotificationBasicContent { lines: Array; } +class NotificationMultiLineContentInner implements NotificationMultiLineContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; + + briefText: string; + + longTitle: string; + + lines: Array; +} + export interface NotificationPictureContent extends NotificationBasicContent { briefText: string; @@ -101,6 +167,23 @@ export interface NotificationPictureContent extends NotificationBasicContent { picture: image.PixelMap; } +class NotificationPictureContentInner implements NotificationPictureContent { + + title: string; + + text: string; + + additionalText?: string; + + lockscreenPicture?: image.PixelMap; + + briefText: string; + + expandedTitle: string; + + picture: image.PixelMap; +} + export interface NotificationSystemLiveViewContent extends NotificationBasicContent { typeCode: number; @@ -118,6 +201,37 @@ export interface NotificationSystemLiveViewContent extends NotificationBasicCont liveViewType?: LiveViewTypes; } +class NotificationSystemLiveViewContentInner implements NotificationSystemLiveViewContent { + + briefText: string; + + expandedTitle: string; + + picture: image.PixelMap; + + typeCode: number; + + capsule?: NotificationCapsule; + + button?: NotificationButton; + + cardButtons?: Array; + + time?: NotificationTime; + + progress?: NotificationProgress; + + liveViewType?: LiveViewTypes; + + get title(): string { + return this.title; + } + + set title(value: string) { + this.title = value; + } +} + export interface NotificationCapsule { title?: string; @@ -133,6 +247,21 @@ export interface NotificationCapsule { capsuleButtons?: Array; } +class NotificationCapsuleInner implements NotificationCapsule { + + title?: string; + + icon?: image.PixelMap; + + backgroundColor?: string; + + content?: string; + + time?: number; + + capsuleButtons?: Array; +} + export interface NotificationIconButton { name: string; @@ -144,6 +273,17 @@ export interface NotificationIconButton { hidePanel?: boolean; } +class NotificationIconButtonInner implements NotificationIconButton { + + name: string; + + iconResource: IconType; + + text?: string; + + hidePanel?: boolean; +} + export interface NotificationButton { names?: Array; @@ -153,6 +293,15 @@ export interface NotificationButton { iconsResource?: Array; } +class NotificationButtonInner implements NotificationButton { + + names?: Array; + + icons?: Array; + + iconsResource?: Array; +} + export interface NotificationTime { initialTime?: number; @@ -164,6 +313,17 @@ export interface NotificationTime { isInTitle?: boolean; } +class NotificationTimeInner implements NotificationTime { + + initialTime?: number; + + isCountDown?: boolean; + + isPaused?: boolean; + + isInTitle?: boolean; +} + export interface NotificationProgress { maxValue?: number; @@ -173,6 +333,15 @@ export interface NotificationProgress { isPercentage?: boolean; } +class NotificationProgressInner implements NotificationProgress { + + maxValue?: number; + + currentValue?: number; + + isPercentage?: boolean; +} + export interface NotificationContent { notificationContentType?: notificationManager.ContentType; @@ -187,5 +356,22 @@ export interface NotificationContent { systemLiveView?: NotificationSystemLiveViewContent; + liveView?: NotificationLiveViewContent; +} + +class NotificationContentInner implements NotificationContent { + + notificationContentType?: notificationManager.ContentType; + + normal?: NotificationBasicContent; + + longText?: NotificationLongTextContent; + + multiLine?: NotificationMultiLineContent; + + picture?: NotificationPictureContent; + + systemLiveView?: NotificationSystemLiveViewContent; + liveView?: NotificationLiveViewContent; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets index c928d8edb..ea7236275 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets @@ -73,6 +73,59 @@ export interface NotificationRequest { forceDistributed?: boolean; notDistributed?: boolean; } + +class NotificationRequestInner implements NotificationRequest { + content: NotificationContent; + id?: number; + appMessageId?: string; + notificationSlotType?: notificationManager.SlotType; + isOngoing?: boolean; + isUnremovable?: boolean; + updateOnly?: boolean; + deliveryTime?: number; + tapDismissed?: boolean; + autoDeletedTime?: number; + wantAgent?: WantAgent; + extraInfo?: Record; + color?: number; + colorEnabled?: boolean; + isAlertOnce?: boolean; + isStopwatch?: boolean; + isCountDown?: boolean; + isFloatingIcon?: boolean; + label?: string; + badgeIconStyle?: number; + showDeliveryTime?: boolean; + actionButtons?: Array; + smallIcon?: image.PixelMap; + largeIcon?: image.PixelMap; + overlayIcon?: image.PixelMap; + groupName?: string; + readonly creatorBundleName?: string; + readonly creatorUid?: number; + readonly creatorPid?: number; + readonly creatorUserId?: number; + readonly creatorInstanceKey?: number; + sound?: string; + classification?: string; + readonly hashCode?: string; + isRemoveAllowed?: boolean; + readonly source?: number; + template?: NotificationTemplate; + distributedOption?: DistributedOptions; + readonly deviceId?: string; + readonly notificationFlags?: NotificationFlags; + removalWantAgent?: WantAgent; + badgeNumber?: number; + representativeBundle?: BundleOption; + readonly agentBundle?: BundleOption; + unifiedGroupInfo?: UnifiedGroupInfo; + notificationControlFlags?: number; + readonly appInstanceKey?: string; + forceDistributed?: boolean; + notDistributed?: boolean; +} + export interface DistributedOptions { isDistributed?: boolean; supportDisplayDevices?: Array; diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index fd6081b97..d84e4043d 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -25,6 +25,8 @@ namespace OHOS { namespace NotificationSts { static const char *NotificationSlotClassName = "Lnotification/notificationSlot/NotificationSlotInner;"; +bool GetAniString(ani_env* env, const std::string str, ani_string& aniStr); +ani_string GetAniString(ani_env* env, const std::string str); ani_status GetStdString(ani_env *env, ani_string str, std::string &res); ani_status GetPropertyRef(ani_env *env, ani_object obj, const char *name, ani_ref &ref, ani_boolean &isUndefined); ani_status GetPropertyString(ani_env *env, ani_object obj, const char *name, @@ -62,6 +64,57 @@ inline ani_boolean BoolToAniBoolean(bool value) return value ? ANI_TRUE : ANI_FALSE; } +template +static ani_object ConvertToAniArrayString(ani_env* env, + const containerType& nativeArray, Converter converter, Args&&... args) +{ + ani_class arrayCls = nullptr; + ani_status status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("FindClass failed %{public}d", status); + return nullptr; + } + + ani_method arrayCtor; + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod failed %{public}d", status); + return nullptr; + } + + ani_size length = nativeArray.size(); + ani_object arrayObj; + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, length); + if (status != ANI_OK) { + ANS_LOGE("Object_New failed %{public}d", status); + return nullptr; + } + + ani_size i = 0; + for (const auto& iter : nativeArray) { + ani_object item = converter(env, iter, std::forward(args)...); + status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, item); + env->Reference_Delete(item); + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + ++i; + } + + return arrayObj; +} + +[[maybe_unused]]static ani_object ConvertVectorToAniArrayString(ani_env* env, + const std::vector& strings) +{ + return ConvertToAniArrayString(env, strings, [](ani_env* env, const std::string& nativeStr) { + ani_string aniStr = nullptr; + return GetAniString(env, nativeStr) ? aniStr : nullptr; + }); +} + + #define ANI_FAILED_AND_RETURN(status) \ do \ { \ @@ -73,6 +126,127 @@ do } \ } while (0) +#define RETURN_NULL_IF_NULL(ptr) \ + do { \ + if ((ptr) == nullptr) { \ + ANS_LOGE("ptr is null"); \ + return nullptr; \ + } \ + } while (0) +#define RETURN_FALSE_IF_NULL(ptr) \ + do { \ + if ((ptr) == nullptr) { \ + ANS_LOGE("ptr is null"); \ + return false; \ + } \ + } while (0) +#define RETURN_NULL_IF_FALSE(condition) \ + do { \ + if (!(condition)) { \ + ANS_LOGE("condition is false"); \ + return nullptr; \ + } \ + } while (0) +#define RETURN_FALSE_IF_FALSE(condition) \ + do { \ + if (!(condition)) { \ + return false; \ + } \ + } while (0) +#define RETURN_ANI_STATUS_IF_NOT_OK(res, err) \ + do { \ + if ((res) != ANI_OK) { \ + ANS_LOGE(err); \ + return res; \ + } \ + } while (0) + +template +bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + std::string setterName(""); + setterName.append(propertyName); + ani_method setter; + ani_status status = env->Class_FindMethod(cls, setterName.c_str(), nullptr, &setter); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod %{public}s failed %{public}d", propertyName, status); + return false; + } + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v) { + status = env->Object_CallMethod_Void(object, setter, static_cast(value)); + } else { + status = env->Object_CallMethod_Void(object, setter, value); + } + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethod_Void %{public}s failed %{public}d", propertyName, status); + return false; + } + return true; +} + +template +bool CallSetterOptional( + ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) +{ + RETURN_FALSE_IF_NULL(env); + RETURN_FALSE_IF_NULL(cls); + RETURN_FALSE_IF_NULL(object); + if constexpr (std::is_pointer_v && std::is_base_of_v<__ani_ref, std::remove_pointer_t>) { + return CallSetter(env, cls, object, propertyName, value); + } + const char* valueClassName = nullptr; + const char* ctorSig = nullptr; + if constexpr (std::is_same_v) { + valueClassName = "Lstd/core/Boolean;"; + ctorSig = "Z:V"; + } else if constexpr (std::is_same_v) { + valueClassName = "Lstd/core/Char;"; + ctorSig = "C:V"; + } else if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v) { + valueClassName = "Lstd/core/Double;"; + ctorSig = "D:V"; + } else { + ANS_LOGE("Classname %{public}s Unsupported", propertyName); + return false; + } + ani_class valueClass = nullptr; + ani_status status = env->FindClass(valueClassName, &valueClass); + if (status != ANI_OK) { + ANS_LOGE("FindClass %{public}s %{public}s failed %{public}d", propertyName, valueClassName, status); + return false; + } + ani_method ctor = nullptr; + status = env->Class_FindMethod(valueClass, "", ctorSig, &ctor); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod %{public}s failed %{public}d", propertyName, status); + return false; + } + ani_object valueObj = nullptr; + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v) { + status = env->Object_New(valueClass, ctor, &valueObj, static_cast(value)); + } else { + ANS_LOGE("Classname %{public}s Unsupported", propertyName); + return false; + } + if (status != ANI_OK) { + ANS_LOGE("Object_New %{public}s failed %{public}d", propertyName, status); + return false; + } + return CallSetter(env, cls, object, propertyName, valueObj); +} + } // namespace NotificationSts } // namespace OHOS #endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_utils.h b/frameworks/ani/notification_manager/include/sts_notification_utils.h index c6d08ebe9..b7e11c416 100644 --- a/frameworks/ani/notification_manager/include/sts_notification_utils.h +++ b/frameworks/ani/notification_manager/include/sts_notification_utils.h @@ -51,6 +51,7 @@ using namespace OHOS::Media; void UnwrapWantAgent(ani_env *env, ani_object agent, void** result); std::shared_ptr GetPixelMapFromEnvSp([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object obj); +ani_object CreatePixelMap([[maybe_unused]] ani_env* env, std::shared_ptr pixelMap); ani_status UnwrapResource(ani_env *env, ani_object obj, ResourceManager::Resource resource); ani_status UnwrapNotificationTemplate(ani_env *env, @@ -85,8 +86,12 @@ void UnWarpNotificationCapsule(ani_env *env, ani_object obj, ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, std::shared_ptr &localLiveViewContent); /* NotificationRequest */ -void UnWarpNotificationRequest(ani_env *env, ani_object obj, +ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, std::shared_ptr ¬ificationRequest); + +ani_object WarpNotificationRequest(ani_env *env, std::shared_ptr notificationRequest); +bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object); } } #endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_common_util.cpp b/frameworks/ani/notification_manager/src/sts_common_util.cpp index c55b0890d..ec01ec102 100644 --- a/frameworks/ani/notification_manager/src/sts_common_util.cpp +++ b/frameworks/ani/notification_manager/src/sts_common_util.cpp @@ -57,6 +57,27 @@ static const std::unordered_map ERROR_CODE_TO_MESSAGE { constexpr const char* CLASSNAME_BOOLEAN = "Lstd/core/Boolean;"; constexpr const char* CLASSNAME_DOUBLE = "Lstd/core/Double;"; +bool GetAniString(ani_env* env, const std::string str, ani_string& aniStr) +{ + ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); + if (status != ANI_OK) { + ANS_LOGE("String_NewUTF8 failed %{public}d", status); + return false; + } + return true; +} + +ani_string GetAniString(ani_env* env, const std::string str) +{ + ani_string aniStr; + ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); + if (status != ANI_OK) { + ANS_LOGE("String_NewUTF8 failed %{public}d", status); + return nullptr; + } + return aniStr; +} + ani_status GetStdString(ani_env *env, ani_string str, std::string &res) { ani_size sz {}; diff --git a/frameworks/ani/notification_manager/src/sts_notification_content.cpp b/frameworks/ani/notification_manager/src/sts_notification_content.cpp index 2cc668a8a..61ddbbf32 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_content.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_content.cpp @@ -13,12 +13,12 @@ * limitations under the License. */ -#include "sts_notification_utils.h" -#include "sts_common_util.h" +#include "ani_common_want.h" #include "ans_log_wrapper.h" #include "pixel_map_ani.h" +#include "sts_common_util.h" #include "sts_notification_enum_type.h" -#include "ani_common_want.h" +#include "sts_notification_utils.h" #include "want_params.h" namespace OHOS { @@ -503,7 +503,7 @@ ani_status GetKeyString(ani_env *env, ani_object obj, int index, ani_string &str return status; } -ani_status GetMapByKeys(ani_env *env, ani_object obj, std::vector keys, +ani_status GetPixelMapByKeys(ani_env *env, ani_object obj, std::vector keys, std::map>> &pictureMap) { ani_status status = ANI_ERROR; @@ -566,7 +566,7 @@ ani_status GetPictureInfoMap(ani_env *env, ani_object obj, } keys.push_back(strAni); } - status = GetMapByKeys(env, obj, keys, pictureMap); + status = GetPixelMapByKeys(env, obj, keys, pictureMap); return status; } @@ -684,5 +684,652 @@ ani_status UnWarpNotificationLocalLiveViewContent(ani_env *env, ani_object obj, return status; } + +ani_object GetWantAgentArrayAniObject(ani_env *env, std::vector> wantAgents) +{ + ani_status status = ANI_ERROR; + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, wantAgents.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + // need to do + //ani_size index = 0; + //for (auto &wantAgent : wantAgents) { + //need to do Convert wantAgent to ani object + // ani_object item = ConvertNotificationIconButtonToAniObject(env, button); + //RETURN_NULL_IF_NULL(item); + //if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + // std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + // return nullptr; + //} + //index ++; + //} + return arrayObj; +} + +ani_object SetResourceObject(ani_env *env, const std::shared_ptr &resource) +{ + ani_class resourceCls = nullptr; + ani_object resourceObject = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lglobal/resource/ResourceInner;", resourceCls, resourceObject)); + // bundleName: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniString(env, resource->bundleName, stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "bundleName", stringValue)); + // moduleName: string; + RETURN_NULL_IF_FALSE(GetAniString(env, resource->moduleName, stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "moduleName", stringValue)); + // id: number; + RETURN_NULL_IF_FALSE(CallSetter(env, resourceCls, resourceObject, "id", resource->id)); + + // need to do check + //napiдʱûиѡֶδDzǾͲôˣ + /* params?: Array; + type?: number; */ + return resourceObject; +} + +ani_object ConvertNotificationIconButtonToAniObject(ani_env *env, const NotificationIconButton &button) +{ + ani_class iconButtonCls = nullptr; + ani_object iconButtonObject = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationIconButtonInner;", iconButtonCls, iconButtonObject)); + // name: string + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniString(env, button.GetName(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "name", stringValue)); + // text?: string; + RETURN_NULL_IF_FALSE(GetAniString(env, button.GetText(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "text", stringValue)); + // hidePanel?: boolean; + RETURN_NULL_IF_FALSE(CallSetterOptional( + env, iconButtonCls, iconButtonObject, "hidePanel", BoolToAniBoolean(button.GetHidePanel()))); + // iconResource: IconType; type IconType = Resource | image.PixelMap; + std::shared_ptr icon = button.GetIconImage(); + if (icon) { + ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, icon); + if (pixelMapObject == nullptr) { + ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); + return nullptr; + } + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", pixelMapObject)); + } else { + ani_object resourceObject = SetResourceObject(env, button.GetIconResource()); + if (resourceObject == nullptr) { + ANS_LOGE("SetResourceObject failed, resourceObject is nullptr"); + return nullptr; + } + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "iconResource", resourceObject)); + } + return iconButtonObject; +} + +bool SetTime(ani_env *env, const NotificationTime &time, bool isInitialTimeExist, ani_object &timeObject) +{ + ani_class timeClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationTimeInner;", timeClass, timeObject)); + // initialTime?: number; + if (isInitialTimeExist) { + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "initialTime", + time.GetInitialTime())); + } + // isCountDown?: boolean; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isCountDown", + BoolToAniBoolean(time.GetIsCountDown()))); + // isPaused?: boolean; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isPaused", + BoolToAniBoolean(time.GetIsPaused()))); + // isInTitle?: boolean; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, timeClass, timeObject, "isInTitle", + BoolToAniBoolean(time.GetIsInTitle()))); + return true; +} + +ani_object ConvertVectorToAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps) +{ + RETURN_NULL_IF_NULL(env); + if (pixelMaps.size() <= 0) { + return nullptr; + } + + ani_class arrayCls = nullptr; + ani_status status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("FindClass failed %{public}d", status); + return nullptr; + } + + ani_method arrayCtor; + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod failed %{public}d", status); + return nullptr; + } + + ani_size length = pixelMaps.size(); + ani_object arrayObj; + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, length); + if (status != ANI_OK) { + ANS_LOGE("Object_New failed %{public}d", status); + return nullptr; + } + ani_size i = 0; + for (auto &pixelMap : pixelMaps) { + ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, pixelMap); + if (pixelMapObject == nullptr) { + ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); + return nullptr; + } + status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, pixelMapObject); + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + return arrayObj; +} + +ani_object ConvertVectorToAniArrayResource(ani_env *env, + const std::vector> &resources) +{ + if (resources.empty()) { + ANS_LOGE("resources is empty"); + return nullptr; + } + ani_class arrayCls = nullptr; + ani_status status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("FindClass failed %{public}d", status); + return nullptr; + } + + ani_method arrayCtor; + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("Class_FindMethod failed %{public}d", status); + return nullptr; + } + + ani_size length = resources.size(); + ani_object arrayObj; + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, length); + if (status != ANI_OK) { + ANS_LOGE("Object_New failed %{public}d", status); + return nullptr; + } + ani_size i = 0; + for (auto &resource : resources) { + ani_object resourceObject = SetResourceObject(env, resource); + if (resourceObject == nullptr) { + ANS_LOGE("SetResourceObject failed, resourceObject is nullptr"); + return nullptr; + } + status = env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", i, resourceObject); + if (status != ANI_OK) { + ANS_LOGE("Object_CallMethodByName_Void failed %{public}d", status); + return nullptr; + } + i++; + } + return arrayObj; +} + +bool SetButton(ani_env *env, const NotificationLocalLiveViewButton &button, ani_object &buttonObject) +{ + ani_class buttonClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationButtonInner;", buttonClass, buttonObject)); + // names?: Array; + std::vector names = button.GetAllButtonNames(); + ani_object namesObjectArray = ConvertVectorToAniArrayString(env, names); + if (namesObjectArray == nullptr) { + ANS_LOGE("namesObjectArray is nullptr"); + return false; + } + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, buttonClass, buttonObject, "names", namesObjectArray)); + // icons?: Array; + std::vector> icons = button.GetAllButtonIcons(); + ani_object iconsObjectArray = ConvertVectorToAniArrayPixelMap(env, icons); + if (iconsObjectArray == nullptr) { + ANS_LOGE("iconsObjectArray is nullptr"); + return false; + } + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, buttonClass, buttonObject, "icons", iconsObjectArray)); + // iconsResource?: Array; + std::vector> iconsResource = button.GetAllButtonIconResource(); + ani_object resourceObjectArray = ConvertVectorToAniArrayResource(env, iconsResource); + if (resourceObjectArray == nullptr) { + ANS_LOGE("resourceObjectArray is nullptr"); + return false; + } + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, buttonClass, buttonObject, "iconsResource", resourceObjectArray)); + return true; +} + +bool SetProgress(ani_env *env, const NotificationProgress &progress, ani_object &progressObject) +{ + ani_class progressClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationProgressInner;", progressClass, progressObject)); + // maxValue?: number; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "maxValue", + progress.GetMaxValue())); + // currentValue?: number; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "currentValue", + progress.GetCurrentValue())); + // isPercentage?: boolean; + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, progressClass, progressObject, "isPercentage", + BoolToAniBoolean(progress.GetIsPercentage()))); + return true; +} + +ani_object SetCardButton(ani_env *env, const std::vector buttons) +{ + ani_status status = ANI_ERROR; + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, buttons.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_size index = 0; + for (auto &button : buttons) { + ani_object item = ConvertNotificationIconButtonToAniObject(env, button); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; +} + +bool SetCapsule(ani_env *env, const NotificationCapsule &capsule, ani_object &capsuleObject) +{ + ani_class capsuleClass = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationCapsuleInner;", capsuleClass, capsuleObject)); + // title?: string; + ani_string stringValue = nullptr; + if(GetAniString(env, capsule.GetTitle(), stringValue)) { + CallSetterOptional(env, capsuleClass, capsuleObject, "title", stringValue); + } + // icon?: image.PixelMap; + std::shared_ptr icon = capsule.GetIcon(); + if (icon) { + ani_object pixelMapObject = Media::PixelMapAni::CreatePixelMap(env, icon); + if (pixelMapObject == nullptr) { + ANS_LOGE("CreatePixelMap failed, pixelMapObject is nullptr"); + } else { + CallSetterOptional(env, capsuleClass, capsuleObject, "icon", pixelMapObject); + } + } + // backgroundColor?: string; + if(GetAniString(env, capsule.GetBackgroundColor(), stringValue)) { + CallSetterOptional(env, capsuleClass, capsuleObject, "backgroundColor", stringValue); + } + //content?: string; + if(GetAniString(env, capsule.GetContent(), stringValue)) { + CallSetterOptional(env, capsuleClass, capsuleObject, "content", stringValue); + } + // time?: number; + CallSetterOptional(env, capsuleClass, capsuleObject, "time", capsule.GetTime()); + // capsuleButtons?: Array; + std::vector buttons = capsule.GetCapsuleButton(); + ani_object buttonsObjectArray = SetCardButton(env, buttons); + if (buttonsObjectArray != nullptr) { + CallSetterOptional(env, capsuleClass, capsuleObject, "capsuleButtons", buttonsObjectArray); + } + return true; +} + +bool SetNotificationBasicContent( + ani_env* env, ani_class contentCls, const NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + ani_string aniStr; + if(GetAniString(env, basicContent->GetTitle(), aniStr)) { + CallSetterOptional(env, contentCls, object, "title", aniStr); + } + if(GetAniString(env, basicContent->GetText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "text", aniStr); + } + if(GetAniString(env, basicContent->GetAdditionalText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "additionalText", aniStr); + } + ani_object lockScreenPicObj = CreatePixelMap(env, basicContent->GetLockScreenPicture()); + if (lockScreenPicObj != nullptr) { + CallSetter(env, contentCls, object, "lockScreenPicture", lockScreenPicObj); + } + return true; +} + +bool SetNotificationLongTextContent( + ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter SetNotificationLongTextContent"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + NotificationLongTextContent *content = static_cast(basicContent); + if (content == nullptr) { + ANS_LOGE("longTextContent is null"); + return false; + } + SetNotificationBasicContent(env, contentCls, content, object); + + ani_string aniStr; + if(GetAniString(env, content->GetLongText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "longText", aniStr); + } + if(GetAniString(env, content->GetBriefText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "briefText", aniStr); + } + if(GetAniString(env, content->GetExpandedTitle(), aniStr)) { + CallSetterOptional(env, contentCls, object, "expandedTitle", aniStr); + } + return true; +} + +bool SetNotificationPictureContent( + ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter SetNotificationPictureContent"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + NotificationPictureContent *content = static_cast(basicContent); + if (content == nullptr) { + ANS_LOGE("longTextContent is null"); + return false; + } + SetNotificationBasicContent(env, contentCls, content, object); + + ani_string aniStr; + if(GetAniString(env, content->GetBriefText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "briefText", aniStr); + } + if(GetAniString(env, content->GetExpandedTitle(), aniStr)) { + CallSetterOptional(env, contentCls, object, "expandedTitle", aniStr); + } + ani_object pictureObj = CreatePixelMap(env, content->GetBigPicture()); + if (pictureObj != nullptr) { + CallSetter(env, contentCls, object, "picture", pictureObj); + } + return true; +} + +bool SetNotificationMultiLineContent( + ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter SetNotificationMultiLineContent"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + NotificationMultiLineContent *content = static_cast(basicContent); + if (content == nullptr) { + ANS_LOGE("longTextContent is null"); + return false; + } + SetNotificationBasicContent(env, contentCls, content, object); + + ani_string aniStr; + if(GetAniString(env, content->GetBriefText(), aniStr)) { + CallSetterOptional(env, contentCls, object, "briefText", aniStr); + } + if(GetAniString(env, content->GetExpandedTitle(), aniStr)) { + CallSetterOptional(env, contentCls, object, "longTitle", aniStr); + } + std::vector allLines = content->GetAllLines(); + ani_object allLinesObject = ConvertVectorToAniArrayString(env, allLines); + CallSetter(env, contentCls, object, "lines", allLinesObject); + //need to do : lineWantAgents: Array GetLineWantAgents + ani_object lineWantAgentsObject = GetWantAgentArrayAniObject(env, content->GetLineWantAgents()); + CallSetter(env, contentCls, object, "lineWantAgents", lineWantAgentsObject); + return true; +} + +bool SetNotificationLocalLiveViewContent( + ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + NotificationLocalLiveViewContent *content = static_cast(basicContent); + if (content == nullptr) { + ANS_LOGE("longTextContent is null"); + return false; + } + SetNotificationBasicContent(env, contentCls, content, object); + + CallSetterOptional(env, contentCls, object, "typeCode", content->GetType()); + + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE)) { + ani_object capsuleObject = nullptr; + if(SetCapsule(env, content->GetCapsule(), capsuleObject) && capsuleObject != nullptr) { + CallSetter(env, contentCls, object, "capsule", capsuleObject); + } + } + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::BUTTON)) { + // need to do : SetButton(env, localLiveViewContent->GetButton(), button) + // button: NotificationLocalLiveViewButton + ani_object buttonObject = nullptr; + if(SetButton(env, content->GetButton(), buttonObject) && buttonObject != nullptr) { + CallSetter(env, contentCls, object, "button", buttonObject); + } + } + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::CARD_BUTTON)) { + std::vector buttons = content->GetCardButton(); + ani_object buttonsObjectArray = SetCardButton(env, buttons); + if (buttonsObjectArray != nullptr) { + CallSetterOptional(env, contentCls, object, "cardButtons", buttonsObjectArray); + } + } + + ani_enum_item enumItem = nullptr; + if(LiveViewTypesCToEts(env, content->GetLiveViewType(), enumItem) && enumItem != nullptr) { + CallSetter(env, contentCls, object, "liveViewType", enumItem); + } + + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::PROGRESS)) { + ani_object progressObject = nullptr; + if(SetProgress(env, content->GetProgress(), progressObject) && progressObject != nullptr) { + CallSetter(env, contentCls, object, "progress", progressObject); + } + } + + if (content->isFlagExist(NotificationLocalLiveViewContent::LiveViewContentInner::TIME)) { + bool flag = content->isFlagExist( + NotificationLocalLiveViewContent::LiveViewContentInner::INITIAL_TIME); + ani_object timeObject = nullptr; + if(SetTime(env, content->GetTime(), flag, timeObject) && timeObject != nullptr) { + CallSetter(env, contentCls, object, "time", timeObject); + } + + } + return true; +} + +bool SetNotificationLiveViewContent( + ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) +{ + ANS_LOGD("enter SetNotificationLocalLiveViewContent"); + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return false; + } + NotificationLiveViewContent *content = static_cast(basicContent); + if (content == nullptr) { + ANS_LOGE("longTextContent is null"); + return false; + } + + ani_object lockScreenPicObj = CreatePixelMap(env, content->GetLockScreenPicture()); + if (lockScreenPicObj != nullptr) { + CallSetter(env, contentCls, object, "lockScreenPicture", lockScreenPicObj); + } + + ani_enum_item enumItem = nullptr; + if(LiveViewStatusCToEts(env, content->GetLiveViewStatus(), enumItem) && enumItem != nullptr) { + CallSetter(env, contentCls, object, "status", enumItem); + } + + CallSetterOptional(env, contentCls, object, "version", static_cast(content->GetVersion())); + + std::shared_ptr extraInfoData = content->GetExtraInfo(); + if (extraInfoData != nullptr) { + ani_ref extraInfoObj = WrapWantParams(env, *extraInfoData); + if (extraInfoObj != nullptr) { + CallSetter(env, contentCls, object, "extraInfo", extraInfoObj); + } + } + // need to do + //// pictureInfo?: {[key, string]: Array} + //if (liveViewContent->GetPicture().empty()) { + // ANS_LOGD("No pictures in live view."); + // return true; + //} + //napi_value pictureMapObj = SetLiveViewPictureInfo(env, liveViewContent->GetPicture()); + //if (pictureMapObj == nullptr) { + // ANS_LOGE("Set live view picture map failed."); + // return false; + //} + //napi_set_named_property(env, result, "pictureInfo", pictureMapObj); + + return true; +} + +bool SetNotificationContent(ani_env* env, std::shared_ptr content, + ContentType type, ani_object &object) +{ + ani_class cls; + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationContentInner;", cls, object)); + std::shared_ptr basicContent = content->GetNotificationContent(); + if (basicContent == nullptr) { + ANS_LOGE("content is null"); + return false; + } + ani_object aniContext; + ani_class clsContent; + switch (type) { + case ContentType::BASIC_TEXT: // normal?: NotificationBasicContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationBasicContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "normal", aniContext)); + break; + case ContentType::LONG_TEXT: // longText?: NotificationLongTextContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationLongTextContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationLongTextContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "longText", aniContext)); + break; + case ContentType::PICTURE: // picture?: NotificationPictureContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationPictureContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationPictureContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "picture", aniContext)); + break; + // need to do + //case ContentType::CONVERSATION: // conversation?: NotificationConversationalContent + //ret = SetNotificationConversationalContent(env, basicContent.get(), contentResult); + // break; + case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationMultiLineContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationMultiLineContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "multiLine", aniContext)); + break; + case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationLocalLiveViewContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "systemLiveView", aniContext)); + break; + case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent + RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, + "Lnotification/notificationContent/NotificationLiveViewContentInner;", clsContent, aniContext)); + RETURN_FALSE_IF_NULL(clsContent); + RETURN_FALSE_IF_NULL(aniContext); + RETURN_FALSE_IF_FALSE(SetNotificationLiveViewContent(env, clsContent, basicContent.get(), aniContext)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "liveView", aniContext)); + break; + default: + ANS_LOGE("ContentType is does not exist"); + return false; + } + return true; +} + +bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + ContentType type = request->GetNotificationType(); + ani_enum_item typeItem; + RETURN_FALSE_IF_FALSE(ContentTypeCToEts(env, type, typeItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "contentType", typeItem)); + + std::shared_ptr content = request->GetContent(); + ani_object contentObj; + RETURN_FALSE_IF_FALSE(SetNotificationContent(env, content, type, contentObj)); + RETURN_FALSE_IF_FALSE(contentObj == nullptr); + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "content", contentObj)); + return true; +} } } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index d74a040c2..ba325080c 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -26,6 +26,7 @@ #include "uri.h" #include "inner_errors.h" #include "sts_do_not_disturb_profile.h" +#include "sts_error_utils.h" using namespace OHOS::NotificationSts; namespace OHOS { @@ -54,8 +55,8 @@ static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) ANS_LOGD("sts IsBadgeDisplayed call"); Notification::NotificationBundleOption option; bool ret = UnwrapBundleOption(env, obj, option); - ANS_LOGD("sts IsBadgeDisplayed option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), - option.GetUid()); + ANS_LOGD("sts IsBadgeDisplayed option bundleName: %{public}s, uid: %{public}d, ret: %{public}d", option.GetBundleName().c_str(), + option.GetUid(), ret); bool isDisplayed = false; int returncode = 0; if (ret) { @@ -87,47 +88,55 @@ static ani_double GetActiveNotificationCount(ani_env *env) static ani_boolean isNotificationEnabled([[maybe_unused]]ani_env *env, ani_object jsUserId, ani_object jsBundleOption) { - ani_int userId = 0; + int32_t userId = 0; bool allowed = false; int32_t ret = 0; ani_boolean isUserIdUndefined = ANI_FALSE; ani_boolean isBundleUndefined = ANI_FALSE; - ANS_LOGD("sts DisplayBadge call"); + ANS_LOGI("isNotificationEnabled enter"); env->Reference_IsUndefined(jsUserId, &isUserIdUndefined); env->Reference_IsUndefined(jsBundleOption, &isBundleUndefined); - ANS_LOGD("isNotificationEnabled isUserIdUndefined = %{public}d isBundleUndefined = %{public}d", + ANS_LOGI("isNotificationEnabled isUserIdUndefined = %{public}d isBundleUndefined = %{public}d", isUserIdUndefined, isBundleUndefined); // 3. 解析 userId if (!isUserIdUndefined) { - ANS_LOGD("isNotificationEnabled ==>> isUserIdUndefined"); + ANS_LOGI("isNotificationEnabled ==>> isUserIdUndefined"); if (ANI_OK !=env->Object_CallMethodByName_Int(jsUserId, "intValue", nullptr, &userId)) { - ANS_LOGD("isNotificationEnabled Object_CallMethodByName_Int Fail"); + ANS_LOGI("isNotificationEnabled Object_CallMethodByName_Int Fail"); userId = 0; - return ANI_FALSE; + int externalCode = CJSystemapi::Notification::ERROR_PARAM_INVALID; + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + return BoolToAniBoolean(allowed); } + ANS_LOGI("isNotificationEnabled IsAllowedNotify userId = %{public}d", userId); + ret = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); - ANS_LOGD("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); + } else if (!isBundleUndefined) { - ANS_LOGD("isNotificationEnabled ==>> isBundleUndefined"); - + ANS_LOGI("isNotificationEnabled ==>> isBundleUndefined"); Notification::NotificationBundleOption option; UnwrapBundleOption(env, jsBundleOption, option); + ANS_LOGI("uid = %{public}d, bundle = %{public}s", option.GetUid(), option.GetBundleName().c_str()); ret = Notification::NotificationHelper::IsAllowedNotify(option, allowed); } else { - ANS_LOGD("isNotificationEnabled ==>> no parameter"); + ANS_LOGI("isNotificationEnabled ==>> no parameter"); ret = Notification::NotificationHelper::IsAllowedNotify(allowed); - ANS_LOGD("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); } + ANS_LOGI("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); if (ret != ANI_OK) { - return ANI_FALSE; + int err = CJSystemapi::Notification::ErrorToExternal(ret); + OHOS::AbilityRuntime::ThrowStsError(env, err, FindAnsErrMsg(err)); + allowed = false; } else { - return allowed ? ANI_TRUE : ANI_FALSE; + ANS_LOGI("isNotificationEnabled allowed %{public}d", allowed); + allowed ? (allowed = true) : (allowed = false); } + return BoolToAniBoolean(allowed); } static ani_int getSlotFlagsByBundle(ani_env *env, ani_object obj) diff --git a/frameworks/ani/notification_manager/src/sts_notification_request.cpp b/frameworks/ani/notification_manager/src/sts_notification_request.cpp index f4924e5c4..76563a8a4 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_request.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_request.cpp @@ -26,6 +26,344 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::AAFwk; using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; +bool SetNotificationRequestByString(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + ani_string stringValue = nullptr; + // classification?: string + if (GetAniString(env, request->GetClassification(), stringValue)) { + CallSetterOptional(env, cls, object, "classification", stringValue); + } + // need to do + // statusBarText?: string + // if (StringToAniStr(env, request->GetStatusBarText(), stringValue)) { + // RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, STATUS_BAR_TEXT, stringValue)); + // } + // label?: string + if (GetAniString(env, request->GetLabel(), stringValue)) { + CallSetterOptional(env, cls, object, "label", stringValue); + } + // groupName?: string + if (GetAniString(env, request->GetGroupName(), stringValue)) { + CallSetterOptional(env, cls, object, "groupName", stringValue); + } + // readonly creatorBundleName?: string + if (GetAniString(env, request->GetCreatorBundleName(), stringValue)) { + CallSetterOptional(env, cls, object, "creatorBundleName", stringValue); + } + // readonly sound?: string + if (GetAniString(env, request->GetSound(), stringValue)) { + CallSetterOptional(env, cls, object, "sound", stringValue); + } + // readonly appInstanceKey?: string + if (GetAniString(env, request->GetAppInstanceKey(), stringValue)) { + CallSetterOptional(env, cls, object, "appInstanceKey", stringValue); + } + return true; +} + +bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // id?: number + CallSetterOptional(env, cls, object, "id", request->GetNotificationId()); + // slotType?: SlotType + ani_enum_item slotTypeItem {}; + if(SlotTypeCToEts(env, request->GetSlotType(), slotTypeItem)) { + CallSetterOptional(env, cls, object, "slotType", slotTypeItem); + } + + // deliveryTime?: number + CallSetterOptional(env, cls, object, "deliveryTime", request->GetDeliveryTime()); + // autoDeletedTime?: number + CallSetterOptional(env, cls, object, "autoDeletedTime", request->GetAutoDeletedTime()); + // color ?: number + CallSetterOptional(env, cls, object, "color", request->GetColor()); + // badgeIconStyle ?: number + CallSetterOptional(env, cls, object, "badgeIconStyle", + static_cast(request->GetBadgeIconStyle())); + // readonly creatorUid?: number + CallSetterOptional(env, cls, object, "creatorUid", request->GetCreatorUid()); + // readonly creatorPid?: number + CallSetterOptional(env, cls, object, "creatorPid", request->GetCreatorPid()); + // badgeNumber?: number + CallSetterOptional(env, cls, object, "badgeNumber", request->GetBadgeNumber()); + // readonly creatorInstanceKey?: number + CallSetterOptional(env, cls, object, "creatorInstanceKey", request->GetCreatorInstanceKey()); + return true; +} + +bool SetNotificationRequestByBool(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // isOngoing?: boolean + CallSetterOptional(env, cls, object, "isOngoing", BoolToAniBoolean(request->IsInProgress())); + // isUnremovable?: boolean + CallSetterOptional(env, cls, object, "isUnremovable", BoolToAniBoolean(request->IsUnremovable())); + // tapDismissed?: boolean + CallSetterOptional(env, cls, object, "tapDismissed", BoolToAniBoolean(request->IsTapDismissed())); + // colorEnabled?: boolean + CallSetterOptional(env, cls, object, "colorEnabled", BoolToAniBoolean(request->IsColorEnabled())); + // isAlertOnce?: boolean + CallSetterOptional(env, cls, object, "isAlertOnce", BoolToAniBoolean(request->IsAlertOneTime())); + // isStopwatch?: boolean + CallSetterOptional(env, cls, object, "isStopwatch", BoolToAniBoolean(request->IsShowStopwatch())); + // isCountDown?: boolean + CallSetterOptional(env, cls, object, "isCountDown", BoolToAniBoolean(request->IsCountdownTimer())); + // isFloatingIcon?: boolean + CallSetterOptional(env, cls, object, "isFloatingIcon", BoolToAniBoolean(request->IsFloatingIcon())); + // showDeliveryTime?: boolean + CallSetterOptional(env, cls, object, "showDeliveryTime", BoolToAniBoolean(request->IsShowDeliveryTime())); + // updateOnly?: boolean + CallSetterOptional(env, cls, object, "updateOnly", BoolToAniBoolean(request->IsUpdateOnly())); + return true; +} + +ani_object ConvertNotificationActionButtonToAniObject(ani_env* env, + const std::shared_ptr &actionButton) +{ + if (actionButton == nullptr) { + ANS_LOGE("actionButton is null"); + return nullptr; + } + ani_object iconButtonObject = nullptr; + ani_class iconButtonCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationActionButton/NotificationActionButtonInner;", iconButtonCls, iconButtonObject)); + // title: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniString(env, actionButton->GetTitle(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "title", stringValue)); + // wantAgent: WantAgent; + // need to do + // extras?: Record; napiûдḶ֪́Ǹɶģ + + // need to do + //TODO(δת) + + // userInput?: NotificationUserInput -> inputKey: string; + ani_object userInputObject = nullptr; + ani_class userInputCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationUserInput/NotificationUserInputInner;", userInputCls, userInputObject)); + std::shared_ptr userInput = actionButton->GetUserInput(); + RETURN_NULL_IF_FALSE(GetAniString(env, userInput->GetInputKey(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, userInputCls, userInputObject, "inputKey", stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, iconButtonCls, iconButtonObject, "userInput", userInputObject)); + + return iconButtonObject; +} + +ani_object SetNotificationActionButtonArray(ani_env* env, + const std::vector> &actionButtons) +{ + if (actionButtons.empty()) { + ANS_LOGE("actionButtons is empty"); + return nullptr; + } + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + ani_status status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, actionButtons.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + ani_size index = 0; + for (auto &button : actionButtons) { + ani_object item = ConvertNotificationActionButtonToAniObject(env, button); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; +} + +ani_object SetNotificationTemplateInfo(ani_env* env, const std::shared_ptr &templ) +{ + if (templ == nullptr) { + ANS_LOGE("templ is null"); + return nullptr; + } + ani_object templateObject = nullptr; + ani_class templateCls = nullptr; + RETURN_NULL_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationTemplate/NotificationTemplateInner;", templateCls, templateObject)); + // name: string; + ani_string stringValue = nullptr; + RETURN_NULL_IF_FALSE(GetAniString(env, templ->GetTemplateName(), stringValue)); + RETURN_NULL_IF_FALSE(CallSetter(env, templateCls, templateObject, "name", stringValue)); + // data: Record; + std::shared_ptr data = templ->GetTemplateData(); + if (data) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *data); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, templateCls, templateObject, "data", valueRef)); + } + return templateObject; +} + +bool SetNotificationFlags(ani_env* env, const std::shared_ptr &flags, ani_object &flagsObject) +{ + if (flags == nullptr) { + ANS_LOGE("flags is null"); + return false; + } + + ani_class flagsCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationFlags/NotificationFlagsInner;", flagsCls, flagsObject)); + // readonly soundEnabled?: NotificationFlagStatus; + int32_t soundEnabled = static_cast(flags->IsSoundEnabled()); + ani_enum_item enumItem = nullptr; + RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + soundEnabled, enumItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "soundEnabled", enumItem)); + // readonly vibrationEnabled?: NotificationFlagStatus; + int32_t vibrationEnabled = static_cast(flags->IsVibrationEnabled()); + RETURN_FALSE_IF_FALSE(EnumConvertNativeToAni(env, "Lnotification/notificationFlags/NotificationFlagStatus;", + vibrationEnabled, enumItem)); + RETURN_FALSE_IF_FALSE(CallSetter(env, flagsCls, flagsObject, "vibrationEnabled", enumItem)); + // readonly reminderFlags?: number; + uint32_t reminderFlags = flags->GetReminderFlags(); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, flagsCls, flagsObject, "reminderFlags", reminderFlags)); + return true; +} + +bool SetAgentBundle(ani_env* env, + const std::shared_ptr &agentBundle, ani_object &agentBundleObject) +{ + if (agentBundle == nullptr) { + ANS_LOGE("agentBundle is null"); + return false; + } + ani_class agentBundleCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/NotificationCommonDef/BundleOptionInner;", agentBundleCls, agentBundleObject)); + // bundle: string; + ani_string stringValue = nullptr; + RETURN_FALSE_IF_FALSE(GetAniString(env, agentBundle->GetBundleName(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetter(env, agentBundleCls, agentBundleObject, "bundle", stringValue)); + // uid?: number; + uint32_t uid = agentBundle->GetUid(); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, agentBundleCls, agentBundleObject, "uid", uid)); + return true; +} + +bool SetNotificationUnifiedGroupInfo(ani_env* env, + const std::shared_ptr &groupInfo, ani_object &groupInfoObject) +{ + if (groupInfo == nullptr) { + ANS_LOGE("groupInfo is null"); + return false; + } + ani_class groupInfoCls = nullptr; + RETURN_FALSE_IF_FALSE(CreateClassObjByClassName(env, + "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)); + // key?: string; + ani_string stringValue = nullptr; + RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetKey(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "key", stringValue)); + // title?: string; + RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetTitle(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "title", stringValue)); + // content?: string; + RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetContent(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "content", stringValue)); + // sceneName?: string; + RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetSceneName(), stringValue)); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "sceneName", stringValue)); + // extraInfo?: Record; + std::shared_ptr extraInfo = groupInfo->GetExtraInfo(); + if (extraInfo) { + ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *extraInfo); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef)); + } + + // need to do check + //TODO(δת) + + return true; +} + +bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, std::shared_ptr request, + ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // content: NotificationContent + RETURN_FALSE_IF_FALSE(SetNotificationRequestByNotificationContent(env, cls, request, object)); + + // need to do TODO(δת) ˴napiת + // extraInfo?: {[key:string] : any} + + // actionButtons?: Array + std::vector> actionButtons = request->GetActionButtons(); + ani_object actionButtonsArrayObj = SetNotificationActionButtonArray(env, actionButtons); + if (actionButtonsArrayObj != nullptr) { + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "actionButtons", actionButtonsArrayObj)); + } + // template?: NotificationTemplate + std::shared_ptr templ = request->GetTemplate(); + if (templ) { + ani_object templateObject = SetNotificationTemplateInfo(env, templ); + if (templateObject != nullptr) { + RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "template", templateObject)); + } + } + // readonly notificationFlags?: NotificationFlags + std::shared_ptr flags = request->GetFlags(); + if (flags) { + ani_object flagsObject = nullptr; + if (SetNotificationFlags(env, flags, flagsObject) && flagsObject != nullptr) { + CallSetter(env, cls, object, "notificationFlags", flagsObject); + } + } + // readonly agentBundle?: agentBundle + std::shared_ptr agentBundle = request->GetAgentBundle(); + if (agentBundle) { + ani_object agentBundleObject = nullptr; + if (SetAgentBundle(env, agentBundle, agentBundleObject) && agentBundleObject != nullptr) { + CallSetter(env, cls, object, "agentBundle", agentBundleObject); + } + } + // unifiedGroupInfo?: unifiedGroupInfo + std::shared_ptr groupInfo = request->GetUnifiedGroupInfo(); + if (groupInfo) { + ani_object infoObject = nullptr; + if(SetNotificationUnifiedGroupInfo(env, groupInfo, infoObject) && infoObject != nullptr) { + CallSetter(env, cls, object, "unifiedGroupInfo", infoObject); + } + } + return true; +} + void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions) { bool isDistributed = false; @@ -190,38 +528,32 @@ void GetNotificationRequestByNumber(ani_env *env, ani_object obj, request->SetNotificationId(0); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "deliveryTime", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetDeliveryTime(static_cast(mDouble)); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "autoDeletedTime", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetAutoDeletedTime(static_cast(mDouble)); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "color", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetColor(static_cast(mDouble)); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "badgeIconStyle", isUndefined, mDouble) && isUndefined == ANI_FALSE) { int32_t style = static_cast(mDouble); request->SetBadgeIconStyle(static_cast(style)); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "badgeNumber", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetBadgeNumber(static_cast(mDouble)); } - isUndefined = ANI_TRUE; if(ANI_OK == GetPropertyDoubleOrUndefined(env, obj, "notificationControlFlags", isUndefined, mDouble) && isUndefined == ANI_FALSE) { request->SetNotificationControlFlags(static_cast(mDouble)); @@ -636,36 +968,49 @@ ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, GetNotificationTemplate(env, obj, notificationRequest); GetNotificationUnifiedGroupInfo(env, obj, notificationRequest); GetNotificationBundleOption(env, obj, notificationRequest); - + // need to do GetNotificationMaxScreenWantAgent /* // maxScreenWantAgent?: WantAgent if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { return nullptr; } - // template?: NotificationTemplate - if (GetNotificationTemplate(env, value, request) == nullptr) { - return nullptr; - } - // unifiedGroupInfo?: NotificationUnifiedGroupInfo - if (GetNotificationUnifiedGroupInfo(env, value, request) == nullptr) { - return nullptr; - } - // representativeBundle?: BundleOption - if (GetNotificationBundleOption(env, value, request) == nullptr) { - return nullptr; - } */ return status; } -void UnWarpNotificationRequest(ani_env *env, ani_object obj, +ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, std::shared_ptr ¬ificationRequest) { + ani_status status = ANI_ERROR; GetNotificationRequestByNumber(env, obj, notificationRequest); GetNotificationRequestByString(env, obj, notificationRequest); GetNotificationRequestByBoolean(env, obj, notificationRequest); - GetNotificationRequestByCustom(env, obj, notificationRequest); + status = GetNotificationRequestByCustom(env, obj, notificationRequest); + return status; } + +ani_object WarpNotificationRequest(ani_env *env, std::shared_ptr notificationRequest) +{ + ani_class cls; + ani_object outAniObj; + if(!CreateClassObjByClassName(env, + "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)) { + return nullptr; + } + if(!SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)) { + return nullptr; + } + if(!SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)) { + return nullptr; + } + if(!SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)) { + return nullptr; + } + if(SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)) { + return nullptr; + } + return outAniObj; } -} \ No newline at end of file +} // name space NotificationSts +} // name space OHOS diff --git a/frameworks/ani/notification_manager/src/sts_notification_utils.cpp b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp index 1a7d6cf86..bf4baf847 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_utils.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_utils.cpp @@ -45,6 +45,31 @@ void UnwrapWantAgent(ani_env *env, ani_object agent, void** result) *result = reinterpret_cast(param_value); } +ani_object CreatePixelMap([[maybe_unused]] ani_env* env, std::shared_ptr pixelMap) +{ + if (pixelMap == nullptr) { + return nullptr; + } + std::unique_ptr pPixelMapAni = std::make_unique(); + pPixelMapAni->nativePixelMap_ = pixelMap; + static const char* className = "L@ohos/multimedia/image/image/PixelMapInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + ANS_LOGE("Not found L@ohos/multimedia/image/image/PixelMapInner"); + return nullptr; + } + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", "J:V", &ctor)) { + ANS_LOGE("Not found ani_method"); + return nullptr; + } + ani_object aniValue; + if (ANI_OK != env->Object_New(cls, ctor, &aniValue, reinterpret_cast(pPixelMapAni.release()))) { + ANS_LOGE("New Context Fail"); + } + return aniValue; +} + std::shared_ptr GetPixelMapFromEnvSp([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object obj) { ani_status ret; -- Gitee From 8ece7cf2a2cb383da0821df4cb752ca6ef2d0c2b Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Fri, 9 May 2025 15:07:07 +0800 Subject: [PATCH 7/9] =?UTF-8?q?feat:=E4=BF=AE=E6=94=B9=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- .../ets/notification/notificationContent.ets | 80 +++++++++++-------- .../ets/notification/notificationRequest.ets | 2 +- .../src/sts_bundle_option.cpp | 8 +- .../src/sts_notification_manager.cpp | 70 +++++++++++----- 4 files changed, 99 insertions(+), 61 deletions(-) diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets index 94e5e2a89..1679a06fb 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -43,9 +43,9 @@ export interface NotificationBasicContent { class NotificationBasicContentInner implements NotificationBasicContent { - title: string; + title: string = ""; - text: string; + text: string = ""; additionalText?: string; @@ -63,19 +63,19 @@ export interface NotificationLongTextContent extends NotificationBasicContent { class NotificationLongTextContentInner implements NotificationLongTextContent { - title: string; + title: string = ""; - text: string; + text: string = ""; additionalText?: string; lockscreenPicture?: image.PixelMap; - longText: string; + longText: string = ""; - briefText: string; + briefText: string = ""; - expandedTitle: string; + expandedTitle: string = ""; } export enum LiveViewStatus { @@ -113,15 +113,15 @@ export interface NotificationLiveViewContent extends NotificationBasicContent { class NotificationLiveViewContentInner implements NotificationLiveViewContent { - title: string; + title: string = ""; - text: string; + text: string = ""; additionalText?: string; lockscreenPicture?: image.PixelMap; - status: LiveViewStatus; + status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; version?: number; @@ -143,19 +143,19 @@ export interface NotificationMultiLineContent extends NotificationBasicContent { class NotificationMultiLineContentInner implements NotificationMultiLineContent { - title: string; + title: string = ""; - text: string; + text: string = ""; additionalText?: string; lockscreenPicture?: image.PixelMap; - briefText: string; + briefText: string = ""; - longTitle: string; + longTitle: string = ""; - lines: Array; + lines: Array = {}; } export interface NotificationPictureContent extends NotificationBasicContent { @@ -168,20 +168,24 @@ export interface NotificationPictureContent extends NotificationBasicContent { } class NotificationPictureContentInner implements NotificationPictureContent { + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } - title: string; + title: string = ""; - text: string; + text: string = ""; additionalText?: string; lockscreenPicture?: image.PixelMap; - briefText: string; + briefText: string = ""; - expandedTitle: string; + expandedTitle: string = ""; - picture: image.PixelMap; + picture: image.PixelMap = this.CreatePixelMap(); } export interface NotificationSystemLiveViewContent extends NotificationBasicContent { @@ -202,14 +206,26 @@ export interface NotificationSystemLiveViewContent extends NotificationBasicCont } class NotificationSystemLiveViewContentInner implements NotificationSystemLiveViewContent { + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } - briefText: string; + title: string = ""; - expandedTitle: string; + text: string = ""; - picture: image.PixelMap; + additionalText?: string; - typeCode: number; + lockscreenPicture?: image.PixelMap; + + briefText: string = ""; + + expandedTitle: string = ""; + + picture: image.PixelMap = this.CreatePixelMap(); + + typeCode: number = 0; capsule?: NotificationCapsule; @@ -222,14 +238,6 @@ class NotificationSystemLiveViewContentInner implements NotificationSystemLiveVi progress?: NotificationProgress; liveViewType?: LiveViewTypes; - - get title(): string { - return this.title; - } - - set title(value: string) { - this.title = value; - } } export interface NotificationCapsule { @@ -275,9 +283,13 @@ export interface NotificationIconButton { class NotificationIconButtonInner implements NotificationIconButton { - name: string; + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } + return image.createPixelMapSync(opts); + } + name: string = ""; - iconResource: IconType; + iconResource: IconType = this.CreatePixelMap(); text?: string; diff --git a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets index ea7236275..ea2f6e604 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets @@ -75,7 +75,7 @@ export interface NotificationRequest { } class NotificationRequestInner implements NotificationRequest { - content: NotificationContent; + content: NotificationContent = {}; id?: number; appMessageId?: string; notificationSlotType?: notificationManager.SlotType; diff --git a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp index cb5dafbc9..abed948bf 100644 --- a/frameworks/ani/notification_manager/src/sts_bundle_option.cpp +++ b/frameworks/ani/notification_manager/src/sts_bundle_option.cpp @@ -32,7 +32,7 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification } std::string bundleName; - if (ANI_OK != (status = GetStdString(env, reinterpret_cast(bundleNameRef), bundleName))) { + if (ANI_OK != (status = GetStdString(env, static_cast(bundleNameRef), bundleName))) { ANS_LOGD("WrapBundleOption GetStdString failed"); return false; } @@ -43,12 +43,12 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification status = env->Object_GetPropertyByName_Ref(obj, "uid", &uidRef); if (ANI_OK != status) { ANS_LOGD("WrapBundleOption Object_GetPropertyByName_Ref uid fail, status: %{public}d", status); - return true; + return false; } ani_boolean isUndefined = true; if ((status = env->Reference_IsUndefined(uidRef, &isUndefined)) != ANI_OK) { ANS_LOGD("WrapBundleOption Object_GetPropertyByName_Ref status : %{public}d", status); - return true; + return false; } if (isUndefined) { ANS_LOGD("WrapBundleOption uid is undefined"); @@ -58,7 +58,7 @@ bool UnwrapBundleOption(ani_env *env, ani_object obj, Notification::Notification status = env->Object_CallMethodByName_Double(static_cast(uidRef), "doubleValue", nullptr, &result); if (ANI_OK != status) { ANS_LOGD("WrapBundleOption Object_CallMethodByName_Double uid fail, status: %{public}d", status); - return true; + return false; } int32_t uid = static_cast(result); diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index ba325080c..348219429 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -27,6 +27,7 @@ #include "inner_errors.h" #include "sts_do_not_disturb_profile.h" #include "sts_error_utils.h" +#include "ans_inner_errors.h" using namespace OHOS::NotificationSts; namespace OHOS { @@ -34,13 +35,21 @@ namespace NotificationManagerSts { static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) { - ANS_LOGD("sts DisplayBadge call"); + ANS_LOGD("sts DisplayBadge call"); + int returncode = 0; Notification::NotificationBundleOption option; - UnwrapBundleOption(env, obj, option); - ANS_LOGD("sts DisplayBadge option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), - option.GetUid()); - int ret = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, AniBooleanToBool(enable)); - int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + bool bFlag = UnwrapBundleOption(env, obj, option); + ANS_LOGD("sts DisplayBadge option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), + option.GetUid(), bFlag); + if(bFlag) { + returncode = Notification::NotificationHelper::SetShowBadgeEnabledForBundle(option, AniBooleanToBool(enable)); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts DisplayBadge ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); @@ -53,18 +62,26 @@ static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) { ANS_LOGD("sts IsBadgeDisplayed call"); - Notification::NotificationBundleOption option; - bool ret = UnwrapBundleOption(env, obj, option); - ANS_LOGD("sts IsBadgeDisplayed option bundleName: %{public}s, uid: %{public}d, ret: %{public}d", option.GetBundleName().c_str(), - option.GetUid(), ret); - bool isDisplayed = false; int returncode = 0; - if (ret) { - returncode = Notification::NotificationHelper::GetShowBadgeEnabledForBundle(option, isDisplayed); - } else { + bool isDisplayed = false; + if (obj == nullptr) { returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); + } else { + Notification::NotificationBundleOption option; + bool bFlag = UnwrapBundleOption(env, obj, option); + ANS_LOGD("sts IsBadgeDisplayed option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), + option.GetUid(), bFlag); + if(bFlag) { + returncode = Notification::NotificationHelper::GetShowBadgeEnabledForBundle(option, isDisplayed); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts IsBadgeDisplayed ERROR_INTERNAL_ERROR"); + return BoolToAniBoolean(false); + } } - int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); @@ -232,14 +249,23 @@ static void CancelAll(ani_env* env) static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) { - ANS_LOGD("sts GetSlotsByBundle enter"); - Notification::NotificationBundleOption option; - UnwrapBundleOption(env, bundleOption, option); - ANS_LOGD("sts GetSlotsByBundle option bundleName: %{public}s, uid: %{public}d", option.GetBundleName().c_str(), - option.GetUid()); + ANS_LOGD("sts GetSlotsByBundle enter"); + int returncode = 0; std::vector> slots; - auto ret = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); - int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + Notification::NotificationBundleOption option; + bool bFlag = UnwrapBundleOption(env, bundleOption, option); + ANS_LOGD("sts GetSlotsByBundle option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), + option.GetUid(), bFlag); + if(bFlag) { + returncode = Notification::NotificationHelper::GetNotificationSlotsForBundle(option, slots); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts GetSlotsByBundle ERROR_INTERNAL_ERROR"); + return nullptr; + } + + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); if (externalCode != 0) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); -- Gitee From bed517fd7af5b518324a65557a032bf29ccea356 Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Sat, 10 May 2025 15:39:42 +0800 Subject: [PATCH 8/9] =?UTF-8?q?feat:=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- frameworks/ani/notification_manager/BUILD.gn | 1 + .../ets/@ohos.notificationManager.ets | 88 +++--- .../notification/NotificationCommonDef.ets | 2 +- .../include/sts_notification_request.h | 7 +- .../include/sts_notification_utils.h | 6 +- .../src/sts_notification_content.cpp | 94 +++--- .../src/sts_notification_manager.cpp | 203 +++++++++--- .../src/sts_notification_request.cpp | 290 ++++++++++++++++-- .../src/sts_notification_template.cpp | 2 +- 9 files changed, 535 insertions(+), 158 deletions(-) diff --git a/frameworks/ani/notification_manager/BUILD.gn b/frameworks/ani/notification_manager/BUILD.gn index daac4373f..feb0ff453 100644 --- a/frameworks/ani/notification_manager/BUILD.gn +++ b/frameworks/ani/notification_manager/BUILD.gn @@ -55,6 +55,7 @@ ohos_shared_library("notification_manager_ani_kit") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_path}/cj/ffi:cj_notification_manager_ffi", + #"${core_path}:ans_core", ] external_deps = [ diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index 483ffb517..f09f3c203 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -45,6 +45,25 @@ export default namespace notificationManager { trustlist?: Array = new Array(); } + export enum DoNotDisturbType { + TYPE_NONE = 0, + TYPE_ONCE = 1, + TYPE_DAILY = 2, + TYPE_CLEARLY = 3 + } + + export interface DoNotDisturbDate { + type: DoNotDisturbType; + begin: Date; + end: Date; + } + + class DoNotDisturbDateInner implements DoNotDisturbDate { + type: DoNotDisturbType; + begin: Date; + end: Date; + } + export native function nativeDisplayBadge(bundle: BundleOption, enable: boolean): void; export native function nativeIsBadgeDisplayed(bundle: BundleOption): boolean; export native function nativeGetActiveNotificationCount(): number; @@ -54,6 +73,7 @@ export default namespace notificationManager { export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; export native function nativeisNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; export native function nativeCancelWithId(id: number): void; + export native function nativeCancelWithIdOptionalLabel(id: number, label?: string): void; export native function nativeCancelWithIdLabel(id: number, label: string): void; export native function nativeCancelWithBundle(bundle: BundleOption, id: number): void; export native function nativeCancelAll(): void; @@ -142,13 +162,13 @@ export default namespace notificationManager { export function isNotificationEnabled(userId: number): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); - p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - resolve(ret); - }, (error: Object): void => { - reject(error); - }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(userId, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } @@ -171,12 +191,12 @@ export default namespace notificationManager { { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, bundleOption); }); - p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - resolve(ret); - }, (error: Object): void => { - reject(error); - }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } @@ -198,13 +218,13 @@ export default namespace notificationManager { export function isNotificationEnabled(): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); - p.then((data: NullishType): void => { - let ret : boolean = data as boolean; - resolve(ret); - }, (error: Object): void => { - reject(error); - }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationEnabled(undefined, undefined); }); + p.then((data: NullishType): void => { + let ret : boolean = data as boolean; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); }); return pPromise; } @@ -283,27 +303,17 @@ export default namespace notificationManager { export function cancel(id: number, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function cancel(id: number): Promise { - let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithId(id); }); - p.then((data: NullishType): void => { - resolve(undefined); - }, (error: Object): void => { - reject(error); - }); - }); - return pPromise; - } - - export function cancel(id: number, label: string): Promise { + export function cancel(id: number, label?: string): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); + let p = taskpool.execute((): void => { return nativeCancelWithIdOptionalLabel(id, label); }); p.then((data: NullishType): void => { resolve(undefined); }, (error: Object): void => { @@ -316,9 +326,11 @@ export default namespace notificationManager { export function cancel(id: number, label: string, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelWithIdLabel(id, label); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } @@ -349,9 +361,11 @@ export default namespace notificationManager { export function cancelAll(callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeCancelAll(); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } diff --git a/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets index a434e6b75..32fc5f345 100644 --- a/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets +++ b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets @@ -20,5 +20,5 @@ export interface BundleOption { class BundleOptionInner implements BundleOption { public bundle: string = ''; - public uid?: number = 0; + public uid?: number; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_request.h b/frameworks/ani/notification_manager/include/sts_notification_request.h index 7148054bb..0e23308d4 100644 --- a/frameworks/ani/notification_manager/include/sts_notification_request.h +++ b/frameworks/ani/notification_manager/include/sts_notification_request.h @@ -16,6 +16,7 @@ #ifndef OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_REQUEST_H #define OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_REQUEST_H #include "ani.h" +#include "notification.h" namespace OHOS { @@ -26,8 +27,12 @@ struct StsDistributedOptions { std::vector supportOperateDevices = {}; int32_t remindType = -1; }; - +ani_object ConvertNotificationToAni(ani_env* env, const OHOS::Notification::Notification *notification); void UnWarpDistributedOptions(ani_env *env, ani_object obj, StsDistributedOptions distributedOptions); +ani_object ConvertNotificationArrayToAni(ani_env* env, + const std::vector> ¬ifications); +ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, + std::shared_ptr ¬ificationRequest); } } #endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_ENUM_SLOT_TYPE_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_notification_utils.h b/frameworks/ani/notification_manager/include/sts_notification_utils.h index b7e11c416..1350afd60 100644 --- a/frameworks/ani/notification_manager/include/sts_notification_utils.h +++ b/frameworks/ani/notification_manager/include/sts_notification_utils.h @@ -55,7 +55,7 @@ ani_object CreatePixelMap([[maybe_unused]] ani_env* env, std::shared_ptr ¬ificationRequest); ani_object WarpNotificationRequest(ani_env *env, std::shared_ptr notificationRequest); -bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, std::shared_ptr request, - ani_object &object); +bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object); } } #endif //OHOS_DISTRIBUTED_NOTIFICATION_SERVER_STS_NOTIFICATION_UTILS_H \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_content.cpp b/frameworks/ani/notification_manager/src/sts_notification_content.cpp index 61ddbbf32..84c35ae28 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_content.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_content.cpp @@ -736,11 +736,6 @@ ani_object SetResourceObject(ani_env *env, const std::shared_ptrid)); - - // need to do check - //napiдʱûиѡֶδDzǾͲôˣ - /* params?: Array; - type?: number; */ return resourceObject; } @@ -805,7 +800,7 @@ bool SetTime(ani_env *env, const NotificationTime &time, bool isInitialTimeExist ani_object ConvertVectorToAniArrayPixelMap(ani_env *env, const std::vector> &pixelMaps) { RETURN_NULL_IF_NULL(env); - if (pixelMaps.size() <= 0) { + if (pixelMaps.empty()) { return nullptr; } @@ -1190,6 +1185,36 @@ bool SetNotificationLocalLiveViewContent( return true; } +bool GetAniPictrueInfo(ani_env *env, std::map>> pictureMap, + ani_object &pictureInfoObj) +{ + ani_class recordCls; + ani_method ctor; + if (ANI_OK != env->FindClass("Lescompat/Record;", &recordCls)) { + return false; + } + + if (ANI_OK != env->Class_FindMethod(recordCls, "", nullptr, &ctor)) { + return false; + } + + if (ANI_OK != env->Object_New(recordCls, ctor, &pictureInfoObj)) { + return false; + } + for (const auto& [key, value] : pictureMap) { + ani_string aniKey = GetAniString(env, key); + ani_object aniPictrueArray = ConvertVectorToAniArrayPixelMap(env, value); + if (aniKey == nullptr || aniPictrueArray == nullptr) { + return false; + } + if (ANI_OK != env->Object_CallMethodByName_Void(pictureInfoObj, "$_set", + "Lstd/core/Object;Lstd/core/Object;:V", aniKey, aniPictrueArray)) { + return false; + } + } + return true; +} + bool SetNotificationLiveViewContent( ani_env* env, ani_class contentCls, NotificationBasicContent *basicContent, ani_object &object) { @@ -1223,28 +1248,31 @@ bool SetNotificationLiveViewContent( CallSetter(env, contentCls, object, "extraInfo", extraInfoObj); } } - // need to do - //// pictureInfo?: {[key, string]: Array} - //if (liveViewContent->GetPicture().empty()) { - // ANS_LOGD("No pictures in live view."); - // return true; - //} - //napi_value pictureMapObj = SetLiveViewPictureInfo(env, liveViewContent->GetPicture()); - //if (pictureMapObj == nullptr) { - // ANS_LOGE("Set live view picture map failed."); - // return false; - //} - //napi_set_named_property(env, result, "pictureInfo", pictureMapObj); + // pictureInfo?: {[key, string]: Array} + if (content->GetPicture().empty()) { + ANS_LOGD("No pictures in live view."); + return true; + } + ani_object pictureInfoObj = nullptr; + if (GetAniPictrueInfo(env, content->GetPicture(), pictureInfoObj) && pictureInfoObj != nullptr) { + CallSetter(env, contentCls, object, "pictureInfo", pictureInfoObj); + } + return true; return true; } -bool SetNotificationContent(ani_env* env, std::shared_ptr content, - ContentType type, ani_object &object) +bool SetNotificationContent(ani_env* env, std::shared_ptr content, ani_object &object) { ani_class cls; RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationContentInner;", cls, object)); + // notificationContentType?: notificationManager.ContentType; + ani_enum_item contentTypeItem {}; + RETURN_FALSE_IF_FALSE(ContentTypeCToEts(env, content->GetContentType(), contentTypeItem)); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "notificationContentType", contentTypeItem)); + STSContentType stsContentType = STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + RETURN_FALSE_IF_FALSE(StsContentTypeUtils::CToSts(content->GetContentType(), stsContentType)); std::shared_ptr basicContent = content->GetNotificationContent(); if (basicContent == nullptr) { ANS_LOGE("content is null"); @@ -1252,8 +1280,8 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c } ani_object aniContext; ani_class clsContent; - switch (type) { - case ContentType::BASIC_TEXT: // normal?: NotificationBasicContent + switch (stsContentType) { + case STSContentType::NOTIFICATION_CONTENT_BASIC_TEXT: // normal?: NotificationBasicContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationBasicContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1261,7 +1289,7 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c RETURN_FALSE_IF_FALSE(SetNotificationBasicContent(env, clsContent, basicContent.get(), aniContext)); RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "normal", aniContext)); break; - case ContentType::LONG_TEXT: // longText?: NotificationLongTextContent + case STSContentType::NOTIFICATION_CONTENT_LONG_TEXT: // longText?: NotificationLongTextContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLongTextContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1269,7 +1297,7 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c RETURN_FALSE_IF_FALSE(SetNotificationLongTextContent(env, clsContent, basicContent.get(), aniContext)); RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "longText", aniContext)); break; - case ContentType::PICTURE: // picture?: NotificationPictureContent + case STSContentType::NOTIFICATION_CONTENT_PICTURE: // picture?: NotificationPictureContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationPictureContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1278,10 +1306,10 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "picture", aniContext)); break; // need to do - //case ContentType::CONVERSATION: // conversation?: NotificationConversationalContent + //case STSContentType::NOTIFICATION_CONTENT_CONVERSATION: // conversation?: NotificationConversationalContent //ret = SetNotificationConversationalContent(env, basicContent.get(), contentResult); // break; - case ContentType::MULTILINE: // multiLine?: NotificationMultiLineContent + case STSContentType::NOTIFICATION_CONTENT_MULTILINE: // multiLine?: NotificationMultiLineContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationMultiLineContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1289,7 +1317,7 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c RETURN_FALSE_IF_FALSE(SetNotificationMultiLineContent(env, clsContent, basicContent.get(), aniContext)); RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "multiLine", aniContext)); break; - case ContentType::LOCAL_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent + case STSContentType::NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW: // systemLiveView?: NotificationLocalLiveViewContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationSystemLiveViewContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1297,7 +1325,7 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c RETURN_FALSE_IF_FALSE(SetNotificationLocalLiveViewContent(env, clsContent, basicContent.get(), aniContext)); RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "systemLiveView", aniContext)); break; - case ContentType::LIVE_VIEW: // liveView?: NotificationLiveViewContent + case STSContentType::NOTIFICATION_CONTENT_LIVE_VIEW: // liveView?: NotificationLiveViewContent RETURN_FALSE_IF_FALSE(!CreateClassObjByClassName(env, "Lnotification/notificationContent/NotificationLiveViewContentInner;", clsContent, aniContext)); RETURN_FALSE_IF_NULL(clsContent); @@ -1312,21 +1340,17 @@ bool SetNotificationContent(ani_env* env, std::shared_ptr c return true; } -bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, std::shared_ptr request, - ani_object &object) +bool SetNotificationRequestByNotificationContent(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { ANS_LOGE("request is nullptr"); return false; } - ContentType type = request->GetNotificationType(); - ani_enum_item typeItem; - RETURN_FALSE_IF_FALSE(ContentTypeCToEts(env, type, typeItem)); - RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "contentType", typeItem)); std::shared_ptr content = request->GetContent(); ani_object contentObj; - RETURN_FALSE_IF_FALSE(SetNotificationContent(env, content, type, contentObj)); + RETURN_FALSE_IF_FALSE(SetNotificationContent(env, content, contentObj)); RETURN_FALSE_IF_FALSE(contentObj == nullptr); RETURN_FALSE_IF_FALSE(CallSetter(env, cls, object, "content", contentObj)); return true; diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index 348219429..ee401e17d 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -28,6 +28,7 @@ #include "sts_do_not_disturb_profile.h" #include "sts_error_utils.h" #include "ans_inner_errors.h" +#include "sts_notification_request.h" using namespace OHOS::NotificationSts; namespace OHOS { @@ -50,8 +51,7 @@ static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) return; } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); ANS_LOGE("sts DisplayBadge error, errorCode: %{public}d", externalCode); return; @@ -82,8 +82,7 @@ static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); ANS_LOGE("sts IsBadgeDisplayed error, errorCode: %{public}d", externalCode); return BoolToAniBoolean(false); @@ -108,39 +107,47 @@ static ani_boolean isNotificationEnabled([[maybe_unused]]ani_env *env, ani_objec int32_t userId = 0; bool allowed = false; int32_t ret = 0; + int externalCode = 0; ani_boolean isUserIdUndefined = ANI_FALSE; ani_boolean isBundleUndefined = ANI_FALSE; - ANS_LOGI("isNotificationEnabled enter"); + ANS_LOGD("isNotificationEnabled enter"); - env->Reference_IsUndefined(jsUserId, &isUserIdUndefined); - env->Reference_IsUndefined(jsBundleOption, &isBundleUndefined); - - ANS_LOGI("isNotificationEnabled isUserIdUndefined = %{public}d isBundleUndefined = %{public}d", + if ((env->Reference_IsUndefined(jsUserId, &isUserIdUndefined) != ANI_OK) || + (env->Reference_IsUndefined(jsBundleOption, &isBundleUndefined) != ANI_OK)) { + ANS_LOGI("isNotificationEnabled Reference_IsUndefined error"); + externalCode = CJSystemapi::Notification::ERROR_INTERNAL_ERROR; + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + return BoolToAniBoolean(allowed); + } + + ANS_LOGD("isNotificationEnabled isUserIdUndefined = %{public}d isBundleUndefined = %{public}d", isUserIdUndefined, isBundleUndefined); - // 3. 解析 userId if (!isUserIdUndefined) { - ANS_LOGI("isNotificationEnabled ==>> isUserIdUndefined"); + ANS_LOGD("isNotificationEnabled ==>> isUserIdUndefined"); if (ANI_OK !=env->Object_CallMethodByName_Int(jsUserId, "intValue", nullptr, &userId)) { ANS_LOGI("isNotificationEnabled Object_CallMethodByName_Int Fail"); - userId = 0; - int externalCode = CJSystemapi::Notification::ERROR_PARAM_INVALID; + externalCode = CJSystemapi::Notification::ERROR_INTERNAL_ERROR; OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); return BoolToAniBoolean(allowed); } - ANS_LOGI("isNotificationEnabled IsAllowedNotify userId = %{public}d", userId); + ANS_LOGD("isNotificationEnabled IsAllowedNotify userId = %{public}d", userId); ret = Notification::NotificationHelper::IsAllowedNotify(userId, allowed); - } else if (!isBundleUndefined) { - ANS_LOGI("isNotificationEnabled ==>> isBundleUndefined"); + ANS_LOGD("isNotificationEnabled ==>> isBundleUndefined"); Notification::NotificationBundleOption option; - UnwrapBundleOption(env, jsBundleOption, option); - ANS_LOGI("uid = %{public}d, bundle = %{public}s", option.GetUid(), option.GetBundleName().c_str()); + if (!UnwrapBundleOption(env, jsBundleOption, option)) { + ANS_LOGI("isNotificationEnabled:: isBundleUndefined. UnwrapBundleOption ERROR"); + externalCode = CJSystemapi::Notification::ERROR_INTERNAL_ERROR; + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + return BoolToAniBoolean(allowed); + } + ANS_LOGD("uid = %{public}d, bundle = %{public}s", option.GetUid(), option.GetBundleName().c_str()); ret = Notification::NotificationHelper::IsAllowedNotify(option, allowed); } else { - ANS_LOGI("isNotificationEnabled ==>> no parameter"); + ANS_LOGD("isNotificationEnabled ==>> no parameter"); ret = Notification::NotificationHelper::IsAllowedNotify(allowed); } ANS_LOGI("isNotificationEnabled IsAllowedNotify ret = %{public}d allowed = %{public}d", ret, allowed); @@ -150,7 +157,6 @@ static ani_boolean isNotificationEnabled([[maybe_unused]]ani_env *env, ani_objec OHOS::AbilityRuntime::ThrowStsError(env, err, FindAnsErrMsg(err)); allowed = false; } else { - ANS_LOGI("isNotificationEnabled allowed %{public}d", allowed); allowed ? (allowed = true) : (allowed = false); } return BoolToAniBoolean(allowed); @@ -198,53 +204,105 @@ static ani_boolean IsNotificationSlotEnabled(ani_env *env, ani_object bundleOpti return isEnable ? ANI_TRUE : ANI_FALSE; } -static void CancelWithId(ani_env* env, ani_int id) +static void CancelWithId(ani_env* env, ani_double id) { - ANS_LOGD("Cancel by ID callback id:%{public}d", id); - int32_t ret = Notification::NotificationHelper::CancelNotification(id); - if (ret != ERR_OK) { - ANS_LOGE("Cancel failed! Error:%{public}d", ret); + ANS_LOGD("sts CancelWithId call, id:%{public}lf", id); + int32_t ret = Notification::NotificationHelper::CancelNotification(static_cast(id)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts CancelWithId error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts CancelWithId end, externalCode: %{public}d", externalCode); +} + +static void CancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string label) +{ + ANS_LOGD("sts CancelWithIdOptinalLabel call, id:%{public}lf", id); + ani_boolean isUndefined = ANI_FALSE; + env->Reference_IsUndefined(label, &isUndefined); + int32_t ret = 0; + if(isUndefined) { + ANS_LOGE("sts CancelWithIdOptinalLabel the label is undefined"); + ret = Notification::NotificationHelper::CancelNotification(static_cast(id)); + } else { + std::string labelStr; + if (ANI_OK != GetStdString(env, label, labelStr)) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts CancelWithIdOptinalLabel ERROR_INTERNAL_ERROR"); + return; + } + ANS_LOGD("sts CancelWithIdOptinalLabel id:%{public}lf label:%{public}s", id, labelStr.c_str()); + ret = Notification::NotificationHelper::CancelNotification(labelStr, id); } + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts CancelWithIdOptinalLabel error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts CancelWithIdOptinalLabel end, externalCode: %{public}d", externalCode); } -static void CancelWithIdLabel(ani_env* env, ani_int id, ani_string label) +static void CancelWithIdLabel(ani_env* env, ani_double id, ani_string label) { + ANS_LOGD("sts CancelWithIdLabel call, id:%{public}lf", id); std::string labelStr; if (ANI_OK != GetStdString(env, label, labelStr)) { - ANS_LOGE("Label parse failed!"); + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts CancelWithIdLabel ERROR_INTERNAL_ERROR"); return; } - - ANS_LOGD("Cancel by label id:%{public}d label:%{public}s", id, labelStr.c_str()); - int32_t ret = Notification::NotificationHelper::CancelNotification(labelStr, id); - if (ret != ERR_OK) { - ANS_LOGE("Cancel failed! Error:%{public}d", ret); + ANS_LOGD("sts CancelWithIdLabel id:%{public}lf label:%{public}s", id, labelStr.c_str()); + int32_t ret = Notification::NotificationHelper::CancelNotification(labelStr, static_cast(id)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts CancelWithIdLabel error, errorCode: %{public}d", externalCode); + return; } + ANS_LOGD("sts CancelWithIdLabel end, externalCode: %{public}d", externalCode); } -static void CancelWithBundle(ani_env* env, ani_object bundleObj, ani_int id) +static void CancelWithBundle(ani_env* env, ani_object bundleObj, ani_double id) { + ANS_LOGD("sts CancelWithBundle call, id: %{public}lf", id); + int returncode = 0; Notification::NotificationBundleOption option; - if (!NotificationSts::UnwrapBundleOption(env, bundleObj, option)) { - ANS_LOGE("Invalid BundleOption!"); + bool bFlag = UnwrapBundleOption(env, bundleObj, option); + ANS_LOGD("sts CancelWithBundle option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), + option.GetUid(), bFlag); + if(bFlag) { + returncode = Notification::NotificationHelper::CancelAsBundleWithAgent(option, static_cast(id)); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts CancelWithBundle ERROR_INTERNAL_ERROR"); return; } - - ANS_LOGD("Cancel by bundle:%{public}s id:%{public}d", - option.GetBundleName().c_str(), id); - int32_t ret = Notification::NotificationHelper::CancelAsBundle(option, id); - if (ret != ERR_OK) { - ANS_LOGE("Cancel failed! Error:%{public}d", ret); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts CancelWithBundle error, errorCode: %{public}d", externalCode); + return; } + ANS_LOGD("sts CancelWithBundle end, ret: %{public}d", externalCode); } static void CancelAll(ani_env* env) { - ANS_LOGD("Cancel all notifications"); + ANS_LOGD("sts CancelAll call"); int32_t ret = Notification::NotificationHelper::CancelAllNotifications(); - if (ret != ERR_OK) { - ANS_LOGE("CancelAll failed! Error:%{public}d", ret); + int externalCode = CJSystemapi::Notification::ErrorToExternal(ret); + if (externalCode != ERR_OK) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts CancelAll error, errorCode: %{public}d", externalCode); + return; } + ANS_LOGD("sts CancelAll end, ret: %{public}d", externalCode); } static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) @@ -266,8 +324,7 @@ static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) } int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); - if (externalCode != 0) - { + if (externalCode != ERR_OK) { OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); ANS_LOGE("sts GetSlotsByBundle error, errorCode: %{public}d", externalCode); return nullptr; @@ -333,6 +390,55 @@ static void SetNotificationEnableSlotByOld(ani_env *env, ani_object bundleOption isForceControl); } +static ani_object NativeGetAllActiveNotifications(ani_env *env, [[maybe_unused]]ani_class aniClass) +{ + std::vector> notifications; + int32_t ret = NotificationHelper::GetAllActiveNotifications(notifications); + if (ret!= ERR_OK) { + ANS_LOGE("GetAllActiveNotifications failed, ret = %{public}d", ret); + return nullptr; + } + + ani_object arrayObject = NotificationSts::ConvertNotificationArrayToAni(env, notifications); + if (arrayObject == nullptr) { + ANS_LOGE("ConvertNotificationArrayToAni failed"); + return nullptr; + } + return arrayObject; +} + +static void NativePublish(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj) +{ + std::shared_ptr notificationRequest = std::make_shared(); + if (UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { + ANS_LOGE("UnWarpNotificationRequest failed"); + return; + } + int32_t ret = NotificationHelper::PublishNotification(*notificationRequest); + if (ret != 0) { + ANS_LOGE("PublishNotification failed, return ret = %{public}d", ret); + } + ANS_LOGD("NativePublish leave"); +} + +static void NativePublishIncludeUserId(ani_env *env, [[maybe_unused]]ani_class aniClass, ani_object obj, + ani_double userId) +{ + //NotificationRequest request; + std::shared_ptr notificationRequest = std::make_shared(); + if (UnWarpNotificationRequest(env, obj, notificationRequest) != ANI_OK) { + ANS_LOGE("UnWarpNotificationRequest failed"); + return; + } + notificationRequest->SetOwnerUserId(static_cast(userId)); + int32_t ret = NotificationHelper::PublishNotification(*notificationRequest); + if (ret != 0) { + ANS_LOGE("PublishNotification failed, return ret = %{public}d", ret); + } + ANS_LOGD("NativePublishIncludeUserId leave"); + +} + void StsNotificationManagerRegistryInit(ani_env *env) { ANS_LOGD("StsNotificationManagerRegistryInit call"); @@ -361,6 +467,7 @@ void StsNotificationManagerRegistryInit(ani_env *env) reinterpret_cast(IsNotificationSlotEnabled)}, ani_native_function {"nativeCancelWithId", nullptr, reinterpret_cast(CancelWithId)}, ani_native_function {"nativeCancelWithIdLabel", nullptr, reinterpret_cast(CancelWithIdLabel)}, + ani_native_function {"nativeCancelWithIdOptionalLabel", nullptr, reinterpret_cast(CancelWithIdOptinalLabel)}, ani_native_function {"nativeCancelWithBundle", nullptr, reinterpret_cast(CancelWithBundle)}, ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(CancelAll)}, ani_native_function {"nativeGetSlotsByBundle", nullptr, reinterpret_cast(GetSlotsByBundle)}, @@ -369,6 +476,10 @@ void StsNotificationManagerRegistryInit(ani_env *env) ani_native_function {"nativeSetNotificationEnableSlot", nullptr, reinterpret_cast(SetNotificationEnableSlot)}, ani_native_function {"nativeSetNotificationEnableSlotByOld", nullptr, reinterpret_cast(SetNotificationEnableSlotByOld)}, + ani_native_function {"nativeGetAllActiveNotifications", nullptr, + reinterpret_cast(NativeGetAllActiveNotifications)}, + ani_native_function {"nativePublishIncludeUserId", nullptr, reinterpret_cast(NativePublishIncludeUserId)}, + ani_native_function {"nativePublish", nullptr, reinterpret_cast(NativePublish)}, }; diff --git a/frameworks/ani/notification_manager/src/sts_notification_request.cpp b/frameworks/ani/notification_manager/src/sts_notification_request.cpp index 76563a8a4..baac7d1da 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_request.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_request.cpp @@ -19,6 +19,12 @@ #include "want_params.h" #include "want_agent.h" #include "sts_notification_request.h" +#include "notification_distributed_options.h" +#include "notification_constant.h" +#include "notification.h" +#include "pixel_map_ani.h" +#include "notification_template.h" +#include "ans_convert_enum.h" namespace OHOS { namespace NotificationSts { @@ -26,7 +32,7 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::AAFwk; using WantAgent = OHOS::AbilityRuntime::WantAgent::WantAgent; -bool SetNotificationRequestByString(ani_env* env, ani_class cls, std::shared_ptr request, +bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { @@ -66,7 +72,7 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, std::shared_ptr return true; } -bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, std::shared_ptr request, +bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { @@ -101,7 +107,7 @@ bool SetNotificationRequestByNumber(ani_env* env, ani_class cls, std::shared_ptr return true; } -bool SetNotificationRequestByBool(ani_env* env, ani_class cls, std::shared_ptr request, +bool SetNotificationRequestByBool(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { @@ -148,10 +154,10 @@ ani_object ConvertNotificationActionButtonToAniObject(ani_env* env, RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "title", stringValue)); // wantAgent: WantAgent; // need to do - // extras?: Record; napiûдḶ֪́Ǹɶģ + // extras?: Record; napi��û�д������Ĺ��̣���֪���Ǹ�ɶ�ģ� // need to do - //TODO(δת) + //TODO(δת������) // userInput?: NotificationUserInput -> inputKey: string; ani_object userInputObject = nullptr; @@ -286,31 +292,31 @@ bool SetNotificationUnifiedGroupInfo(ani_env* env, "Lnotification/notificationRequest/UnifiedGroupInfoInner;", groupInfoCls, groupInfoObject)); // key?: string; ani_string stringValue = nullptr; - RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetKey(), stringValue)); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "key", stringValue)); + if (GetAniString(env, groupInfo->GetKey(), stringValue)) { + CallSetterOptional(env, groupInfoCls, groupInfoObject, "key", stringValue); + } // title?: string; - RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetTitle(), stringValue)); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "title", stringValue)); + if (GetAniString(env, groupInfo->GetTitle(), stringValue)) { + CallSetterOptional(env, groupInfoCls, groupInfoObject, "title", stringValue); + } // content?: string; - RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetContent(), stringValue)); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "content", stringValue)); + if (GetAniString(env, groupInfo->GetContent(), stringValue)) { + CallSetterOptional(env, groupInfoCls, groupInfoObject, "content", stringValue); + } // sceneName?: string; - RETURN_FALSE_IF_FALSE(GetAniString(env, groupInfo->GetSceneName(), stringValue)); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "sceneName", stringValue)); + if (GetAniString(env, groupInfo->GetSceneName(), stringValue)) { + CallSetterOptional(env, groupInfoCls, groupInfoObject, "sceneName", stringValue); + } // extraInfo?: Record; std::shared_ptr extraInfo = groupInfo->GetExtraInfo(); if (extraInfo) { ani_ref valueRef = OHOS::AppExecFwk::WrapWantParams(env, *extraInfo); - RETURN_FALSE_IF_FALSE(CallSetterOptional(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef)); + CallSetterOptional(env, groupInfoCls, groupInfoObject, "extraInfo", valueRef); } - - // need to do check - //TODO(δת) - return true; } -bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, std::shared_ptr request, +bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, const OHOS::Notification::NotificationRequest *request, ani_object &object) { if (request == nullptr) { @@ -319,9 +325,12 @@ bool SetNotificationRequestByCustom(ani_env* env, ani_class cls, std::shared_ptr } // content: NotificationContent RETURN_FALSE_IF_FALSE(SetNotificationRequestByNotificationContent(env, cls, request, object)); - - // need to do TODO(δת) ˴napiת // extraInfo?: {[key:string] : any} + std::shared_ptr additionalData = request->GetAdditionalData(); + if (additionalData) { + ani_ref extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "extraInfo", extraInfo)); + } // actionButtons?: Array std::vector> actionButtons = request->GetActionButtons(); @@ -873,9 +882,9 @@ void GetNotificationTemplate(ani_env *env, ani_object obj, } ani_boolean isUndefind = ANI_TRUE; if ((status = env->Reference_IsUndefined(templateRef, &isUndefind)) == ANI_OK && isUndefind == ANI_FALSE) { - Notification::NotificationTemplate tmplate; + OHOS::Notification::NotificationTemplate tmplate; UnwrapNotificationTemplate(env, static_cast(templateRef), tmplate); - request->SetTemplate(std::make_shared(tmplate)); + request->SetTemplate(std::make_shared(tmplate)); } } @@ -942,14 +951,14 @@ void GetNotificationBundleOption(ani_env *env, ani_object obj, if ((status = env->Reference_IsUndefined(optionRef, &isUndefind)) != ANI_OK || isUndefind == ANI_TRUE) { return; } - Notification::NotificationBundleOption option; + OHOS::Notification::NotificationBundleOption option; if(ANI_OK == UnwrapBundleOption(env, static_cast(optionRef), option)) { - request->SetBundleOption(std::make_shared(option)); + request->SetBundleOption(std::make_shared(option)); } } ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, - std::shared_ptr ¬ificationRequest) + std::shared_ptr ¬ificationRequest) { ani_status status = ANI_ERROR; if((status = GetNotificationContent(env, obj, notificationRequest)) != ANI_OK) { @@ -990,27 +999,240 @@ ani_status UnWarpNotificationRequest(ani_env *env, ani_object obj, return status; } -ani_object WarpNotificationRequest(ani_env *env, std::shared_ptr notificationRequest) +bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const NotificationRequest *request, + ani_object &object) { - ani_class cls; - ani_object outAniObj; + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // smallIcon?: image.PixelMap + std::shared_ptr littleIcon = request->GetLittleIcon(); + if (littleIcon) { + ani_object smallIconResult = Media::PixelMapAni::CreatePixelMap(env, littleIcon); + if (smallIconResult == nullptr) { + ANS_LOGE("CreatePixelMap failed,, smallIconResult is nullptr "); + return false; + } + CallSetterOptional(env, cls, object, "smallIcon", smallIconResult); + } + // largeIcon?: image.PixelMap + std::shared_ptr largeIcon = request->GetBigIcon(); + if (largeIcon) { + ani_object largeIconResult = Media::PixelMapAni::CreatePixelMap(env, largeIcon); + if (largeIconResult == nullptr) { + ANS_LOGE("CreatePixelMap failed, largeIconResult is nullptr"); + return false; + } + CallSetterOptional(env, cls, object, "largeIcon", largeIconResult); + } + // overlayIcon?: image.PixelMap + std::shared_ptr overlayIcon = request->GetOverlayIcon(); + if (overlayIcon) { + ani_object overlayIconResult = Media::PixelMapAni::CreatePixelMap(env, overlayIcon); + if (overlayIconResult == nullptr) { + ANS_LOGE("CreatePixelMap failed, overlayIconResult is nullptr"); + return false; + } + CallSetterOptional(env, cls, object, "overlayIcon", overlayIconResult); + } + return true; +} + +bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::NotificationRequest *notificationRequest, + ani_class &cls, ani_object &outAniObj) +{ + if (notificationRequest == nullptr) { + ANS_LOGE("notification is null"); + return false; + } if(!CreateClassObjByClassName(env, "Lnotification/notificationRequest/NotificationRequestInner;", cls, outAniObj)) { - return nullptr; + return false; } if(!SetNotificationRequestByBool(env, cls, notificationRequest, outAniObj)) { - return nullptr; + return false; } if(!SetNotificationRequestByString(env, cls, notificationRequest, outAniObj)) { - return nullptr; + return false; } if(!SetNotificationRequestByNumber(env, cls, notificationRequest, outAniObj)) { - return nullptr; + return false; + } + // need to do + /* if (!SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)) { + ANS_LOGE("SetNotificationRequestByWantAgent failed"); + return false; + } */ + if (!SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)) { + return false; } if(SetNotificationRequestByCustom(env, cls, notificationRequest, outAniObj)) { + return false; + } + return true; +} + +bool DeviceRemindTypeCToEts(const NotificationConstant::RemindType &inType, NotificationNapi::DeviceRemindType &outType) +{ + switch (inType) { + case NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND: + outType = NotificationNapi::DeviceRemindType::IDLE_DONOT_REMIND; + break; + case NotificationConstant::RemindType::DEVICE_IDLE_REMIND: + outType = NotificationNapi::DeviceRemindType::IDLE_REMIND; + break; + case NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND: + outType = NotificationNapi::DeviceRemindType::ACTIVE_DONOT_REMIND; + break; + case NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND: + outType = NotificationNapi::DeviceRemindType::ACTIVE_REMIND; + break; + default: + ANS_LOGE("DeviceRemindType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool SetNotificationByDistributedOptions(ani_env *env, const OHOS::Notification::Notification *notification, + ani_class cls, ani_object &outAniObj) +{ + if (notification == nullptr) { + ANS_LOGE("notification is null"); + return false; + } + NotificationDistributedOptions options = notification->GetNotificationRequest().GetNotificationDistributedOptions(); + // isDistributed?: boolean; + if (notification->GetDeviceId().empty()) { + CallSetterOptional(env, cls, outAniObj, "isDistributed", + BoolToAniBoolean(false)); + } else { + CallSetterOptional(env, cls, outAniObj, "isDistributed", + BoolToAniBoolean(options.IsDistributed())); + } + // readonly remindType?: number; + enum NotificationNapi::DeviceRemindType outType = NotificationNapi::DeviceRemindType::IDLE_DONOT_REMIND; + if (!DeviceRemindTypeCToEts(notification->GetRemindType(), outType)) { + return false; + } + CallSetterOptional(env, cls, outAniObj, "remindType", static_cast(outType)); + // supportDisplayDevices?: Array; + std::vector displayDevices = options.GetDevicesSupportDisplay(); + ani_object devicesObjectArray = ConvertVectorToAniArrayString(env, displayDevices); + if (devicesObjectArray == nullptr) { + ANS_LOGE("devicesObjectArray is nullptr"); + return false; + } + CallSetterOptional(env, cls, outAniObj, "supportDisplayDevices", devicesObjectArray); + // supportOperateDevices?: Array; + std::vector operateDevices = options.GetDevicesSupportOperate(); + ani_object operateObjectArray = ConvertVectorToAniArrayString(env, operateDevices); + if (operateObjectArray == nullptr) { + ANS_LOGE("operateObjectArray is nullptr"); + return false; + } + CallSetterOptional(env, cls, outAniObj, "supportOperateDevices", operateObjectArray); + return true; +} + +ani_object ConvertNotificationToAni(ani_env* env, const OHOS::Notification::Notification *notification) +{ + if (notification == nullptr) { + ANS_LOGE("notification is null"); + return nullptr; + } + ani_class requestcls = nullptr; + ani_object requestObj = nullptr; + NotificationRequest request = notification->GetNotificationRequest(); + if (!WarpNotificationRequest(env, &request, requestcls, requestObj)) { + return nullptr; + } + // readonly hashCode?: string; + ani_string stringValue = nullptr; + if (GetAniString(env, notification->GetKey(), stringValue)) { + CallSetterOptional(env, requestcls, requestObj, "hashCode", stringValue); + } + // readonly creatorUserId?: number; + CallSetterOptional(env, requestcls, requestObj, "creatorUserId", notification->GetRecvUserId()); + // distributedOption?: DistributedOptions; + ani_object distributedObj = nullptr; + ani_class distributedCls = nullptr; + if(!CreateClassObjByClassName(env, + "Lnotification/notificationRequest/DistributedOptionsInner;", distributedCls, distributedObj)) { + return nullptr; + } + if (!SetNotificationByDistributedOptions(env, notification, distributedCls, distributedObj)) { + return nullptr; + } + CallSetterOptional(env, requestcls, requestObj, "distributedOption", distributedObj); + // isRemoveAllowed?: boolean; + CallSetterOptional(env, requestcls, requestObj, "isRemoveAllowed", + BoolToAniBoolean(notification->IsRemoveAllowed())); + // readonly source?: number; + int32_t source = static_cast(notification->GetSourceType()); + CallSetterOptional(env, requestcls, requestObj, "source", source); + // readonly deviceId?: string; + if (GetAniString(env, notification->GetDeviceId(), stringValue)) { + CallSetterOptional(env, requestcls, requestObj, "deviceId", stringValue); + } + // notificationControlFlags?: number; + CallSetterOptional(env, requestcls, requestObj, "notificationControlFlags", + notification->GetNotificationRequest().GetNotificationControlFlags()); + // isFloatingIcon?: boolean; + CallSetterOptional(env, requestcls, requestObj, "isFloatingIcon", + BoolToAniBoolean(notification->IsFloatingIcon())); + // readonly creatorBundleName?: string; + if (GetAniString(env, notification->GetBundleName(), stringValue)) { + CallSetterOptional(env, requestcls, requestObj, "creatorBundleName", stringValue); + } + // readonly creatorUid?: number; + CallSetterOptional(env, requestcls, requestObj, "creatorUid", + notification->GetNotificationRequest().GetOwnerUid()); + // readonly creatorPid?: number; + CallSetterOptional(env, requestcls, requestObj, "creatorPid", notification->GetPid()); + return requestObj; +} + +ani_object ConvertNotificationArrayToAni(ani_env* env, + const std::vector> ¬ifications) +{ + ani_class arrayCls = nullptr; + ani_method arrayCtor; + ani_object arrayObj; + ani_status status = ANI_ERROR; + status = env->FindClass("Lescompat/Array;", &arrayCls); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + + status = env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); + return nullptr; + } + + status = env->Object_New(arrayCls, arrayCtor, &arrayObj, notifications.size()); + if (status != ANI_OK) { + ANS_LOGE("status : %{public}d", status); return nullptr; } - return outAniObj; + ani_size index = 0; + for (auto ¬ification : notifications) { + if (notification == nullptr) { + ANS_LOGE("notification is nullptr"); + return nullptr; + } + ani_object item = ConvertNotificationToAni(env, notification.GetRefPtr()); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } + return arrayObj; } } // name space NotificationSts } // name space OHOS diff --git a/frameworks/ani/notification_manager/src/sts_notification_template.cpp b/frameworks/ani/notification_manager/src/sts_notification_template.cpp index 9abf544df..47ee412e1 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_template.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_template.cpp @@ -23,7 +23,7 @@ namespace OHOS { namespace NotificationSts { using namespace OHOS::AppExecFwk; using namespace OHOS::AAFwk; -ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, Notification::NotificationTemplate& tmplate) +ani_status UnwrapNotificationTemplate(ani_env *env, ani_object aniObj, OHOS::Notification::NotificationTemplate& tmplate) { ani_status status = ANI_ERROR; ani_ref nameRef; -- Gitee From 4881fb7509643b6a289f1cc2b92288a64b525589 Mon Sep 17 00:00:00 2001 From: liujx9645 Date: Tue, 13 May 2025 09:25:08 +0800 Subject: [PATCH 9/9] =?UTF-8?q?feat:=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by:liujx9645 --- frameworks/ani/notification_manager/BUILD.gn | 2 +- .../ets/@ohos.notificationManager.ets | 60 +++-- .../notification/NotificationCommonDef.ets | 2 +- .../notification/notificationActionButton.ets | 11 + .../ets/notification/notificationContent.ets | 111 +++++---- .../ets/notification/notificationFlags.ets | 2 +- .../ets/notification/notificationRequest.ets | 174 ++++++++------ .../ets/notification/notificationSlot.ets | 26 +-- .../ets/notification/notificationTemplate.ets | 5 + .../notification/notificationUserInput.ets | 4 + .../include/sts_common_util.h | 31 ++- .../src/sts_notification_content.cpp | 23 +- .../src/sts_notification_manager.cpp | 218 ++++++++++++++---- .../src/sts_notification_request.cpp | 56 ++++- 14 files changed, 507 insertions(+), 218 deletions(-) diff --git a/frameworks/ani/notification_manager/BUILD.gn b/frameworks/ani/notification_manager/BUILD.gn index feb0ff453..d91eb3ccd 100644 --- a/frameworks/ani/notification_manager/BUILD.gn +++ b/frameworks/ani/notification_manager/BUILD.gn @@ -55,7 +55,6 @@ ohos_shared_library("notification_manager_ani_kit") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_path}/cj/ffi:cj_notification_manager_ffi", - #"${core_path}:ans_core", ] external_deps = [ @@ -67,6 +66,7 @@ ohos_shared_library("notification_manager_ani_kit") { "ability_runtime:ani_common", "ability_runtime:aniwantagent", "ability_runtime:wantagent_innerkits", + "ability_runtime:ani_wantagent_common", "ability_runtime:runtime", "napi:ace_napi", "image_framework:image_native", diff --git a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets index f09f3c203..73c1e825d 100644 --- a/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets +++ b/frameworks/ani/notification_manager/ets/@ohos.notificationManager.ets @@ -14,6 +14,7 @@ */ import { BundleOption } from 'notification.NotificationCommonDef'; +import { NotificationRequest } from 'notification.notificationRequest'; import { BusinessError, AsyncCallback } from '@ohos.base'; import { NotificationSlot } from 'notification.notificationSlot'; @@ -71,7 +72,7 @@ export default namespace notificationManager { export native function nativegetSlotFlagsByBundle(bundle: BundleOption): int; export native function nativesetSlotFlagsByBundle(bundle: BundleOption, slotFlags: number): void; export native function nativeSetNotificationEnable(bundle: BundleOption, enable: boolean): void; - export native function nativeisNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; + export native function nativeIsNotificationSlotEnabled(bundle: BundleOption, type: SlotType): boolean; export native function nativeCancelWithId(id: number): void; export native function nativeCancelWithIdOptionalLabel(id: number, label?: string): void; export native function nativeCancelWithIdLabel(id: number, label: string): void; @@ -82,6 +83,7 @@ export default namespace notificationManager { export native function nativeremoveDoNotDisturbProfile(templates: Array): void; export native function nativeSetNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): void; export native function nativeSetNotificationEnableSlotByOld(bundle: BundleOption, type: SlotType, enable: boolean): void; + export native function nativegetActiveNotifications():Array; export function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeDisplayBadge(bundle, enable); }); @@ -269,16 +271,17 @@ export default namespace notificationManager { export function setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeSetNotificationEnable(bundle, enable); }); p.then((data: NullishType): void => { - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise - { + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { - let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; resolve(ret); @@ -289,14 +292,16 @@ export default namespace notificationManager { return pPromise; } - export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void - { - let p = taskpool.execute((): boolean => { return nativeisNotificationSlotEnabled(bundle, type); }); + export function isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void { + let p = taskpool.execute((): boolean => { return nativeIsNotificationSlotEnabled(bundle, type); }); p.then((data: NullishType): void => { let ret : boolean = data as boolean; - let err: BusinessError = {code: 1, data: undefined}; + let err: BusinessError = {code: 0, data: undefined}; callback(err, ret); }, (error: Object): void => { + let ret : boolean = false; + let err: BusinessError = error as BusinessError; + callback(err, ret); }) } @@ -419,28 +424,29 @@ export default namespace notificationManager { return pPromise; } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void - { + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlotByOld(bundle, type, enable); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 1, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void - { + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl: boolean, callback: AsyncCallback): void { let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); p.then((data: NullishType): void => { let err: BusinessError = {code: 1, data: undefined}; callback(err, undefined); }, (error: Object): void => { + let err: BusinessError = error as BusinessError; + callback(err, undefined); }) } - export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise - { + export function setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, isForceControl?: boolean): Promise { let pPromise = new Promise((resolve: ResolveCallback, reject: RejectCallback): void => { let p = taskpool.execute((): void => { return nativeSetNotificationEnableSlot(bundle, type, enable, isForceControl); }); p.then((data: NullishType): void => { @@ -451,4 +457,28 @@ export default namespace notificationManager { }); return pPromise; } + + export function getActiveNotifications(callback: AsyncCallback>): void + { + let p = taskpool.execute((): Array => { return nativegetActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + let err: BusinessError = {code: 1, data: undefined}; + callback(err, ret); + }, (error: Object): void => { + }) + } + + export function getActiveNotifications(): Promise> { + let pPromise = new Promise>((resolve: ResolveCallback>, reject: RejectCallback): void => { + let p = taskpool.execute((): Array => { return nativegetActiveNotifications(); }); + p.then((data: NullishType): void => { + let ret : Array = data as Array; + resolve(ret); + }, (error: Object): void => { + reject(error); + }); + }); + return pPromise; + } } diff --git a/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets index 32fc5f345..df9b94892 100644 --- a/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets +++ b/frameworks/ani/notification_manager/ets/notification/NotificationCommonDef.ets @@ -20,5 +20,5 @@ export interface BundleOption { class BundleOptionInner implements BundleOption { public bundle: string = ''; - public uid?: number; + public uid?: number | undefined; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets b/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets index 857960052..509e4a494 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationActionButton.ets @@ -25,4 +25,15 @@ export interface NotificationActionButton { extras?: Record; userInput?: NotificationUserInput; +} + +class NotificationActionButtonInner implements NotificationActionButton { + + title: string = ""; + + wantAgent: WantAgent = {}; + + extras?: Record | undefined; + + userInput?: NotificationUserInput | undefined; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets index 1679a06fb..11d78c74e 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationContent.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationContent.ets @@ -19,7 +19,7 @@ import type notificationManager from '@ohos.notificationManager'; type IconType = Resource | image.PixelMap; -export class RecordTools { +class RecordTools { public static GetKeys(record: Record): Array { try { let keys: Array = Object.keys(record); @@ -30,6 +30,14 @@ export class RecordTools { } } +class ResourceInner implements Resource { + bundleName: string = ""; + moduleName: string = ""; + id: number = 0; + params?: Array | undefined; + type?: number | undefined; +} + export interface NotificationBasicContent { title: string; @@ -47,9 +55,9 @@ class NotificationBasicContentInner implements NotificationBasicContent { text: string = ""; - additionalText?: string; + additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; } export interface NotificationLongTextContent extends NotificationBasicContent { @@ -69,7 +77,7 @@ class NotificationLongTextContentInner implements NotificationLongTextContent { additionalText?: string; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; longText: string = ""; @@ -117,19 +125,19 @@ class NotificationLiveViewContentInner implements NotificationLiveViewContent { text: string = ""; - additionalText?: string; + additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; status: LiveViewStatus = LiveViewStatus.LIVE_VIEW_CREATE; - version?: number; + version?: number | undefined; - extraInfo?: Record; + extraInfo?: Record | undefined; - pictureInfo?: Record>; + pictureInfo?: Record> | undefined; - isLocalUpdateOnly?: boolean; + isLocalUpdateOnly?: boolean | undefined; } export interface NotificationMultiLineContent extends NotificationBasicContent { @@ -147,9 +155,9 @@ class NotificationMultiLineContentInner implements NotificationMultiLineContent text: string = ""; - additionalText?: string; + additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; briefText: string = ""; @@ -177,9 +185,9 @@ class NotificationPictureContentInner implements NotificationPictureContent { text: string = ""; - additionalText?: string; + additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; briefText: string = ""; @@ -206,18 +214,18 @@ export interface NotificationSystemLiveViewContent extends NotificationBasicCont } class NotificationSystemLiveViewContentInner implements NotificationSystemLiveViewContent { - private CreatePixelMap() : image.PixelMap { - let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } - return image.createPixelMapSync(opts); - } + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 6 } } + return image.createPixelMapSync(opts); + } title: string = ""; text: string = ""; - additionalText?: string; + additionalText?: string | undefined; - lockscreenPicture?: image.PixelMap; + lockscreenPicture?: image.PixelMap | undefined; briefText: string = ""; @@ -227,17 +235,17 @@ class NotificationSystemLiveViewContentInner implements NotificationSystemLiveVi typeCode: number = 0; - capsule?: NotificationCapsule; + capsule?: NotificationCapsule | undefined; - button?: NotificationButton; + button?: NotificationButton | undefined; - cardButtons?: Array; + cardButtons?: Array | undefined; - time?: NotificationTime; + time?: NotificationTime | undefined; - progress?: NotificationProgress; + progress?: NotificationProgress | undefined; - liveViewType?: LiveViewTypes; + liveViewType?: LiveViewTypes | undefined; } export interface NotificationCapsule { @@ -257,17 +265,17 @@ export interface NotificationCapsule { class NotificationCapsuleInner implements NotificationCapsule { - title?: string; + title?: string | undefined; - icon?: image.PixelMap; + icon?: image.PixelMap | undefined; - backgroundColor?: string; + backgroundColor?: string | undefined; - content?: string; + content?: string | undefined; - time?: number; + time?: number | undefined; - capsuleButtons?: Array; + capsuleButtons?: Array | undefined; } export interface NotificationIconButton { @@ -283,17 +291,18 @@ export interface NotificationIconButton { class NotificationIconButtonInner implements NotificationIconButton { - private CreatePixelMap() : image.PixelMap { - let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } - return image.createPixelMapSync(opts); - } + private CreatePixelMap() : image.PixelMap { + let opts: image.InitializationOptions = { size: { height: 4, width: 4 } } + return image.createPixelMapSync(opts); + } + name: string = ""; iconResource: IconType = this.CreatePixelMap(); - text?: string; + text?: string | undefined; - hidePanel?: boolean; + hidePanel?: boolean | undefined; } export interface NotificationButton { @@ -307,11 +316,11 @@ export interface NotificationButton { class NotificationButtonInner implements NotificationButton { - names?: Array; + names?: Array | undefined; - icons?: Array; + icons?: Array | undefined; - iconsResource?: Array; + iconsResource?: Array | undefined; } export interface NotificationTime { @@ -347,11 +356,11 @@ export interface NotificationProgress { class NotificationProgressInner implements NotificationProgress { - maxValue?: number; + maxValue?: number | undefined; - currentValue?: number; + currentValue?: number | undefined; - isPercentage?: boolean; + isPercentage?: boolean | undefined; } export interface NotificationContent { @@ -373,17 +382,17 @@ export interface NotificationContent { class NotificationContentInner implements NotificationContent { - notificationContentType?: notificationManager.ContentType; + notificationContentType?: notificationManager.ContentType | undefined; - normal?: NotificationBasicContent; + normal?: NotificationBasicContent | undefined; - longText?: NotificationLongTextContent; + longText?: NotificationLongTextContent | undefined; - multiLine?: NotificationMultiLineContent; + multiLine?: NotificationMultiLineContent | undefined; - picture?: NotificationPictureContent; + picture?: NotificationPictureContent | undefined; - systemLiveView?: NotificationSystemLiveViewContent; + systemLiveView?: NotificationSystemLiveViewContent | undefined; - liveView?: NotificationLiveViewContent; + liveView?: NotificationLiveViewContent | undefined; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets b/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets index e5404faed..e5480471a 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationFlags.ets @@ -37,5 +37,5 @@ class NotificationFlagsInner implements NotificationFlags { vibrationEnabled?: NotificationFlagStatus| undefined; - reminderFlags?: number = -1; + reminderFlags?: number | undefined; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets index ea2f6e604..8a8224ecc 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationRequest.ets @@ -22,6 +22,60 @@ import { NotificationFlags } from 'notification.notificationFlags'; import { WantAgent } from '@ohos.app.ability.wantAgent'; import { BundleOption } from 'notification.NotificationCommonDef'; +export interface DistributedOptions { + isDistributed?: boolean; + supportDisplayDevices?: Array; + supportOperateDevices?: Array; + readonly remindType?: number; +} + +class DistributedOptionsInner implements DistributedOptions { + isDistributed?: boolean | undefined; + supportDisplayDevices?: Array | undefined; + supportOperateDevices?: Array | undefined; + readonly remindType?: number | undefined; +} + +export interface NotificationFilter { + bundle: BundleOption; + notificationKey: notificationSubscribe.NotificationKey; + extraInfoKeys?: Array; +} + +class NotificationFilterInner implements NotificationFilter { + bundle: BundleOption = {}; + notificationKey: notificationSubscribe.NotificationKey = {}; + extraInfoKeys?: Array | undefined; +} + +export interface NotificationCheckRequest { + contentType: notificationManager.ContentType; + slotType: notificationManager.SlotType; + extraInfoKeys: Array; +} + +class NotificationCheckRequestInner implements NotificationCheckRequest { + contentType: notificationManager.ContentType = notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + slotType: notificationManager.SlotType = notificationManager.SlotType.OTHER_TYPES; + extraInfoKeys: Array = {}; +} + +export interface UnifiedGroupInfo { + key?: string; + title?: string; + content?: string; + sceneName?: string; + extraInfo?: Record; +} + +class UnifiedGroupInfoInner implements UnifiedGroupInfo { + key?: string | undefined; + title?: string | undefined; + content?: string | undefined; + sceneName?: string | undefined; + extraInfo?: Record | undefined; +} + export interface NotificationRequest { content: NotificationContent; id?: number; @@ -76,76 +130,52 @@ export interface NotificationRequest { class NotificationRequestInner implements NotificationRequest { content: NotificationContent = {}; - id?: number; - appMessageId?: string; - notificationSlotType?: notificationManager.SlotType; - isOngoing?: boolean; - isUnremovable?: boolean; - updateOnly?: boolean; - deliveryTime?: number; - tapDismissed?: boolean; - autoDeletedTime?: number; - wantAgent?: WantAgent; - extraInfo?: Record; - color?: number; - colorEnabled?: boolean; - isAlertOnce?: boolean; - isStopwatch?: boolean; - isCountDown?: boolean; - isFloatingIcon?: boolean; - label?: string; - badgeIconStyle?: number; - showDeliveryTime?: boolean; - actionButtons?: Array; - smallIcon?: image.PixelMap; - largeIcon?: image.PixelMap; - overlayIcon?: image.PixelMap; - groupName?: string; - readonly creatorBundleName?: string; - readonly creatorUid?: number; - readonly creatorPid?: number; - readonly creatorUserId?: number; - readonly creatorInstanceKey?: number; - sound?: string; - classification?: string; - readonly hashCode?: string; - isRemoveAllowed?: boolean; - readonly source?: number; - template?: NotificationTemplate; - distributedOption?: DistributedOptions; - readonly deviceId?: string; - readonly notificationFlags?: NotificationFlags; - removalWantAgent?: WantAgent; - badgeNumber?: number; - representativeBundle?: BundleOption; - readonly agentBundle?: BundleOption; - unifiedGroupInfo?: UnifiedGroupInfo; - notificationControlFlags?: number; - readonly appInstanceKey?: string; - forceDistributed?: boolean; - notDistributed?: boolean; -} - -export interface DistributedOptions { - isDistributed?: boolean; - supportDisplayDevices?: Array; - supportOperateDevices?: Array; - readonly remindType?: number; -} -export interface NotificationFilter { - bundle: BundleOption; - notificationKey: notificationSubscribe.NotificationKey; - extraInfoKeys?: Array; -} -export interface NotificationCheckRequest { - contentType: notificationManager.ContentType; - slotType: notificationManager.SlotType; - extraInfoKeys: Array; + id?: number | undefined; + appMessageId?: string | undefined; + notificationSlotType?: notificationManager.SlotType | undefined; + isOngoing?: boolean | undefined; + isUnremovable?: boolean | undefined; + updateOnly?: boolean | undefined; + deliveryTime?: number | undefined; + tapDismissed?: boolean | undefined; + autoDeletedTime?: number | undefined; + wantAgent?: WantAgent | undefined; + extraInfo?: Record | undefined; + color?: number | undefined; + colorEnabled?: boolean | undefined; + isAlertOnce?: boolean | undefined; + isStopwatch?: boolean | undefined; + isCountDown?: boolean | undefined; + isFloatingIcon?: boolean | undefined; + label?: string | undefined; + badgeIconStyle?: number | undefined; + showDeliveryTime?: boolean | undefined; + actionButtons?: Array | undefined; + smallIcon?: image.PixelMap | undefined; + largeIcon?: image.PixelMap | undefined; + overlayIcon?: image.PixelMap | undefined; + groupName?: string | undefined; + readonly creatorBundleName?: string | undefined; + readonly creatorUid?: number | undefined; + readonly creatorPid?: number | undefined; + readonly creatorUserId?: number | undefined; + readonly creatorInstanceKey?: number | undefined; + sound?: string | undefined; + classification?: string | undefined; + readonly hashCode?: string | undefined; + isRemoveAllowed?: boolean | undefined; + readonly source?: number | undefined; + template?: NotificationTemplate | undefined; + distributedOption?: DistributedOptions | undefined; + readonly deviceId?: string | undefined; + readonly notificationFlags?: NotificationFlags | undefined; + removalWantAgent?: WantAgent | undefined; + badgeNumber?: number | undefined; + representativeBundle?: BundleOption | undefined; + readonly agentBundle?: BundleOption | undefined; + unifiedGroupInfo?: UnifiedGroupInfo | undefined; + notificationControlFlags?: number | undefined; + readonly appInstanceKey?: string | undefined; + forceDistributed?: boolean | undefined; + notDistributed?: boolean | undefined; } -export interface UnifiedGroupInfo { - key?: string; - title?: string; - content?: string; - sceneName?: string; - extraInfo?: Record; -} \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets b/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets index e69b84515..8c6466d19 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationSlot.ets @@ -18,18 +18,18 @@ export interface NotificationSlot { } class NotificationSlotInner implements NotificationSlot { - notificationType?: notificationManager.SlotType; + notificationType?: notificationManager.SlotType | undefined; //level?: notification.SlotLevel; - desc?: string; - badgeFlag?: boolean; - bypassDnd?: boolean; - lockscreenVisibility?: number; - vibrationEnabled?: boolean; - sound?: string; - lightEnabled?: boolean; - lightColor?: number; - vibrationValues?: Array; - readonly enabled?: boolean; - readonly reminderMode?: number; - readonly authorizedStatus?: number; + desc?: string | undefined; + badgeFlag?: boolean | undefined; + bypassDnd?: boolean | undefined; + lockscreenVisibility?: number | undefined; + vibrationEnabled?: boolean | undefined; + sound?: string | undefined; + lightEnabled?: boolean | undefined; + lightColor?: number | undefined; + vibrationValues?: Array | undefined; + readonly enabled?: boolean | undefined; + readonly reminderMode?: number | undefined; + readonly authorizedStatus?: number | undefined; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets b/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets index 1c0a07e43..8033b7723 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationTemplate.ets @@ -16,4 +16,9 @@ export interface NotificationTemplate { name: string; data: Record; +} + +class NotificationTemplateInner implements NotificationTemplate { + name: string = ""; + data: Record = {}; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets b/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets index eef5e12cc..6ac04f685 100644 --- a/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets +++ b/frameworks/ani/notification_manager/ets/notification/notificationUserInput.ets @@ -15,4 +15,8 @@ export interface NotificationUserInput { inputKey: string; +} + +class NotificationUserInputInner implements NotificationUserInput { + inputKey: string = ""; } \ No newline at end of file diff --git a/frameworks/ani/notification_manager/include/sts_common_util.h b/frameworks/ani/notification_manager/include/sts_common_util.h index d84e4043d..ce13d9ef3 100644 --- a/frameworks/ani/notification_manager/include/sts_common_util.h +++ b/frameworks/ani/notification_manager/include/sts_common_util.h @@ -162,7 +162,7 @@ do } while (0) template -bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) +bool CallSetter(ani_env* env, ani_class cls, ani_object &object, const char* propertyName, valueType value) { RETURN_FALSE_IF_NULL(env); RETURN_FALSE_IF_NULL(cls); @@ -177,7 +177,7 @@ bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* prop } if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) { status = env->Object_CallMethod_Void(object, setter, static_cast(value)); } else { @@ -192,7 +192,7 @@ bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* prop template bool CallSetterOptional( - ani_env* env, ani_class cls, ani_object object, const char* propertyName, valueType value) + ani_env* env, ani_class cls, ani_object &object, const char* propertyName, valueType value) { RETURN_FALSE_IF_NULL(env); RETURN_FALSE_IF_NULL(cls); @@ -210,7 +210,7 @@ bool CallSetterOptional( ctorSig = "C:V"; } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) { valueClassName = "Lstd/core/Double;"; ctorSig = "D:V"; @@ -231,11 +231,15 @@ bool CallSetterOptional( return false; } ani_object valueObj = nullptr; - if constexpr (std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || - std::is_same_v || - std::is_same_v || std::is_same_v) { + if constexpr (std::is_same_v || std::is_same_v) { + status = env->Object_New(valueClass, ctor, &valueObj, value); + } else if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v) { status = env->Object_New(valueClass, ctor, &valueObj, static_cast(value)); + } else if constexpr (std::is_same_v) { + status = env->Object_New(valueClass, ctor, &valueObj, static_cast(value)); } else { ANS_LOGE("Classname %{public}s Unsupported", propertyName); return false; @@ -247,6 +251,17 @@ bool CallSetterOptional( return CallSetter(env, cls, object, propertyName, valueObj); } +[[maybe_unused]]static bool CallSetterNull(ani_env* env, ani_class cls, ani_object &object, const char* propertyName) +{ + ani_ref nullRef = nullptr; + ani_status status = env->GetNull(&nullRef); + if (status != ANI_OK) { + ANS_LOGE("GetNull %{public}s failed %{public}d", propertyName, status); + return false; + } + + return CallSetter(env, cls, object, propertyName, nullRef); +} } // namespace NotificationSts } // namespace OHOS #endif \ No newline at end of file diff --git a/frameworks/ani/notification_manager/src/sts_notification_content.cpp b/frameworks/ani/notification_manager/src/sts_notification_content.cpp index 84c35ae28..00e42f8ba 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_content.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_content.cpp @@ -20,6 +20,7 @@ #include "sts_notification_enum_type.h" #include "sts_notification_utils.h" #include "want_params.h" +#include "ani_common_want_agent.h" namespace OHOS { namespace NotificationSts { @@ -707,17 +708,17 @@ ani_object GetWantAgentArrayAniObject(ani_env *env, std::vectorObject_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ - // std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; - // return nullptr; - //} - //index ++; - //} + ani_object item = AppExecFwk::WrapWantAgent(env, wantAgent.get()); + RETURN_NULL_IF_NULL(item); + if(ANI_OK != env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, item)){ + std::cerr << "Object_CallMethodByName_Void $_set Faild " << std::endl; + return nullptr; + } + index ++; + } return arrayObj; } @@ -726,7 +727,7 @@ ani_object SetResourceObject(ani_env *env, const std::shared_ptrbundleName, stringValue)); diff --git a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp index ee401e17d..7e65e47ed 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_manager.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_manager.cpp @@ -37,7 +37,7 @@ namespace NotificationManagerSts { static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) { ANS_LOGD("sts DisplayBadge call"); - int returncode = 0; + int returncode = -1; Notification::NotificationBundleOption option; bool bFlag = UnwrapBundleOption(env, obj, option); ANS_LOGD("sts DisplayBadge option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), @@ -62,7 +62,7 @@ static void DisplayBadge(ani_env *env, ani_object obj, ani_boolean enable) static ani_boolean IsBadgeDisplayed(ani_env *env, ani_object obj) { ANS_LOGD("sts IsBadgeDisplayed call"); - int returncode = 0; + int returncode = -1; bool isDisplayed = false; if (obj == nullptr) { returncode = Notification::NotificationHelper::GetShowBadgeEnabled(isDisplayed); @@ -162,45 +162,113 @@ static ani_boolean isNotificationEnabled([[maybe_unused]]ani_env *env, ani_objec return BoolToAniBoolean(allowed); } -static ani_int getSlotFlagsByBundle(ani_env *env, ani_object obj) +static ani_int GetSlotFlagsByBundle(ani_env *env, ani_object obj) { ANS_LOGD("sts getSlotFlagsByBundle call"); Notification::NotificationBundleOption option; - UnwrapBundleOption(env, obj, option); + bool bFlag = UnwrapBundleOption(env, obj, option); + if (!bFlag) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts getSlotFlagsByBundle ERROR_INTERNAL_ERROR"); + return ERROR_INTERNAL_ERROR; + } uint32_t slotFlags = 0; - Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); + int returncode = Notification::NotificationHelper::GetNotificationSlotFlagsAsBundle(option, slotFlags); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts getSlotFlagsByBundle error, errorCode: %{public}d", externalCode); + return ERROR_INTERNAL_ERROR; + } + ANS_LOGI("sts getSlotFlagsByBundle end, slotFlags: %{public}d, ret: %{public}d", slotFlags, externalCode); return slotFlags; } -static void setSlotFlagsByBundle(ani_env *env, ani_object obj) +static void SetSlotFlagsByBundle(ani_env *env, ani_object obj) { ANS_LOGD("sts setSlotFlagsByBundle call"); Notification::NotificationBundleOption option; - UnwrapBundleOption(env, obj, option); + bool bFlag = UnwrapBundleOption(env, obj, option); + if (!bFlag) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts setSlotFlagsByBundle ERROR_INTERNAL_ERROR"); + return; + } uint32_t slotFlags = 0; - Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); + int returncode = Notification::NotificationHelper::SetNotificationSlotFlagsAsBundle(option, slotFlags); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts setSlotFlagsByBundle error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts setSlotFlagsByBundle end, ret: %{public}d", externalCode); return; } static void SetNotificationEnable(ani_env *env, ani_object bundleOption, ani_boolean enable) { - ANS_LOGD("SetNotificationEnable enter "); - Notification::NotificationBundleOption option; - UnwrapBundleOption(env, bundleOption, option); + ANS_LOGD("setNotificationEnable enter "); + Notification::NotificationBundleOption option; + bool bFlag = UnwrapBundleOption(env, bundleOption, option); + ANS_LOGD("setNotificationEnable option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", + option.GetBundleName().c_str(), option.GetUid(), bFlag); std::string deviceId {""}; - Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(option, deviceId, + int returncode = -1; + if(bFlag) { + returncode = Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(option, deviceId, AniBooleanToBool(enable)); + } else { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("setNotificationEnable ERROR_INTERNAL_ERROR"); + return; + } + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("setNotificationEnable error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("setNotificationEnable end, externalCode: %{public}d", externalCode); } static ani_boolean IsNotificationSlotEnabled(ani_env *env, ani_object bundleOption, ani_enum_item type) { ANS_LOGD("isNotificationSlotEnabledSync enter"); Notification::NotificationBundleOption option; - UnwrapBundleOption(env, bundleOption, option); + + bool bFlag = UnwrapBundleOption(env, bundleOption, option); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("unwrapBundleOption error ERROR_INTERNAL_ERROR"); + return BoolToAniBoolean(false); + } + ANS_LOGD("setNotificationEnable option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", + option.GetBundleName().c_str(), option.GetUid(), bFlag); + + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; - NotificationSts::SlotTypeEtsToC(env, type, slotType); + bFlag = NotificationSts::SlotTypeEtsToC(env, type, slotType); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("slotTypeEtsToC error ERROR_INTERNAL_ERROR"); + return BoolToAniBoolean(false); + } + bool isEnable = false; - Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); + int returncode = Notification::NotificationHelper::GetEnabledForBundleSlot(option, slotType, isEnable); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("isNotificationSlotEnabledSync error, errorCode: %{public}d", externalCode); + return BoolToAniBoolean(false); + } + ANS_LOGD("isNotificationSlotEnabledSync end, isEnable: %{public}d, externalCode: %{public}d", isEnable, externalCode); return isEnable ? ANI_TRUE : ANI_FALSE; } @@ -222,7 +290,7 @@ static void CancelWithIdOptinalLabel(ani_env* env, ani_double id, ani_string lab ANS_LOGD("sts CancelWithIdOptinalLabel call, id:%{public}lf", id); ani_boolean isUndefined = ANI_FALSE; env->Reference_IsUndefined(label, &isUndefined); - int32_t ret = 0; + int32_t ret = -1; if(isUndefined) { ANS_LOGE("sts CancelWithIdOptinalLabel the label is undefined"); ret = Notification::NotificationHelper::CancelNotification(static_cast(id)); @@ -270,7 +338,7 @@ static void CancelWithIdLabel(ani_env* env, ani_double id, ani_string label) static void CancelWithBundle(ani_env* env, ani_object bundleObj, ani_double id) { ANS_LOGD("sts CancelWithBundle call, id: %{public}lf", id); - int returncode = 0; + int returncode = -1; Notification::NotificationBundleOption option; bool bFlag = UnwrapBundleOption(env, bundleObj, option); ANS_LOGD("sts CancelWithBundle option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", option.GetBundleName().c_str(), @@ -308,7 +376,7 @@ static void CancelAll(ani_env* env) static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) { ANS_LOGD("sts GetSlotsByBundle enter"); - int returncode = 0; + int returncode = -1; std::vector> slots; Notification::NotificationBundleOption option; bool bFlag = UnwrapBundleOption(env, bundleOption, option); @@ -335,59 +403,131 @@ static ani_ref GetSlotsByBundle(ani_env *env, ani_object bundleOption) return outAniObj; } -static void addDoNotDisturbProfile(ani_env *env, ani_object obj) +static void AddDoNotDisturbProfile(ani_env *env, ani_object obj) { ANS_LOGD("sts addDoNotDisturbProfile call"); std::vector> profiles; - UnwrapArrayDoNotDisturbProfile(env, obj, profiles); - Notification::NotificationHelper::AddDoNotDisturbProfiles(profiles); + bool bFlag = UnwrapArrayDoNotDisturbProfile(env, obj, profiles); + if (!bFlag) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts addDoNotDisturbProfile ERROR_INTERNAL_ERROR"); + return; + } + int returncode = Notification::NotificationHelper::AddDoNotDisturbProfiles(profiles); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts addDoNotDisturbProfile error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts addDoNotDisturbProfile end, ret: %{public}d", externalCode); return; } -static void removeDoNotDisturbProfile(ani_env *env, ani_object obj) +static void RemoveDoNotDisturbProfile(ani_env *env, ani_object obj) { ANS_LOGD("sts removeDoNotDisturbProfile call"); std::vector> profiles; - UnwrapArrayDoNotDisturbProfile(env, obj, profiles); - Notification::NotificationHelper::RemoveDoNotDisturbProfiles(profiles); + bool bFlag = UnwrapArrayDoNotDisturbProfile(env, obj, profiles); + if (!bFlag) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("sts removeDoNotDisturbProfile ERROR_INTERNAL_ERROR"); + return; + } + int returncode = Notification::NotificationHelper::RemoveDoNotDisturbProfiles(profiles); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("sts removeDoNotDisturbProfile error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("sts removeDoNotDisturbProfile end, ret: %{public}d", externalCode); return; } static void SetNotificationEnableSlot(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable, ani_object isForceControl) { - ANS_LOGD("SetNotificationEnableSlot enter "); + ANS_LOGD("setNotificationEnableSlot enter "); ani_boolean isUndefined = false; ani_boolean res = 0.0; Notification::NotificationBundleOption option; + bool bFlag = UnwrapBundleOption(env, bundleOption, option); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("unwrapBundleOption error ERROR_INTERNAL_ERROR"); + return; + } + ANS_LOGD("setNotificationEnableSlot option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", + option.GetBundleName().c_str(), option.GetUid(), bFlag); Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; - NotificationSts::SlotTypeEtsToC(env, type, slotType); - UnwrapBundleOption(env, bundleOption, option); + bFlag = NotificationSts::SlotTypeEtsToC(env, type, slotType); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("slotTypeEtsToC error ERROR_INTERNAL_ERROR"); + return; + } env->Reference_IsUndefined(isForceControl, &isUndefined); + int returncode = 0; if(isUndefined) { bool forceControl = false; - Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), forceControl); + ANS_LOGD("setNotificationEnableSlot end, returncode: %{public}d", + CJSystemapi::Notification::ErrorToExternal(returncode)); return; } else { if (ANI_OK !=env->Object_CallMethodByName_Boolean(isForceControl, "booleanValue", nullptr, &res)){ - ANS_LOGD("SetNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); + ANS_LOGD("setNotificationEnableSlot Object_CallMethodByName_Boolean Fail"); } } - Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), AniBooleanToBool(res)); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("setNotificationEnableSlot error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("setNotificationEnableSlot end, externalCode: %{public}d", externalCode); } static void SetNotificationEnableSlotByOld(ani_env *env, ani_object bundleOption, ani_enum_item type, ani_boolean enable) { - ANS_LOGD("SetNotificationEnableSlotByOld enter "); + ANS_LOGD("setNotificationEnableSlotByOld enter "); Notification::NotificationBundleOption option; - UnwrapBundleOption(env, bundleOption, option); + bool bFlag = UnwrapBundleOption(env, bundleOption, option); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("unwrapBundleOption error ERROR_INTERNAL_ERROR"); + return; + } + ANS_LOGD("setNotificationEnableSlotByOld option bundleName: %{public}s, uid: %{public}d, bFlag: %{public}d", + option.GetBundleName().c_str(), option.GetUid(), bFlag); + Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType::OTHER; - NotificationSts::SlotTypeEtsToC(env, type, slotType); + bFlag = NotificationSts::SlotTypeEtsToC(env, type, slotType); + if(bFlag != true) { + OHOS::AbilityRuntime::ThrowStsError(env, OHOS::Notification::ERROR_INTERNAL_ERROR, + FindAnsErrMsg(OHOS::Notification::ERROR_INTERNAL_ERROR)); + ANS_LOGE("slotTypeEtsToC error ERROR_INTERNAL_ERROR"); + return; + } bool isForceControl = false; - Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), + int returncode = Notification::NotificationHelper::SetEnabledForBundleSlot(option, slotType, AniBooleanToBool(enable), isForceControl); + int externalCode = CJSystemapi::Notification::ErrorToExternal(returncode); + if (externalCode != 0) { + OHOS::AbilityRuntime::ThrowStsError(env, externalCode, FindAnsErrMsg(externalCode)); + ANS_LOGE("setNotificationEnableSlotByOld error, errorCode: %{public}d", externalCode); + return; + } + ANS_LOGD("setNotificationEnableSlotByOld end, externalCode: %{public}d", externalCode); } static ani_object NativeGetAllActiveNotifications(ani_env *env, [[maybe_unused]]ani_class aniClass) @@ -460,10 +600,10 @@ void StsNotificationManagerRegistryInit(ani_env *env) ani_native_function {"nativeGetActiveNotificationCount", ":D", reinterpret_cast(GetActiveNotificationCount)}, ani_native_function {"nativeIsNotificationEnabled", nullptr, reinterpret_cast(isNotificationEnabled)}, - ani_native_function {"nativegetSlotFlagsByBundle", nullptr, reinterpret_cast(getSlotFlagsByBundle)}, - ani_native_function {"nativesetSlotFlagsByBundle", nullptr, reinterpret_cast(setSlotFlagsByBundle)}, + ani_native_function {"nativegetSlotFlagsByBundle", nullptr, reinterpret_cast(GetSlotFlagsByBundle)}, + ani_native_function {"nativesetSlotFlagsByBundle", nullptr, reinterpret_cast(SetSlotFlagsByBundle)}, ani_native_function {"nativeSetNotificationEnable", nullptr, reinterpret_cast(SetNotificationEnable)}, - ani_native_function {"nativeisNotificationSlotEnabled", nullptr, + ani_native_function {"nativeIsNotificationSlotEnabled", nullptr, reinterpret_cast(IsNotificationSlotEnabled)}, ani_native_function {"nativeCancelWithId", nullptr, reinterpret_cast(CancelWithId)}, ani_native_function {"nativeCancelWithIdLabel", nullptr, reinterpret_cast(CancelWithIdLabel)}, @@ -471,8 +611,8 @@ void StsNotificationManagerRegistryInit(ani_env *env) ani_native_function {"nativeCancelWithBundle", nullptr, reinterpret_cast(CancelWithBundle)}, ani_native_function {"nativeCancelAll", nullptr, reinterpret_cast(CancelAll)}, ani_native_function {"nativeGetSlotsByBundle", nullptr, reinterpret_cast(GetSlotsByBundle)}, - ani_native_function {"nativeaddDoNotDisturbProfile", nullptr, reinterpret_cast(addDoNotDisturbProfile)}, - ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, reinterpret_cast(removeDoNotDisturbProfile)}, + ani_native_function {"nativeaddDoNotDisturbProfile", nullptr, reinterpret_cast(AddDoNotDisturbProfile)}, + ani_native_function {"nativeremoveDoNotDisturbProfile", nullptr, reinterpret_cast(RemoveDoNotDisturbProfile)}, ani_native_function {"nativeSetNotificationEnableSlot", nullptr, reinterpret_cast(SetNotificationEnableSlot)}, ani_native_function {"nativeSetNotificationEnableSlotByOld", nullptr, reinterpret_cast(SetNotificationEnableSlotByOld)}, diff --git a/frameworks/ani/notification_manager/src/sts_notification_request.cpp b/frameworks/ani/notification_manager/src/sts_notification_request.cpp index baac7d1da..c1894b2c5 100644 --- a/frameworks/ani/notification_manager/src/sts_notification_request.cpp +++ b/frameworks/ani/notification_manager/src/sts_notification_request.cpp @@ -25,6 +25,7 @@ #include "pixel_map_ani.h" #include "notification_template.h" #include "ans_convert_enum.h" +#include "ani_common_want_agent.h" namespace OHOS { namespace NotificationSts { @@ -44,7 +45,7 @@ bool SetNotificationRequestByString(ani_env* env, ani_class cls, const OHOS::Not if (GetAniString(env, request->GetClassification(), stringValue)) { CallSetterOptional(env, cls, object, "classification", stringValue); } - // need to do + // need to do ets中没有找到statusBarText属性 // statusBarText?: string // if (StringToAniStr(env, request->GetStatusBarText(), stringValue)) { // RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, STATUS_BAR_TEXT, stringValue)); @@ -153,8 +154,18 @@ ani_object ConvertNotificationActionButtonToAniObject(ani_env* env, RETURN_NULL_IF_FALSE(GetAniString(env, actionButton->GetTitle(), stringValue)); RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "title", stringValue)); // wantAgent: WantAgent; + std::shared_ptr agent = actionButton->GetWantAgent(); + if (agent == nullptr) { + ANS_LOGI("agent is null"); + return nullptr; + } else { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + RETURN_NULL_IF_FALSE(CallSetterOptional(env, iconButtonCls, iconButtonObject, "wantAgent", wantAgent)); + } + // need to do - // extras?: Record; napi��û�д������Ĺ��̣���֪���Ǹ�ɶ�ģ� + // extras?: Record; napi中没有处理它的过程???但有一个icon?: image.PixelMap处理 napi��û�д������Ĺ��̣���֪���Ǹ�ɶ�ģ� + //napi位置:notification_distributed_notification_service-OpenHarmony_feature_20250328\frameworks\js\napi\src\common_convert_request.cpp 419行 // need to do //TODO(δת������) @@ -977,7 +988,7 @@ ani_status GetNotificationRequestByCustom(ani_env *env, ani_object obj, GetNotificationTemplate(env, obj, notificationRequest); GetNotificationUnifiedGroupInfo(env, obj, notificationRequest); GetNotificationBundleOption(env, obj, notificationRequest); - // need to do GetNotificationMaxScreenWantAgent + // need to do GetNotificationMaxScreenWantAgent 没看明白 /* // maxScreenWantAgent?: WantAgent if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { @@ -1039,6 +1050,40 @@ bool SetNotificationRequestByPixelMap(ani_env* env, ani_class cls, const Notific return true; } +bool SetNotificationRequestByWantAgent(ani_env* env, ani_class cls, + const OHOS::Notification::NotificationRequest *request, ani_object &object) +{ + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return false; + } + // wantAgent?: WantAgent + std::shared_ptr agent = request->GetWantAgent(); + if (agent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, agent.get()); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "wantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "wantAgent")); + } + // removalWantAgent?: WantAgent + std::shared_ptr removalAgent = request->GetRemovalWantAgent(); + if (removalAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, removalAgent.get()); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "removalWantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "removalWantAgent")); + } + // maxScreenWantAgent?: WantAgent + std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); + if (maxScreenAgent) { + ani_object wantAgent = AppExecFwk::WrapWantAgent(env, maxScreenAgent.get()); + RETURN_FALSE_IF_FALSE(CallSetterOptional(env, cls, object, "maxScreenWantAgent", wantAgent)); + } else { + RETURN_FALSE_IF_FALSE(CallSetterNull(env, cls, object, "maxScreenWantAgent")); + } + return true; +} + bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::NotificationRequest *notificationRequest, ani_class &cls, ani_object &outAniObj) { @@ -1060,10 +1105,9 @@ bool WarpNotificationRequest(ani_env *env, const OHOS::Notification::Notificatio return false; } // need to do - /* if (!SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)) { - ANS_LOGE("SetNotificationRequestByWantAgent failed"); + if (!SetNotificationRequestByWantAgent(env, cls, notificationRequest, outAniObj)) { return false; - } */ + } if (!SetNotificationRequestByPixelMap(env, cls, notificationRequest, outAniObj)) { return false; } -- Gitee