diff --git a/OAT.xml b/OAT.xml
index aa01ceabe357535c840cb743727fb16106185a8e..40b888b56532e719775f2237f805ea8182088e8f 100644
--- a/OAT.xml
+++ b/OAT.xml
@@ -1,5 +1,5 @@
-
+
+
{{ requestNotification }}
-
-
-
+
+
+
+
+
+
+
+
diff --git a/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js b/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js
index 928dc3b8b789e0fdcf0c8a6239d2dfde8a806ec1..9c9463b90b63bc234247f02fa3a5982b471defb7 100644
--- a/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js
+++ b/frameworks/ans/dialog/dialog_ui/js/pages/index/index.js
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
import router from '@ohos.router'
export default {
@@ -10,6 +25,9 @@ export default {
},
onInit() {
console.info('getParams: ' + JSON.stringify(router.getParams()));
+ this.requestNotification = this.$t('message.requestNotification');
+ this.allowButton = this.$t('message.allowButton');
+ this.cancelButton = this.$t('message.cancelButton');
},
onAllow() {
console.info('clicked allow');
diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn
index a0aa9d6ccf3c7a5039278afb806ca60395040791..17e50e5b8e5a48e16dae2b00f58967adca561472 100644
--- a/frameworks/ans/native/BUILD.gn
+++ b/frameworks/ans/native/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Huawei Device Co., Ltd.
+# Copyright (c) 2021-2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@@ -29,7 +29,10 @@ config("ans_innerkits_public_config") {
"//third_party/jsoncpp/include",
"//utils/system/safwk/native/include",
]
- configs = [ "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits_public_config" ]
+ configs = [
+ "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits_public_config",
+ "//foundation/multimedia/image_standard/interfaces/innerkits:image_external_config",
+ ]
}
ohos_shared_library("ans_innerkits") {
@@ -85,11 +88,12 @@ ohos_shared_library("ans_innerkits") {
external_deps = [
"ability_base:want",
+ "ability_base:zuri",
"ability_runtime:wantagent_innerkits",
- "dmsfwk_standard:zuri",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"multimedia_image_standard:image_native",
+ "native_appdatamgr:native_rdb",
"samgr_standard:samgr_proxy",
]
diff --git a/frameworks/ans/native/src/enabled_notification_callback_data.cpp b/frameworks/ans/native/src/enabled_notification_callback_data.cpp
index 32d678a67126baa5d56c2cd8e04de5dbcd2288ff..4346035d4da050139f0e29e10286e1bc4581294c 100644
--- a/frameworks/ans/native/src/enabled_notification_callback_data.cpp
+++ b/frameworks/ans/native/src/enabled_notification_callback_data.cpp
@@ -96,7 +96,7 @@ EnabledNotificationCallbackData *EnabledNotificationCallbackData::Unmarshalling(
bool EnabledNotificationCallbackData::ReadFromParcel(Parcel &parcel)
{
bundle_ = Str16ToStr8(parcel.ReadString16());
- uid_ = parcel.ReadInt32();
+ uid_ = static_cast
(parcel.ReadInt32());
enable_ = parcel.ReadBool();
return true;
diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp
index 385eafd0f6eee5a71a2cc4740d29038c64047202..ce57886a26dd1ce2414b686951aa4453a88ef670 100644
--- a/frameworks/ans/native/src/message_user.cpp
+++ b/frameworks/ans/native/src/message_user.cpp
@@ -212,7 +212,7 @@ bool MessageUser::ReadFromParcel(Parcel &parcel)
isMachine_ = parcel.ReadBool();
isUserImportant_ = parcel.ReadBool();
- int empty = VALUE_NULL;
+ int32_t empty = VALUE_NULL;
if (!parcel.ReadInt32(empty)) {
ANS_LOGE("Failed to read VALUE");
return false;
diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp
index 613c42646030dd35bc5e0fceaaac6a6e29f23e53..7723258b80e2da49c025bb80cfe43d1747543a60 100644
--- a/frameworks/ans/native/src/notification.cpp
+++ b/frameworks/ans/native/src/notification.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -40,7 +40,7 @@ Notification::Notification(const Notification &other)
{
enableSound_ = other.enableSound_;
enableLight_ = other.enableLight_;
- enableViration_ = other.enableViration_;
+ enableVibration_ = other.enableVibration_;
key_ = other.key_;
ledLightColor_ = other.ledLightColor_;
lockscreenVisibleness_ = other.lockscreenVisibleness_;
@@ -69,7 +69,7 @@ bool Notification::EnableSound() const
bool Notification::EnableVibrate() const
{
- return enableViration_;
+ return enableVibration_;
}
std::string Notification::GetBundleName() const
@@ -145,7 +145,7 @@ Uri Notification::GetSound() const
return Uri("");
}
-pid_t Notification::GetUid() const
+int32_t Notification::GetUid() const
{
if (request_ == nullptr) {
return 0;
@@ -230,8 +230,8 @@ bool Notification::MarshallingBool(Parcel &parcel) const
return false;
}
- if (!parcel.WriteBool(enableViration_)) {
- ANS_LOGE("Can't write enableViration_");
+ if (!parcel.WriteBool(enableVibration_)) {
+ ANS_LOGE("Can't write enableVibration_");
return false;
}
@@ -246,7 +246,7 @@ bool Notification::MarshallingBool(Parcel &parcel) const
bool Notification::MarshallingString(Parcel &parcel) const
{
if (!parcel.WriteString(key_)) {
- ANS_LOGE("Can't wirte key");
+ ANS_LOGE("Can't write key");
return false;
}
@@ -258,7 +258,7 @@ bool Notification::MarshallingString(Parcel &parcel) const
}
if (!parcel.WriteString(deviceId_)) {
- ANS_LOGE("Can't wirte deviceId");
+ ANS_LOGE("Can't write deviceId");
return false;
}
@@ -344,8 +344,8 @@ void Notification::ReadFromParcelBool(Parcel &parcel)
// Read enableSound_
enableSound_ = parcel.ReadBool();
- // Read enableViration_
- enableViration_ = parcel.ReadBool();
+ // Read enableVibration_
+ enableVibration_ = parcel.ReadBool();
// Read isRemoveAllowed_
isRemoveAllowed_ = parcel.ReadBool();
@@ -427,9 +427,9 @@ void Notification::SetEnableLight(const bool &enable)
enableLight_ = enable;
}
-void Notification::SetEnableViration(const bool &enable)
+void Notification::SetEnableVibration(const bool &enable)
{
- enableViration_ = enable;
+ enableVibration_ = enable;
}
void Notification::SetLedLightColor(const int32_t &color)
diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp
index cc3ba9f0c52089569b25aeb4d137b040fba6ded2..ea87da8274ec1c68dc4ba6eef8393bb9802d2521 100644
--- a/frameworks/ans/native/src/notification_action_button.cpp
+++ b/frameworks/ans/native/src/notification_action_button.cpp
@@ -17,8 +17,8 @@
#include "ans_image_util.h"
#include "ans_log_wrapper.h"
-#include "ohos/aafwk/content/want_params_wrapper.h"
#include "want_agent_helper.h"
+#include "want_params_wrapper.h"
namespace OHOS {
namespace Notification {
@@ -26,7 +26,7 @@ std::shared_ptr NotificationActionButton::Create(const
const std::string &title, const std::shared_ptr &wantAgent,
const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton,
bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs,
- const std::vector> &userInputs, bool isContextual)
+ const std::shared_ptr &userInput, bool isContextual)
{
if (isContextual && (!icon || !wantAgent)) {
ANS_LOGE("icon or wantAgent can not be null when isContextual is true");
@@ -42,18 +42,10 @@ std::shared_ptr NotificationActionButton::Create(const
}
}
+ std::shared_ptr textInput = userInput;
std::vector> onlyInputs = mimeTypeOnlyInputs;
- std::vector> textInputs {};
- for (auto &userInput : userInputs) {
- if (!userInput) {
- continue;
- }
-
- if (userInput->IsMimeTypeOnly()) {
- onlyInputs.push_back(userInput);
- } else {
- textInputs.push_back(userInput);
- }
+ if (userInput && (userInput->IsMimeTypeOnly())) {
+ onlyInputs.push_back(userInput);
}
auto pActionButton = new (std::nothrow) NotificationActionButton(icon,
@@ -63,7 +55,7 @@ std::shared_ptr NotificationActionButton::Create(const
semanticActionButton,
autoCreatedReplies,
onlyInputs,
- textInputs,
+ textInput,
isContextual);
if (pActionButton == nullptr) {
ANS_LOGE("create NotificationActionButton object failed");
@@ -88,7 +80,7 @@ std::shared_ptr NotificationActionButton::Create(
actionButton->GetSemanticActionButton(),
actionButton->IsAutoCreatedReplies(),
actionButton->GetMimeTypeOnlyUserInputs(),
- actionButton->GetUserInputs(),
+ actionButton->GetUserInput(),
actionButton->IsContextDependent());
}
@@ -96,7 +88,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr &wantAgent,
const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton,
bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs,
- const std::vector> &userInputs, bool isContextual)
+ const std::shared_ptr &userInput, bool isContextual)
: icon_(icon),
title_(title),
wantAgent_(wantAgent),
@@ -104,7 +96,7 @@ NotificationActionButton::NotificationActionButton(const std::shared_ptr> NotificationActionButton::Ge
void NotificationActionButton::AddNotificationUserInput(const std::shared_ptr &userInput)
{
- if (!userInput) {
- ANS_LOGE("The userInput is invalid.");
- return;
- }
-
- userInputs_.emplace_back(userInput);
+ userInput_ = userInput;
}
-std::vector> NotificationActionButton::GetUserInputs() const
+const std::shared_ptr NotificationActionButton::GetUserInput() const
{
- return userInputs_;
+ return userInput_;
}
void NotificationActionButton::SetAutoCreatedReplies(bool autoCreatedReplies)
@@ -212,14 +199,12 @@ std::string NotificationActionButton::Dump()
mimeTypeOnlyUserInputs += ", ";
}
- std::string userInputs = "";
- for (auto &item : userInputs_) {
- if (!item) {
- userInputs += "nullptr, ";
- continue;
- }
- userInputs += item->Dump();
- userInputs += ", ";
+ std::string userInput = "";
+ if (userInput_ == nullptr) {
+ userInput += "nullptr, ";
+ } else {
+ userInput += userInput_->Dump();
+ userInput += ", ";
}
return "NotificationActionButton{ "
@@ -228,7 +213,7 @@ std::string NotificationActionButton::Dump()
", autoCreatedReplies = " + (autoCreatedReplies_ ? "true" : "false") +
", isContextual = " + (isContextual_ ? "true" : "false") +
", mimeTypeOnlyUserInputs = [" + mimeTypeOnlyUserInputs + "]" +
- ", userInputs = [" + userInputs + "]" +
+ ", userInputs = [" + userInput + "]" +
" }";
}
@@ -350,24 +335,17 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const
}
}
- if (!parcel.WriteInt32(static_cast(userInputs_.size()))) {
- ANS_LOGE("Failed to write the size of userInputs");
+ valid = userInput_ ? true : false;
+ if (!parcel.WriteBool(valid)) {
+ ANS_LOGE("Failed to write the flag which indicate whether userInput is null");
return false;
}
- for (auto it = userInputs_.begin(); it != userInputs_.end(); ++it) {
- valid = (*it) ? true : false;
- if (!parcel.WriteBool(valid)) {
- ANS_LOGE("Failed to write the flag which indicate whether userInput is null");
+ if (valid) {
+ if (!parcel.WriteParcelable(userInput_.get())) {
+ ANS_LOGE("Failed to write userInput");
return false;
}
-
- if (valid) {
- if (!parcel.WriteParcelable(it->get())) {
- ANS_LOGE("Failed to write userInput");
- return false;
- }
- }
}
return true;
@@ -427,19 +405,13 @@ bool NotificationActionButton::ReadFromParcel(Parcel &parcel)
}
}
- auto vsize = parcel.ReadInt32();
- for (auto it = 0; it < vsize; ++it) {
- valid = parcel.ReadBool();
- NotificationUserInput *member {nullptr};
- if (valid) {
- member = parcel.ReadParcelable();
- if (member == nullptr) {
- ANS_LOGE("Failed to read userInput");
- return false;
- }
+ valid = parcel.ReadBool();
+ if (valid) {
+ userInput_ = std::shared_ptr(parcel.ReadParcelable());
+ if (!userInput_) {
+ ANS_LOGE("Failed to read userInput");
+ return false;
}
-
- userInputs_.emplace_back(member);
}
return true;
diff --git a/frameworks/ans/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp
index dbd39018996bea0abbe673bbffd8aaecac360848..44a866ba1a5c802e527411d57c1a509d7fb0f0a0 100644
--- a/frameworks/ans/native/src/notification_content.cpp
+++ b/frameworks/ans/native/src/notification_content.cpp
@@ -122,7 +122,7 @@ bool NotificationContent::ToJson(nlohmann::json &jsonObject) const
}
nlohmann::json contentObj;
- if (!NotificationJsonConverter::ConvertToJosn(content_.get(), contentObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(content_.get(), contentObj)) {
ANS_LOGE("Cannot convert content to JSON");
return false;
}
@@ -258,19 +258,19 @@ bool NotificationContent::ConvertJsonToContent(NotificationContent *target, cons
NotificationBasicContent *pBasicContent {nullptr};
switch (target->contentType_) {
case NotificationContent::Type::BASIC_TEXT:
- pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj);
break;
case NotificationContent::Type::CONVERSATION:
- pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj);
break;
case NotificationContent::Type::LONG_TEXT:
- pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj);
break;
case NotificationContent::Type::MULTILINE:
- pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj);
break;
case NotificationContent::Type::PICTURE:
- pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ pBasicContent = NotificationJsonConverter::ConvertFromJson(contentObj);
break;
default:
ANS_LOGE("Invalid contentType");
diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp
index 08f3599b71af42ee59cf801cb61c56a16dc69216..f63c5300d34eff731e67f8e70cc973101e8e589c 100644
--- a/frameworks/ans/native/src/notification_conversational_content.cpp
+++ b/frameworks/ans/native/src/notification_conversational_content.cpp
@@ -101,7 +101,7 @@ bool NotificationConversationalContent::ToJson(nlohmann::json &jsonObject) const
}
nlohmann::json userObj;
- if (!NotificationJsonConverter::ConvertToJosn(&messageUser_, userObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(&messageUser_, userObj)) {
ANS_LOGE("Cannot convert messageUser to JSON");
return false;
}
@@ -117,7 +117,7 @@ bool NotificationConversationalContent::ToJson(nlohmann::json &jsonObject) const
}
nlohmann::json msgObj;
- if (!NotificationJsonConverter::ConvertToJosn(msg.get(), msgObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(msg.get(), msgObj)) {
ANS_LOGE("Cannot convert conversationalMessage to JSON");
return false;
}
@@ -146,7 +146,7 @@ NotificationConversationalContent *NotificationConversationalContent::FromJson(c
const auto &jsonEnd = jsonObject.cend();
if (jsonObject.find("messageUser") != jsonEnd) {
auto userObj = jsonObject.at("messageUser");
- auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj);
+ auto pUser = NotificationJsonConverter::ConvertFromJson(userObj);
if (pUser != nullptr) {
pContent->messageUser_ = *pUser;
@@ -158,7 +158,7 @@ NotificationConversationalContent *NotificationConversationalContent::FromJson(c
if (jsonObject.find("messages") != jsonEnd) {
nlohmann::json msgsArr = jsonObject.at("messages");
for (auto &msgObj : msgsArr) {
- auto pMsg = NotificationJsonConverter::ConvertFromJosn(msgObj);
+ auto pMsg = NotificationJsonConverter::ConvertFromJson(msgObj);
if (pMsg == nullptr) {
ANS_LOGE("Failed to parse message ");
@@ -196,7 +196,7 @@ bool NotificationConversationalContent::Marshalling(Parcel &parcel) const
return false;
}
- if (!parcel.WriteInt32(static_cast(messages_.size()))) {
+ if (!parcel.WriteUint64(messages_.size())) {
ANS_LOGE("Failed to write the size of messages");
return false;
}
@@ -254,8 +254,8 @@ bool NotificationConversationalContent::ReadFromParcel(Parcel &parcel)
}
messageUser_ = *pUser;
- auto vsize = parcel.ReadInt32();
- for (auto it = 0; it < vsize; ++it) {
+ auto vsize = parcel.ReadUint64();
+ for (uint64_t it = 0; it < vsize; ++it) {
auto valid = parcel.ReadBool();
if (!valid) {
ANS_LOGE("Invalid message, read from parcel failed");
diff --git a/frameworks/ans/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp
index 520a5fbfca36af631ac6a78b337c3edc8a2b25e2..51d33ed265991280e1fbb6fbebfb278e28c2b6f1 100644
--- a/frameworks/ans/native/src/notification_conversational_message.cpp
+++ b/frameworks/ans/native/src/notification_conversational_message.cpp
@@ -71,7 +71,7 @@ bool NotificationConversationalMessage::ToJson(nlohmann::json &jsonObject) const
jsonObject["text"] = text_;
nlohmann::json userObj;
- if (!NotificationJsonConverter::ConvertToJosn(&sender_, userObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(&sender_, userObj)) {
ANS_LOGE("Cannot convert sender to JSON");
return false;
}
@@ -107,7 +107,7 @@ NotificationConversationalMessage *NotificationConversationalMessage::FromJson(c
if (jsonObject.find("sender") != jsonEnd) {
auto userObj = jsonObject.at("sender");
- auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj);
+ auto pUser = NotificationJsonConverter::ConvertFromJson(userObj);
if (pUser != nullptr) {
pMessage->sender_ = *pUser;
diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp
index 532ab1ed3871d59638d71ba432b6b2bbda0d9652..294d93a01fd9b31c82b1b5f55031f057481d592b 100644
--- a/frameworks/ans/native/src/notification_helper.cpp
+++ b/frameworks/ans/native/src/notification_helper.cpp
@@ -80,7 +80,7 @@ ErrCode NotificationHelper::GetNotificationSlotGroups(std::vector::GetInstance()->GetNotificationSlotGroups(groups);
}
-ErrCode NotificationHelper::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, int &num)
+ErrCode NotificationHelper::GetNotificationSlotNumAsBundle(const NotificationBundleOption &bundleOption, uint64_t &num)
{
return DelayedSingleton::GetInstance()->GetNotificationSlotNumAsBundle(bundleOption, num);
}
@@ -115,7 +115,14 @@ ErrCode NotificationHelper::CancelAllNotifications()
return DelayedSingleton::GetInstance()->CancelAllNotifications();
}
-ErrCode NotificationHelper::GetActiveNotificationNums(int32_t &num)
+ErrCode NotificationHelper::CancelAsBundle(
+ int32_t notificationId, const std::string &representativeBundle, int32_t userId)
+{
+ return DelayedSingleton::GetInstance()->CancelAsBundle(
+ notificationId, representativeBundle, userId);
+}
+
+ErrCode NotificationHelper::GetActiveNotificationNums(uint64_t &num)
{
return DelayedSingleton::GetInstance()->GetActiveNotificationNums(num);
}
@@ -403,5 +410,17 @@ ErrCode NotificationHelper::GetDoNotDisturbDate(const int32_t &userId, Notificat
{
return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(userId, doNotDisturbDate);
}
+
+ErrCode NotificationHelper::SetEnabledForBundleSlot(
+ const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled)
+{
+ return DelayedSingleton::GetInstance()->SetEnabledForBundleSlot(bundleOption, slotType, enabled);
+}
+
+ErrCode NotificationHelper::GetEnabledForBundleSlot(
+ const NotificationBundleOption &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled)
+{
+ return DelayedSingleton::GetInstance()->GetEnabledForBundleSlot(bundleOption, slotType, enabled);
+}
} // namespace Notification
} // namespace OHOS
\ No newline at end of file
diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp
index beba5fa04ed5db1bbd15280f74d9fc8ba2fc30a7..0efbdbe6b3bc9f755fc1cf4e1d8d6fa69d8c8471 100644
--- a/frameworks/ans/native/src/notification_request.cpp
+++ b/frameworks/ans/native/src/notification_request.cpp
@@ -17,8 +17,8 @@
#include "ans_image_util.h"
#include "ans_log_wrapper.h"
-#include "ohos/aafwk/content/want_params_wrapper.h"
#include "want_agent_helper.h"
+#include "want_params_wrapper.h"
namespace OHOS {
namespace Notification {
@@ -203,6 +203,16 @@ void NotificationRequest::SetPermitSystemGeneratedContextualActionButtons(bool p
permitted_ = permitted;
}
+bool NotificationRequest::IsAgentNotification() const
+{
+ return isAgent_;
+}
+
+void NotificationRequest::SetIsAgentNotification(bool isAgent)
+{
+ isAgent_ = isAgent;
+}
+
void NotificationRequest::AddMessageUser(const std::shared_ptr &messageUser)
{
if (!messageUser) {
@@ -585,16 +595,26 @@ pid_t NotificationRequest::GetCreatorPid() const
return creatorPid_;
}
-void NotificationRequest::SetCreatorUid(pid_t uid)
+void NotificationRequest::SetCreatorUid(int32_t uid)
{
creatorUid_ = uid;
}
-pid_t NotificationRequest::GetCreatorUid() const
+int32_t NotificationRequest::GetCreatorUid() const
{
return creatorUid_;
}
+void NotificationRequest::SetOwnerUid(int32_t uid)
+{
+ ownerUid_ = uid;
+}
+
+int32_t NotificationRequest::GetOwnerUid() const
+{
+ return ownerUid_;
+}
+
void NotificationRequest::SetLabel(const std::string &label)
{
label_ = label;
@@ -635,6 +655,16 @@ int32_t NotificationRequest::GetCreatorUserId() const
return creatorUserId_;
}
+void NotificationRequest::SetOwnerUserId(int32_t userId)
+{
+ ownerUserId_ = userId;
+}
+
+int32_t NotificationRequest::GetOwnerUserId() const
+{
+ return ownerUserId_;
+}
+
std::string NotificationRequest::Dump()
{
return "NotificationRequest{ "
@@ -645,7 +675,9 @@ std::string NotificationRequest::Dump()
", creatorBundleName = " + creatorBundleName_ +
", creatorPid = " + std::to_string(static_cast(creatorPid_)) +
", creatorUid = " + std::to_string(static_cast(creatorUid_)) +
- ", ownerBundleName = " + ownerBundleName_ + ", groupName = " + groupName_ +
+ ", ownerBundleName = " + ownerBundleName_ +
+ ", ownerUid = " + std::to_string(static_cast(ownerUid_)) +
+ ", groupName = " + groupName_ +
", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ +
", sortingKey = " + sortingKey_ +
", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) +
@@ -667,6 +699,7 @@ std::string NotificationRequest::Dump()
", unremovable = " + (unremovable_ ? "true" : "false") +
", floatingIcon = " + (floatingIcon_ ? "true" : "false") +
", onlyLocal = " + (onlyLocal_ ? "true" : "false") + ", permitted = " + (permitted_ ? "true" : "false") +
+ ", isAgent = " + (isAgent_ ? "true" : "false") +
", removalWantAgent = " + (removalWantAgent_ ? "not null" : "null") +
", maxScreenWantAgent = " + (maxScreenWantAgent_ ? "not null" : "null") +
", additionalParams = " + (additionalParams_ ? "not null" : "null") +
@@ -681,6 +714,7 @@ std::string NotificationRequest::Dump()
", distributedOptions = " + distributedOptions_.Dump() +
", notificationFlags = " + (notificationFlags_ ? "not null" : "null") +
", creatorUserId = " + std::to_string(creatorUserId_) +
+ ", ownerUserId = " + std::to_string(ownerUserId_) +
", receiverUserId = " + std::to_string(receiverUserId_) +
" }";
}
@@ -848,11 +882,21 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const
return false;
}
+ if (!parcel.WriteInt32(static_cast(ownerUid_))) {
+ ANS_LOGE("Failed to write owner uid");
+ return false;
+ }
+
if (!parcel.WriteInt32(static_cast(creatorUserId_))) {
ANS_LOGE("Failed to write creator userId");
return false;
}
+ if (!parcel.WriteInt32(static_cast(ownerUserId_))) {
+ ANS_LOGE("Failed to write owner userId");
+ return false;
+ }
+
if (!parcel.WriteInt32(static_cast(receiverUserId_))) {
ANS_LOGE("Failed to write receiver userId");
return false;
@@ -997,6 +1041,11 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const
return false;
}
+ if (!parcel.WriteBool(isAgent_)) {
+ ANS_LOGE("Failed to write flag indicating whether an agent notification");
+ return false;
+ }
+
// write objects which managed by std::shared_ptr
bool valid {false};
@@ -1105,7 +1154,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const
}
// write std::vector
- if (!parcel.WriteInt32(static_cast(actionButtons_.size()))) {
+ if (!parcel.WriteUint64(actionButtons_.size())) {
ANS_LOGE("Failed to write the size of actionButtons");
return false;
}
@@ -1117,7 +1166,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const
}
}
- if (!parcel.WriteInt32(static_cast(messageUsers_.size()))) {
+ if (!parcel.WriteUint64(messageUsers_.size())) {
ANS_LOGE("Failed to write the size of messageUsers");
return false;
}
@@ -1191,8 +1240,10 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel)
autoDeletedTime_ = parcel.ReadInt64();
creatorPid_ = static_cast(parcel.ReadInt32());
- creatorUid_ = static_cast(parcel.ReadInt32());
+ creatorUid_ = parcel.ReadInt32();
+ ownerUid_ = parcel.ReadInt32();
creatorUserId_ = parcel.ReadInt32();
+ ownerUserId_ = parcel.ReadInt32();
receiverUserId_ = parcel.ReadInt32();
if (!parcel.ReadString(settingsText_)) {
@@ -1259,6 +1310,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel)
floatingIcon_ = parcel.ReadBool();
onlyLocal_ = parcel.ReadBool();
permitted_ = parcel.ReadBool();
+ isAgent_ = parcel.ReadBool();
bool valid {false};
@@ -1337,8 +1389,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel)
}
}
- auto vsize = parcel.ReadInt32();
- for (auto it = 0; it < vsize; ++it) {
+ auto vsize = parcel.ReadUint64();
+ for (uint64_t it = 0; it < vsize; ++it) {
auto member = parcel.ReadParcelable();
if (member == nullptr) {
ANS_LOGE("Failed to read actionButton");
@@ -1348,8 +1400,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel)
actionButtons_.emplace_back(member);
}
- vsize = parcel.ReadInt32();
- for (auto it = 0; it < vsize; ++it) {
+ vsize = parcel.ReadUint64();
+ for (uint64_t it = 0; it < vsize; ++it) {
auto member = parcel.ReadParcelable();
if (member == nullptr) {
ANS_LOGE("Failed to read messageUser");
@@ -1444,8 +1496,11 @@ void NotificationRequest::CopyBase(const NotificationRequest &other)
this->creatorPid_ = other.creatorPid_;
this->creatorUid_ = other.creatorUid_;
+ this->ownerUid_ = other.ownerUid_;
this->creatorUserId_ = other.creatorUserId_;
+ this->ownerUserId_ = other.ownerUserId_;
this->receiverUserId_ = other.receiverUserId_;
+ this->isAgent_ = other.isAgent_;
this->slotType_ = other.slotType_;
this->settingsText_ = other.settingsText_;
@@ -1505,7 +1560,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const
nlohmann::json contentObj;
if (notificationContent_) {
- if (!NotificationJsonConverter::ConvertToJosn(notificationContent_.get(), contentObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(notificationContent_.get(), contentObj)) {
ANS_LOGE("Cannot convert notificationContent to JSON");
return false;
}
@@ -1519,7 +1574,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const
}
nlohmann::json btnObj;
- if (!NotificationJsonConverter::ConvertToJosn(btn.get(), btnObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(btn.get(), btnObj)) {
ANS_LOGE("Cannot convert actionButton to JSON");
return false;
}
@@ -1539,7 +1594,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const
jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_);
nlohmann::json optObj;
- if (!NotificationJsonConverter::ConvertToJosn(&distributedOptions_, optObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(&distributedOptions_, optObj)) {
ANS_LOGE("Cannot convert distributedOptions to JSON");
return false;
}
@@ -1547,7 +1602,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const
if (notificationFlags_) {
nlohmann::json flagsObj;
- if (!NotificationJsonConverter::ConvertToJosn(notificationFlags_.get(), flagsObj)) {
+ if (!NotificationJsonConverter::ConvertToJson(notificationFlags_.get(), flagsObj)) {
ANS_LOGE("Cannot convert notificationFlags to JSON");
return false;
}
@@ -1587,15 +1642,15 @@ void NotificationRequest::ConvertJsonToNum(NotificationRequest *target, const nl
}
if (jsonObject.find("creatorPid") != jsonEnd) {
- target->creatorPid_ = jsonObject.at("creatorPid").get();
+ target->creatorPid_ = jsonObject.at("creatorPid").get();
}
if (jsonObject.find("creatorUserId") != jsonEnd) {
- target->creatorUserId_ = jsonObject.at("creatorUserId").get();
+ target->creatorUserId_ = jsonObject.at("creatorUserId").get();
}
if (jsonObject.find("receiverUserId") != jsonEnd) {
- target->receiverUserId_ = jsonObject.at("receiverUserId").get();
+ target->receiverUserId_ = jsonObject.at("receiverUserId").get();
}
}
@@ -1732,7 +1787,7 @@ bool NotificationRequest::ConvertJsonToNotificationContent(
if (jsonObject.find("content") != jsonEnd) {
auto contentObj = jsonObject.at("content");
if (!contentObj.is_null()) {
- auto pContent = NotificationJsonConverter::ConvertFromJosn(contentObj);
+ auto pContent = NotificationJsonConverter::ConvertFromJson(contentObj);
if (pContent == nullptr) {
ANS_LOGE("Failed to parse notification content!");
return false;
@@ -1758,7 +1813,7 @@ bool NotificationRequest::ConvertJsonToNotificationActionButton(
if (jsonObject.find("actionButtons") != jsonEnd) {
auto buttonArr = jsonObject.at("actionButtons");
for (auto &btnObj : buttonArr) {
- auto pBtn = NotificationJsonConverter::ConvertFromJosn(btnObj);
+ auto pBtn = NotificationJsonConverter::ConvertFromJson(btnObj);
if (pBtn == nullptr) {
ANS_LOGE("Failed to parse actionButton!");
return false;
@@ -1784,7 +1839,7 @@ bool NotificationRequest::ConvertJsonToNotificationDistributedOptions(
if (jsonObject.find("distributedOptions") != jsonEnd) {
auto optObj = jsonObject.at("distributedOptions");
if (!optObj.is_null()) {
- auto pOpt = NotificationJsonConverter::ConvertFromJosn(optObj);
+ auto pOpt = NotificationJsonConverter::ConvertFromJson(optObj);
if (pOpt == nullptr) {
ANS_LOGE("Failed to parse distributedOptions!");
return false;
@@ -1810,7 +1865,7 @@ bool NotificationRequest::ConvertJsonToNotificationFlags(
if (jsonObject.find("notificationFlags") != jsonEnd) {
auto flagsObj = jsonObject.at("notificationFlags");
if (!flagsObj.is_null()) {
- auto pFlags = NotificationJsonConverter::ConvertFromJosn(flagsObj);
+ auto pFlags = NotificationJsonConverter::ConvertFromJson(flagsObj);
if (pFlags == nullptr) {
ANS_LOGE("Failed to parse notificationFlags!");
return false;
diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp
index 04f4c9c5afac95d7e420395ab9bdedc368888549..e41616918dab38dd063bc087708795b546c508fd 100644
--- a/frameworks/ans/native/src/notification_slot.cpp
+++ b/frameworks/ans/native/src/notification_slot.cpp
@@ -19,7 +19,7 @@
namespace OHOS {
namespace Notification {
-const int MAX_TEXT_LENGTH = 1000;
+const int32_t MAX_TEXT_LENGTH = 1000;
NotificationSlot::NotificationSlot(NotificationConstant::SlotType type) : sound_("")
{
@@ -200,6 +200,16 @@ void NotificationSlot::EnableBadge(bool isShowBadge)
isShowBadge_ = isShowBadge;
}
+void NotificationSlot::SetEnable(bool enabled)
+{
+ enabled_ = enabled;
+}
+
+bool NotificationSlot::GetEnable() const
+{
+ return enabled_;
+}
+
std::string NotificationSlot::Dump() const
{
return "NotificationSlot{ "
@@ -217,6 +227,7 @@ std::string NotificationSlot::Dump() const
", vibration = " + MergeVectorToString(vibrationValues_) +
", isShowBadge = " + (isShowBadge_ ? "true" : "false") +
", groupId = " + groupId_ +
+ ", enabled = " + (enabled_ ? "true" : "false") +
" }";
}
@@ -303,6 +314,11 @@ bool NotificationSlot::Marshalling(Parcel &parcel) const
return false;
}
+ if (!parcel.WriteBool(enabled_)) {
+ ANS_LOGE("Failed to write isShowBadge");
+ return false;
+ }
+
return true;
}
@@ -321,7 +337,7 @@ bool NotificationSlot::ReadFromParcel(Parcel &parcel)
lockScreenVisibleness_ = static_cast(parcel.ReadInt32());
groupId_ = parcel.ReadString();
- int empty = VALUE_NULL;
+ int32_t empty = VALUE_NULL;
if (!parcel.ReadInt32(empty)) {
ANS_LOGE("Failed to read int");
return false;
@@ -332,6 +348,7 @@ bool NotificationSlot::ReadFromParcel(Parcel &parcel)
}
parcel.ReadInt64Vector(&vibrationValues_);
+ enabled_ = parcel.ReadBool();
return true;
}
diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp
index c870357e0e3b10edaddb281a343787f1a265e243..cb63278eb9264c8c00cafcb4dd51d63219cfe44b 100644
--- a/frameworks/ans/native/src/notification_slot_group.cpp
+++ b/frameworks/ans/native/src/notification_slot_group.cpp
@@ -19,7 +19,7 @@
namespace OHOS {
namespace Notification {
-const int MAX_TEXT_LENGTH = 1000;
+const int32_t MAX_TEXT_LENGTH = 1000;
const std::string LINE_SEPARATOR = "\n";
NotificationSlotGroup::NotificationSlotGroup()
@@ -104,13 +104,13 @@ bool NotificationSlotGroup::Marshalling(Parcel &parcel) const
return false;
}
- if (slots_.size() == 0) {
- if (!parcel.WriteInt32(0)) {
+ if (slots_.empty()) {
+ if (!parcel.WriteUint64(0)) {
ANS_LOGE("Failed to write the size of slots");
return false;
}
} else {
- if (!parcel.WriteInt32(slots_.size())) {
+ if (!parcel.WriteUint64(slots_.size())) {
ANS_LOGE("Failed to write the size of slots");
return false;
}
@@ -135,9 +135,9 @@ bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel)
id_ = parcel.ReadString();
name_ = parcel.ReadString();
description_ = parcel.ReadString();
- int32_t size = parcel.ReadInt32();
+ uint64_t size = parcel.ReadUint64();
if (size) {
- for (int32_t i = 0; i < size; ++i) {
+ for (uint64_t i = 0; i < size; ++i) {
auto slot = parcel.ReadParcelable();
if (slot == nullptr) {
ANS_LOGE("Failed to read slot");
diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp
index 575141dbfcc0bb35b50f9c2811763e30f8cbcfef..78699b112ca9c87693d2e2f91cccbc54013cd354 100644
--- a/frameworks/ans/native/src/notification_sorting.cpp
+++ b/frameworks/ans/native/src/notification_sorting.cpp
@@ -72,7 +72,7 @@ bool NotificationSorting::Marshalling(Parcel &parcel) const
return false;
}
- if (!parcel.WriteInt32(ranking_)) {
+ if (!parcel.WriteUint64(ranking_)) {
ANS_LOGE("Can't write ranking");
return false;
}
@@ -116,7 +116,7 @@ bool NotificationSorting::ReadFromParcel(Parcel &parcel)
key_ = parcel.ReadString();
// read ranking_
- ranking_ = parcel.ReadInt32();
+ ranking_ = parcel.ReadUint64();
// read importance_
importance_ = parcel.ReadInt32();
@@ -159,7 +159,7 @@ void NotificationSorting::SetImportance(const int32_t &importance)
importance_ = importance;
}
-void NotificationSorting::SetRanking(const int32_t &ranking)
+void NotificationSorting::SetRanking(const uint64_t &ranking)
{
ranking_ = ranking;
}
diff --git a/frameworks/ans/native/src/notification_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp
index 2bd73d2f504f4b270616547b4da9d50490ba497a..1263637ca33c0023a2a478ce02ae3ba2558afbc7 100644
--- a/frameworks/ans/native/src/notification_sorting_map.cpp
+++ b/frameworks/ans/native/src/notification_sorting_map.cpp
@@ -64,16 +64,23 @@ void NotificationSortingMap::SetNotificationSorting(const std::vector sorting) {
+
+ size_t count = 0;
+ for (auto &sorting : sortings_) {
if (!parcel.WriteParcelable(&sorting.second)) {
ANS_LOGE("Can't write sorting");
ret = false;
}
- });
+ count++;
+
+ if (count == MAX_ACTIVE_NUM) {
+ break;
+ }
+ }
return ret;
}
@@ -82,10 +89,11 @@ NotificationSortingMap *NotificationSortingMap::Unmarshalling(Parcel &parcel)
{
std::vector sortings;
// read sorting num
- int32_t size = 0;
- parcel.ReadInt32(size);
+ uint64_t size = 0;
+ parcel.ReadUint64(size);
+ size = (size <= MAX_ACTIVE_NUM) ? size : MAX_ACTIVE_NUM;
- for (int i = 0; i < size; i++) {
+ for (uint64_t i = 0; i < size; i++) {
// read sorting
NotificationSorting *sorting = parcel.ReadParcelable();
if (sorting != nullptr) {
diff --git a/frameworks/ans/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp
index 50cd3a934de9c142bb65bd57214775326a1263d9..ae092ab08736b1b1f9f6e483281159a2709e2100 100644
--- a/frameworks/ans/native/src/notification_subscribe_info.cpp
+++ b/frameworks/ans/native/src/notification_subscribe_info.cpp
@@ -45,7 +45,7 @@ std::vector NotificationSubscribeInfo::GetAppNames() const
return appNames_;
}
-void NotificationSubscribeInfo::AddAppUserId(const int userId)
+void NotificationSubscribeInfo::AddAppUserId(const int32_t userId)
{
userId_ = userId;
}
diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp
index e3a9a3c334858baa5391f370ed84d6b87a2a8676..e77d7addba5c6541f5909051cb0e1a333b3c4d19 100644
--- a/frameworks/ans/native/src/notification_subscriber.cpp
+++ b/frameworks/ans/native/src/notification_subscriber.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -74,7 +74,7 @@ void NotificationSubscriber::SubscriberImpl::OnCanceled(const sptr
}
void NotificationSubscriber::SubscriberImpl::OnCanceled(
- const sptr ¬ification, const sptr ¬ificationMap, int deleteReason)
+ const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason)
{
subscriber_.OnCanceled(std::make_shared(*notification),
std::make_shared(*notificationMap),
@@ -99,9 +99,9 @@ void NotificationSubscriber::SubscriberImpl::OnEnabledNotificationChanged(
bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy()
{
- if (nullptr == proxy_) {
+ if (proxy_ == nullptr) {
std::lock_guard lock(mutex_);
- if (nullptr == proxy_) {
+ if (proxy_ == nullptr) {
sptr systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityManager) {
diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp
index 337eeb50cdd3e8f5d4c2cf6057604474984a85ca..84d928dd73fad84f20cf994413462f92ed12337b 100644
--- a/frameworks/ans/native/src/notification_user_input.cpp
+++ b/frameworks/ans/native/src/notification_user_input.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -16,7 +16,7 @@
#include "notification_user_input.h"
#include "ans_log_wrapper.h"
-#include "ohos/aafwk/content/want_params_wrapper.h"
+#include "want_params_wrapper.h"
namespace OHOS {
namespace Notification {
@@ -248,7 +248,7 @@ bool NotificationUserInput::ToJson(nlohmann::json &jsonObject) const
NotificationUserInput *NotificationUserInput::FromJson(const nlohmann::json &jsonObject)
{
- if (jsonObject.is_null() or !jsonObject.is_object()) {
+ if (jsonObject.is_null() || !jsonObject.is_object()) {
ANS_LOGE("Invalid JSON object");
return nullptr;
}
@@ -336,7 +336,7 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const
return false;
}
- if (!parcel.WriteInt32(static_cast(permitMimeTypes_.size()))) {
+ if (!parcel.WriteUint64(static_cast(permitMimeTypes_.size()))) {
ANS_LOGE("Failed to write the size of permitMimeTypes");
return false;
}
@@ -392,8 +392,8 @@ bool NotificationUserInput::ReadFromParcel(Parcel &parcel)
return false;
}
- auto ssize = parcel.ReadInt32();
- for (auto it = 0; it < ssize; ++it) {
+ auto ssize = parcel.ReadUint64();
+ for (uint64_t it = 0; it < ssize; ++it) {
std::string member {};
if (!parcel.ReadString(member)) {
ANS_LOGE("Failed to read permitMimeTypes");
diff --git a/frameworks/ans/native/src/reminder_helper.cpp b/frameworks/ans/native/src/reminder_helper.cpp
index 5e518b7714e744a67d37dcf9a3c7414c6dff13d8..524d479dcf6be3889181f0fa0cc5ca4f6842aa4f 100644
--- a/frameworks/ans/native/src/reminder_helper.cpp
+++ b/frameworks/ans/native/src/reminder_helper.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13,13 +13,13 @@
* limitations under the License.
*/
+#include "reminder_helper.h"
+
#include "ans_log_wrapper.h"
#include "ans_notification.h"
#include "notification_helper.h"
#include "singleton.h"
-#include "reminder_helper.h"
-
namespace OHOS {
namespace Notification {
ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder)
diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp
index 8c71b7f82560abea9e70fe49f1820d167f11aa48..db70e2f78d42dcfa746a1c5bad79d1e727f6ea7a 100644
--- a/frameworks/ans/native/src/reminder_request.cpp
+++ b/frameworks/ans/native/src/reminder_request.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13,18 +13,24 @@
* limitations under the License.
*/
+#include "reminder_request.h"
+
#include "ans_log_wrapper.h"
#include "bundle_mgr_interface.h"
#include "if_system_ability_manager.h"
+#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "os_account_manager.h"
+#include "reminder_store.h"
#include "system_ability_definition.h"
#include "want_agent_helper.h"
-#include "reminder_request.h"
-
namespace OHOS {
namespace Notification {
+namespace {
+const int32_t BASE_YEAR = 1900;
+}
+
int32_t ReminderRequest::GLOBAL_ID = 0;
const uint64_t ReminderRequest::INVALID_LONG_LONG_VALUE = 0;
const uint16_t ReminderRequest::INVALID_U16_VALUE = 0;
@@ -45,13 +51,45 @@ const std::string ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT = "ohos.event.no
const std::string ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION =
"ohos.event.notification.reminder.REMOVE_NOTIFICATION";
const std::string ReminderRequest::PARAM_REMINDER_ID = "REMINDER_ID";
-const int ReminderRequest::BASE_YEAR = 1900;
+const std::string ReminderRequest::SEP_BUTTON_SINGLE = "";
+const std::string ReminderRequest::SEP_BUTTON_MULTI = "";
+const std::string ReminderRequest::SEP_WANT_AGENT = "";
+
+// For database recovery.
+const std::string ReminderRequest::REMINDER_ID = "reminder_id";
+const std::string ReminderRequest::PKG_NAME = "package_name";
+const std::string ReminderRequest::USER_ID = "user_id";
+const std::string ReminderRequest::UID = "uid";
+const std::string ReminderRequest::APP_LABEL = "app_label";
+const std::string ReminderRequest::REMINDER_TYPE = "reminder_type";
+const std::string ReminderRequest::REMINDER_TIME = "reminder_time";
+const std::string ReminderRequest::TRIGGER_TIME = "trigger_time";
+const std::string ReminderRequest::RTC_TRIGGER_TIME = "rtc_trigger_time";
+const std::string ReminderRequest::TIME_INTERVAL = "time_interval";
+const std::string ReminderRequest::SNOOZE_TIMES = "snooze_times";
+const std::string ReminderRequest::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times";
+const std::string ReminderRequest::RING_DURATION = "ring_duration";
+const std::string ReminderRequest::IS_EXPIRED = "is_expired";
+const std::string ReminderRequest::IS_ACTIVE = "is_active";
+const std::string ReminderRequest::STATE = "state";
+const std::string ReminderRequest::ZONE_ID = "zone_id";
+const std::string ReminderRequest::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout";
+const std::string ReminderRequest::ACTION_BUTTON_INFO = "button_info";
+const std::string ReminderRequest::SLOT_ID = "slot_id";
+const std::string ReminderRequest::NOTIFICATION_ID = "notification_id";
+const std::string ReminderRequest::TITLE = "title";
+const std::string ReminderRequest::CONTENT = "content";
+const std::string ReminderRequest::SNOOZE_CONTENT = "snooze_content";
+const std::string ReminderRequest::EXPIRED_CONTENT = "expired_content";
+const std::string ReminderRequest::AGENT = "agent";
+const std::string ReminderRequest::MAX_SCREEN_AGENT = "maxScreen_agent";
+
+std::string ReminderRequest::sqlOfAddColumns = "";
+std::vector ReminderRequest::columns;
ReminderRequest::ReminderRequest()
{
- wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_;
- maxScreenWantAgentInfo_ =
- maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_;
+ InitServerObj();
}
ReminderRequest::ReminderRequest(const ReminderRequest &other)
@@ -79,12 +117,16 @@ ReminderRequest::ReminderRequest(const ReminderRequest &other)
this->actionButtonMap_ = other.actionButtonMap_;
}
+ReminderRequest::ReminderRequest(int32_t reminderId)
+{
+ reminderId_ = reminderId;
+ InitServerObj();
+}
+
ReminderRequest::ReminderRequest(ReminderType reminderType)
{
reminderType_ = reminderType;
- wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_;
- maxScreenWantAgentInfo_ =
- maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_;
+ InitServerObj();
}
bool ReminderRequest::CanRemove() const
@@ -124,7 +166,7 @@ std::string ReminderRequest::Dump() const
ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type)
{
- if (type != ActionButtonType::CLOSE && type != ActionButtonType::SNOOZE) {
+ if ((type != ActionButtonType::CLOSE) && (type != ActionButtonType::SNOOZE)) {
ANSR_LOGI("Button type only support: %{public}d or %{public}d",
static_cast(ActionButtonType::CLOSE), static_cast(ActionButtonType::SNOOZE));
return *this;
@@ -164,11 +206,16 @@ void ReminderRequest::InitReminderId()
ANSR_LOGI("reminderId_=%{public}d", reminderId_);
}
-void ReminderRequest::InitUserId(const int &userId)
+void ReminderRequest::InitUserId(const int32_t &userId)
{
userId_ = userId;
}
+void ReminderRequest::InitUid(const int32_t &uid)
+{
+ uid_ = uid;
+}
+
bool ReminderRequest::IsExpired() const
{
return isExpired_;
@@ -243,8 +290,8 @@ bool ReminderRequest::HandleTimeZoneChange(
if (isExpired_) {
return false;
}
- ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu",
- (unsigned long long)oldZoneTriggerTime, (unsigned long long)newZoneTriggerTime);
+ ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}" PRIu64 "\
+ , newZoneTriggerTime:%{public}" PRIu64 "", oldZoneTriggerTime, newZoneTriggerTime);
if (oldZoneTriggerTime == newZoneTriggerTime) {
return false;
}
@@ -372,6 +419,192 @@ bool ReminderRequest::OnTimeZoneChange()
triggerTimeInMilli_, GetDurationSinceEpochInMilli(newZoneTriggerTime), nextTriggerTime);
}
+int64_t ReminderRequest::RecoverInt64FromDb(const std::shared_ptr &resultSet,
+ const std::string &columnName, const DbRecoveryType &columnType)
+{
+ if (resultSet == nullptr) {
+ ANSR_LOGE("ResultSet is null");
+ return 0;
+ }
+ switch (columnType) {
+ case (DbRecoveryType::INT): {
+ int32_t value;
+ resultSet->GetInt(ReminderStore::GetColumnIndex(columnName), value);
+ return static_cast(value);
+ }
+ case (DbRecoveryType::LONG): {
+ int64_t value;
+ resultSet->GetLong(ReminderStore::GetColumnIndex(columnName), value);
+ return value;
+ }
+ default: {
+ ANSR_LOGD("ColumnType not support.");
+ break;
+ }
+ }
+ ANSR_LOGE("Recover data error");
+ return 0;
+}
+
+void ReminderRequest::RecoverFromDb(const std::shared_ptr &resultSet)
+{
+ if (resultSet == nullptr) {
+ ANSR_LOGE("ResultSet is null");
+ return;
+ }
+
+ // reminderId
+ resultSet->GetInt(ReminderStore::GetColumnIndex(REMINDER_ID), reminderId_);
+
+ // userId
+ resultSet->GetInt(ReminderStore::GetColumnIndex(USER_ID), userId_);
+
+ // bundleName
+ resultSet->GetString(ReminderStore::GetColumnIndex(PKG_NAME), bundleName_);
+
+ // uid
+ resultSet->GetInt(ReminderStore::GetColumnIndex(UID), uid_);
+
+ // reminderType
+ int32_t reminderType;
+ resultSet->GetInt(ReminderStore::GetColumnIndex(REMINDER_TYPE), reminderType);
+ reminderType_ = ReminderType(reminderType);
+
+ // reminderTime
+ reminderTimeInMilli_ =
+ static_cast(RecoverInt64FromDb(resultSet, REMINDER_TIME, DbRecoveryType::LONG));
+
+ // triggerTime
+ triggerTimeInMilli_ =
+ static_cast(RecoverInt64FromDb(resultSet, TRIGGER_TIME, DbRecoveryType::LONG));
+
+ // timeInterval
+ uint64_t timeIntervalInSecond =
+ static_cast(RecoverInt64FromDb(resultSet, TIME_INTERVAL, DbRecoveryType::LONG));
+ SetTimeInterval(timeIntervalInSecond);
+
+ // snoozeTimes
+ snoozeTimes_ = static_cast(RecoverInt64FromDb(resultSet, SNOOZE_TIMES, DbRecoveryType::INT));
+
+ // dynamicSnoozeTimes
+ snoozeTimesDynamic_ =
+ static_cast(RecoverInt64FromDb(resultSet, DYNAMIC_SNOOZE_TIMES, DbRecoveryType::INT));
+
+ // ringDuration
+ uint64_t ringDurationInSecond =
+ static_cast(RecoverInt64FromDb(resultSet, RING_DURATION, DbRecoveryType::LONG));
+ SetRingDuration(ringDurationInSecond);
+
+ // isExpired
+ std::string isExpired;
+ resultSet->GetString(ReminderStore::GetColumnIndex(IS_EXPIRED), isExpired);
+ isExpired_ = isExpired == "true" ? true : false;
+
+ // state
+ state_ = static_cast(RecoverInt64FromDb(resultSet, STATE, DbRecoveryType::INT));
+
+ // action buttons
+ RecoverActionButton(resultSet);
+
+ // slotType
+ int32_t slotType;
+ resultSet->GetInt(ReminderStore::GetColumnIndex(SLOT_ID), slotType);
+ slotType_ = NotificationConstant::SlotType(slotType);
+
+ // notification id
+ resultSet->GetInt(ReminderStore::GetColumnIndex(NOTIFICATION_ID), notificationId_);
+
+ // title
+ resultSet->GetString(ReminderStore::GetColumnIndex(TITLE), title_);
+
+ // content
+ resultSet->GetString(ReminderStore::GetColumnIndex(CONTENT), content_);
+
+ // snoozeContent
+ resultSet->GetString(ReminderStore::GetColumnIndex(SNOOZE_CONTENT), snoozeContent_);
+
+ // expiredContent
+ resultSet->GetString(ReminderStore::GetColumnIndex(EXPIRED_CONTENT), expiredContent_);
+
+ InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent
+
+ // wantAgent
+ std::string wantAgent;
+ resultSet->GetString(ReminderStore::GetColumnIndex(AGENT), wantAgent);
+ RecoverWantAgent(wantAgent, 0);
+
+ // maxScreenWantAgent
+ std::string maxScreenWantAgent;
+ resultSet->GetString(ReminderStore::GetColumnIndex(MAX_SCREEN_AGENT), maxScreenWantAgent);
+ RecoverWantAgent(wantAgent, 1);
+}
+
+void ReminderRequest::RecoverActionButton(const std::shared_ptr &resultSet)
+{
+ if (resultSet == nullptr) {
+ ANSR_LOGE("ResultSet is null");
+ return;
+ }
+ std::string actionButtonInfo;
+ resultSet->GetString(ReminderStore::GetColumnIndex(ACTION_BUTTON_INFO), actionButtonInfo);
+ std::vector multiButton = StringSplit(actionButtonInfo, SEP_BUTTON_MULTI);
+ for (auto button : multiButton) {
+ std::vector singleButton = StringSplit(button, SEP_BUTTON_SINGLE);
+ SetActionButton(singleButton.at(1), ActionButtonType(std::stoi(singleButton.at(0), nullptr)));
+ }
+}
+
+std::vector ReminderRequest::StringSplit(std::string source, const std::string &split) const
+{
+ std::vector result;
+ if (source.empty()) {
+ return result;
+ }
+ size_t pos = 0;
+ while ((pos = source.find(split)) != std::string::npos) {
+ std::string token = source.substr(0, pos);
+ if (!token.empty()) {
+ result.push_back(token);
+ }
+ source.erase(0, pos + split.length());
+ }
+ if (!source.empty()) {
+ result.push_back(source);
+ }
+ return result;
+}
+
+void ReminderRequest::RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type)
+{
+ std::vector info = StringSplit(wantAgentInfo, ReminderRequest::SEP_WANT_AGENT);
+ uint8_t minLen = 2;
+ if (info.size() < minLen) {
+ ANSR_LOGW("RecoverWantAgent fail");
+ return;
+ }
+ ANSR_LOGD("pkg=%{public}s, ability=%{public}s", info.at(0).c_str(), info.at(1).c_str());
+ switch (type) {
+ case 0: {
+ auto wai = std::make_shared();
+ wai->pkgName = info.at(0);
+ wai->abilityName = info.at(1);
+ SetWantAgentInfo(wai);
+ break;
+ }
+ case 1: {
+ auto maxScreenWantAgentInfo = std::make_shared();
+ maxScreenWantAgentInfo->pkgName = info.at(0);
+ maxScreenWantAgentInfo->abilityName = info.at(1);
+ SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo);
+ break;
+ }
+ default: {
+ ANSR_LOGW("RecoverWantAgent type not support");
+ break;
+ }
+ }
+}
+
ReminderRequest& ReminderRequest::SetMaxScreenWantAgentInfo(
const std::shared_ptr &maxScreenWantAgentInfo)
{
@@ -412,14 +645,14 @@ ReminderRequest& ReminderRequest::SetSnoozeTimesDynamic(const uint8_t snooziTime
ReminderRequest& ReminderRequest::SetTimeInterval(const uint64_t timeIntervalInSeconds)
{
- if (timeIntervalInSeconds < 0 || timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) {
+ if (timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) {
ANSR_LOGW("SetTimeInterval, replace to set (0s), for the given is out of legal range");
timeIntervalInMilli_ = 0;
} else {
uint64_t timeIntervalInMilli = timeIntervalInSeconds * MILLI_SECONDS;
if (timeIntervalInMilli > 0 && timeIntervalInMilli < MIN_TIME_INTERVAL_IN_MILLI) {
- ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}llu<%{public}u",
- MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, (unsigned long long)timeIntervalInSeconds,
+ ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}" PRIu64 "<%{public}u",
+ MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, timeIntervalInSeconds,
MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS);
timeIntervalInMilli_ = MIN_TIME_INTERVAL_IN_MILLI;
} else {
@@ -511,7 +744,7 @@ void ReminderRequest::SetReminderTimeInMilli(const uint64_t reminderTimeInMilli)
ReminderRequest& ReminderRequest::SetRingDuration(const uint64_t ringDurationInSeconds)
{
- if (ringDurationInSeconds <= 0 || ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS)) {
+ if ((ringDurationInSeconds == 0) || (ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS))) {
ANSR_LOGW("setRingDuration, replace to set (1s), for the given is out of legal range");
ringDurationInMilli_ = MILLI_SECONDS;
} else {
@@ -560,6 +793,16 @@ uint64_t ReminderRequest::GetTriggerTimeInMilli() const
return triggerTimeInMilli_;
}
+int32_t ReminderRequest::GetUserId() const
+{
+ return userId_;
+}
+
+int32_t ReminderRequest::GetUid() const
+{
+ return uid_;
+}
+
std::shared_ptr ReminderRequest::GetWantAgentInfo() const
{
return wantAgentInfo_;
@@ -606,6 +849,11 @@ void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std
SetMaxScreenWantAgent(maxScreenWantAgent);
break;
}
+ case UpdateNotificationType::BUNDLE_INFO: {
+ ANSR_LOGI("UpdateNotification hap information");
+ UpdateNotificationBundleInfo();
+ break;
+ }
case UpdateNotificationType::CONTENT: {
break;
}
@@ -705,17 +953,16 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const
}
// write map
- int32_t buttonMapSize = static_cast(actionButtonMap_.size());
- if (!parcel.WriteInt32(buttonMapSize)) {
+ if (!parcel.WriteUint64(static_cast(actionButtonMap_.size()))) {
ANSR_LOGE("Failed to write action button size");
return false;
}
- for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) {
- if (!parcel.WriteUint8(static_cast(it->first))) {
+ for (auto button : actionButtonMap_) {
+ if (!parcel.WriteUint8(static_cast(button.first))) {
ANSR_LOGE("Failed to write action button type");
return false;
}
- if (!parcel.WriteString(static_cast(it->second.title))) {
+ if (!parcel.WriteString(static_cast(button.second.title))) {
ANSR_LOGE("Failed to write action button title");
return false;
}
@@ -725,12 +972,15 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const
ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel)
{
- auto objptr = new ReminderRequest();
- if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) {
+ auto objptr = new (std::nothrow) ReminderRequest();
+ if (objptr == nullptr) {
+ ANSR_LOGE("Failed to create reminder due to no memory.");
+ return objptr;
+ }
+ if (!objptr->ReadFromParcel(parcel)) {
delete objptr;
objptr = nullptr;
}
-
return objptr;
}
@@ -782,7 +1032,7 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel)
ANSR_LOGE("Failed to read tempReminderId");
return false;
}
- reminderId_ = tempReminderId == -1 ? reminderId_ : tempReminderId;
+ reminderId_ = (tempReminderId == -1) ? reminderId_ : tempReminderId;
if (!parcel.ReadInt32(notificationId_)) {
ANSR_LOGE("Failed to read notificationId");
@@ -833,12 +1083,12 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel)
slotType_ = static_cast(slotType);
// read map
- int32_t buttonMapSize = 0;
- if (!parcel.ReadInt32(buttonMapSize)) {
+ uint64_t buttonMapSize = 0;
+ if (!parcel.ReadUint64(buttonMapSize)) {
ANSR_LOGE("Failed to read buttonMapSize");
return false;
}
- for (int i = 0; i < buttonMapSize; i++) {
+ for (uint64_t i = 0; i < buttonMapSize; i++) {
uint8_t buttonType = static_cast(ActionButtonType::INVALID);
if (!parcel.ReadUint8(buttonType)) {
ANSR_LOGE("Failed to read buttonType");
@@ -870,6 +1120,13 @@ bool ReminderRequest::InitNotificationRequest()
return true;
}
+void ReminderRequest::InitServerObj()
+{
+ wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_;
+ maxScreenWantAgentInfo_ =
+ maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_;
+}
+
bool ReminderRequest::IsAlerting() const
{
return (state_ & REMINDER_STATUS_ALERTING) != 0;
@@ -892,6 +1149,21 @@ std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const
return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS);
}
+std::string ReminderRequest::GetButtonInfo() const
+{
+ std::string info = "";
+ bool isFirst = true;
+ for (auto button : actionButtonMap_) {
+ if (!isFirst) {
+ info += SEP_BUTTON_MULTI;
+ }
+ ActionButtonInfo buttonInfo = button.second;
+ info += std::to_string(static_cast(button.first)) + SEP_BUTTON_SINGLE + buttonInfo.title;
+ isFirst = false;
+ }
+ return info;
+}
+
uint64_t ReminderRequest::GetNowInstantMilli() const
{
time_t now;
@@ -907,15 +1179,13 @@ std::string ReminderRequest::GetShowTime(const uint64_t showTime) const
{
if (reminderType_ == ReminderType::TIMER) {
return "";
- } else {
- const time_t showTimeInSecond = static_cast(showTime / MILLI_SECONDS);
- return GetTimeInfoInner(showTimeInSecond, TimeFormat::HM);
}
+ return GetTimeInfoInner(static_cast(showTime / MILLI_SECONDS), TimeFormat::HM);
}
std::string ReminderRequest::GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format) const
{
- uint8_t dateTimeLen = 80;
+ const uint8_t dateTimeLen = 80;
char dateTimeBuffer[dateTimeLen];
struct tm timeInfo;
(void)localtime_r(&timeInSecond, &timeInfo);
@@ -975,12 +1245,12 @@ std::string ReminderRequest::GetState(const uint8_t state) const
void ReminderRequest::AddActionButtons(const bool includeSnooze)
{
- int requestCode = 10;
+ int32_t requestCode = 10;
std::vector flags;
flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
- for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) {
+ for (auto button : actionButtonMap_) {
auto want = std::make_shared();
- auto type = it->first;
+ auto type = button.first;
if (type == ActionButtonType::CLOSE) {
want->SetAction(REMINDER_EVENT_CLOSE_ALERT);
ANSR_LOGD("Add action button, type is close");
@@ -997,7 +1267,7 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze)
want->SetParam(PARAM_REMINDER_ID, reminderId_);
std::vector> wants;
wants.push_back(want);
- auto title = static_cast(it->second.title);
+ auto title = static_cast(button.second.title);
AbilityRuntime::WantAgent::WantAgentInfo buttonWantAgentInfo(
requestCode,
AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT,
@@ -1005,8 +1275,12 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze)
wants,
nullptr
);
+
+ std::string identity = IPCSkeleton::ResetCallingIdentity();
std::shared_ptr buttonWantAgent =
AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(buttonWantAgentInfo, userId_);
+ IPCSkeleton::SetCallingIdentity(identity);
+
std::shared_ptr actionButton
= NotificationActionButton::Create(nullptr, title, buttonWantAgent);
notificationRequest_->AddActionButton(actionButton);
@@ -1015,7 +1289,7 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze)
void ReminderRequest::AddRemovalWantAgent()
{
- int requestCode = 10;
+ int32_t requestCode = 10;
std::vector flags;
flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
auto want = std::make_shared();
@@ -1030,15 +1304,19 @@ void ReminderRequest::AddRemovalWantAgent()
wants,
nullptr
);
+
+ std::string identity = IPCSkeleton::ResetCallingIdentity();
std::shared_ptr wantAgent =
AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_);
+ IPCSkeleton::SetCallingIdentity(identity);
+
notificationRequest_->SetRemovalWantAgent(wantAgent);
}
std::shared_ptr ReminderRequest::CreateWantAgent(
AppExecFwk::ElementName &element) const
{
- int requestCode = 10;
+ int32_t requestCode = 10;
std::vector flags;
flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
auto want = std::make_shared();
@@ -1052,7 +1330,10 @@ std::shared_ptr ReminderRequest::CreateWan
wants,
nullptr
);
- return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_);
+ std::string identity = IPCSkeleton::ResetCallingIdentity();
+ auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_);
+ IPCSkeleton::SetCallingIdentity(identity);
+ return wantAgent;
}
void ReminderRequest::SetMaxScreenWantAgent(AppExecFwk::ElementName &element)
@@ -1073,7 +1354,7 @@ void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string f
if (deSet) {
state_ |= newState;
} else {
- state_ &= ~newState;
+ state_ &= static_cast(~newState);
}
ANSR_LOGI("Switch the reminder(reminderId=%{public}d) state, from %{public}s to %{public}s, called by %{public}s",
reminderId_, GetState(oldState).c_str(), GetState(state_).c_str(), function.c_str());
@@ -1110,7 +1391,7 @@ bool ReminderRequest::UpdateNextReminder(const bool &force)
} else {
result = UpdateNextReminder();
}
- std::string info = result == true ? "success" : "no next";
+ std::string info = result ? "success" : "no next";
ANSR_LOGI("updateNextReminder(id=%{public}d, %{public}s): force=%{public}d, trigger time is: %{public}s",
reminderId_, info.c_str(), force,
GetDateTimeInfo(static_cast(triggerTimeInMilli_ / MILLI_SECONDS)).c_str());
@@ -1121,7 +1402,7 @@ void ReminderRequest::UpdateNotificationCommon()
{
time_t now;
(void)time(&now); // unit is seconds.
- notificationRequest_->SetDeliveryTime(static_cast(now) * MILLI_SECONDS);
+ notificationRequest_->SetDeliveryTime(GetDurationSinceEpochInMilli(now));
notificationRequest_->SetLabel(NOTIFICATION_LABEL);
notificationRequest_->SetShowDeliveryTime(true);
notificationRequest_->SetTapDismissed(true);
@@ -1131,8 +1412,8 @@ void ReminderRequest::UpdateNotificationCommon()
notificationNormalContent->SetTitle(title_);
auto notificationContent = std::make_shared(notificationNormalContent);
notificationRequest_->SetContent(notificationContent);
- if (reminderType_ == ReminderRequest::ReminderType::TIMER
- || reminderType_ == ReminderRequest::ReminderType::ALARM) {
+ if ((reminderType_ == ReminderRequest::ReminderType::TIMER) ||
+ (reminderType_ == ReminderRequest::ReminderType::ALARM)) {
notificationRequest_->SetUnremovable(true);
}
auto flags = std::make_shared();
@@ -1141,6 +1422,25 @@ void ReminderRequest::UpdateNotificationCommon()
notificationRequest_->SetFlags(flags);
}
+void ReminderRequest::UpdateNotificationBundleInfo()
+{
+ std::string ownerBundleName = notificationRequest_->GetOwnerBundleName();
+ if (!(ownerBundleName.empty())) {
+ return;
+ }
+ ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s",
+ ownerBundleName.c_str(), bundleName_.c_str());
+ notificationRequest_->SetOwnerBundleName(bundleName_);
+ notificationRequest_->SetCreatorBundleName(bundleName_);
+ notificationRequest_->SetCreatorUid(uid_);
+ ErrCode errCode = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid_, userId_);
+ if (errCode != ERR_OK) {
+ ANSR_LOGE("GetOsAccountLocalIdFromUid fail.");
+ return;
+ }
+ notificationRequest_->SetCreatorUserId(userId_);
+}
+
void ReminderRequest::UpdateNotificationContent(const bool &setSnooze)
{
if (notificationRequest_ == nullptr) {
@@ -1152,11 +1452,12 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze)
if (timeIntervalInMilli_ != 0) {
// snooze the reminder by manual
extendContent = GetShowTime(triggerTimeInMilli_) +
- snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")");
+ (snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"));
+ notificationRequest_->SetTapDismissed(false);
} else {
// the reminder is expired now, when timeInterval is 0
extendContent = GetShowTime(reminderTimeInMilli_) +
- expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")");
+ (expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"));
}
} else if (IsAlerting()) {
// the reminder is alerting, or ring duration is 0
@@ -1164,12 +1465,12 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze)
} else if (snoozeTimesDynamic_ != snoozeTimes_) {
// the reminder is snoozing by period artithmetic, when the ring duration is over.
extendContent = GetShowTime(triggerTimeInMilli_) +
- snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")");
+ (snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"));
notificationRequest_->SetTapDismissed(false);
} else {
// the reminder has already snoozed by period arithmetic, when the ring duration is over.
extendContent = GetShowTime(reminderTimeInMilli_) +
- expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")");
+ (expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"));
}
displayContent_ = content_ + " " + extendContent;
ANSR_LOGD("Display content=%{public}s", displayContent_.c_str());
@@ -1189,7 +1490,7 @@ void ReminderRequest::UpdateNotificationStateForSnooze()
UpdateActionButtons(true);
}
-int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime)
+int32_t ReminderRequest::GetActualTime(const TimeTransferType &type, int32_t cTime)
{
switch (type) {
case (TimeTransferType::YEAR): // year
@@ -1197,7 +1498,7 @@ int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime)
case (TimeTransferType::MONTH): // month
return 1 + cTime;
case (TimeTransferType::WEEK): { // week
- int sunDay = 7;
+ int32_t sunDay = 7;
if (cTime == 0) {
return sunDay;
} else {
@@ -1209,7 +1510,7 @@ int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime)
}
}
-int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime)
+int32_t ReminderRequest::GetCTime(const TimeTransferType &type, int32_t actualTime)
{
switch (type) {
case (TimeTransferType::YEAR): // year
@@ -1217,7 +1518,7 @@ int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime)
case (TimeTransferType::MONTH): // month
return actualTime - 1;
case (TimeTransferType::WEEK): { // week
- int sunDay = 7;
+ int32_t sunDay = 7;
if (actualTime == sunDay) {
return 0;
} else {
@@ -1229,23 +1530,117 @@ int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime)
}
}
-int32_t ReminderRequest::GetUid(const int &userId, const std::string &bundleName)
+int32_t ReminderRequest::GetUid(const int32_t &userId, const std::string &bundleName)
{
AppExecFwk::ApplicationInfo info;
sptr systemAbilityManager
= SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
+ if (systemAbilityManager == nullptr) {
+ ANSR_LOGE("Failed to get uid due to get systemAbilityManager is null.");
+ return -1;
+ }
sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
sptr bundleMgr = iface_cast(remoteObject);
- bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO,
- static_cast(userId), info);
+ bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, info);
+ ANSR_LOGD("uid=%{public}d", info.uid);
return static_cast(info.uid);
}
-int ReminderRequest::GetUserId(const int &uid)
+int32_t ReminderRequest::GetUserId(const int32_t &uid)
{
- int userId = -1;
+ int32_t userId = -1;
AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
+ ANSR_LOGD("userId=%{public}d", userId);
return userId;
}
+
+void ReminderRequest::AppendValuesBucket(const sptr &reminder,
+ const sptr &bundleOption, NativeRdb::ValuesBucket &values)
+{
+ values.PutInt(REMINDER_ID, reminder->GetReminderId());
+ values.PutString(PKG_NAME, bundleOption->GetBundleName());
+ values.PutInt(USER_ID, reminder->GetUserId());
+ values.PutInt(UID, reminder->GetUid());
+ values.PutString(APP_LABEL, ""); // no use, compatible with old version.
+ values.PutInt(REMINDER_TYPE, static_cast(reminder->GetReminderType()));
+ values.PutLong(REMINDER_TIME, reminder->GetReminderTimeInMilli());
+ values.PutLong(TRIGGER_TIME, reminder->GetTriggerTimeInMilli());
+ values.PutLong(
+ RTC_TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); // no use, compatible with old version.
+ values.PutLong(TIME_INTERVAL, reminder->GetTimeInterval());
+ values.PutInt(SNOOZE_TIMES, reminder->GetSnoozeTimes());
+ values.PutInt(DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic());
+ values.PutLong(RING_DURATION, reminder->GetRingDuration());
+ values.PutString(IS_EXPIRED, reminder->IsExpired() ? "true" : "false");
+ values.PutString(IS_ACTIVE, ""); // no use, compatible with old version.
+ values.PutInt(STATE, reminder->GetState());
+ values.PutString(ZONE_ID, ""); // no use, compatible with old version.
+ values.PutString(HAS_SCHEDULED_TIMEOUT, ""); // no use, compatible with old version.
+ values.PutString(ACTION_BUTTON_INFO, reminder->GetButtonInfo());
+ values.PutInt(SLOT_ID, reminder->GetSlotType());
+ values.PutInt(NOTIFICATION_ID, reminder->GetNotificationId());
+ values.PutString(TITLE, reminder->GetTitle());
+ values.PutString(CONTENT, reminder->GetContent());
+ values.PutString(SNOOZE_CONTENT, reminder->GetSnoozeContent());
+ values.PutString(EXPIRED_CONTENT, reminder->GetExpiredContent());
+ auto wantAgentInfo = reminder->GetWantAgentInfo();
+ if (wantAgentInfo == nullptr) {
+ std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null";
+ values.PutString(AGENT, info);
+ } else {
+ values.PutString(AGENT, wantAgentInfo->pkgName
+ + ReminderRequest::SEP_WANT_AGENT + wantAgentInfo->abilityName);
+ }
+ auto maxScreenWantAgentInfo = reminder->GetMaxScreenWantAgentInfo();
+ if (maxScreenWantAgentInfo == nullptr) {
+ std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null";
+ values.PutString(MAX_SCREEN_AGENT, info);
+ } else {
+ values.PutString(MAX_SCREEN_AGENT, maxScreenWantAgentInfo->pkgName
+ + ReminderRequest::SEP_WANT_AGENT + maxScreenWantAgentInfo->abilityName);
+ }
+}
+
+void ReminderRequest::InitDbColumns()
+{
+ AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", false);
+ AddColumn(PKG_NAME, "TEXT NOT NULL", false);
+ AddColumn(USER_ID, "INT NOT NULL", false);
+ AddColumn(UID, "INT NOT NULL", false);
+ AddColumn(APP_LABEL, "TEXT", false);
+ AddColumn(REMINDER_TYPE, "INT NOT NULL", false);
+ AddColumn(REMINDER_TIME, "BIGINT NOT NULL", false);
+ AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", false);
+ AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL", false);
+ AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", false);
+ AddColumn(SNOOZE_TIMES, "INT NOT NULL", false);
+ AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", false);
+ AddColumn(RING_DURATION, "BIGINT NOT NULL", false);
+ AddColumn(IS_EXPIRED, "TEXT NOT NULL", false);
+ AddColumn(IS_ACTIVE, "TEXT NOT NULL", false);
+ AddColumn(STATE, "INT NOT NULL", false);
+ AddColumn(ZONE_ID, "TEXT", false);
+ AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT", false);
+ AddColumn(ACTION_BUTTON_INFO, "TEXT", false);
+ AddColumn(SLOT_ID, "INT", false);
+ AddColumn(NOTIFICATION_ID, "INT NOT NULL", false);
+ AddColumn(TITLE, "TEXT", false);
+ AddColumn(CONTENT, "TEXT", false);
+ AddColumn(SNOOZE_CONTENT, "TEXT", false);
+ AddColumn(EXPIRED_CONTENT, "TEXT", false);
+ AddColumn(AGENT, "TEXT", false);
+ AddColumn(MAX_SCREEN_AGENT, "TEXT", false);
+}
+
+void ReminderRequest::AddColumn(
+ const std::string &name, const std::string &type, const bool &isEnd)
+{
+ columns.push_back(name);
+ if (!isEnd) {
+ sqlOfAddColumns += name + " " + type + ", ";
+ } else {
+ sqlOfAddColumns += name + " " + type;
+ }
}
}
+}
\ No newline at end of file
diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp
index f5a549729d310340397863571d3a25fe0fd3fc29..3a3ee1af65fca4354147cbddc34999be8bed0af3 100644
--- a/frameworks/ans/native/src/reminder_request_alarm.cpp
+++ b/frameworks/ans/native/src/reminder_request_alarm.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13,10 +13,11 @@
* limitations under the License.
*/
-#include "ans_log_wrapper.h"
-
#include "reminder_request_alarm.h"
+#include "ans_log_wrapper.h"
+#include "reminder_store.h"
+
namespace OHOS {
namespace Notification {
const uint8_t ReminderRequestAlarm::DAYS_PER_WEEK = 7;
@@ -28,6 +29,11 @@ const uint8_t ReminderRequestAlarm::MINUTES_PER_HOUR = 60;
const int8_t ReminderRequestAlarm::INVALID_INT_VALUE = -1;
const int8_t ReminderRequestAlarm::DEFAULT_SNOOZE_TIMES = 3;
+// For database recovery.
+const std::string ReminderRequestAlarm::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week";
+const std::string ReminderRequestAlarm::ALARM_HOUR = "alarm_hour";
+const std::string ReminderRequestAlarm::ALARM_MINUTE = "alarm_minute";
+
ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek)
: ReminderRequest(ReminderRequest::ReminderType::ALARM)
{
@@ -49,11 +55,11 @@ ReminderRequestAlarm::ReminderRequestAlarm(const ReminderRequestAlarm &other) :
void ReminderRequestAlarm::CheckParamValid() const
{
- if (hour_ >= HOURS_PER_DAY || hour_ < 0) {
+ if (hour_ >= HOURS_PER_DAY) {
ANSR_LOGE("setted hour is not between [0, 24)");
throw std::invalid_argument("setted hour is not between [0, 24)");
}
- if (minute_ < 0 || minute_ >= MINUTES_PER_HOUR) {
+ if (minute_ >= MINUTES_PER_HOUR) {
ANSR_LOGE("setted minute is not between [0, 60)");
throw std::invalid_argument("setted minute is not between [0, 60)");
}
@@ -154,10 +160,12 @@ int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target)
if (repeatDays_ == 0) {
return INVALID_INT_VALUE;
}
- int today = GetActualTime(TimeTransferType::WEEK, gmtime(&now)->tm_wday);
- int dayCount = now >= target ? 1 : 0;
+ struct tm nowTime;
+ (void)gmtime_r(&now, &nowTime);
+ int32_t today = GetActualTime(TimeTransferType::WEEK, nowTime.tm_wday);
+ int32_t dayCount = now >= target ? 1 : 0;
for (; dayCount <= DAYS_PER_WEEK; dayCount++) {
- int day = (today + dayCount) % DAYS_PER_WEEK;
+ int32_t day = (today + dayCount) % DAYS_PER_WEEK;
day = (day == 0) ? SUNDAY : day;
if (IsRepeatDay(day)) {
break;
@@ -167,17 +175,17 @@ int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target)
return dayCount;
}
-bool ReminderRequestAlarm::IsRepeatDay(int day) const
+bool ReminderRequestAlarm::IsRepeatDay(int32_t day) const
{
return (repeatDays_ & (1 << (day - 1))) > 0;
}
-std::vector ReminderRequestAlarm::GetDaysOfWeek() const
+std::vector ReminderRequestAlarm::GetDaysOfWeek() const
{
- std::vector repeatDays;
- int days[] = {1, 2, 3, 4, 5, 6, 7};
- int len = sizeof(days) / sizeof(int);
- for (int i = 0; i < len; i++) {
+ std::vector repeatDays;
+ int32_t days[] = {1, 2, 3, 4, 5, 6, 7};
+ int32_t len = sizeof(days) / sizeof(int32_t);
+ for (int32_t i = 0; i < len; i++) {
if (IsRepeatDay(days[i])) {
repeatDays.push_back(days[i]);
}
@@ -269,7 +277,11 @@ ReminderRequestAlarm *ReminderRequestAlarm::Unmarshalling(Parcel &parcel)
{
ANSR_LOGD("New alarm");
auto objptr = new (std::nothrow) ReminderRequestAlarm();
- if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) {
+ if (objptr == nullptr) {
+ ANSR_LOGE("Failed to create reminder alarm due to no memory.");
+ return objptr;
+ }
+ if (!objptr->ReadFromParcel(parcel)) {
delete objptr;
objptr = nullptr;
}
@@ -296,5 +308,46 @@ bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel)
ANSR_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_);
return true;
}
+
+void ReminderRequestAlarm::RecoverFromDb(const std::shared_ptr &resultSet)
+{
+ ReminderRequest::RecoverFromDb(resultSet);
+
+ // repeatDays
+ repeatDays_ =
+ static_cast(RecoverInt64FromDb(resultSet, REPEAT_DAYS_OF_WEEK, DbRecoveryType::INT));
+
+ // hour
+ hour_ =
+ static_cast(RecoverInt64FromDb(resultSet, ALARM_HOUR, DbRecoveryType::INT));
+
+ // minute
+ minute_ =
+ static_cast(RecoverInt64FromDb(resultSet, ALARM_MINUTE, DbRecoveryType::INT));
+}
+
+void ReminderRequestAlarm::AppendValuesBucket(const sptr &reminder,
+ const sptr &bundleOption, NativeRdb::ValuesBucket &values)
+{
+ uint8_t repeatDays = 0;
+ uint8_t hour = 0;
+ uint8_t minute = 0;
+ if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) {
+ ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr());
+ repeatDays = alarm->GetRepeatDay();
+ hour = alarm->GetHour();
+ minute = alarm->GetMinute();
+ }
+ values.PutInt(REPEAT_DAYS_OF_WEEK, repeatDays);
+ values.PutInt(ALARM_HOUR, hour);
+ values.PutInt(ALARM_MINUTE, minute);
+}
+
+void ReminderRequestAlarm::InitDbColumns()
+{
+ ReminderRequest::AddColumn(REPEAT_DAYS_OF_WEEK, "INT", false);
+ ReminderRequest::AddColumn(ALARM_HOUR, "INT", false);
+ ReminderRequest::AddColumn(ALARM_MINUTE, "INT", true);
+}
}
}
\ No newline at end of file
diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp
index 0809af1294726c2a50f9e02e688d28fdf0fc4970..7cc3a58099b57d4458055dd7317073edea00e282 100644
--- a/frameworks/ans/native/src/reminder_request_calendar.cpp
+++ b/frameworks/ans/native/src/reminder_request_calendar.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13,10 +13,10 @@
* limitations under the License.
*/
-#include "ans_log_wrapper.h"
-
#include "reminder_request_calendar.h"
+#include "ans_log_wrapper.h"
+
namespace OHOS {
namespace Notification {
const uint8_t ReminderRequestCalendar::MAX_MONTHS_OF_YEAR = 12;
@@ -25,13 +25,25 @@ const uint8_t ReminderRequestCalendar::JANUARY = 1;
const uint8_t ReminderRequestCalendar::DECEMBER = 12;
const uint8_t ReminderRequestCalendar::DEFAULT_SNOOZE_TIMES = 3;
+// For database recovery.
+const std::string ReminderRequestCalendar::REPEAT_DAYS = "repeat_days";
+const std::string ReminderRequestCalendar::REPEAT_MONTHS = "repeat_months";
+const std::string ReminderRequestCalendar::FIRST_DESIGNATE_YEAR = "first_designate_year";
+const std::string ReminderRequestCalendar::FIRST_DESIGNATE_MONTH = "first_designate_month";
+const std::string ReminderRequestCalendar::FIRST_DESIGNATE_DAY = "first_designate_day";
+const std::string ReminderRequestCalendar::CALENDAR_YEAR = "calendar_year";
+const std::string ReminderRequestCalendar::CALENDAR_MONTH = "calendar_month";
+const std::string ReminderRequestCalendar::CALENDAR_DAY = "calendar_day";
+const std::string ReminderRequestCalendar::CALENDAR_HOUR = "calendar_hour";
+const std::string ReminderRequestCalendar::CALENDAR_MINUTE = "calendar_minute";
+
ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime,
const std::vector &repeatMonths, const std::vector &repeatDays)
: ReminderRequest(ReminderRequest::ReminderType::CALENDAR)
{
- // 1. record the infomation which designated by user at first time.
- firstDesignateYear_ = GetActualTime(TimeTransferType::YEAR, dateTime.tm_year);
- firstDesignateMonth_ = GetActualTime(TimeTransferType::MONTH, dateTime.tm_mon);
+ // 1. record the information which designated by user at first time.
+ firstDesignateYear_ = static_cast(GetActualTime(TimeTransferType::YEAR, dateTime.tm_year));
+ firstDesignateMonth_ = static_cast(GetActualTime(TimeTransferType::MONTH, dateTime.tm_mon));
firstDesignateDay_ = dateTime.tm_mday;
SetRepeatMonths(repeatMonths);
SetRepeatDaysOfMonth(repeatDays);
@@ -39,8 +51,8 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime,
// 2. get the latest valid trigger time.
InitDateTime(dateTime);
- hour_ = dateTime_.tm_hour;
- minute_ = dateTime_.tm_min;
+ hour_ = static_cast(dateTime_.tm_hour);
+ minute_ = static_cast(dateTime_.tm_min);
uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE;
if ((nextTriggerTime = GetNextTriggerTime()) != INVALID_LONG_LONG_VALUE) {
time_t target = static_cast(nextTriggerTime / MILLI_SECONDS);
@@ -51,10 +63,10 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime,
"Not exist next trigger time, please check the param of ReminderRequestCalendar constructor.");
}
- // 2. set the time infomation (used to transfer to proxy service) which is decided to trigger firstly.
- year_ = GetActualTime(TimeTransferType::YEAR, dateTime_.tm_year);
- month_ = GetActualTime(TimeTransferType::MONTH, dateTime_.tm_mon);
- day_ = dateTime_.tm_mday;
+ // 2. set the time information (used to transfer to proxy service) which is decided to trigger firstly.
+ year_ = static_cast(GetActualTime(TimeTransferType::YEAR, dateTime_.tm_year));
+ month_ = static_cast(GetActualTime(TimeTransferType::MONTH, dateTime_.tm_mon));
+ day_ = static_cast(dateTime_.tm_mday);
second_ = 0;
SetTriggerTimeInMilli(nextTriggerTime);
}
@@ -86,7 +98,7 @@ uint8_t ReminderRequestCalendar::GetDaysOfMonth(const uint16_t &year, const uint
uint8_t leapParam1 = 4;
uint8_t leapParam2 = 100;
if (month == february) {
- days = ((((0 == year % leapParam1) && (0 != year % leapParam2)) || (0 == year % solarYear))
+ days = ((((year % leapParam1 == 0) && (year % leapParam2 != 0)) || (year % solarYear == 0))
? leapMonth : nonLeapMonth);
} else {
days = daysArray[month - 1];
@@ -105,7 +117,7 @@ uint8_t ReminderRequestCalendar::GetNextDay(
struct tm setTime;
setTime.tm_year = GetCTime(TimeTransferType::YEAR, settedYear);
setTime.tm_mon = GetCTime(TimeTransferType::MONTH, settedMonth);
- setTime.tm_mday = i;
+ setTime.tm_mday = static_cast(i);
setTime.tm_hour = target.tm_hour;
setTime.tm_min = target.tm_min;
setTime.tm_sec = target.tm_sec;
@@ -191,7 +203,7 @@ uint64_t ReminderRequestCalendar::GetNextTriggerTimeAsRepeatReminder(const tm &n
}
if ((triggerTimeInMilli = GetTimeInstantMilli(setYear, setMonth, setDay, hour_, minute_, second_))
!= INVALID_LONG_LONG_VALUE) {
- ANSR_LOGD("Next calendar time:%{public}u/%{public}u/%{public}u %{public}u:%{public}u:%{public}u",
+ ANSR_LOGD("Next calendar time:%{public}hu/%{public}hhu/%{public}hhu %{public}hhu:%{public}hhu:%{public}hhu",
setYear, setMonth, setDay, hour_, minute_, second_);
}
return triggerTimeInMilli;
@@ -203,10 +215,10 @@ uint64_t ReminderRequestCalendar::GetTimeInstantMilli(
struct tm tar;
tar.tm_year = GetCTime(TimeTransferType::YEAR, year);
tar.tm_mon = GetCTime(TimeTransferType::MONTH, month);
- tar.tm_mday = day;
- tar.tm_hour = hour;
- tar.tm_min = minute;
- tar.tm_sec = second;
+ tar.tm_mday = static_cast(day);
+ tar.tm_hour = static_cast(hour);
+ tar.tm_min = static_cast(minute);
+ tar.tm_sec = static_cast(second);
tar.tm_isdst = -1;
ANSR_LOGD("tar: %{public}d-%{public}d-%{public}d %{public}d:%{public}d:%{public}d",
@@ -223,10 +235,10 @@ void ReminderRequestCalendar::InitDateTime()
{
dateTime_.tm_year = GetCTime(TimeTransferType::YEAR, year_);
dateTime_.tm_mon = GetCTime(TimeTransferType::MONTH, month_);
- dateTime_.tm_mday = day_;
- dateTime_.tm_hour = hour_;
- dateTime_.tm_min = minute_;
- dateTime_.tm_sec = second_;
+ dateTime_.tm_mday = static_cast(day_);
+ dateTime_.tm_hour = static_cast(hour_);
+ dateTime_.tm_min = static_cast(minute_);
+ dateTime_.tm_sec = static_cast(second_);
dateTime_.tm_isdst = -1;
}
@@ -284,7 +296,7 @@ void ReminderRequestCalendar::SetMonth(const uint8_t &month, const bool &isSet)
void ReminderRequestCalendar::SetRepeatMonths(const std::vector &repeatMonths)
{
if (repeatMonths.size() > MAX_MONTHS_OF_YEAR) {
- ANSR_LOGW("The length of repeat months array should not larger than %{public}u", MAX_MONTHS_OF_YEAR);
+ ANSR_LOGW("The length of repeat months array should not larger than %{public}hhu", MAX_MONTHS_OF_YEAR);
throw std::invalid_argument(
"The length of repeat months array should not larger than " + std::to_string(MAX_MONTHS_OF_YEAR));
}
@@ -297,7 +309,7 @@ void ReminderRequestCalendar::SetRepeatMonths(const std::vector &repeat
void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &repeateDays)
{
if (repeateDays.size() > MAX_DAYS_OF_MONTH) {
- ANSR_LOGW("The length of repeat days array should not larger than %{public}u", MAX_DAYS_OF_MONTH);
+ ANSR_LOGW("The length of repeat days array should not larger than %{public}hhu", MAX_DAYS_OF_MONTH);
throw std::invalid_argument(
"The length of repeat days array should not larger than " + std::to_string(MAX_DAYS_OF_MONTH));
}
@@ -310,7 +322,7 @@ void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &r
std::vector ReminderRequestCalendar::GetRepeatMonths() const
{
std::vector repeatMonths;
- for (int i = 0; i < MAX_MONTHS_OF_YEAR; i++) {
+ for (int32_t i = 0; i < MAX_MONTHS_OF_YEAR; i++) {
if (IsRepeatMonth(i + 1)) {
repeatMonths.push_back(i + 1);
}
@@ -321,7 +333,7 @@ std::vector ReminderRequestCalendar::GetRepeatMonths() const
std::vector ReminderRequestCalendar::GetRepeatDays() const
{
std::vector repeatDays;
- for (int i = 0; i < MAX_DAYS_OF_MONTH; i++) {
+ for (int32_t i = 0; i < MAX_DAYS_OF_MONTH; i++) {
if (IsRepeatDay(i + 1)) {
repeatDays.push_back(i + 1);
}
@@ -438,8 +450,12 @@ bool ReminderRequestCalendar::Marshalling(Parcel &parcel) const
ReminderRequestCalendar *ReminderRequestCalendar::Unmarshalling(Parcel &parcel)
{
ANSR_LOGD("New calendar");
- auto objptr = new ReminderRequestCalendar();
- if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) {
+ auto objptr = new (std::nothrow) ReminderRequestCalendar();
+ if (objptr == nullptr) {
+ ANS_LOGE("Failed to create reminder calendar due to no memory.");
+ return objptr;
+ }
+ if (!objptr->ReadFromParcel(parcel)) {
delete objptr;
objptr = nullptr;
}
@@ -498,5 +514,96 @@ bool ReminderRequestCalendar::ReadFromParcel(Parcel &parcel)
}
return true;
}
+
+void ReminderRequestCalendar::RecoverFromDb(const std::shared_ptr &resultSet)
+{
+ ReminderRequest::RecoverFromDb(resultSet);
+
+ // repeatDay
+ repeatDay_ = static_cast(RecoverInt64FromDb(resultSet, REPEAT_DAYS, DbRecoveryType::INT));
+
+ // repeatMonth
+ repeatMonth_ =
+ static_cast(RecoverInt64FromDb(resultSet, REPEAT_MONTHS, DbRecoveryType::INT));
+
+ // firstDesignateYear
+ firstDesignateYear_ =
+ static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_YEAR, DbRecoveryType::INT));
+
+ // firstDesignateMonth
+ firstDesignateMonth_ =
+ static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_MONTH, DbRecoveryType::INT));
+
+ // firstDesignateDay
+ firstDesignateDay_ =
+ static_cast(RecoverInt64FromDb(resultSet, FIRST_DESIGNATE_DAY, DbRecoveryType::INT));
+
+ // year
+ year_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_YEAR, DbRecoveryType::INT));
+
+ // month
+ month_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_MONTH, DbRecoveryType::INT));
+
+ // day
+ day_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_DAY, DbRecoveryType::INT));
+
+ // hour
+ hour_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_HOUR, DbRecoveryType::INT));
+
+ // minute
+ minute_ = static_cast(RecoverInt64FromDb(resultSet, CALENDAR_MINUTE, DbRecoveryType::INT));
+}
+
+void ReminderRequestCalendar::AppendValuesBucket(const sptr &reminder,
+ const sptr &bundleOption, NativeRdb::ValuesBucket &values)
+{
+ uint32_t repeatDay = 0;
+ uint16_t repeatMonth = 0;
+ uint16_t firstDesignateYear = 0;
+ uint8_t firstDesignateMonth = 0;
+ uint8_t firstDesignateDay = 0;
+ uint16_t year = 0;
+ uint8_t month = 0;
+ uint8_t day = 0;
+ uint8_t hour = 0;
+ uint8_t minute = 0;
+ if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) {
+ ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr());
+ repeatDay = calendar->GetRepeatDay();
+ repeatMonth = calendar->GetRepeatMonth();
+ firstDesignateYear = calendar->GetFirstDesignateYear();
+ firstDesignateMonth = calendar->GetFirstDesignageMonth();
+ firstDesignateDay = calendar->GetFirstDesignateDay();
+ year = calendar->GetYear();
+ month = calendar->GetMonth();
+ day = calendar->GetDay();
+ hour = calendar->GetHour();
+ minute = calendar->GetMinute();
+ }
+ values.PutInt(REPEAT_DAYS, repeatDay);
+ values.PutInt(REPEAT_MONTHS, repeatMonth);
+ values.PutInt(FIRST_DESIGNATE_YEAR, firstDesignateYear);
+ values.PutInt(FIRST_DESIGNATE_MONTH, firstDesignateMonth);
+ values.PutInt(FIRST_DESIGNATE_DAY, firstDesignateDay);
+ values.PutInt(CALENDAR_YEAR, year);
+ values.PutInt(CALENDAR_MONTH, month);
+ values.PutInt(CALENDAR_DAY, day);
+ values.PutInt(CALENDAR_HOUR, hour);
+ values.PutInt(CALENDAR_MINUTE, minute);
+}
+
+void ReminderRequestCalendar::InitDbColumns()
+{
+ ReminderRequest::AddColumn(REPEAT_DAYS, "INT", false);
+ ReminderRequest::AddColumn(REPEAT_MONTHS, "INT", false);
+ ReminderRequest::AddColumn(FIRST_DESIGNATE_YEAR, "INT", false);
+ ReminderRequest::AddColumn(FIRST_DESIGNATE_MONTH, "INT", false);
+ ReminderRequest::AddColumn(FIRST_DESIGNATE_DAY, "INT", false);
+ ReminderRequest::AddColumn(CALENDAR_YEAR, "INT", false);
+ ReminderRequest::AddColumn(CALENDAR_MONTH, "INT", false);
+ ReminderRequest::AddColumn(CALENDAR_DAY, "INT", false);
+ ReminderRequest::AddColumn(CALENDAR_HOUR, "INT", false);
+ ReminderRequest::AddColumn(CALENDAR_MINUTE, "INT", false);
+}
}
}
\ No newline at end of file
diff --git a/frameworks/ans/native/src/reminder_request_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp
index d0fd4337b2432cc0974cfcb9d5103ad071705014..4b5c878143304caca833b1dd6382091f202236b7 100644
--- a/frameworks/ans/native/src/reminder_request_timer.cpp
+++ b/frameworks/ans/native/src/reminder_request_timer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13,14 +13,14 @@
* limitations under the License.
*/
+#include "reminder_request_timer.h"
+
#include
#include
#include "ans_log_wrapper.h"
#include "time_service_client.h"
-#include "reminder_request_timer.h"
-
namespace OHOS {
namespace Notification {
ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds)
@@ -33,7 +33,16 @@ ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds)
ReminderRequest::SetTriggerTimeInMilli(
ReminderRequest::GetDurationSinceEpochInMilli(now) + countDownTimeInSeconds_ * ReminderRequest::MILLI_SECONDS);
sptr timer = MiscServices::TimeServiceClient::GetInstance();
- firstRealTimeInMilliSeconds_ = timer->GetBootTimeMs();
+ if (timer == nullptr) {
+ ANSR_LOGW("Failed to get boot time due to TimeServiceClient is null.");
+ } else {
+ int64_t bootTimeMs = timer->GetBootTimeMs();
+ if (bootTimeMs >= 0) {
+ firstRealTimeInMilliSeconds_ = static_cast(bootTimeMs);
+ } else {
+ ANSR_LOGW("Get boot time error.");
+ }
+ }
}
ReminderRequestTimer::ReminderRequestTimer(const ReminderRequestTimer &other) : ReminderRequest(other)
@@ -80,7 +89,7 @@ void ReminderRequestTimer::CheckParamsValid(const uint64_t countDownTimeInSecond
}
}
-void ReminderRequestTimer::UpdateTimeInfo(const std::string description)
+void ReminderRequestTimer::UpdateTimeInfo(const std::string &description)
{
if (IsExpired()) {
return;
@@ -90,9 +99,17 @@ void ReminderRequestTimer::UpdateTimeInfo(const std::string description)
(void)time(&now); // unit is seconds.
whenToChangeSysTime_ = ReminderRequest::GetDurationSinceEpochInMilli(now);
sptr timer = MiscServices::TimeServiceClient::GetInstance();
+ if (timer == nullptr) {
+ ANSR_LOGW("Failed to updateTime info due to TimeServiceClient is null.");
+ return;
+ }
int64_t bootTime = timer->GetBootTimeMs();
+ if (bootTime < 0) {
+ ANSR_LOGW("BootTime is illegal");
+ return;
+ }
SetTriggerTimeInMilli(whenToChangeSysTime_ + (countDownTimeInSeconds_ * MILLI_SECONDS -
- (bootTime - firstRealTimeInMilliSeconds_)));
+ (static_cast(bootTime) - firstRealTimeInMilliSeconds_)));
}
bool ReminderRequestTimer::Marshalling(Parcel &parcel) const
@@ -113,8 +130,12 @@ bool ReminderRequestTimer::Marshalling(Parcel &parcel) const
ReminderRequestTimer *ReminderRequestTimer::Unmarshalling(Parcel &parcel)
{
- auto objptr = new ReminderRequestTimer();
- if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) {
+ auto objptr = new (std::nothrow) ReminderRequestTimer();
+ if (objptr == nullptr) {
+ ANSR_LOGE("Failed to create reminder timer due to no memory.");
+ return objptr;
+ }
+ if (!objptr->ReadFromParcel(parcel)) {
delete objptr;
objptr = nullptr;
}
diff --git a/frameworks/ans/native/src/reminder_store.cpp b/frameworks/ans/native/src/reminder_store.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1cd8e95dcb0c93b3d99815394005417b07bf22ae
--- /dev/null
+++ b/frameworks/ans/native/src/reminder_store.cpp
@@ -0,0 +1,430 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "reminder_store.h"
+
+#include
+#include
+#include
+#include
+
+#include "ability_context.h"
+#include "ans_log_wrapper.h"
+#include "reminder_request_alarm.h"
+#include "reminder_request_calendar.h"
+#include "reminder_request_timer.h"
+
+namespace OHOS {
+namespace Notification {
+namespace {
+const std::string REMINDER_DB_DIR = "/data/system_ce/ans_standard/";
+const std::string REMINDER_DB_NAME = "reminder.db";
+const std::string REMINDER_DB_TABLE = "reminder";
+const uint32_t REMINDER_RDB_VERSION = 1;
+const int32_t STATE_FAIL = -1;
+std::vector columns;
+}
+
+const int32_t ReminderStore::STATE_OK = 0;
+
+int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore &store)
+{
+ ANSR_LOGD("Create table.");
+ std::string CREATE_REMINDER_TABLE = "CREATE TABLE IF NOT EXISTS " + REMINDER_DB_TABLE + " ("
+ + ReminderRequest::sqlOfAddColumns + ")";
+ ANSR_LOGD("CreateTable:%{public}s", CREATE_REMINDER_TABLE.c_str());
+ return store.ExecuteSql(CREATE_REMINDER_TABLE);
+}
+
+int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade(
+ NativeRdb::RdbStore &store, int32_t oldVersion, int32_t newVersion)
+{
+ return NativeRdb::E_OK;
+}
+
+int32_t ReminderStore::Init()
+{
+ ANSR_LOGD("Reminder store init.");
+ int32_t errCode(STATE_FAIL);
+
+ if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) {
+ int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU);
+ if (createDir != 0) {
+ ANSR_LOGE("Failed to create directory %{public}s", REMINDER_DB_DIR.c_str());
+ return errCode;
+ }
+ }
+
+ ReminderRequest::InitDbColumns();
+ ReminderRequestCalendar::InitDbColumns();
+ ReminderRequestAlarm::InitDbColumns();
+ columns.insert(columns.begin(),
+ ReminderRequest::columns.begin(), ReminderRequest::columns.end());
+
+ std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME;
+ NativeRdb::RdbStoreConfig config_(dbConfig);
+ ReminderStoreDataCallBack rdbDataCallBack_;
+ rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config_, REMINDER_RDB_VERSION, rdbDataCallBack_, errCode);
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode);
+ return errCode;
+ }
+ return ReminderStore::InitData();
+}
+
+int32_t ReminderStore::InitData()
+{
+ ANSR_LOGD("Reminder data init.");
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return STATE_FAIL;
+ }
+ std::string deleteCondition = ReminderRequest::IS_EXPIRED + " is true";
+ ReminderStore::Delete(deleteCondition);
+
+ int32_t statusChangedRows = STATE_FAIL;
+ NativeRdb::ValuesBucket statusValues;
+ statusValues.PutInt(ReminderRequest::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE);
+ int32_t statusResult = rdbStore_->Update(statusChangedRows, REMINDER_DB_TABLE, statusValues);
+ ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows);
+ if (statusResult != NativeRdb::E_OK) {
+ ANSR_LOGE("Init data failed.");
+ return STATE_FAIL;
+ }
+
+ int32_t activeChangedRows = STATE_FAIL;
+ NativeRdb::ValuesBucket activeValues;
+ activeValues.PutString(ReminderRequest::IS_ACTIVE, "false");
+ std::string activeUpdateCondition = ReminderRequest::IS_ACTIVE + " is true";
+ std::vector activeWhereArgs;
+ int32_t activeResult = rdbStore_->Update(
+ activeChangedRows, REMINDER_DB_TABLE, activeValues, activeUpdateCondition, activeWhereArgs);
+ ANSR_LOGD("Change status isActive to false, changed rows: %{public}d.", activeChangedRows);
+ if (activeResult != NativeRdb::E_OK) {
+ ANSR_LOGE("Init data failed.");
+ return STATE_FAIL;
+ }
+
+ int32_t scheduledChangedRows = STATE_FAIL;
+ NativeRdb::ValuesBucket scheduledValues;
+ scheduledValues.PutString(ReminderRequest::HAS_SCHEDULED_TIMEOUT, "false");
+ std::string scheduledUpdateCondition = ReminderRequest::HAS_SCHEDULED_TIMEOUT + " is true";
+ std::vector scheduledWhereArgs;
+ int32_t scheduledResult = rdbStore_->Update(
+ scheduledChangedRows, REMINDER_DB_TABLE, scheduledValues, scheduledUpdateCondition, scheduledWhereArgs);
+ ANSR_LOGD("Change status has_ScheduledTimeout to false, changed rows: %{public}d.", scheduledChangedRows);
+ if (scheduledResult != NativeRdb::E_OK) {
+ ANSR_LOGE("Init data failed.");
+ return STATE_FAIL;
+ }
+ return ReminderStore::STATE_OK;
+}
+
+int32_t ReminderStore::Delete(int32_t reminderId)
+{
+ std::string deleteCondition = ReminderRequest::REMINDER_ID
+ + " = " + std::to_string(reminderId);
+ return ReminderStore::Delete(deleteCondition);
+}
+
+int32_t ReminderStore::DeleteUser(int32_t userId)
+{
+ std::string deleteCondition = ReminderRequest::USER_ID + " = " + std::to_string(userId);
+ return ReminderStore::Delete(deleteCondition);
+}
+
+int32_t ReminderStore::Delete(const std::string &pkg, int32_t userId)
+{
+ std::string deleteCondition = ReminderRequest::PKG_NAME + " = \"" + pkg + "\" and "
+ + ReminderRequest::USER_ID + " = " + std::to_string(userId);
+ return ReminderStore::Delete(deleteCondition);
+}
+
+int32_t ReminderStore::Delete(const std::string &deleteCondition)
+{
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return STATE_FAIL;
+ }
+ int32_t deletedRows = STATE_FAIL;
+ std::vector whereArgs;
+ int32_t result = rdbStore_->Delete(deletedRows, REMINDER_DB_TABLE, deleteCondition, whereArgs);
+ if (result != NativeRdb::E_OK) {
+ ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \
+ "result: %{public}d.", deleteCondition.c_str(), result);
+ }
+ ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \
+ "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows);
+ return deletedRows;
+}
+
+int64_t ReminderStore::UpdateOrInsert(
+ const sptr &reminder, const sptr &bundleOption)
+{
+ if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) {
+ ANSR_LOGI("Countdown not support persist.");
+ return STATE_FAIL;
+ }
+ int64_t isSuccess = STATE_FAIL;
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return isSuccess;
+ }
+ if (bundleOption == nullptr) {
+ ANSR_LOGE("BundleOption is null.");
+ return isSuccess;
+ }
+ if (IsReminderExist(reminder)) {
+ isSuccess = Update(reminder, bundleOption);
+ } else {
+ isSuccess = Insert(reminder, bundleOption);
+ }
+ return isSuccess;
+}
+
+int64_t ReminderStore::Insert(
+ const sptr &reminder, const sptr &bundleOption)
+{
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return STATE_FAIL;
+ }
+ int64_t rowId = STATE_FAIL;
+ NativeRdb::ValuesBucket values;
+ ReminderStore::GenerateData(reminder, bundleOption, values);
+ int32_t result = rdbStore_->Insert(rowId, REMINDER_DB_TABLE, values);
+ if (result != NativeRdb::E_OK) {
+ ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.",
+ result, reminder->GetReminderId());
+ return result;
+ }
+ ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId());
+ return result;
+}
+
+int64_t ReminderStore::Update(
+ const sptr &reminder, const sptr &bundleOption)
+{
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return STATE_FAIL;
+ }
+ int32_t changedRows = STATE_FAIL;
+ NativeRdb::ValuesBucket values;
+ ReminderStore::GenerateData(reminder, bundleOption, values);
+ std::string updateCondition = ReminderRequest::REMINDER_ID
+ + " = " + std::to_string(reminder->GetReminderId());
+ std::vector whereArgs;
+ int32_t result = rdbStore_->Update(changedRows, REMINDER_DB_TABLE, values, updateCondition, whereArgs);
+ if ((result != NativeRdb::E_OK) || (changedRows <= 0)) {
+ ANSR_LOGE("Update operation failed, result: %{public}d, updated rows: %{public}d, reminderId=%{public}d.",
+ result, changedRows, reminder->GetReminderId());
+ return result;
+ }
+ ANSR_LOGD("Update successfully, updated rows: %{public}d, reminderId=%{public}d.",
+ changedRows, reminder->GetReminderId());
+ return result;
+}
+
+bool ReminderStore::IsReminderExist(const sptr &reminder)
+{
+ std::string queryCondition = "select " + ReminderRequest::REMINDER_ID
+ + " from " + REMINDER_DB_TABLE + " where "
+ + ReminderRequest::REMINDER_ID + " = " + std::to_string(reminder->GetReminderId());
+ std::vector whereArgs;
+ std::unique_ptr queryResultSet = rdbStore_->QuerySql(queryCondition, whereArgs);
+ if (queryResultSet == nullptr) {
+ ANSR_LOGE("QueryResultSet is null.");
+ return false;
+ }
+ int32_t resultNum;
+ queryResultSet->GetRowCount(resultNum);
+ if (resultNum == 0) {
+ return false;
+ }
+ return true;
+}
+
+std::shared_ptr ReminderStore::Query(const std::string &queryCondition) const
+{
+ std::unique_ptr queryResultSet;
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return queryResultSet;
+ }
+ std::vector whereArgs;
+ queryResultSet = rdbStore_->QuerySql(queryCondition, whereArgs);
+ return queryResultSet;
+}
+
+uint8_t ReminderStore::GetColumnIndex(const std::string& name)
+{
+ uint8_t index = 0;
+ for (auto it = columns.begin(); it != columns.end(); ++it) {
+ if (name == (*it)) {
+ break;
+ }
+ index++;
+ }
+ return index;
+}
+
+int32_t ReminderStore::GetMaxId()
+{
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return STATE_FAIL;
+ }
+ std::string queryCondition = "select " + ReminderRequest::REMINDER_ID
+ + " from " + REMINDER_DB_TABLE + " order by "
+ + ReminderRequest::REMINDER_ID + " desc";
+ std::shared_ptr queryResultSet = ReminderStore::Query(queryCondition);
+ if (queryResultSet == nullptr) {
+ ANSR_LOGE("QueryResultSet is null.");
+ return STATE_FAIL;
+ }
+ int32_t resultNum;
+ queryResultSet->GetRowCount(resultNum);
+ if (resultNum == 0) {
+ ANSR_LOGI("QueryResultSet is zero.");
+ return STATE_FAIL;
+ }
+ queryResultSet->GoToNextRow();
+ int32_t maxId = STATE_FAIL;
+ int32_t result = queryResultSet->GetInt(0, maxId);
+ if (result != NativeRdb::E_OK) {
+ ANSR_LOGE("Query operation failed, result %{public}d.", result);
+ }
+ ANSR_LOGD("MaxId: %{public}d.", maxId);
+ return maxId;
+}
+
+std::vector> ReminderStore::GetAllValidReminders()
+{
+ std::string queryCondition = "select * from " + REMINDER_DB_TABLE + " where "
+ + ReminderRequest::IS_EXPIRED + " is false order by "
+ + ReminderRequest::TRIGGER_TIME + " asc";
+ ANSR_LOGD("Get all reminders");
+ return GetReminders(queryCondition);
+}
+
+std::vector> ReminderStore::GetReminders(const std::string &queryCondition)
+{
+ std::vector> reminders;
+ if (rdbStore_ == nullptr) {
+ ANSR_LOGE("Rdb store is not initialized.");
+ return reminders;
+ }
+ std::shared_ptr queryResultSet = Query(queryCondition);
+ if (queryResultSet == nullptr) {
+ return reminders;
+ }
+ bool isAtLastRow = false;
+ queryResultSet->IsAtLastRow(isAtLastRow);
+ while (!isAtLastRow) {
+ queryResultSet->GoToNextRow();
+ sptr reminder;
+ reminder = BuildReminder(queryResultSet);
+ reminders.push_back(reminder);
+ queryResultSet->IsAtLastRow(isAtLastRow);
+ }
+ ANSR_LOGD("Size=%{public}zu", reminders.size());
+ return reminders;
+}
+
+sptr ReminderStore::BuildReminder(const std::shared_ptr