• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*os_account_manager
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "notification_preferences_database.h"
17 
18 #include <regex>
19 #include <string>
20 #include <sstream>
21 
22 #include "ans_const_define.h"
23 #include "ans_inner_errors.h"
24 #include "os_account_manager_helper.h"
25 #include "ans_log_wrapper.h"
26 #include "ans_trace_wrapper.h"
27 #include "os_account_manager.h"
28 #include "ipc_skeleton.h"
29 #include "bundle_manager_helper.h"
30 #include "notification_analytics_util.h"
31 #include "notification_config_parse.h"
32 #include "uri.h"
33 #include "distributed_data_define.h"
34 namespace OHOS {
35 namespace Notification {
36 /**
37  * Indicates that disturbe key which do not disturbe type.
38  */
39 const static std::string KEY_DO_NOT_DISTURB_TYPE = "ans_doNotDisturbType";
40 
41 /**
42  * Indicates that disturbe key which do not disturbe begin date.
43  */
44 const static std::string KEY_DO_NOT_DISTURB_BEGIN_DATE = "ans_doNotDisturbBeginDate";
45 
46 /**
47  * Indicates that disturbe key which do not disturbe end date.
48  */
49 const static std::string KEY_DO_NOT_DISTURB_END_DATE = "ans_doNotDisturbEndDate";
50 
51 /**
52  * Indicates that disturbe key which do not disturbe id.
53  */
54 const static std::string KEY_DO_NOT_DISTURB_ID = "ans_doNotDisturbId";
55 
56 /**
57  * Indicates that disturbe key which enable all notification.
58  */
59 const static std::string KEY_ENABLE_ALL_NOTIFICATION = "ans_notificationAll";
60 
61 /**
62  * Indicates that disturbe key which bundle label.
63  */
64 const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_";
65 
66 /**
67  * Indicates that disturbe key which under line.
68  */
69 const static std::string KEY_UNDER_LINE = "_";
70 
71 /**
72  * Indicates that disturbe key which middle line.
73  */
74 const static std::string KEY_MIDDLE_LINE = "-";
75 
76 /**
77  * Indicates that disturbe key which bundle begin key.
78  */
79 const static std::string KEY_ANS_BUNDLE = "ans_bundle";
80 
81 /**
82  * Indicates that disturbe key which bundle name.
83  */
84 const static std::string KEY_BUNDLE_NAME = "name";
85 
86 /**
87  * Indicates that disturbe key which bundle imortance.
88  */
89 const static std::string KEY_BUNDLE_IMPORTANCE = "importance";
90 
91 /**
92  * Indicates that disturbe key which bundle show badge.
93  */
94 const static std::string KEY_BUNDLE_SHOW_BADGE = "showBadgeEnable";
95 
96 /**
97  * Indicates that disturbe key which bundle total badge num.
98  */
99 const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum";
100 
101 /**
102  * Indicates that disturbe key which bundle enable notification.
103  */
104 const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification";
105 
106 /**
107  * Indicates that disturbe key which bundle enable notification.
108  */
109 const static std::string KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION = "enabledDistributedNotification";
110 
111 /**
112  * Indicates that disturbe key which bundle enable notification.
113  */
114 const static std::string KEY_SMART_REMINDER_ENABLE_NOTIFICATION = "enabledSmartReminder";
115 
116 /**
117  * Indicates that disturbe key which bundle enable notification.
118  */
119 const static std::string KEY_SILENT_REMINDER_ENABLE_NOTIFICATION = "enabledSilentReminder";
120 
121 /**
122  * Indicates that disturbe key which bundle enable notification.
123  */
124 const static std::string KEY_ENABLE_SLOT_DISTRIBUTED_NOTIFICATION = "enabledSlotDistributedNotification";
125 
126 /**
127  * Indicates that disturbe key which bundle popped dialog.
128  */
129 const static std::string KEY_BUNDLE_POPPED_DIALOG = "poppedDialog";
130 
131 /**
132  * Indicates that disturbe key which bundle uid.
133  */
134 const static std::string KEY_BUNDLE_UID = "uid";
135 
136 /**
137  * Indicates that disturbe key which slot.
138  */
139 const static std::string KEY_SLOT = "slot";
140 
141 /**
142  * Indicates that disturbe key which slot type.
143  */
144 const static std::string KEY_SLOT_TYPE = "type";
145 
146 /**
147  * Indicates that disturbe key which slot id.
148  */
149 const static std::string KEY_SLOT_ID = "id";
150 
151 /**
152  * Indicates that disturbe key which slot name.
153  */
154 const static std::string KEY_SLOT_NAME = "name";
155 
156 /**
157  * Indicates that disturbe key which slot description.
158  */
159 const static std::string KEY_SLOT_DESCRIPTION = "description";
160 
161 /**
162  * Indicates that disturbe key which slot level.
163  */
164 const static std::string KEY_SLOT_LEVEL = "level";
165 
166 /**
167  * Indicates that disturbe key which slot show badge.
168  */
169 const static std::string KEY_SLOT_SHOW_BADGE = "showBadge";
170 
171 /**
172  * Indicates that disturbe key which slot enable light.
173  */
174 const static std::string KEY_SLOT_ENABLE_LIGHT = "enableLight";
175 
176 /**
177  * Indicates that disturbe key which slot enable vibration.
178  */
179 const static std::string KEY_SLOT_ENABLE_VRBRATION = "enableVibration";
180 
181 /**
182  * Indicates that disturbe key which slot led light color.
183  */
184 const static std::string KEY_SLOT_LED_LIGHT_COLOR = "ledLightColor";
185 
186 /**
187  * Indicates that disturbe key which slot lockscreen visibleness.
188  */
189 const static std::string KEY_SLOT_LOCKSCREEN_VISIBLENESS = "lockscreenVisibleness";
190 
191 /**
192  * Indicates that disturbe key which slot sound.
193  */
194 const static std::string KEY_SLOT_SOUND = "sound";
195 
196 /**
197  * Indicates that disturbe key which slot vibration style.
198  */
199 const static std::string KEY_SLOT_VIBRATION_STYLE = "vibrationSytle";
200 
201 /**
202  * Indicates that disturbe key which slot enable bypass end.
203  */
204 const static std::string KEY_SLOT_ENABLE_BYPASS_DND = "enableBypassDnd";
205 
206 /**
207  * Indicates whether the type of slot is enabled.
208  */
209 const static std::string KEY_SLOT_ENABLED = "enabled";
210 
211 /**
212  * Indicates whether the type of bundle is flags.
213  */
214 const static std::string KEY_BUNDLE_SLOTFLGS_TYPE = "bundleReminderFlagsType";
215 
216 /**
217  * Indicates whether the type of slot is flags.
218  */
219 const static std::string KEY_SLOT_SLOTFLGS_TYPE = "reminderFlagsType";
220 
221 /**
222  * Indicates that disturbe key which slot authorized status.
223  */
224 const static std::string KEY_SLOT_AUTHORIZED_STATUS = "authorizedStatus";
225 
226 /**
227  * Indicates that disturbe key which slot authorized hint count.
228  */
229 const static std::string KEY_SLOT_AUTH_HINT_CNT = "authHintCnt";
230 
231 /**
232  * Indicates that reminder mode of slot.
233  */
234 const static std::string KEY_REMINDER_MODE = "reminderMode";
235 
236 constexpr char RELATIONSHIP_JSON_KEY_SERVICE[] = "service";
237 constexpr char RELATIONSHIP_JSON_KEY_APP[] = "app";
238 
239 const static std::string KEY_CLONE_LABEL = "label_ans_clone_";
240 
241 const static std::string KEY_REMOVE_SLOT_FLAG = "label_ans_remove_";
242 
243 const static std::string KEY_REMOVED_FLAG = "1";
244 
245 const static std::string KEY_SECOND_REMOVED_FLAG = "2";
246 
247 constexpr int32_t CLEAR_SLOT_FROM_AVSEESAION = 1;
248 
249 /**
250  * Indicates hashCode rule.
251  */
252 const static std::string KEY_HASH_CODE_RULE = "hashCodeRule";
253 
254 const static std::string CLONE_BUNDLE = "bundle_";
255 const static std::string CLONE_PROFILE = "profile_";
256 const static std::string KEY_DISABLE_NOTIFICATION = "disableNotificationFeature";
257 constexpr int32_t ZERO_USER_ID = 0;
258 const static std::string KEY_SUBSCRIBER_EXISTED_FLAG = "existFlag";
259 const static int32_t DISTRIBUTED_KEY_NUM = 4;
260 const static int32_t DISTRIBUTED_KEY_BUNDLE_INDEX = 1;
261 const static int32_t DISTRIBUTED_KEY_UID_INDEX = 2;
262 
263 /**
264  * Indicates that distributed notification switch.
265  */
266 static const char* const KEY_DISTRIBUTED_NOTIFICATION_SWITCH = "distributedNotificationSwitch";
267 
268 /**
269  * Indicates the target device's authorization status.
270  */
271 static const char* const KEY_ENABLE_DISTRIBUTED_AUTH_STATUS = "enabledDistributedAuthStatus";
272 
273 /**
274  * Indicates that distributed device list.
275  */
276 static const char* const KEY_DISTRIBUTED_DEVICE_LIST = "distributedDeviceList";
277 
NotificationPreferencesDatabase()278 NotificationPreferencesDatabase::NotificationPreferencesDatabase()
279 {
280     NotificationRdbConfig notificationRdbConfig;
281     rdbDataManager_ = std::make_shared<NotificationDataMgr>(notificationRdbConfig);
282     ANS_LOGD("Notification Rdb is created");
283 }
284 
~NotificationPreferencesDatabase()285 NotificationPreferencesDatabase::~NotificationPreferencesDatabase()
286 {
287     ANS_LOGD("called");
288 }
289 
CheckRdbStore()290 bool NotificationPreferencesDatabase::CheckRdbStore()
291 {
292     if (rdbDataManager_ != nullptr) {
293         int32_t result = rdbDataManager_->Init();
294         if (result == NativeRdb::E_OK) {
295             return true;
296         }
297     }
298 
299     return false;
300 }
301 
PutSlotsToDisturbeDB(const std::string & bundleName,const int32_t & bundleUid,const std::vector<sptr<NotificationSlot>> & slots)302 bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB(
303     const std::string &bundleName, const int32_t &bundleUid, const std::vector<sptr<NotificationSlot>> &slots)
304 {
305     NOTIFICATION_HITRACE(HITRACE_TAG_NOTIFICATION);
306     ANS_LOGD("called");
307     if (bundleName.empty()) {
308         ANS_LOGE("Bundle name is null.");
309         return false;
310     }
311 
312     if (slots.empty()) {
313         ANS_LOGE("Slot is empty.");
314         return false;
315     }
316 
317     std::unordered_map<std::string, std::string> values;
318     for (auto iter : slots) {
319         bool result = SlotToEntry(bundleName, bundleUid, iter, values);
320         if (!result) {
321             return result;
322         }
323     }
324     int32_t userId = -1;
325     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
326     if (!CheckRdbStore()) {
327         ANS_LOGE("null RdbStore");
328         return false;
329     }
330     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
331     return (result == NativeRdb::E_OK);
332 }
333 
PutBundlePropertyToDisturbeDB(const NotificationPreferencesInfo::BundleInfo & bundleInfo)334 bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB(
335     const NotificationPreferencesInfo::BundleInfo &bundleInfo)
336 {
337     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_17, EventBranchId::BRANCH_0);
338     if (bundleInfo.GetBundleName().empty()) {
339         ANS_LOGE("Bundle name is null.");
340         NotificationAnalyticsUtil::ReportModifyEvent(message);
341         return false;
342     }
343 
344     message.Message(bundleInfo.GetBundleName() + "_" +std::to_string(bundleInfo.GetBundleUid()));
345     if (!CheckRdbStore()) {
346         ANS_LOGE("null RdbStore");
347         NotificationAnalyticsUtil::ReportModifyEvent(message.BranchId(BRANCH_1));
348         return false;
349     }
350     std::string values;
351     std::string bundleKeyStr = KEY_BUNDLE_LABEL + GenerateBundleLablel(bundleInfo);
352     int32_t userId = -1;
353     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
354     bool result = false;
355     GetValueFromDisturbeDB(bundleKeyStr, userId, [&](const int32_t &status, std::string &value) {
356         switch (status) {
357             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
358                 result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo);
359                 break;
360             }
361             case NativeRdb::E_OK: {
362                 ANS_LOGE("Current bundle has exsited.");
363                 break;
364             }
365             default:
366                 break;
367         }
368     });
369     return result;
370 }
371 
IsNotificationSlotFlagsExists(const sptr<NotificationBundleOption> & bundleOption)372 bool NotificationPreferencesDatabase::IsNotificationSlotFlagsExists(const sptr<NotificationBundleOption> &bundleOption)
373 {
374     if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
375         return false;
376     }
377     std::string bundleKey = bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid()));
378     std::string key = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE);
379     std::string value;
380     int32_t userId = -1;
381     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
382     int32_t result = rdbDataManager_->QueryData(key, value, userId);
383     return  (result == NativeRdb::E_OK) || (!value.empty());
384 }
385 
PutShowBadge(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const bool & enable)386 bool NotificationPreferencesDatabase::PutShowBadge(
387     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable)
388 {
389     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_17, EventBranchId::BRANCH_2);
390     message.Message("en:" + std::to_string(enable));
391     if (bundleInfo.GetBundleName().empty()) {
392         ANS_LOGE("Bundle name is nullptr.");
393         NotificationAnalyticsUtil::ReportModifyEvent(message);
394         return false;
395     }
396     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, showBadge[%{public}d]",
397         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), enable);
398 
399     if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) {
400         return false;
401     }
402 
403     std::string bundleKey = GenerateBundleLablel(bundleInfo);
404     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable,
405         bundleInfo.GetBundleUid());
406     return (result == NativeRdb::E_OK);
407 }
408 
PutImportance(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const int32_t & importance)409 bool NotificationPreferencesDatabase::PutImportance(
410     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &importance)
411 {
412     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_17, EventBranchId::BRANCH_3);
413     message.Message("im:" + std::to_string(importance));
414     if (bundleInfo.GetBundleName().empty()) {
415         ANS_LOGE("Bundle name is empty.");
416         message.Message("Bundle name is null");
417         NotificationAnalyticsUtil::ReportModifyEvent(message);
418         return false;
419     }
420     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, importance[%{public}d]",
421         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), importance);
422 
423     if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) {
424         return false;
425     }
426 
427     std::string bundleKey = GenerateBundleLablel(bundleInfo);
428     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_IMPORTANCE_TYPE, importance,
429         bundleInfo.GetBundleUid());
430     return (result == NativeRdb::E_OK);
431 }
432 
PutTotalBadgeNums(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const int32_t & totalBadgeNum)433 bool NotificationPreferencesDatabase::PutTotalBadgeNums(
434     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int32_t &totalBadgeNum)
435 {
436     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_17, EventBranchId::BRANCH_4);
437     if (bundleInfo.GetBundleName().empty()) {
438         ANS_LOGE("Bundle name is blank.");
439         NotificationAnalyticsUtil::ReportModifyEvent(message);
440         return false;
441     }
442     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, totalBadgeNum[%{public}d]",
443         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), totalBadgeNum);
444 
445     if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) {
446         return false;
447     }
448     std::string bundleKey = GenerateBundleLablel(bundleInfo);
449     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum,
450         bundleInfo.GetBundleUid());
451     return (result == NativeRdb::E_OK);
452 }
453 
PutNotificationsEnabledForBundle(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const NotificationConstant::SWITCH_STATE & state)454 bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle(
455     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const NotificationConstant::SWITCH_STATE &state)
456 {
457     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_17, EventBranchId::BRANCH_5);
458     if (bundleInfo.GetBundleName().empty()) {
459         ANS_LOGE("Bundle name is null.");
460         NotificationAnalyticsUtil::ReportModifyEvent(message);
461         return false;
462     }
463 
464     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, state[%{public}d]",
465         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), static_cast<int32_t>(state));
466     if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) {
467         return false;
468     }
469 
470     std::string bundleKey = GenerateBundleLablel(bundleInfo);
471     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE,
472         static_cast<int32_t>(state), bundleInfo.GetBundleUid());
473     return (result == NativeRdb::E_OK);
474 }
475 
PutNotificationsEnabled(const int32_t & userId,const bool & enabled)476 bool NotificationPreferencesDatabase::PutNotificationsEnabled(const int32_t &userId, const bool &enabled)
477 {
478     if (!CheckRdbStore()) {
479         ANS_LOGE("null RdbStore");
480         return false;
481     }
482 
483     std::string typeKey =
484         std::string().append(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId));
485     std::string enableValue = std::to_string(enabled);
486     int32_t result = rdbDataManager_->InsertData(typeKey, enableValue, userId);
487     if (result != NativeRdb::E_OK) {
488         ANS_LOGE("Store enable notification failed. %{public}d", result);
489         return false;
490     }
491     return true;
492 }
493 
PutSlotFlags(NotificationPreferencesInfo::BundleInfo & bundleInfo,const int32_t & slotFlags)494 bool NotificationPreferencesDatabase::PutSlotFlags(NotificationPreferencesInfo::BundleInfo &bundleInfo,
495     const int32_t &slotFlags)
496 {
497     if (!CheckRdbStore()) {
498         ANS_LOGE("null RdbStore");
499         return false;
500     }
501 
502     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, slotFlags[%{public}d]",
503         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), slotFlags);
504     std::string bundleKey = GenerateBundleLablel(bundleInfo);
505     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_SLOTFLGS_TYPE, slotFlags,
506         bundleInfo.GetBundleUid());
507     return (result == NativeRdb::E_OK);
508 }
509 
PutHasPoppedDialog(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const bool & hasPopped)510 bool NotificationPreferencesDatabase::PutHasPoppedDialog(
511     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &hasPopped)
512 {
513     if (bundleInfo.GetBundleName().empty()) {
514         ANS_LOGE("Bundle name is null.");
515         return false;
516     }
517     ANS_LOGI("bundelName:%{public}s, uid:%{public}d, hasPopped[%{public}d]",
518         bundleInfo.GetBundleName().c_str(), bundleInfo.GetBundleUid(), hasPopped);
519 
520     if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) {
521         return false;
522     }
523 
524     std::string bundleKey = GenerateBundleLablel(bundleInfo);
525     int32_t result = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_POPPED_DIALOG_TYPE, hasPopped,
526         bundleInfo.GetBundleUid());
527     return (result == NativeRdb::E_OK);
528 }
529 
PutDoNotDisturbDate(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)530 bool NotificationPreferencesDatabase::PutDoNotDisturbDate(
531     const int32_t &userId, const sptr<NotificationDoNotDisturbDate> &date)
532 {
533     if (date == nullptr) {
534         ANS_LOGE("null date");
535         return false;
536     }
537 
538     if (!CheckRdbStore()) {
539         ANS_LOGE("null RdbStore");
540         return false;
541     }
542 
543     std::string typeKey =
544         std::string().append(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId));
545     std::string typeValue = std::to_string((int)date->GetDoNotDisturbType());
546 
547     std::string beginDateKey =
548         std::string().append(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
549     std::string beginDateValue = std::to_string(date->GetBeginDate());
550 
551     std::string endDateKey =
552         std::string().append(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
553     std::string endDateValue = std::to_string(date->GetEndDate());
554 
555     std::unordered_map<std::string, std::string> values = {
556         {typeKey, typeValue},
557         {beginDateKey, beginDateValue},
558         {endDateKey, endDateValue},
559     };
560 
561     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
562     if (result != NativeRdb::E_OK) {
563         ANS_LOGE("Store DoNotDisturbDate failed. %{public}d", result);
564         return false;
565     }
566 
567     return true;
568 }
569 
AddDoNotDisturbProfiles(int32_t userId,const std::vector<sptr<NotificationDoNotDisturbProfile>> & profiles)570 bool NotificationPreferencesDatabase::AddDoNotDisturbProfiles(
571     int32_t userId, const std::vector<sptr<NotificationDoNotDisturbProfile>> &profiles)
572 {
573     if (profiles.empty()) {
574         ANS_LOGE("Invalid dates.");
575         return false;
576     }
577     if (!CheckRdbStore()) {
578         ANS_LOGE("null RdbStore");
579         return false;
580     }
581     std::unordered_map<std::string, std::string> values;
582     for (auto profile : profiles) {
583         if (profile == nullptr) {
584             ANS_LOGE("null profile");
585             return false;
586         }
587         std::string key = std::string().append(KEY_DO_NOT_DISTURB_ID).append(KEY_UNDER_LINE).append(
588             std::to_string(userId)).append(KEY_UNDER_LINE).append(std::to_string((int64_t)profile->GetProfileId()));
589         values[key] = profile->ToJson();
590     }
591     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
592     if (result != NativeRdb::E_OK) {
593         ANS_LOGE("Add do not disturb profiles failed.");
594         return false;
595     }
596     return true;
597 }
598 
RemoveDoNotDisturbProfiles(int32_t userId,const std::vector<sptr<NotificationDoNotDisturbProfile>> & profiles)599 bool NotificationPreferencesDatabase::RemoveDoNotDisturbProfiles(
600     int32_t userId, const std::vector<sptr<NotificationDoNotDisturbProfile>> &profiles)
601 {
602     if (profiles.empty()) {
603         ANS_LOGW("Invalid dates.");
604         return false;
605     }
606     if (!CheckRdbStore()) {
607         ANS_LOGE("null RdbStore");
608         return false;
609     }
610     std::vector<std::string> keys;
611     for (auto profile : profiles) {
612         if (profile == nullptr) {
613             ANS_LOGE("null profile");
614             return false;
615         }
616         std::string key = std::string().append(KEY_DO_NOT_DISTURB_ID).append(KEY_UNDER_LINE).append(
617             std::to_string(userId)).append(KEY_UNDER_LINE).append(std::to_string((int64_t)profile->GetProfileId()));
618         keys.push_back(key);
619     }
620     int32_t result = rdbDataManager_->DeleteBatchData(keys, userId);
621     if (result != NativeRdb::E_OK) {
622         ANS_LOGE("Delete do not disturb profiles failed.");
623         return false;
624     }
625     return true;
626 }
627 
GetDoNotDisturbProfiles(const std::string & key,sptr<NotificationDoNotDisturbProfile> & profile,const int32_t & userId)628 bool NotificationPreferencesDatabase::GetDoNotDisturbProfiles(
629     const std::string &key, sptr<NotificationDoNotDisturbProfile> &profile, const int32_t &userId)
630 {
631     if (!CheckRdbStore()) {
632         ANS_LOGE("null RdbStore");
633         return false;
634     }
635     std::string values;
636     int32_t result = rdbDataManager_->QueryData(key, values, userId);
637     if (result != NativeRdb::E_OK) {
638         ANS_LOGE("Use default value. error code is %{public}d", result);
639         return false;
640     }
641     profile = new (std::nothrow) NotificationDoNotDisturbProfile();
642     if (profile == nullptr) {
643         ANS_LOGE("null profile");
644         return false;
645     }
646     profile->FromJson(values);
647     return true;
648 }
649 
GetValueFromDisturbeDB(const std::string & key,const int32_t & userId,std::function<void (std::string &)> callback)650 void NotificationPreferencesDatabase::GetValueFromDisturbeDB(
651     const std::string &key, const int32_t &userId, std::function<void(std::string &)> callback)
652 {
653     if (!CheckRdbStore()) {
654         ANS_LOGE("null RdbStore");
655         return;
656     }
657     std::string value;
658     int32_t result = rdbDataManager_->QueryData(key, value, userId);
659     if (result == NativeRdb::E_ERROR) {
660         ANS_LOGE("Get value failed, use default value. error code is %{public}d", result);
661         return;
662     }
663     callback(value);
664 }
665 
GetValueFromDisturbeDB(const std::string & key,const int32_t & userId,std::function<void (int32_t &,std::string &)> callback)666 void NotificationPreferencesDatabase::GetValueFromDisturbeDB(
667     const std::string &key, const int32_t &userId, std::function<void(int32_t &, std::string &)> callback)
668 {
669     if (!CheckRdbStore()) {
670         ANS_LOGE("null RdbStore");
671         return;
672     }
673     std::string value;
674     int32_t result = rdbDataManager_->QueryData(key, value, userId);
675     callback(result, value);
676 }
677 
CheckBundle(const std::string & bundleName,const int32_t & bundleUid)678 bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, const int32_t &bundleUid)
679 {
680     std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleName + std::to_string(bundleUid);
681     ANS_LOGD("CheckBundle bundleKeyStr %{public}s", bundleKeyStr.c_str());
682     bool result = true;
683     int32_t userId = -1;
684     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
685     GetValueFromDisturbeDB(bundleKeyStr, userId, [&](const int32_t &status, std::string &value) {
686         switch (status) {
687             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
688                 NotificationPreferencesInfo::BundleInfo bundleInfo;
689                 bundleInfo.SetBundleName(bundleName);
690                 bundleInfo.SetBundleUid(bundleUid);
691                 NotificationConstant::SWITCH_STATE defaultState = CheckApiCompatibility(bundleName, bundleUid) ?
692                     NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_ON :
693                     NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF;
694                 bundleInfo.SetEnableNotification(defaultState);
695                 result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo);
696                 break;
697             }
698             case NativeRdb::E_OK: {
699                 result = true;
700                 break;
701             }
702             default:
703                 result = false;
704                 break;
705         }
706     });
707     return result;
708 }
709 
PutBundlePropertyValueToDisturbeDB(const NotificationPreferencesInfo::BundleInfo & bundleInfo)710 bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB(
711     const NotificationPreferencesInfo::BundleInfo &bundleInfo)
712 {
713     std::unordered_map<std::string, std::string> values;
714     std::string bundleKey = bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid()));
715     GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_NAME), bundleInfo.GetBundleName(), values);
716     GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_BADGE_TOTAL_NUM),
717         std::to_string(bundleInfo.GetBadgeTotalNum()),
718         values);
719     GenerateEntry(
720         GenerateBundleKey(bundleKey, KEY_BUNDLE_IMPORTANCE), std::to_string(bundleInfo.GetImportance()), values);
721     GenerateEntry(
722         GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE), std::to_string(bundleInfo.GetIsShowBadge()), values);
723     GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_ENABLE_NOTIFICATION),
724         std::to_string(static_cast<int32_t>(bundleInfo.GetEnableNotification())),
725         values);
726     GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_POPPED_DIALOG),
727         std::to_string(bundleInfo.GetHasPoppedDialog()),
728         values);
729     GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_UID), std::to_string(bundleInfo.GetBundleUid()), values);
730     if (!CheckRdbStore()) {
731         ANS_LOGE("null RdbStore");
732         return false;
733     }
734     int32_t userId = -1;
735     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
736     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
737     if (result != NativeRdb::E_OK) {
738         ANS_LOGE("Store bundle failed. %{public}d", result);
739         return false;
740     }
741     return true;
742 }
743 
ParseFromDisturbeDB(NotificationPreferencesInfo & info,int32_t userId)744 bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info, int32_t userId)
745 {
746     ANS_LOGD("called");
747     if (!CheckRdbStore()) {
748         ANS_LOGE("null RdbStore");
749         return false;
750     }
751     std::vector<int> activeUserId;
752     if (userId == -1) {
753         OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId);
754     } else {
755         activeUserId.push_back(userId);
756     }
757 
758     for (auto iter : activeUserId) {
759         GetDoNotDisturbType(info, iter);
760         GetDoNotDisturbBeginDate(info, iter);
761         GetDoNotDisturbEndDate(info, iter);
762         GetEnableAllNotification(info, iter);
763         GetDoNotDisturbProfile(info, iter);
764     }
765     GetDisableNotificationInfo(info);
766 
767     return true;
768 }
769 
770 
GetBundleInfo(const sptr<NotificationBundleOption> & bundleOption,NotificationPreferencesInfo::BundleInfo & bundleInfo)771 bool NotificationPreferencesDatabase::GetBundleInfo(const sptr<NotificationBundleOption> &bundleOption,
772     NotificationPreferencesInfo::BundleInfo &bundleInfo)
773 {
774     std::string bundleDBKey = KEY_BUNDLE_LABEL + bundleOption->GetBundleName() +
775         std::to_string(bundleOption->GetUid());
776     int32_t userId = -1;
777     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
778     std::string bundleKey;
779     int32_t result = rdbDataManager_->QueryData(bundleDBKey, bundleKey, userId);
780     if (result != NativeRdb::E_OK) {
781         ANS_LOGE("Get Bundle Info failed,key:%{public}s", bundleDBKey.c_str());
782         return false;
783     }
784     ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str());
785     std::string bundleKeyType = GenerateBundleKey(bundleKey);
786     std::unordered_map<std::string, std::string> bundleEntries;
787     rdbDataManager_->QueryDataBeginWithKey(bundleKeyType, bundleEntries, userId);
788     ANS_LOGD("Bundle key is %{public}s.", bundleKeyType.c_str());
789     std::string keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE);
790     bool badgeEnableExist = false;
791     for (auto bundleEntry : bundleEntries) {
792         if (IsSlotKey(bundleKeyType, bundleEntry.first)) {
793             ParseSlotFromDisturbeDB(bundleInfo, bundleKey, bundleEntry, userId);
794         } else {
795             ParseBundlePropertyFromDisturbeDB(bundleInfo, bundleKey, bundleEntry);
796         }
797 
798         if (keyStr.compare(bundleEntry.first) == 0) {
799             badgeEnableExist = true;
800         }
801     }
802 
803     if (!badgeEnableExist) {
804         bundleInfo.SetIsShowBadge(static_cast<bool>(true));
805     }
806     return true;
807 }
808 
RemoveAllDataFromDisturbeDB()809 bool NotificationPreferencesDatabase::RemoveAllDataFromDisturbeDB()
810 {
811     ANS_LOGD("called");
812     if (!CheckRdbStore()) {
813         ANS_LOGE("null RdbStore");
814         return false;
815     }
816     int32_t result = rdbDataManager_->Destroy();
817     return (result == NativeRdb::E_OK);
818 }
819 
RemoveBundleFromDisturbeDB(const std::string & bundleKey,const int32_t & bundleUid)820 bool NotificationPreferencesDatabase::RemoveBundleFromDisturbeDB(
821     const std::string &bundleKey, const int32_t &bundleUid)
822 {
823     ANS_LOGD("called");
824     if (!CheckRdbStore()) {
825         ANS_LOGE("null RdbStore");
826         return false;
827     }
828     int32_t userId = -1;
829     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
830 
831     std::unordered_map<std::string, std::string> values;
832     int32_t result = rdbDataManager_->QueryDataBeginWithKey(
833         (KEY_ANS_BUNDLE + KEY_UNDER_LINE + bundleKey + KEY_UNDER_LINE), values, userId);
834 
835     if (result == NativeRdb::E_ERROR) {
836         ANS_LOGE("Get Bundle Info failed.");
837         return false;
838     }
839 
840     std::vector<std::string> keys;
841     for (auto iter : values) {
842         keys.push_back(iter.first);
843     }
844 
845     std::string bundleDBKey = KEY_BUNDLE_LABEL + KEY_BUNDLE_NAME + KEY_UNDER_LINE + bundleKey;
846     keys.push_back(bundleDBKey);
847     result = rdbDataManager_->DeleteBatchData(keys, userId);
848     if (result != NativeRdb::E_OK) {
849         ANS_LOGE("delete bundle Info failed.");
850         return false;
851     }
852     return true;
853 }
854 
RemoveSlotFromDisturbeDB(const std::string & bundleKey,const NotificationConstant::SlotType & type,const int32_t & bundleUid)855 bool NotificationPreferencesDatabase::RemoveSlotFromDisturbeDB(
856     const std::string &bundleKey, const NotificationConstant::SlotType &type, const int32_t &bundleUid)
857 {
858     NOTIFICATION_HITRACE(HITRACE_TAG_NOTIFICATION);
859     ANS_LOGD("called");
860     int32_t userId = -1;
861     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
862     if (bundleKey.empty()) {
863         ANS_LOGE("Bundle name is empty.");
864         return false;
865     }
866 
867     if (!CheckRdbStore()) {
868         ANS_LOGE("null RdbStore");
869         return false;
870     }
871 
872     std::unordered_map<std::string, std::string> values;
873     std::string slotType = std::to_string(type);
874     int32_t result = rdbDataManager_->QueryDataBeginWithKey(
875         (GenerateSlotKey(bundleKey, slotType) + KEY_UNDER_LINE), values, userId);
876     if (result == NativeRdb::E_ERROR) {
877         return false;
878     }
879     std::vector<std::string> keys;
880     for (auto iter : values) {
881         keys.push_back(iter.first);
882     }
883 
884     result = rdbDataManager_->DeleteBatchData(keys, userId);
885     if (result != NativeRdb::E_OK) {
886         ANS_LOGE("delete bundle Info failed.");
887         return false;
888     }
889 
890     return true;
891 }
892 
GetAllNotificationEnabledBundles(std::vector<NotificationBundleOption> & bundleOption)893 bool NotificationPreferencesDatabase::GetAllNotificationEnabledBundles(
894     std::vector<NotificationBundleOption> &bundleOption)
895 {
896     ANS_LOGD("called");
897     if (!CheckRdbStore()) {
898         ANS_LOGE("null RdbStore");
899         return false;
900     }
901     std::unordered_map<std::string, std::string> datas;
902     const std::string ANS_BUNDLE_BEGIN = "ans_bundle_";
903     int32_t userId = -1;
904     OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
905     int32_t errCode = rdbDataManager_->QueryDataBeginWithKey(ANS_BUNDLE_BEGIN, datas, userId);
906     if (errCode != NativeRdb::E_OK) {
907         ANS_LOGE("Query data begin with ans_bundle_ from db error");
908         return false;
909     }
910     return HandleDataBaseMap(datas, bundleOption);
911 }
912 
GetAllDistribuedEnabledBundles(int32_t userId,const std::string & deviceType,std::vector<NotificationBundleOption> & bundleOption)913 bool NotificationPreferencesDatabase::GetAllDistribuedEnabledBundles(int32_t userId,
914     const std::string &deviceType, std::vector<NotificationBundleOption> &bundleOption)
915 {
916     ANS_LOGD("called");
917     if (!CheckRdbStore()) {
918         ANS_LOGE("null RdbStore");
919         return false;
920     }
921     std::string key = std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append(KEY_MIDDLE_LINE);
922     ANS_LOGD("key is %{public}s", key.c_str());
923     std::unordered_map<std::string, std::string> values;
924     int32_t result = rdbDataManager_->QueryDataBeginWithKey(key, values, userId);
925     if (result == NativeRdb::E_EMPTY_VALUES_BUCKET) {
926         return true;
927     } else if (result != NativeRdb::E_OK) {
928         ANS_LOGE("Get failed, key %{public}s,result %{public}d.", key.c_str(), result);
929         return NativeRdb::E_ERROR;
930     }
931 
932     for (auto& Item : values) {
933         if (!static_cast<bool>(StringToInt(Item.second))) {
934             continue;
935         }
936         std::vector<std::string> result;
937         StringSplit(Item.first, '-', result);
938         if (result.size() != DISTRIBUTED_KEY_NUM && result.back() != deviceType) {
939             continue;
940         }
941         int32_t uid = StringToInt(result[DISTRIBUTED_KEY_UID_INDEX]);
942         NotificationBundleOption bundleInfo(result[DISTRIBUTED_KEY_BUNDLE_INDEX], uid);
943         bundleOption.push_back(bundleInfo);
944         result.clear();
945     }
946     return true;
947 }
948 
StringSplit(const std::string content,char delim,std::vector<std::string> & result) const949 void NotificationPreferencesDatabase::StringSplit(const std::string content, char delim,
950     std::vector<std::string>& result) const
951 {
952     std::string token;
953     std::istringstream in(content);
954     while (std::getline(in, token, delim)) {
955         result.push_back(token);
956     }
957 }
958 
HandleDataBaseMap(const std::unordered_map<std::string,std::string> & datas,std::vector<NotificationBundleOption> & bundleOption)959 bool NotificationPreferencesDatabase::HandleDataBaseMap(
960     const std::unordered_map<std::string, std::string> &datas, std::vector<NotificationBundleOption> &bundleOption)
961 {
962     std::regex matchBundlenamePattern("^ans_bundle_(.*)_name$");
963     std::smatch match;
964     int32_t currentUserId = SUBSCRIBE_USER_INIT;
965     ErrCode result = ERR_OK;
966     result = OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId);
967     if (result != ERR_OK) {
968         ANS_LOGE("Get account id fail");
969         return false;
970     }
971     constexpr int MIDDLE_KEY = 1;
972     for (const auto &dataMapItem : datas) {
973         const std::string &key = dataMapItem.first;
974         const std::string &value = dataMapItem.second;
975         if (!std::regex_match(key, match, matchBundlenamePattern)) {
976             continue;
977         }
978         std::string matchKey = match[MIDDLE_KEY].str();
979         std::string matchUid = "ans_bundle_" + matchKey + "_uid";
980         std::string matchEnableNotification = "ans_bundle_" + matchKey + "_enabledNotification";
981         auto enableNotificationItem = datas.find(matchEnableNotification);
982         if (enableNotificationItem == datas.end()) {
983             continue;
984         }
985         NotificationConstant::SWITCH_STATE state = static_cast<NotificationConstant::SWITCH_STATE>(
986             StringToInt(enableNotificationItem->second));
987         bool enabled = (state == NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON ||
988             state == NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_ON);
989         if (enabled) {
990             auto uidItem = datas.find(matchUid);
991             if (uidItem == datas.end()) {
992                 continue;
993             }
994             int userid = -1;
995             result =
996                 OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(StringToInt(uidItem->second), userid);
997             if (result != ERR_OK) {
998                 return false;
999             }
1000             if (userid != currentUserId && !(currentUserId == DEFAULT_USER_ID && userid == ZERO_USER_ID)) {
1001                 continue;
1002             }
1003             NotificationBundleOption obj(value, StringToInt(uidItem->second));
1004             bundleOption.emplace_back(obj);
1005         }
1006     }
1007     return true;
1008 }
1009 
RemoveAllSlotsFromDisturbeDB(const std::string & bundleKey,const int32_t & bundleUid)1010 bool NotificationPreferencesDatabase::RemoveAllSlotsFromDisturbeDB(
1011     const std::string &bundleKey, const int32_t &bundleUid)
1012 {
1013     ANS_LOGD("called");
1014     int32_t userId = -1;
1015     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
1016     if (bundleKey.empty()) {
1017         ANS_LOGE("Bundle name is null.");
1018         return false;
1019     }
1020 
1021     if (!CheckRdbStore()) {
1022         ANS_LOGE("null RdbStore");
1023         return false;
1024     }
1025 
1026     std::unordered_map<std::string, std::string> values;
1027     int32_t result = rdbDataManager_->QueryDataBeginWithKey(
1028         (GenerateSlotKey(bundleKey) + KEY_UNDER_LINE), values, userId);
1029     if (result == NativeRdb::E_ERROR) {
1030         return false;
1031     }
1032     std::vector<std::string> keys;
1033     for (auto iter : values) {
1034         keys.push_back(iter.first);
1035     }
1036 
1037     result = rdbDataManager_->DeleteBatchData(keys, userId);
1038     return (result == NativeRdb::E_OK);
1039 }
1040 
1041 template <typename T>
PutBundlePropertyToDisturbeDB(const std::string & bundleKey,const BundleType & type,const T & t,const int32_t & bundleUid)1042 int32_t NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB(
1043     const std::string &bundleKey, const BundleType &type, const T &t, const int32_t &bundleUid)
1044 {
1045     std::string keyStr;
1046     switch (type) {
1047         case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE:
1048             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_BADGE_TOTAL_NUM);
1049             break;
1050         case BundleType::BUNDLE_IMPORTANCE_TYPE:
1051             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_IMPORTANCE);
1052             break;
1053         case BundleType::BUNDLE_SHOW_BADGE_TYPE:
1054             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE);
1055             break;
1056         case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE:
1057             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_ENABLE_NOTIFICATION);
1058             break;
1059         case BundleType::BUNDLE_POPPED_DIALOG_TYPE:
1060             ANS_LOGD("Into BUNDLE_POPPED_DIALOG_TYPE:GenerateBundleKey.");
1061             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_POPPED_DIALOG);
1062             break;
1063         case BundleType::BUNDLE_SLOTFLGS_TYPE:
1064             ANS_LOGD("Into BUNDLE_SLOTFLGS_TYPE:GenerateBundleKey.");
1065             keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE);
1066             break;
1067         default:
1068             break;
1069     }
1070     if (!CheckRdbStore()) {
1071         ANS_LOGE("null RdbStore");
1072         return false;
1073     }
1074     int32_t userId = -1;
1075     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
1076     std::string valueStr = std::to_string(t);
1077     int32_t result = rdbDataManager_->InsertData(keyStr, valueStr, userId);
1078     return result;
1079 }
1080 
PutBundleToDisturbeDB(const std::string & bundleKey,const NotificationPreferencesInfo::BundleInfo & bundleInfo)1081 bool NotificationPreferencesDatabase::PutBundleToDisturbeDB(
1082     const std::string &bundleKey, const NotificationPreferencesInfo::BundleInfo &bundleInfo)
1083 {
1084     if (!CheckRdbStore()) {
1085         ANS_LOGE("null RdbStore");
1086         return false;
1087     }
1088     int32_t userId = -1;
1089     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
1090 
1091     ANS_LOGD("Key not fund, so create a bundle, bundle key is %{public}s.", bundleKey.c_str());
1092     int32_t result = rdbDataManager_->InsertData(bundleKey, GenerateBundleLablel(bundleInfo), userId);
1093     if (result != NativeRdb::E_OK) {
1094         ANS_LOGE("Store bundle name to db is failed.");
1095         return false;
1096     }
1097 
1098     if (!PutBundlePropertyValueToDisturbeDB(bundleInfo)) {
1099         return false;
1100     }
1101     return true;
1102 }
1103 
GenerateEntry(const std::string & key,const std::string & value,std::unordered_map<std::string,std::string> & values) const1104 void NotificationPreferencesDatabase::GenerateEntry(
1105     const std::string &key, const std::string &value, std::unordered_map<std::string, std::string> &values) const
1106 {
1107     values.emplace(key, value);
1108 }
1109 
SlotToEntry(const std::string & bundleName,const int32_t & bundleUid,const sptr<NotificationSlot> & slot,std::unordered_map<std::string,std::string> & values)1110 bool NotificationPreferencesDatabase::SlotToEntry(const std::string &bundleName, const int32_t &bundleUid,
1111     const sptr<NotificationSlot> &slot, std::unordered_map<std::string, std::string> &values)
1112 {
1113     if (slot == nullptr) {
1114         ANS_LOGE("null slot");
1115         return false;
1116     }
1117 
1118     if (!CheckBundle(bundleName, bundleUid)) {
1119         return false;
1120     }
1121 
1122     std::string bundleKey = bundleName + std::to_string(bundleUid);
1123     GenerateSlotEntry(bundleKey, slot, values);
1124     return true;
1125 }
1126 
GenerateSlotEntry(const std::string & bundleKey,const sptr<NotificationSlot> & slot,std::unordered_map<std::string,std::string> & values) const1127 void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundleKey,
1128     const sptr<NotificationSlot> &slot, std::unordered_map<std::string, std::string> &values) const
1129 {
1130     std::string slotType = std::to_string(slot->GetType());
1131     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_TYPE), std::to_string(slot->GetType()), values);
1132     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ID), slot->GetId(), values);
1133     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_NAME), slot->GetName(), values);
1134     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_DESCRIPTION), slot->GetDescription(), values);
1135     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_LEVEL), std::to_string(slot->GetLevel()), values);
1136     GenerateEntry(
1137         GenerateSlotKey(bundleKey, slotType, KEY_SLOT_SHOW_BADGE), std::to_string(slot->IsShowBadge()), values);
1138     GenerateEntry(
1139         GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLE_LIGHT), std::to_string(slot->CanEnableLight()), values);
1140     GenerateEntry(
1141         GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLE_VRBRATION), std::to_string(slot->CanVibrate()), values);
1142     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_LED_LIGHT_COLOR),
1143         std::to_string(slot->GetLedLightColor()), values);
1144     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_LOCKSCREEN_VISIBLENESS),
1145         std::to_string(static_cast<int>(slot->GetLockScreenVisibleness())), values);
1146     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_SOUND), slot->GetSound().ToString(), values);
1147     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLE_BYPASS_DND),
1148         std::to_string(slot->IsEnableBypassDnd()), values);
1149     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE),
1150         VectorToString(slot->GetVibrationStyle()), values);
1151     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLED), std::to_string(slot->GetEnable()), values);
1152     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_AUTHORIZED_STATUS),
1153         std::to_string(slot->GetAuthorizedStatus()), values);
1154     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_AUTH_HINT_CNT),
1155         std::to_string(slot->GetAuthHintCnt()), values);
1156     GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_REMINDER_MODE),
1157         std::to_string(slot->GetReminderMode()), values);
1158 }
1159 
ParseBundleFromDistureDB(NotificationPreferencesInfo & info,const std::unordered_map<std::string,std::string> & values,const int32_t & userId)1160 void NotificationPreferencesDatabase::ParseBundleFromDistureDB(NotificationPreferencesInfo &info,
1161     const std::unordered_map<std::string, std::string> &values, const int32_t &userId)
1162 {
1163     if (!CheckRdbStore()) {
1164         ANS_LOGE("null RdbStore");
1165         return;
1166     }
1167     for (auto item : values) {
1168         std::string bundleKey = item.second;
1169         ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str());
1170         std::unordered_map<std::string, std::string> bundleEntries;
1171         rdbDataManager_->QueryDataBeginWithKey((GenerateBundleKey(bundleKey)), bundleEntries, userId);
1172         ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str());
1173         NotificationPreferencesInfo::BundleInfo bunldeInfo;
1174         NotificationPreferencesInfo::SilentReminderInfo silentReminderInfo;
1175         std::string keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE);
1176         bool badgeEnableExist = false;
1177         for (auto bundleEntry : bundleEntries) {
1178             if (IsSlotKey(GenerateBundleKey(bundleKey), bundleEntry.first)) {
1179                 ParseSlotFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry, userId);
1180             } else if (IsSilentReminderKey(GenerateBundleKey(bundleKey), bundleEntry.first)) {
1181                 ParseSilentReminderFromDisturbeDB(silentReminderInfo, bundleEntry);
1182             } else {
1183                 ParseBundlePropertyFromDisturbeDB(bunldeInfo, bundleKey, bundleEntry);
1184             }
1185 
1186             if (keyStr.compare(bundleEntry.first) == 0) {
1187                 badgeEnableExist = true;
1188             }
1189         }
1190 
1191         if (!badgeEnableExist) {
1192             bunldeInfo.SetIsShowBadge(static_cast<bool>(true));
1193         }
1194 
1195         info.SetBundleInfoFromDb(bunldeInfo, bundleKey);
1196         info.SetSilentReminderInfoFromDb(silentReminderInfo, bundleKey);
1197     }
1198 }
1199 
ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & bundleKey,const std::pair<std::string,std::string> & entry,const int32_t & userId)1200 void NotificationPreferencesDatabase::ParseSlotFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo,
1201     const std::string &bundleKey, const std::pair<std::string, std::string> &entry, const int32_t &userId)
1202 {
1203     std::string slotKey = entry.first;
1204     std::string typeStr = SubUniqueIdentifyFromString(GenerateSlotKey(bundleKey) + KEY_UNDER_LINE, slotKey);
1205     NotificationConstant::SlotType slotType = static_cast<NotificationConstant::SlotType>(StringToInt(typeStr));
1206     sptr<NotificationSlot> slot = nullptr;
1207     if (!bundleInfo.GetSlot(slotType, slot)) {
1208         slot = new (std::nothrow) NotificationSlot(slotType);
1209         if (slot == nullptr) {
1210             ANS_LOGE("null slot");
1211             return;
1212         }
1213     }
1214     std::string findString = GenerateSlotKey(bundleKey, typeStr) + KEY_UNDER_LINE;
1215     ParseSlot(findString, slot, entry, userId);
1216     bundleInfo.SetSlot(slot);
1217 }
1218 
ParseSilentReminderFromDisturbeDB(NotificationPreferencesInfo::SilentReminderInfo & silentReminderInfo,const std::pair<std::string,std::string> & entry)1219 void NotificationPreferencesDatabase::ParseSilentReminderFromDisturbeDB(
1220     NotificationPreferencesInfo::SilentReminderInfo &silentReminderInfo,
1221     const std::pair<std::string, std::string> &entry)
1222 {
1223     bool enable = static_cast<bool>(StringToInt(entry.second));
1224     silentReminderInfo.enableStatus =
1225         enable ? NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON
1226         : NotificationConstant::SWITCH_STATE::USER_MODIFIED_OFF;
1227 }
1228 
ParseBundlePropertyFromDisturbeDB(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & bundleKey,const std::pair<std::string,std::string> & entry)1229 void NotificationPreferencesDatabase::ParseBundlePropertyFromDisturbeDB(
1230     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleKey,
1231     const std::pair<std::string, std::string> &entry)
1232 {
1233     std::string typeStr = FindLastString(GenerateBundleKey(bundleKey), entry.first);
1234     std::string valueStr = entry.second;
1235 
1236     if (typeStr.compare(KEY_BUNDLE_NAME) == 0) {
1237         return ParseBundleName(bundleInfo, valueStr);
1238     }
1239     if (typeStr.compare(KEY_BUNDLE_IMPORTANCE) == 0) {
1240         return ParseBundleImportance(bundleInfo, valueStr);
1241     }
1242     if (typeStr.compare(KEY_BUNDLE_SHOW_BADGE) == 0) {
1243         return ParseBundleShowBadgeEnable(bundleInfo, valueStr);
1244     }
1245     if (typeStr.compare(KEY_BUNDLE_BADGE_TOTAL_NUM) == 0) {
1246         return ParseBundleBadgeNum(bundleInfo, valueStr);
1247     }
1248     if (typeStr.compare(KEY_BUNDLE_ENABLE_NOTIFICATION) == 0) {
1249         return ParseBundleEnableNotification(bundleInfo, valueStr);
1250     }
1251     if (typeStr.compare(KEY_BUNDLE_POPPED_DIALOG) == 0) {
1252         return ParseBundlePoppedDialog(bundleInfo, valueStr);
1253     }
1254     if (typeStr.compare(KEY_BUNDLE_UID) == 0) {
1255         return ParseBundleUid(bundleInfo, valueStr);
1256     }
1257     if (typeStr.compare(KEY_BUNDLE_SLOTFLGS_TYPE) == 0) {
1258         return ParseBundleSlotFlags(bundleInfo, valueStr);
1259     }
1260 }
1261 
ParseSlot(const std::string & findString,sptr<NotificationSlot> & slot,const std::pair<std::string,std::string> & entry,const int32_t & userId)1262 void NotificationPreferencesDatabase::ParseSlot(const std::string &findString, sptr<NotificationSlot> &slot,
1263     const std::pair<std::string, std::string> &entry, const int32_t &userId)
1264 {
1265     std::string typeStr = FindLastString(findString, entry.first);
1266     std::string valueStr = entry.second;
1267     ANS_LOGD("db key = %{public}s , %{public}s : %{public}s ",
1268         entry.first.c_str(),
1269         typeStr.c_str(),
1270         entry.second.c_str());
1271     SetSoltProperty(slot, typeStr, valueStr, findString, userId);
1272 }
1273 
SetSoltProperty(sptr<NotificationSlot> & slot,std::string & typeStr,std::string & valueStr,const std::string & findString,const int32_t & userId)1274 void NotificationPreferencesDatabase::SetSoltProperty(sptr<NotificationSlot> &slot, std::string &typeStr,
1275     std::string &valueStr, const std::string &findString, const int32_t &userId)
1276 {
1277     if (typeStr.compare(KEY_SLOT_DESCRIPTION) == 0) {
1278         return ParseSlotDescription(slot, valueStr);
1279     }
1280     if (typeStr.compare(KEY_SLOT_LEVEL) == 0) {
1281         return ParseSlotLevel(slot, valueStr);
1282     }
1283     if (typeStr.compare(KEY_SLOT_SHOW_BADGE) == 0) {
1284         return ParseSlotShowBadge(slot, valueStr);
1285     }
1286     if (typeStr.compare(KEY_SLOT_ENABLE_LIGHT) == 0) {
1287         return ParseSlotEnableLight(slot, valueStr);
1288     }
1289     if (typeStr.compare(KEY_SLOT_ENABLE_VRBRATION) == 0) {
1290         return ParseSlotEnableVrbration(slot, valueStr);
1291     }
1292     if (typeStr.compare(KEY_SLOT_LED_LIGHT_COLOR) == 0) {
1293         return ParseSlotLedLightColor(slot, valueStr);
1294     }
1295     if (typeStr.compare(KEY_SLOT_LOCKSCREEN_VISIBLENESS) == 0) {
1296         return ParseSlotLockscreenVisibleness(slot, valueStr);
1297     }
1298     if (typeStr.compare(KEY_SLOT_SOUND) == 0) {
1299         return ParseSlotSound(slot, valueStr);
1300     }
1301     if (typeStr.compare(KEY_SLOT_VIBRATION_STYLE) == 0) {
1302         return ParseSlotVibrationSytle(slot, valueStr);
1303     }
1304     if (typeStr.compare(KEY_SLOT_ENABLE_BYPASS_DND) == 0) {
1305         return ParseSlotEnableBypassDnd(slot, valueStr);
1306     }
1307     if (typeStr.compare(KEY_SLOT_ENABLED) == 0) {
1308         return ParseSlotEnabled(slot, valueStr);
1309     }
1310     if (typeStr.compare(KEY_SLOT_SLOTFLGS_TYPE) == 0) {
1311         return ParseSlotFlags(slot, valueStr);
1312     }
1313     if (typeStr.compare(KEY_SLOT_AUTHORIZED_STATUS) == 0) {
1314         return ParseSlotAuthorizedStatus(slot, valueStr);
1315     }
1316     if (typeStr.compare(KEY_SLOT_AUTH_HINT_CNT) == 0) {
1317         return ParseSlotAuthHitnCnt(slot, valueStr);
1318     }
1319     ExecuteDisturbeDB(slot, typeStr, valueStr, findString, userId);
1320 }
1321 
ExecuteDisturbeDB(sptr<NotificationSlot> & slot,std::string & typeStr,std::string & valueStr,const std::string & findString,const int32_t & userId)1322 void NotificationPreferencesDatabase::ExecuteDisturbeDB(sptr<NotificationSlot> &slot, std::string &typeStr,
1323     std::string &valueStr, const std::string &findString, const int32_t &userId)
1324 {
1325     if (typeStr.compare(KEY_REMINDER_MODE) == 0) {
1326         return ParseSlotReminderMode(slot, valueStr);
1327     }
1328     if (!typeStr.compare(KEY_SLOT_VIBRATION_STYLE)) {
1329         GetValueFromDisturbeDB(findString + KEY_SLOT_ENABLE_VRBRATION, userId,
1330             [&](std::string &value) { ParseSlotEnableVrbration(slot, value); });
1331     }
1332 }
1333 
FindLastString(const std::string & findString,const std::string & inputString) const1334 std::string NotificationPreferencesDatabase::FindLastString(
1335     const std::string &findString, const std::string &inputString) const
1336 {
1337     std::string keyStr;
1338     size_t pos = findString.size();
1339     if (pos != std::string::npos) {
1340         keyStr = inputString.substr(pos);
1341     }
1342     return keyStr;
1343 }
1344 
VectorToString(const std::vector<int64_t> & data) const1345 std::string NotificationPreferencesDatabase::VectorToString(const std::vector<int64_t> &data) const
1346 {
1347     std::stringstream streamStr;
1348     std::copy(data.begin(), data.end(), std::ostream_iterator<int>(streamStr, KEY_UNDER_LINE.c_str()));
1349     return streamStr.str();
1350 }
1351 
StringToVector(const std::string & str,std::vector<int64_t> & data) const1352 void NotificationPreferencesDatabase::StringToVector(const std::string &str, std::vector<int64_t> &data) const
1353 {
1354     if (str.empty()) {
1355         return;
1356     }
1357 
1358     if (str.find_first_of(KEY_UNDER_LINE) != std::string::npos) {
1359         std::string str1 = str.substr(0, str.find_first_of(KEY_UNDER_LINE));
1360         std::string afterStr = str.substr(str.find_first_of(KEY_UNDER_LINE) + 1);
1361         data.push_back(StringToInt(str1));
1362         StringToVector(afterStr, data);
1363     }
1364 }
1365 
StringToInt(const std::string & str) const1366 int32_t NotificationPreferencesDatabase::StringToInt(const std::string &str) const
1367 {
1368     int32_t value = 0;
1369     if (!str.empty()) {
1370         value = atoi(str.c_str());
1371     }
1372     return value;
1373 }
1374 
StringToInt64(const std::string & str) const1375 int64_t NotificationPreferencesDatabase::StringToInt64(const std::string &str) const
1376 {
1377     int64_t value = 0;
1378     if (!str.empty()) {
1379         value = atoll(str.c_str());
1380     }
1381     return value;
1382 }
1383 
IsSlotKey(const std::string & bundleKey,const std::string & key) const1384 bool NotificationPreferencesDatabase::IsSlotKey(const std::string &bundleKey, const std::string &key) const
1385 {
1386     std::string tempStr = FindLastString(bundleKey, key);
1387     size_t pos = tempStr.find_first_of(KEY_UNDER_LINE);
1388     std::string slotStr;
1389     if (pos != std::string::npos) {
1390         slotStr = tempStr.substr(0, pos);
1391     }
1392     if (!slotStr.compare(KEY_SLOT)) {
1393         return true;
1394     }
1395     return false;
1396 }
1397 
IsSilentReminderKey(const std::string & bundleKey,const std::string & key) const1398 bool NotificationPreferencesDatabase::IsSilentReminderKey(const std::string &bundleKey, const std::string &key) const
1399 {
1400     std::string tempStr = FindLastString(bundleKey, key);
1401     size_t pos = tempStr.find_first_of(KEY_UNDER_LINE);
1402     if (!tempStr.compare(KEY_SILENT_REMINDER_ENABLE_NOTIFICATION)) {
1403         return true;
1404     }
1405     return false;
1406 }
1407 
GenerateSlotKey(const std::string & bundleKey,const std::string & type,const std::string & subType) const1408 std::string NotificationPreferencesDatabase::GenerateSlotKey(
1409     const std::string &bundleKey, const std::string &type, const std::string &subType) const
1410 {
1411     /* slot key
1412      *
1413      * KEY_ANS_BUNDLE_bundlename_slot_type_0_id
1414      * KEY_ANS_BUNDLE_bundlename_slot_type_0_des
1415      * KEY_ANS_BUNDLE_bundlename_slot_type_1_id
1416      * KEY_ANS_BUNDLE_bundlename_slot_type_1_des
1417      *
1418      */
1419     std::string key = GenerateBundleKey(bundleKey).append(KEY_SLOT).append(KEY_UNDER_LINE).append(KEY_SLOT_TYPE);
1420     if (!type.empty()) {
1421         key.append(KEY_UNDER_LINE).append(type);
1422     }
1423     if (!subType.empty()) {
1424         key.append(KEY_UNDER_LINE).append(subType);
1425     }
1426     ANS_LOGD("Slot key is : %{public}s.", key.c_str());
1427     return key;
1428 }
1429 
GenerateSilentReminderKey(const NotificationPreferencesInfo::SilentReminderInfo & silentReminderInfo) const1430 std::string NotificationPreferencesDatabase::GenerateSilentReminderKey(
1431     const NotificationPreferencesInfo::SilentReminderInfo &silentReminderInfo) const
1432 {
1433     std::string bundleKey = std::string().append(silentReminderInfo.bundleName)
1434         .append(std::to_string(silentReminderInfo.uid));
1435     return GenerateBundleKey(bundleKey, KEY_SILENT_REMINDER_ENABLE_NOTIFICATION);
1436 }
1437 
GenerateBundleKey(const std::string & bundleKey,const std::string & type) const1438 std::string NotificationPreferencesDatabase::GenerateBundleKey(
1439     const std::string &bundleKey, const std::string &type) const
1440 {
1441     /* bundle key
1442      *
1443      * label_KEY_ANS_KEY_BUNDLE_NAME = ""
1444      * KEY_ANS_BUNDLE_bundlename_
1445      * KEY_ANS_BUNDLE_bundlename_
1446      * KEY_ANS_BUNDLE_bundlename_
1447      * KEY_ANS_BUNDLE_bundlename_
1448      *
1449      */
1450     ANS_LOGD("%{public}s, bundleKey[%{public}s] type[%{public}s]", __FUNCTION__, bundleKey.c_str(), type.c_str());
1451     std::string key =
1452         std::string().append(KEY_ANS_BUNDLE).append(KEY_UNDER_LINE).append(bundleKey).append(KEY_UNDER_LINE);
1453     if (!type.empty()) {
1454         key.append(type);
1455     }
1456     ANS_LOGD("Bundle key : %{public}s.", key.c_str());
1457     return key;
1458 }
1459 
SubUniqueIdentifyFromString(const std::string & findString,const std::string & keyStr) const1460 std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString(
1461     const std::string &findString, const std::string &keyStr) const
1462 {
1463     std::string slotType;
1464     std::string tempStr = FindLastString(findString, keyStr);
1465     size_t pos = tempStr.find_last_of(KEY_UNDER_LINE);
1466     if (pos != std::string::npos) {
1467         slotType = tempStr.substr(0, pos);
1468     }
1469 
1470     return slotType;
1471 }
1472 
ParseBundleName(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1473 void NotificationPreferencesDatabase::ParseBundleName(
1474     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1475 {
1476     ANS_LOGD("SetBundleName bundle name is %{public}s.", value.c_str());
1477     bundleInfo.SetBundleName(value);
1478 }
1479 
ParseBundleImportance(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1480 void NotificationPreferencesDatabase::ParseBundleImportance(
1481     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1482 {
1483     ANS_LOGD("SetBundleImportance bundle importance is %{public}s.", value.c_str());
1484     bundleInfo.SetImportance(static_cast<NotificationSlot::NotificationLevel>(StringToInt(value)));
1485 }
1486 
ParseBundleShowBadgeEnable(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1487 void NotificationPreferencesDatabase::ParseBundleShowBadgeEnable(
1488     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1489 {
1490     ANS_LOGD("SetBundleShowBadge bundle show badge is %{public}s.", value.c_str());
1491     bundleInfo.SetIsShowBadge(static_cast<bool>(StringToInt(value)));
1492 }
1493 
ParseBundleBadgeNum(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1494 void NotificationPreferencesDatabase::ParseBundleBadgeNum(
1495     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1496 {
1497     ANS_LOGD("SetBundleBadgeNum bundle badge num is %{public}s.", value.c_str());
1498     bundleInfo.SetBadgeTotalNum(StringToInt(value));
1499 }
1500 
ParseBundleEnableNotification(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1501 void NotificationPreferencesDatabase::ParseBundleEnableNotification(
1502     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1503 {
1504     ANS_LOGD("SetBundleEnableNotification bundle enable is %{public}s.", value.c_str());
1505     bundleInfo.SetEnableNotification(static_cast<NotificationConstant::SWITCH_STATE>(StringToInt(value)));
1506 }
1507 
ParseBundlePoppedDialog(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1508 void NotificationPreferencesDatabase::ParseBundlePoppedDialog(
1509     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1510 {
1511     ANS_LOGD("SetBundlePoppedDialog bundle has popped dialog is %{public}s.", value.c_str());
1512     bundleInfo.SetHasPoppedDialog(static_cast<bool>(StringToInt(value)));
1513 }
1514 
ParseBundleUid(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1515 void NotificationPreferencesDatabase::ParseBundleUid(
1516     NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const
1517 {
1518     ANS_LOGD("SetBundleUid uuid is %{public}s.", value.c_str());
1519     bundleInfo.SetBundleUid(StringToInt(value));
1520 }
1521 
ParseSlotDescription(sptr<NotificationSlot> & slot,const std::string & value) const1522 void NotificationPreferencesDatabase::ParseSlotDescription(sptr<NotificationSlot> &slot, const std::string &value) const
1523 {
1524     ANS_LOGD("ParseSlotDescription slot des is %{public}s.", value.c_str());
1525     std::string slotDescription = value;
1526     slot->SetDescription(slotDescription);
1527 }
1528 
ParseSlotLevel(sptr<NotificationSlot> & slot,const std::string & value) const1529 void NotificationPreferencesDatabase::ParseSlotLevel(sptr<NotificationSlot> &slot, const std::string &value) const
1530 {
1531     ANS_LOGD("ParseSlotLevel slot level is %{public}s.", value.c_str());
1532     NotificationSlot::NotificationLevel level = static_cast<NotificationSlot::NotificationLevel>(StringToInt(value));
1533     slot->SetLevel(level);
1534 }
1535 
ParseSlotShowBadge(sptr<NotificationSlot> & slot,const std::string & value) const1536 void NotificationPreferencesDatabase::ParseSlotShowBadge(sptr<NotificationSlot> &slot, const std::string &value) const
1537 {
1538     ANS_LOGD("ParseSlotShowBadge slot show badge is %{public}s.", value.c_str());
1539     bool showBadge = static_cast<bool>(StringToInt(value));
1540     slot->EnableBadge(showBadge);
1541 }
1542 
ParseSlotFlags(sptr<NotificationSlot> & slot,const std::string & value) const1543 void NotificationPreferencesDatabase::ParseSlotFlags(sptr<NotificationSlot> &slot, const std::string &value) const
1544 {
1545     ANS_LOGD("ParseSlotFlags slot show flags is %{public}s.", value.c_str());
1546     uint32_t slotFlags = static_cast<uint32_t>(StringToInt(value));
1547     slot->SetSlotFlags(slotFlags);
1548 }
1549 
ParseBundleSlotFlags(NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & value) const1550 void NotificationPreferencesDatabase::ParseBundleSlotFlags(NotificationPreferencesInfo::BundleInfo &bundleInfo,
1551     const std::string &value) const
1552 {
1553     ANS_LOGD("ParseBundleSlotFlags slot show flags is %{public}s.", value.c_str());
1554     bundleInfo.SetSlotFlags(StringToInt(value));
1555 }
1556 
ParseSlotEnableLight(sptr<NotificationSlot> & slot,const std::string & value) const1557 void NotificationPreferencesDatabase::ParseSlotEnableLight(sptr<NotificationSlot> &slot, const std::string &value) const
1558 {
1559     ANS_LOGD("ParseSlotEnableLight slot enable light is %{public}s.", value.c_str());
1560     bool enableLight = static_cast<bool>(StringToInt(value));
1561     slot->SetEnableLight(enableLight);
1562 }
1563 
ParseSlotEnableVrbration(sptr<NotificationSlot> & slot,const std::string & value) const1564 void NotificationPreferencesDatabase::ParseSlotEnableVrbration(
1565     sptr<NotificationSlot> &slot, const std::string &value) const
1566 {
1567     ANS_LOGD("ParseSlotEnableVrbration slot enable vir is %{public}s.", value.c_str());
1568     bool enableVrbration = static_cast<bool>(StringToInt(value));
1569     slot->SetEnableVibration(enableVrbration);
1570 }
1571 
ParseSlotLedLightColor(sptr<NotificationSlot> & slot,const std::string & value) const1572 void NotificationPreferencesDatabase::ParseSlotLedLightColor(
1573     sptr<NotificationSlot> &slot, const std::string &value) const
1574 {
1575     ANS_LOGD("ParseSlotLedLightColor slot led is %{public}s.", value.c_str());
1576     int32_t ledLightColor = static_cast<int32_t>(StringToInt(value));
1577     slot->SetLedLightColor(ledLightColor);
1578 }
1579 
ParseSlotLockscreenVisibleness(sptr<NotificationSlot> & slot,const std::string & value) const1580 void NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness(
1581     sptr<NotificationSlot> &slot, const std::string &value) const
1582 {
1583 
1584     ANS_LOGD("ParseSlotLockscreenVisibleness slot visible is %{public}s.", value.c_str());
1585     NotificationConstant::VisiblenessType visible =
1586         static_cast<NotificationConstant::VisiblenessType>(StringToInt(value));
1587     slot->SetLockscreenVisibleness(visible);
1588 }
1589 
ParseSlotSound(sptr<NotificationSlot> & slot,const std::string & value) const1590 void NotificationPreferencesDatabase::ParseSlotSound(sptr<NotificationSlot> &slot, const std::string &value) const
1591 {
1592     ANS_LOGD("ParseSlotSound slot sound is %{public}s.", value.c_str());
1593     std::string slotUri = value;
1594     Uri uri(slotUri);
1595     slot->SetSound(uri);
1596 }
1597 
ParseSlotVibrationSytle(sptr<NotificationSlot> & slot,const std::string & value) const1598 void NotificationPreferencesDatabase::ParseSlotVibrationSytle(
1599     sptr<NotificationSlot> &slot, const std::string &value) const
1600 {
1601     ANS_LOGD("ParseSlotVibrationSytle slot vibration style is %{public}s.", value.c_str());
1602     std::vector<int64_t> vibrationStyle;
1603     StringToVector(value, vibrationStyle);
1604     slot->SetVibrationStyle(vibrationStyle);
1605 }
1606 
ParseSlotEnableBypassDnd(sptr<NotificationSlot> & slot,const std::string & value) const1607 void NotificationPreferencesDatabase::ParseSlotEnableBypassDnd(
1608     sptr<NotificationSlot> &slot, const std::string &value) const
1609 {
1610     ANS_LOGD("ParseSlotEnableBypassDnd slot by pass dnd is %{public}s.", value.c_str());
1611     bool enable = static_cast<bool>(StringToInt(value));
1612     slot->EnableBypassDnd(enable);
1613 }
1614 
ParseSlotEnabled(sptr<NotificationSlot> & slot,const std::string & value) const1615 void NotificationPreferencesDatabase::ParseSlotEnabled(
1616     sptr<NotificationSlot> &slot, const std::string &value) const
1617 {
1618     ANS_LOGD("ParseSlotEnabled slot enabled is %{public}s.", value.c_str());
1619     bool enabled = static_cast<bool>(StringToInt(value));
1620     slot->SetEnable(enabled);
1621 }
1622 
ParseSlotAuthorizedStatus(sptr<NotificationSlot> & slot,const std::string & value) const1623 void NotificationPreferencesDatabase::ParseSlotAuthorizedStatus(
1624     sptr<NotificationSlot> &slot, const std::string &value) const
1625 {
1626     ANS_LOGD("ParseSlotAuthorizedStatus slot status is %{public}s.", value.c_str());
1627     int32_t status = static_cast<int32_t>(StringToInt(value));
1628     slot->SetAuthorizedStatus(status);
1629 }
1630 
ParseSlotAuthHitnCnt(sptr<NotificationSlot> & slot,const std::string & value) const1631 void NotificationPreferencesDatabase::ParseSlotAuthHitnCnt(
1632     sptr<NotificationSlot> &slot, const std::string &value) const
1633 {
1634     ANS_LOGD("ParseSlotAuthHitnCnt slot count is %{public}s.", value.c_str());
1635     int32_t count = static_cast<int32_t>(StringToInt(value));
1636     slot->SetAuthHintCnt(count);
1637 }
1638 
ParseSlotReminderMode(sptr<NotificationSlot> & slot,const std::string & value) const1639 void NotificationPreferencesDatabase::ParseSlotReminderMode(
1640     sptr<NotificationSlot> &slot, const std::string &value) const
1641 {
1642     ANS_LOGD("ParseSlotReminderMode slot reminder mode is %{public}s.", value.c_str());
1643     int32_t reminderMode = static_cast<int32_t>(StringToInt(value));
1644     slot->SetReminderMode(reminderMode);
1645 }
1646 
GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo & bundleInfo) const1647 std::string NotificationPreferencesDatabase::GenerateBundleLablel(
1648     const NotificationPreferencesInfo::BundleInfo &bundleInfo) const
1649 {
1650     return bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid()));
1651 }
1652 
GetDoNotDisturbType(NotificationPreferencesInfo & info,int32_t userId)1653 void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreferencesInfo &info, int32_t userId)
1654 {
1655     std::string key =
1656         std::string().append(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1657     GetValueFromDisturbeDB(
1658         key, userId, [&](const int32_t &status, std::string &value) {
1659             sptr<NotificationDoNotDisturbDate> disturbDate = new (std::nothrow)
1660                 NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0);
1661             if (disturbDate == nullptr) {
1662                 ANS_LOGE("null disturbDate");
1663                 return;
1664             }
1665             info.GetDoNotDisturbDate(userId, disturbDate);
1666             if (status == NativeRdb::E_EMPTY_VALUES_BUCKET) {
1667                 PutDoNotDisturbDate(userId, disturbDate);
1668             } else if (status == NativeRdb::E_OK) {
1669                 if (!value.empty()) {
1670                     if (disturbDate != nullptr) {
1671                         disturbDate->SetDoNotDisturbType(
1672                             (NotificationConstant::DoNotDisturbType)StringToInt(value));
1673                     }
1674                 }
1675             } else {
1676                 ANS_LOGW("Parse disturbe mode failed, use default value.");
1677             }
1678             info.SetDoNotDisturbDate(userId, disturbDate);
1679         });
1680 }
1681 
GetDoNotDisturbBeginDate(NotificationPreferencesInfo & info,int32_t userId)1682 void NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int32_t userId)
1683 {
1684     std::string key =
1685         std::string().append(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1686     GetValueFromDisturbeDB(
1687         key, userId, [&](const int32_t &status, std::string &value) {
1688             sptr<NotificationDoNotDisturbDate> disturbDate = new (std::nothrow)
1689                 NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0);
1690             if (disturbDate == nullptr) {
1691                 ANS_LOGE("null disturbDate");
1692                 return;
1693             }
1694             info.GetDoNotDisturbDate(userId, disturbDate);
1695             if (status == NativeRdb::E_EMPTY_VALUES_BUCKET) {
1696                 PutDoNotDisturbDate(userId, disturbDate);
1697             } else if (status == NativeRdb::E_OK) {
1698                 if (!value.empty()) {
1699                     if (disturbDate != nullptr) {
1700                         disturbDate->SetBeginDate(StringToInt64(value));
1701                     }
1702                 }
1703             } else {
1704                 ANS_LOGW("Parse disturbe start time failed, use default value.");
1705             }
1706             info.SetDoNotDisturbDate(userId, disturbDate);
1707         });
1708 }
1709 
GetDoNotDisturbEndDate(NotificationPreferencesInfo & info,int32_t userId)1710 void NotificationPreferencesDatabase::GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int32_t userId)
1711 {
1712     std::string key =
1713         std::string().append(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1714     GetValueFromDisturbeDB(
1715         key, userId, [&](const int32_t &status, std::string &value) {
1716             sptr<NotificationDoNotDisturbDate> disturbDate = new (std::nothrow)
1717                 NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0);
1718             if (disturbDate == nullptr) {
1719                 ANS_LOGE("null disturbDate");
1720                 return;
1721             }
1722             info.GetDoNotDisturbDate(userId, disturbDate);
1723             if (status == NativeRdb::E_EMPTY_VALUES_BUCKET) {
1724                 PutDoNotDisturbDate(userId, disturbDate);
1725             } else if (status == NativeRdb::E_OK) {
1726                 if (!value.empty()) {
1727                     if (disturbDate != nullptr) {
1728                         disturbDate->SetEndDate(StringToInt64(value));
1729                     }
1730                 }
1731             } else {
1732                 ANS_LOGW("Parse disturbe end time failed, use default value.");
1733             }
1734             info.SetDoNotDisturbDate(userId, disturbDate);
1735         });
1736 }
1737 
GetEnableAllNotification(NotificationPreferencesInfo & info,int32_t userId)1738 void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPreferencesInfo &info, int32_t userId)
1739 {
1740     std::string key =
1741         std::string().append(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId));
1742     GetValueFromDisturbeDB(
1743         key, userId, [&](const int32_t &status, std::string &value) {
1744             if (status == NativeRdb::E_EMPTY_VALUES_BUCKET) {
1745                 bool enable = true;
1746                 if (!info.GetEnabledAllNotification(userId, enable)) {
1747                     info.SetEnabledAllNotification(userId, enable);
1748                     ANS_LOGW("Enable setting not found, default true.");
1749                 }
1750                 PutNotificationsEnabled(userId, enable);
1751             } else if (status == NativeRdb::E_OK) {
1752                 if (!value.empty()) {
1753                     info.SetEnabledAllNotification(userId, static_cast<bool>(StringToInt(value)));
1754                 }
1755             } else {
1756                 ANS_LOGW("Parse enable all notification failed, use default value.");
1757             }
1758         });
1759 }
1760 
GetDoNotDisturbProfile(NotificationPreferencesInfo & info,int32_t userId)1761 void NotificationPreferencesDatabase::GetDoNotDisturbProfile(NotificationPreferencesInfo &info, int32_t userId)
1762 {
1763     if (!CheckRdbStore()) {
1764         ANS_LOGE("null RdbStore");
1765         return;
1766     }
1767     std::unordered_map<std::string, std::string> datas;
1768     int32_t result = rdbDataManager_->QueryAllData(datas, userId);
1769     if (result != NativeRdb::E_OK) {
1770         ANS_LOGE("Query all data failed.");
1771         return;
1772     }
1773     std::vector<sptr<NotificationDoNotDisturbProfile>> profiles;
1774     for (const auto &data : datas) {
1775         std::string key = data.first;
1776         auto result = key.find(KEY_DO_NOT_DISTURB_ID);
1777         if (result != std::string::npos) {
1778             sptr<NotificationDoNotDisturbProfile> profile;
1779             GetDoNotDisturbProfiles(data.first, profile, userId);
1780             profiles.emplace_back(profile);
1781         }
1782     }
1783     info.AddDoNotDisturbProfiles(userId, profiles);
1784 }
1785 
RemoveNotificationEnable(const int32_t userId)1786 bool NotificationPreferencesDatabase::RemoveNotificationEnable(const int32_t userId)
1787 {
1788     ANS_LOGD("called");
1789     if (!CheckRdbStore()) {
1790         ANS_LOGE("null RdbStore");
1791         return false;
1792     }
1793 
1794     std::string key =
1795         std::string(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId));
1796     int32_t result = rdbDataManager_->DeleteData(key, userId);
1797     if (result != NativeRdb::E_OK) {
1798         ANS_LOGE("delete bundle Info failed.");
1799         return false;
1800     }
1801 
1802     ANS_LOGD("%{public}s remove notification enable, userId : %{public}d", __FUNCTION__, userId);
1803     return true;
1804 }
1805 
RemoveDoNotDisturbDate(const int32_t userId)1806 bool NotificationPreferencesDatabase::RemoveDoNotDisturbDate(const int32_t userId)
1807 {
1808     ANS_LOGD("called");
1809     if (!CheckRdbStore()) {
1810         ANS_LOGE("null RdbStore");
1811         return false;
1812     }
1813 
1814     std::string typeKey =
1815         std::string(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1816     std::string beginDateKey =
1817         std::string(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1818     std::string endDateKey =
1819         std::string(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId));
1820 
1821     std::vector<std::string> keys = {
1822         typeKey,
1823         beginDateKey,
1824         endDateKey
1825     };
1826 
1827     int32_t result = rdbDataManager_->DeleteBatchData(keys, userId);
1828     if (result != NativeRdb::E_OK) {
1829         ANS_LOGE("delete DoNotDisturb date failed.");
1830         return false;
1831     }
1832 
1833     ANS_LOGD("%{public}s remove DoNotDisturb date, userId : %{public}d", __FUNCTION__, userId);
1834     return true;
1835 }
1836 
RemoveAnsBundleDbInfo(std::string bundleName,int32_t uid)1837 bool NotificationPreferencesDatabase::RemoveAnsBundleDbInfo(std::string bundleName, int32_t uid)
1838 {
1839     if (!CheckRdbStore()) {
1840         ANS_LOGE("null RdbStore");
1841         return false;
1842     }
1843 
1844     std::string key = KEY_BUNDLE_LABEL + bundleName + std::to_string(uid);
1845     int32_t userId = -1;
1846     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId);
1847     int32_t result = rdbDataManager_->DeleteData(key, userId);
1848     if (result != NativeRdb::E_OK) {
1849         ANS_LOGE("Delete ans bundle db info failed, bundle[%{public}s:%{public}d]", bundleName.c_str(), uid);
1850         return false;
1851     }
1852 
1853     ANS_LOGE("Remove ans bundle db info, bundle[%{public}s:%{public}d]", bundleName.c_str(), uid);
1854     return true;
1855 }
1856 
RemoveSilentEnabledDbByBundle(std::string bundleName,int32_t uid)1857 bool NotificationPreferencesDatabase::RemoveSilentEnabledDbByBundle(std::string bundleName, int32_t uid)
1858 {
1859     if (!CheckRdbStore()) {
1860         ANS_LOGE("RdbStore is nullptr.");
1861         return false;
1862     }
1863 
1864     std::string key = GenerateSilentReminderKey(
1865         {bundleName, uid, NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF});
1866     int32_t userId = -1;
1867     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId);
1868     int32_t result = rdbDataManager_->DeleteData(key, userId);
1869     if (result != NativeRdb::E_OK) {
1870         ANS_LOGE("Delete Silent db info failed, bundle[%{public}s:%{public}d]", bundleName.c_str(), uid);
1871         return false;
1872     }
1873 
1874     ANS_LOGI("Remove Silent db info, bundle[%{public}s:%{public}d]", bundleName.c_str(), uid);
1875     return true;
1876 }
1877 
RemoveEnabledDbByBundleName(std::string bundleName,const int32_t & bundleUid)1878 bool NotificationPreferencesDatabase::RemoveEnabledDbByBundleName(std::string bundleName, const int32_t &bundleUid)
1879 {
1880     if (!CheckRdbStore()) {
1881         ANS_LOGE("null RdbStore");
1882         return false;
1883     }
1884     int32_t userId = -1;
1885     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId);
1886     std::string key = std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append(
1887         KEY_MIDDLE_LINE).append(std::string(bundleName).append(KEY_MIDDLE_LINE));
1888     ANS_LOGD("key is %{public}s", key.c_str());
1889     int32_t result = NativeRdb::E_OK;
1890     std::unordered_map<std::string, std::string> values;
1891     result = rdbDataManager_->QueryDataBeginWithKey(key, values, userId);
1892     if (result == NativeRdb::E_EMPTY_VALUES_BUCKET) {
1893         return true;
1894     } else if (result != NativeRdb::E_OK) {
1895         ANS_LOGE("Get failed, key %{public}s,result %{public}d.", key.c_str(), result);
1896         return NativeRdb::E_ERROR;
1897     }
1898 
1899     std::vector<std::string> keys;
1900     for (auto iter : values) {
1901         ANS_LOGD("Get failed, key %{public}s", iter.first.c_str());
1902         keys.push_back(iter.first);
1903     }
1904 
1905     result = rdbDataManager_->DeleteBatchData(keys, userId);
1906     if (result != NativeRdb::E_OK) {
1907         ANS_LOGE("delete bundle Info failed.");
1908         return false;
1909     }
1910 
1911     return true;
1912 }
1913 
SetKvToDb(const std::string & key,const std::string & value,const int32_t & userId)1914 int32_t NotificationPreferencesDatabase::SetKvToDb(
1915     const std::string &key, const std::string &value, const int32_t &userId)
1916 {
1917     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2);
1918     if (!CheckRdbStore()) {
1919         ANS_LOGE("null RdbStore");
1920         message.Message("RdbStore is nullptr.");
1921         NotificationAnalyticsUtil::ReportModifyEvent(message);
1922         return NativeRdb::E_ERROR;
1923     }
1924     int32_t result = rdbDataManager_->InsertData(key, value, userId);
1925     if (result != NativeRdb::E_OK) {
1926         message.Message("Set key failed: " + key);
1927         NotificationAnalyticsUtil::ReportModifyEvent(message);
1928         ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result);
1929         return NativeRdb::E_ERROR;
1930     }
1931 
1932     ANS_LOGD("Key:%{public}s, value:%{public}s.", key.c_str(), value.c_str());
1933 
1934     return NativeRdb::E_OK;
1935 }
1936 
SetByteToDb(const std::string & key,const std::vector<uint8_t> & value,const int32_t & userId)1937 int32_t NotificationPreferencesDatabase::SetByteToDb(
1938     const std::string &key, const std::vector<uint8_t> &value, const int32_t &userId)
1939 {
1940     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2);
1941     if (!CheckRdbStore()) {
1942         message.Message("RdbStore is nullptr.");
1943         NotificationAnalyticsUtil::ReportModifyEvent(message);
1944         ANS_LOGE("null RdbStore");
1945         return NativeRdb::E_ERROR;
1946     }
1947     int32_t result = rdbDataManager_->InsertData(key, value, userId);
1948     if (result != NativeRdb::E_OK) {
1949         message.Message("Set key failed: " + key);
1950         NotificationAnalyticsUtil::ReportModifyEvent(message);
1951         ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result);
1952         return NativeRdb::E_ERROR;
1953     }
1954 
1955     return NativeRdb::E_OK;
1956 }
1957 
GetKvFromDb(const std::string & key,std::string & value,const int32_t & userId)1958 int32_t NotificationPreferencesDatabase::GetKvFromDb(
1959     const std::string &key, std::string &value, const int32_t &userId)
1960 {
1961     if (!CheckRdbStore()) {
1962         ANS_LOGE("null RdbStore");
1963         return NativeRdb::E_ERROR;
1964     }
1965 
1966     int32_t result = rdbDataManager_->QueryData(key, value, userId);
1967     if (result != NativeRdb::E_OK) {
1968         ANS_LOGE("Get key-value failed, key %{public}s, result %{public}d.", key.c_str(), result);
1969         return NativeRdb::E_ERROR;
1970     }
1971 
1972     ANS_LOGD("Key:%{public}s, value:%{public}s.", key.c_str(), value.c_str());
1973 
1974     return NativeRdb::E_OK;
1975 }
1976 
1977 #ifdef ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER
GetKvFromDb(const std::string & key,std::string & value,const int32_t & userId,int32_t & retCode)1978 int32_t NotificationPreferencesDatabase::GetKvFromDb(
1979     const std::string &key, std::string &value, const int32_t &userId, int32_t &retCode)
1980 {
1981     if (!CheckRdbStore()) {
1982         ANS_LOGE("null RdbStore");
1983         return NativeRdb::E_ERROR;
1984     }
1985 
1986     retCode = rdbDataManager_->QueryData(key, value, userId);
1987     return retCode;
1988 }
1989 #endif
1990 
GetByteFromDb(const std::string & key,std::vector<uint8_t> & value,const int32_t & userId)1991 int32_t NotificationPreferencesDatabase::GetByteFromDb(
1992     const std::string &key, std::vector<uint8_t> &value, const int32_t &userId)
1993 {
1994     if (!CheckRdbStore()) {
1995         ANS_LOGE("null RdbStore");
1996         return NativeRdb::E_ERROR;
1997     }
1998 
1999     int32_t result = rdbDataManager_->QueryData(key, value, userId);
2000     if (result != NativeRdb::E_OK) {
2001         ANS_LOGE("Get byte failed, key %{public}s, result %{public}d.", key.c_str(), result);
2002         return NativeRdb::E_ERROR;
2003     }
2004 
2005     return NativeRdb::E_OK;
2006 }
2007 
GetBatchKvsFromDb(const std::string & key,std::unordered_map<std::string,std::string> & values,const int32_t & userId)2008 int32_t NotificationPreferencesDatabase::GetBatchKvsFromDb(
2009     const std::string &key, std::unordered_map<std::string, std::string>  &values, const int32_t &userId)
2010 {
2011     if (!CheckRdbStore()) {
2012         ANS_LOGE("null RdbStore");
2013         return NativeRdb::E_ERROR;
2014     }
2015 
2016     int32_t result = rdbDataManager_->QueryDataBeginWithKey(key, values, userId);
2017     if (result != NativeRdb::E_OK) {
2018         ANS_LOGE("Get batch notification request failed, key %{public}s, result %{public}d.", key.c_str(), result);
2019         return NativeRdb::E_ERROR;
2020     }
2021     ANS_LOGD("Key:%{public}s.", key.c_str());
2022     return NativeRdb::E_OK;
2023 }
2024 
GetBatchKvsFromDbContainsKey(const std::string & key,std::unordered_map<std::string,std::string> & values,const int32_t & userId)2025 int32_t NotificationPreferencesDatabase::GetBatchKvsFromDbContainsKey(
2026     const std::string &key, std::unordered_map<std::string, std::string>  &values, const int32_t &userId)
2027 {
2028     if (!CheckRdbStore()) {
2029         ANS_LOGE("null RdbStore");
2030         return NativeRdb::E_ERROR;
2031     }
2032 
2033     int32_t result = rdbDataManager_->QueryDataContainsWithKey(key, values, userId);
2034     if (result != NativeRdb::E_OK) {
2035         ANS_LOGE("QueryDataContainsWithKey failed, key %{public}s, result %{public}d.", key.c_str(), result);
2036         return NativeRdb::E_ERROR;
2037     }
2038     ANS_LOGD("Key:%{public}s.", key.c_str());
2039     return NativeRdb::E_OK;
2040 }
2041 
DeleteKvFromDb(const std::string & key,const int32_t & userId)2042 int32_t NotificationPreferencesDatabase::DeleteKvFromDb(const std::string &key, const int32_t &userId)
2043 {
2044     if (!CheckRdbStore()) {
2045         ANS_LOGE("null RdbStore");
2046         return NativeRdb::E_ERROR;
2047     }
2048 
2049     int32_t result = rdbDataManager_->DeleteData(key, userId);
2050     if (result != NativeRdb::E_OK) {
2051         ANS_LOGE("Delete key-value failed, key %{public}s, result %{public}d.", key.c_str(), result);
2052         return NativeRdb::E_ERROR;
2053     }
2054 
2055     ANS_LOGD("Delete key:%{public}s.", key.c_str());
2056 
2057     return NativeRdb::E_OK;
2058 }
2059 
DeleteBatchKvFromDb(const std::vector<std::string> & keys,const int32_t & userId)2060 int32_t NotificationPreferencesDatabase::DeleteBatchKvFromDb(const std::vector<std::string> &keys,
2061     const int32_t &userId)
2062 {
2063     if (!CheckRdbStore()) {
2064         ANS_LOGE("null RdbStore");
2065         return NativeRdb::E_ERROR;
2066     }
2067 
2068     int32_t result = rdbDataManager_->DeleteBatchData(keys, userId);
2069     if (result != NativeRdb::E_OK) {
2070         ANS_LOGE("Delete key-value failed, result %{public}d.", result);
2071         return NativeRdb::E_ERROR;
2072     }
2073 
2074     return NativeRdb::E_OK;
2075 }
2076 
DropUserTable(const int32_t userId)2077 int32_t NotificationPreferencesDatabase::DropUserTable(const int32_t userId)
2078 {
2079     if (!CheckRdbStore()) {
2080         ANS_LOGE("null RdbStore");
2081         return NativeRdb::E_ERROR;
2082     }
2083 
2084     int32_t result = rdbDataManager_->DropUserTable(userId);
2085     if (result != NativeRdb::E_OK) {
2086         ANS_LOGE("Delete table failed, result %{public}d.", result);
2087         return NativeRdb::E_ERROR;
2088     }
2089     return NativeRdb::E_OK;
2090 }
2091 
IsAgentRelationship(const std::string & agentBundleName,const std::string & sourceBundleName)2092 bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &agentBundleName,
2093     const std::string &sourceBundleName)
2094 {
2095     if (!CheckRdbStore()) {
2096         ANS_LOGE("null RdbStore");
2097         return false;
2098     }
2099     std::string agentShip = "";
2100     int32_t result = rdbDataManager_->QueryData("PROXY_PKG", agentShip);
2101     if (result != NativeRdb::E_OK) {
2102         ANS_LOGE("Query agent relationships failed.");
2103         return false;
2104     }
2105     ANS_LOGD("The agent relationship is :%{public}s.", agentShip.c_str());
2106     nlohmann::json jsonAgentShip = nlohmann::json::parse(agentShip, nullptr, false);
2107     if (jsonAgentShip.is_null() || jsonAgentShip.empty()) {
2108         ANS_LOGE("Invalid JSON object");
2109         return false;
2110     }
2111     if (jsonAgentShip.is_discarded() || !jsonAgentShip.is_array()) {
2112         ANS_LOGE("Parse agent ship failed due to data is discarded or not array");
2113         return false;
2114     }
2115 
2116     nlohmann::json jsonTarget;
2117     jsonTarget[RELATIONSHIP_JSON_KEY_SERVICE] = agentBundleName;
2118     jsonTarget[RELATIONSHIP_JSON_KEY_APP] = sourceBundleName;
2119     bool isAgentRelationship = false;
2120     for (const auto &item : jsonAgentShip) {
2121         if (jsonTarget == item) {
2122             isAgentRelationship = true;
2123             break;
2124         }
2125     }
2126 
2127     return isAgentRelationship;
2128 }
2129 
PutDistributedEnabledForBundle(const std::string deviceType,const NotificationPreferencesInfo::BundleInfo & bundleInfo,const bool & enabled)2130 bool NotificationPreferencesDatabase::PutDistributedEnabledForBundle(const std::string deviceType,
2131     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled)
2132 {
2133     ANS_LOGD("%{public}s, deviceType:%{public}s,enabled[%{public}d]", __FUNCTION__, deviceType.c_str(), enabled);
2134     if (bundleInfo.GetBundleName().empty()) {
2135         ANS_LOGE("Bundle name is null.");
2136         return false;
2137     }
2138     int32_t userId = -1;
2139     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
2140 
2141     std::string key = GenerateBundleLablel(bundleInfo, deviceType);
2142     int32_t result = PutDataToDB(key, enabled, userId);
2143     ANS_LOGD("result[%{public}d]", result);
2144     return (result == NativeRdb::E_OK);
2145 }
2146 
PutDistributedBundleOption(const std::vector<sptr<DistributedBundleOption>> & bundles,const std::string & deviceType,const int32_t & userId)2147 bool NotificationPreferencesDatabase::PutDistributedBundleOption(
2148     const std::vector<sptr<DistributedBundleOption>> &bundles,
2149     const std::string &deviceType,
2150     const int32_t &userId
2151 )
2152 {
2153     ANS_LOGI("PutDistributedBundleOption start");
2154 
2155     if (!CheckRdbStore()) {
2156         ANS_LOGE("null RdbStore");
2157         return NativeRdb::E_ERROR;
2158     }
2159     std::unordered_map<std::string, std::string> existSwitchMap;
2160     int32_t result = rdbDataManager_->QueryDataBeginWithKey(
2161         KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION, existSwitchMap, userId);
2162     if (result != NativeRdb::E_OK && result != NativeRdb::E_EMPTY_VALUES_BUCKET) {
2163         ANS_LOGE("get exist distributed switch error");
2164         return false;
2165     }
2166 
2167     bool retResult = true;
2168     std::unordered_map<std::string, std::string> values;
2169     for (auto bundleOption : bundles) {
2170         std::string bundleName = bundleOption->GetBundle()->GetBundleName();
2171         int32_t uid = bundleOption->GetBundle()->GetUid();
2172 
2173         NotificationPreferencesInfo::BundleInfo bundleInfo;
2174         bundleInfo.SetBundleName(bundleName);
2175         bundleInfo.SetBundleUid(uid);
2176         std::string key = GenerateBundleLablel(bundleInfo, deviceType);
2177 
2178         auto ite = existSwitchMap.find(key);
2179         if (ite != existSwitchMap.end()) {
2180             bool iteResult = static_cast<bool>(StringToInt(ite->second));
2181             if (iteResult == bundleOption->isEnable()) {
2182                 continue;
2183             }
2184             result = rdbDataManager_->InsertData(key, std::to_string(bundleOption->isEnable()), userId);
2185             if (result != NativeRdb::E_OK) {
2186                 retResult = false;
2187                 ANS_LOGE("update distributed switch failed, %{public}s %{public}d", bundleName.c_str(), uid);
2188             }
2189         } else {
2190             values.emplace(key, std::to_string(bundleOption->isEnable()));
2191         }
2192     }
2193 
2194     if (!values.empty()) {
2195         result = rdbDataManager_->InsertBatchData(values, userId);
2196         if (result != NativeRdb::E_OK) {
2197             retResult = false;
2198             ANS_LOGE("batch insert distributed switch failed");
2199         }
2200     }
2201     return retResult;
2202 }
2203 
GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo & bundleInfo,const std::string & deviceType) const2204 std::string NotificationPreferencesDatabase::GenerateBundleLablel(
2205     const NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &deviceType) const
2206 {
2207     return std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append(KEY_MIDDLE_LINE).append(
2208         std::string(bundleInfo.GetBundleName()).append(KEY_MIDDLE_LINE).append(std::to_string(
2209             bundleInfo.GetBundleUid())).append(KEY_MIDDLE_LINE).append(deviceType));
2210 }
2211 
GenerateBundleLablel(const std::string & deviceType,const std::string & deviceId,const int32_t userId) const2212 std::string NotificationPreferencesDatabase::GenerateBundleLablel(
2213     const std::string &deviceType,
2214     const std::string &deviceId,
2215     const int32_t userId) const
2216 {
2217     return std::string(KEY_ENABLE_DISTRIBUTED_AUTH_STATUS).append(KEY_MIDDLE_LINE)
2218         .append(deviceType).append(KEY_MIDDLE_LINE)
2219         .append(deviceId).append(KEY_MIDDLE_LINE)
2220         .append(std::to_string(userId));
2221 }
2222 
2223 template <typename T>
PutDataToDB(const std::string & key,const T & value,const int32_t & userId)2224 int32_t NotificationPreferencesDatabase::PutDataToDB(const std::string &key, const T &value, const int32_t &userId)
2225 {
2226     if (!CheckRdbStore()) {
2227         ANS_LOGE("null RdbStore");
2228         return false;
2229     }
2230     std::string valueStr = std::to_string(value);
2231     int32_t result = rdbDataManager_->InsertData(key, valueStr, userId);
2232     return result;
2233 }
2234 
PutDistributedEnabled(const std::string & deviceType,const NotificationConstant::SWITCH_STATE & enabled)2235 bool NotificationPreferencesDatabase::PutDistributedEnabled(
2236     const std::string &deviceType, const NotificationConstant::SWITCH_STATE &enabled)
2237 {
2238     ANS_LOGD("%{public}s, deviceType: %{public}s, enabled: %{public}d",
2239         __FUNCTION__, deviceType.c_str(), static_cast<int32_t>(enabled));
2240     int32_t userId = SUBSCRIBE_USER_INIT;
2241     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2242     if (userId == SUBSCRIBE_USER_INIT) {
2243         ANS_LOGE("Current user acquisition failed");
2244         return false;
2245     }
2246     std::string key = std::string(KEY_DISTRIBUTED_NOTIFICATION_SWITCH).append(KEY_MIDDLE_LINE).append(
2247         deviceType).append(KEY_MIDDLE_LINE).append(std::to_string(userId));
2248     int32_t result = PutDataToDB(key, static_cast<int32_t>(enabled), userId);
2249     ANS_LOGD("key: %{public}s, result: %{public}d", key.c_str(), result);
2250     return (result == NativeRdb::E_OK);
2251 }
2252 
GetDistributedEnabled(const std::string & deviceType,NotificationConstant::SWITCH_STATE & enabled)2253 bool NotificationPreferencesDatabase::GetDistributedEnabled(
2254     const std::string &deviceType, NotificationConstant::SWITCH_STATE &enabled)
2255 {
2256     ANS_LOGD("%{public}s, deviceType: %{public}s", __FUNCTION__, deviceType.c_str());
2257     int32_t userId = SUBSCRIBE_USER_INIT;
2258     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2259     if (userId == SUBSCRIBE_USER_INIT) {
2260         ANS_LOGE("Current user acquisition failed");
2261         return false;
2262     }
2263     std::string key = std::string(KEY_DISTRIBUTED_NOTIFICATION_SWITCH).append(KEY_MIDDLE_LINE).append(
2264         deviceType).append(KEY_MIDDLE_LINE).append(std::to_string(userId));
2265     bool result = false;
2266     enabled = NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF;
2267     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2268         switch (status) {
2269             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2270                 result = true;
2271                 break;
2272             }
2273             case NativeRdb::E_OK: {
2274                 result = true;
2275                 enabled = static_cast<NotificationConstant::SWITCH_STATE>(StringToInt(value));
2276                 break;
2277             }
2278             default:
2279                 result = false;
2280                 break;
2281         }
2282     });
2283     return result;
2284 }
2285 
GetDistributedAuthStatus(const std::string & deviceType,const std::string & deviceId,int32_t targetUserId,bool & isAuth)2286 bool NotificationPreferencesDatabase::GetDistributedAuthStatus(
2287     const std::string &deviceType, const std::string &deviceId, int32_t targetUserId, bool &isAuth)
2288 {
2289     int32_t userId = SUBSCRIBE_USER_INIT;
2290     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2291     if (userId == SUBSCRIBE_USER_INIT) {
2292         ANS_LOGE("Current user acquisition failed");
2293         return false;
2294     }
2295     ANS_LOGD("%{public}s, deviceType: %{public}s, deviceId: %{public}s, targetUserId: %{public}d",
2296         __FUNCTION__, deviceType.c_str(), StringAnonymous(deviceId).c_str(), targetUserId);
2297     std::string key = GenerateBundleLablel(deviceType, deviceId, targetUserId);
2298     bool result = false;
2299     isAuth = false;
2300     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2301         switch (status) {
2302             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2303                 result = true;
2304                 break;
2305             }
2306             case NativeRdb::E_OK: {
2307                 result = true;
2308                 isAuth = StringToInt(value) != 0;
2309                 break;
2310             }
2311             default:
2312                 result = false;
2313                 break;
2314         }
2315     });
2316     return result;
2317 }
2318 
SetSilentReminderEnabled(const NotificationPreferencesInfo::SilentReminderInfo & silentReminderInfo)2319 bool NotificationPreferencesDatabase::SetSilentReminderEnabled(
2320     const NotificationPreferencesInfo::SilentReminderInfo &silentReminderInfo)
2321 {
2322     if (silentReminderInfo.bundleName.empty()) {
2323         ANS_LOGE("Bundle name is null.");
2324         return false;
2325     }
2326     int32_t userId = -1;
2327     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(silentReminderInfo.uid, userId);
2328 
2329     std::string key = GenerateSilentReminderKey(silentReminderInfo);
2330     bool enableStatus = false;
2331     if (silentReminderInfo.enableStatus == NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON) {
2332         enableStatus = true;
2333     }
2334     int32_t result = PutDataToDB(key, static_cast<int32_t>(enableStatus), userId);
2335     ANS_LOGI("SilentReminder result:%{public}d, key:%{public}s, enableStatus:%{public}d",
2336         result, key.c_str(), silentReminderInfo.enableStatus);
2337     return (result == NativeRdb::E_OK);
2338 }
2339 
IsSilentReminderEnabled(NotificationPreferencesInfo::SilentReminderInfo & silentReminderInfo)2340 bool NotificationPreferencesDatabase::IsSilentReminderEnabled(
2341     NotificationPreferencesInfo::SilentReminderInfo &silentReminderInfo)
2342 {
2343     if (silentReminderInfo.bundleName.empty()) {
2344         ANS_LOGE("Bundle name is null.");
2345         return false;
2346     }
2347 
2348     std::string key = GenerateSilentReminderKey(silentReminderInfo);
2349     bool result = false;
2350     int32_t userId = -1;
2351     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(silentReminderInfo.uid, userId);
2352     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2353         switch (status) {
2354             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2355                 result = true;
2356                 silentReminderInfo.enableStatus = NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF;
2357                 break;
2358             }
2359             case NativeRdb::E_OK: {
2360                 result = true;
2361                 NotificationConstant::SWITCH_STATE enableStatus =
2362                     StringToInt(value) ? NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON :
2363                     NotificationConstant::SWITCH_STATE::USER_MODIFIED_OFF;
2364                 silentReminderInfo.enableStatus = enableStatus;
2365                 break;
2366             }
2367             default:
2368                 result = false;
2369                 break;
2370         }
2371     });
2372     return result;
2373 }
2374 
SetDistributedAuthStatus(const std::string & deviceType,const std::string & deviceId,int32_t targetUserId,bool isAuth)2375 bool NotificationPreferencesDatabase::SetDistributedAuthStatus(
2376     const std::string &deviceType, const std::string &deviceId, int32_t targetUserId, bool isAuth)
2377 {
2378     int32_t userId = SUBSCRIBE_USER_INIT;
2379     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2380     if (userId == SUBSCRIBE_USER_INIT) {
2381         ANS_LOGE("Current user acquisition failed");
2382         return false;
2383     }
2384     ANS_LOGD("%{public}s, deviceType: %{public}s, deviceId: %{public}s, targetUserId: %{public}d",
2385         __FUNCTION__, deviceType.c_str(), StringAnonymous(deviceId).c_str(), targetUserId);
2386     std::string key = GenerateBundleLablel(deviceType, deviceId, targetUserId);
2387     int32_t result = PutDataToDB(key, static_cast<int32_t>(isAuth), userId);
2388     ANS_LOGD("key: %{public}s, result: %{public}d", key.c_str(), result);
2389     return (result == NativeRdb::E_OK);
2390 }
2391 
PutDistributedDevicelist(const std::string & deviceTypes,const int32_t & userId)2392 bool NotificationPreferencesDatabase::PutDistributedDevicelist(const std::string &deviceTypes, const int32_t &userId)
2393 {
2394     ANS_LOGD("%{public}s, deviceTypes: %{public}s, userId: %{public}d", __FUNCTION__, deviceTypes.c_str(), userId);
2395     if (!CheckRdbStore()) {
2396         ANS_LOGE("null RdbStore");
2397         return false;
2398     }
2399     int32_t result = rdbDataManager_->InsertData(KEY_DISTRIBUTED_DEVICE_LIST, deviceTypes, userId);
2400     return (result == NativeRdb::E_OK);
2401 }
2402 
GetDistributedDevicelist(std::string & deviceTypes)2403 bool NotificationPreferencesDatabase::GetDistributedDevicelist(std::string &deviceTypes)
2404 {
2405     int32_t userId = SUBSCRIBE_USER_INIT;
2406     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2407     if (userId == SUBSCRIBE_USER_INIT) {
2408         ANS_LOGE("Current user acquisition failed");
2409         return false;
2410     }
2411     bool result = false;
2412     GetValueFromDisturbeDB(KEY_DISTRIBUTED_DEVICE_LIST, userId, [&](const int32_t &status, std::string &value) {
2413         switch (status) {
2414             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2415                 result = true;
2416                 break;
2417             }
2418             case NativeRdb::E_OK: {
2419                 result = true;
2420                 deviceTypes = value;
2421                 break;
2422             }
2423             default:
2424                 result = false;
2425                 break;
2426         }
2427     });
2428     return result;
2429 }
2430 
GetDistributedEnabledForBundle(const std::string deviceType,const NotificationPreferencesInfo::BundleInfo & bundleInfo,bool & enabled)2431 bool NotificationPreferencesDatabase::GetDistributedEnabledForBundle(const std::string deviceType,
2432     const NotificationPreferencesInfo::BundleInfo &bundleInfo, bool &enabled)
2433 {
2434     ANS_LOGD("%{public}s, deviceType:%{public}s,enabled[%{public}d]", __FUNCTION__, deviceType.c_str(), enabled);
2435     if (bundleInfo.GetBundleName().empty()) {
2436         ANS_LOGE("Bundle name is null.");
2437         return false;
2438     }
2439 
2440     std::string key = GenerateBundleLablel(bundleInfo, deviceType);
2441     bool result = false;
2442     enabled = false;
2443     int32_t userId = -1;
2444     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
2445     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2446         switch (status) {
2447             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2448                 result = true;
2449                 enabled = false;
2450                 break;
2451             }
2452             case NativeRdb::E_OK: {
2453                 result = true;
2454                 enabled = static_cast<bool>(StringToInt(value));
2455                 break;
2456             }
2457             default:
2458                 result = false;
2459                 break;
2460         }
2461     });
2462     ANS_LOGD("enabled:[%{public}d]KEY:%{public}s", enabled, key.c_str());
2463     return result;
2464 }
2465 
GenerateBundleLablel(const std::string & deviceType,const int32_t userId) const2466 std::string NotificationPreferencesDatabase::GenerateBundleLablel(const std::string &deviceType,
2467     const int32_t userId) const
2468 {
2469     return std::string(KEY_SMART_REMINDER_ENABLE_NOTIFICATION).append(KEY_MIDDLE_LINE).append(
2470         deviceType).append(KEY_MIDDLE_LINE).append(std::to_string(userId));
2471 }
2472 
GenerateBundleLablel(const NotificationConstant::SlotType & slotType,const std::string & deviceType,const int32_t userId) const2473 std::string NotificationPreferencesDatabase::GenerateBundleLablel(
2474     const NotificationConstant::SlotType &slotType,
2475     const std::string &deviceType,
2476     const int32_t userId) const
2477 {
2478     return std::string(KEY_ENABLE_SLOT_DISTRIBUTED_NOTIFICATION).append(KEY_MIDDLE_LINE)
2479         .append(deviceType).append(KEY_MIDDLE_LINE)
2480         .append(std::to_string(static_cast<int32_t>(slotType))).append(KEY_MIDDLE_LINE)
2481         .append(std::to_string(userId));
2482 }
2483 
SetSmartReminderEnabled(const std::string deviceType,const bool & enabled)2484 bool NotificationPreferencesDatabase::SetSmartReminderEnabled(const std::string deviceType, const bool &enabled)
2485 {
2486     ANS_LOGD("%{public}s, deviceType:%{public}s,enabled[%{public}d]", __FUNCTION__, deviceType.c_str(), enabled);
2487     int32_t userId = SUBSCRIBE_USER_INIT;
2488     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2489     if (userId == SUBSCRIBE_USER_INIT) {
2490         ANS_LOGE("Current user acquisition failed");
2491         return false;
2492     }
2493 
2494     std::string key = GenerateBundleLablel(deviceType, userId);
2495     ANS_LOGD("%{public}s, key:%{public}s,enabled[%{public}d]", __FUNCTION__, key.c_str(), enabled);
2496     int32_t result = PutDataToDB(key, enabled, userId);
2497     return (result == NativeRdb::E_OK);
2498 }
2499 
IsSmartReminderEnabled(const std::string deviceType,bool & enabled)2500 bool NotificationPreferencesDatabase::IsSmartReminderEnabled(const std::string deviceType, bool &enabled)
2501 {
2502     ANS_LOGD("%{public}s, deviceType:%{public}s,enabled[%{public}d]", __FUNCTION__, deviceType.c_str(), enabled);
2503     int32_t userId = SUBSCRIBE_USER_INIT;
2504     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2505     if (userId == SUBSCRIBE_USER_INIT) {
2506         ANS_LOGE("Current user acquisition failed");
2507         return false;
2508     }
2509 
2510     std::string key = GenerateBundleLablel(deviceType, userId);
2511     bool result = false;
2512     enabled = false;
2513     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2514         switch (status) {
2515             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2516                 result = true;
2517                 GetSmartReminderEnableFromCCM(deviceType, enabled);
2518                 break;
2519             }
2520             case NativeRdb::E_OK: {
2521                 result = true;
2522                 enabled = static_cast<bool>(StringToInt(value));
2523                 break;
2524             }
2525             default:
2526                 result = false;
2527                 break;
2528         }
2529     });
2530     return result;
2531 }
2532 
SetDistributedEnabledBySlot(const NotificationConstant::SlotType & slotType,const std::string & deviceType,const bool enabled)2533 bool NotificationPreferencesDatabase::SetDistributedEnabledBySlot(
2534     const NotificationConstant::SlotType &slotType, const std::string &deviceType, const bool enabled)
2535 {
2536     ANS_LOGD("%{public}s, %{public}d,deviceType:%{public}s,enabled[%{public}d]",
2537         __FUNCTION__, slotType, deviceType.c_str(), enabled);
2538     int32_t userId = SUBSCRIBE_USER_INIT;
2539     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2540     if (userId == SUBSCRIBE_USER_INIT) {
2541         ANS_LOGE("Current user acquisition failed");
2542         return false;
2543     }
2544 
2545     std::string key = GenerateBundleLablel(slotType, deviceType, userId);
2546     ANS_LOGD("%{public}s, key:%{public}s,enabled[%{public}d]", __FUNCTION__, key.c_str(), enabled);
2547     int32_t result = PutDataToDB(key, enabled, userId);
2548     return (result == NativeRdb::E_OK);
2549 }
2550 
IsDistributedEnabledBySlot(const NotificationConstant::SlotType & slotType,const std::string & deviceType,bool & enabled)2551 bool NotificationPreferencesDatabase::IsDistributedEnabledBySlot(
2552     const NotificationConstant::SlotType &slotType, const std::string &deviceType, bool &enabled)
2553 {
2554     ANS_LOGD("%{public}s, %{public}d,deviceType:%{public}s]",
2555         __FUNCTION__, slotType, deviceType.c_str());
2556     int32_t userId = SUBSCRIBE_USER_INIT;
2557     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
2558     if (userId == SUBSCRIBE_USER_INIT) {
2559         ANS_LOGE("Current user acquisition failed");
2560         return false;
2561     }
2562 
2563     std::string key = GenerateBundleLablel(slotType, deviceType, userId);
2564     bool result = false;
2565     enabled = false;
2566     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
2567         switch (status) {
2568             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2569                 result = true;
2570                 enabled = true;
2571                 break;
2572             }
2573             case NativeRdb::E_OK: {
2574                 result = true;
2575                 enabled = static_cast<bool>(StringToInt(value));
2576                 break;
2577             }
2578             default:
2579                 result = false;
2580                 break;
2581         }
2582     });
2583     return result;
2584 }
2585 
GetAdditionalConfig(const std::string & key)2586 std::string NotificationPreferencesDatabase::GetAdditionalConfig(const std::string &key)
2587 {
2588     if (!CheckRdbStore()) {
2589         ANS_LOGE("null RdbStore");
2590         return "";
2591     }
2592     std::string configValue = "";
2593     int32_t result = rdbDataManager_->QueryData(key, configValue);
2594     if (result != NativeRdb::E_OK) {
2595         ANS_LOGE("Query additional config failed.");
2596         return "";
2597     }
2598     ANS_LOGD("The additional config key is :%{public}s, value is :%{public}s.", key.c_str(), configValue.c_str());
2599     return configValue;
2600 }
2601 
CheckApiCompatibility(const std::string & bundleName,const int32_t & uid)2602 bool NotificationPreferencesDatabase::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid)
2603 {
2604     ANS_LOGD("called");
2605     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
2606     if (bundleManager == nullptr) {
2607         return false;
2608     }
2609     return bundleManager->CheckApiCompatibility(bundleName, uid);
2610 }
2611 
UpdateBundlePropertyToDisturbeDB(int32_t userId,const NotificationPreferencesInfo::BundleInfo & bundleInfo)2612 bool NotificationPreferencesDatabase::UpdateBundlePropertyToDisturbeDB(int32_t userId,
2613     const NotificationPreferencesInfo::BundleInfo &bundleInfo)
2614 {
2615     if (bundleInfo.GetBundleName().empty()) {
2616         ANS_LOGE("Bundle name is null.");
2617         return false;
2618     }
2619 
2620     if (!CheckRdbStore()) {
2621         ANS_LOGE("null RdbStore");
2622         return false;
2623     }
2624     std::string value;
2625     std::string bundleLabelKey = KEY_BUNDLE_LABEL + GenerateBundleLablel(bundleInfo);
2626     int32_t result = rdbDataManager_->QueryData(bundleLabelKey, value, userId);
2627     if (result == NativeRdb::E_EMPTY_VALUES_BUCKET) {
2628         if (rdbDataManager_->InsertData(bundleLabelKey, GenerateBundleLablel(bundleInfo), userId)
2629             != NativeRdb::E_OK) {
2630             ANS_LOGE("Store bundle name %{public}s to db is failed.", bundleLabelKey.c_str());
2631             return false;
2632         }
2633     }
2634     if (result == NativeRdb::E_EMPTY_VALUES_BUCKET || result == NativeRdb::E_OK) {
2635         return PutBundlePropertyValueToDisturbeDB(bundleInfo);
2636     }
2637     ANS_LOGW("Query bundle name %{public}s failed %{public}d.", bundleLabelKey.c_str(), result);
2638     return false;
2639 }
2640 
UpdateBundleSlotToDisturbeDB(int32_t userId,const std::string & bundleName,const int32_t & bundleUid,const std::vector<sptr<NotificationSlot>> & slots)2641 bool NotificationPreferencesDatabase::UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName,
2642     const int32_t &bundleUid, const std::vector<sptr<NotificationSlot>> &slots)
2643 {
2644     if (bundleName.empty()) {
2645         ANS_LOGE("Bundle name is null.");
2646         return false;
2647     }
2648     if (slots.empty()) {
2649         ANS_LOGI("Slot is empty.");
2650         return true;
2651     }
2652 
2653     std::string bundleKey = bundleName + std::to_string(bundleUid);
2654     std::unordered_map<std::string, std::string> values;
2655     for (auto& slot : slots) {
2656         GenerateSlotEntry(bundleKey, slot, values);
2657     }
2658     if (!CheckRdbStore()) {
2659         ANS_LOGE("null RdbStore");
2660         return false;
2661     }
2662     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
2663     return (result == NativeRdb::E_OK);
2664 }
2665 
DelCloneProfileInfo(const int32_t & userId,const sptr<NotificationDoNotDisturbProfile> & info)2666 bool NotificationPreferencesDatabase::DelCloneProfileInfo(const int32_t &userId,
2667     const sptr<NotificationDoNotDisturbProfile>& info)
2668 {
2669     if (!CheckRdbStore()) {
2670         ANS_LOGE("null RdbStore");
2671         return false;
2672     }
2673 
2674     std::string key = KEY_CLONE_LABEL + CLONE_PROFILE + std::to_string(info->GetProfileId());
2675     int32_t result = rdbDataManager_->DeleteData(key, userId);
2676     if (result != NativeRdb::E_OK) {
2677         ANS_LOGE("delete clone profile Info failed.");
2678         return false;
2679     }
2680     return true;
2681 }
2682 
DelBatchCloneProfileInfo(const int32_t & userId,const std::vector<sptr<NotificationDoNotDisturbProfile>> & profileInfo)2683 bool NotificationPreferencesDatabase::DelBatchCloneProfileInfo(const int32_t &userId,
2684     const std::vector<sptr<NotificationDoNotDisturbProfile>>& profileInfo)
2685 {
2686     std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE;
2687     if (!CheckRdbStore()) {
2688         ANS_LOGE("null RdbStore");
2689         return false;
2690     }
2691 
2692     std::vector<std::string> keys;
2693     for (auto info : profileInfo) {
2694         std::string key = cloneProfile + std::to_string(info->GetProfileId());
2695         keys.emplace_back(key);
2696     }
2697 
2698     int32_t result = rdbDataManager_->DeleteBatchData(keys, userId);
2699     if (result != NativeRdb::E_OK) {
2700         ANS_LOGE("delete clone bundle Info failed.");
2701         return false;
2702     }
2703     return true;
2704 }
2705 
UpdateBatchCloneProfileInfo(const int32_t & userId,const std::vector<sptr<NotificationDoNotDisturbProfile>> & profileInfo)2706 bool NotificationPreferencesDatabase::UpdateBatchCloneProfileInfo(const int32_t &userId,
2707     const std::vector<sptr<NotificationDoNotDisturbProfile>>& profileInfo)
2708 {
2709     std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE;
2710     std::unordered_map<std::string, std::string> values;
2711     for (auto& info : profileInfo) {
2712         std::string key = cloneProfile + std::to_string(info->GetProfileId());
2713         std::string jsonString = info->ToJson();
2714         values.emplace(key, jsonString);
2715     }
2716     return UpdateCloneToDisturbeDB(userId, values);
2717 }
2718 
GetAllCloneProfileInfo(const int32_t & userId,std::vector<sptr<NotificationDoNotDisturbProfile>> & profilesInfo)2719 void NotificationPreferencesDatabase::GetAllCloneProfileInfo(const int32_t &userId,
2720     std::vector<sptr<NotificationDoNotDisturbProfile>>& profilesInfo)
2721 {
2722     std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE;
2723     std::unordered_map<std::string, std::string> values;
2724     if (GetBatchKvsFromDb(cloneProfile, values, userId) != ERR_OK) {
2725         ANS_LOGW("Get clone bundle map info failed %{public}d.", userId);
2726         return;
2727     }
2728 
2729     for (auto item : values) {
2730         sptr<NotificationDoNotDisturbProfile> profile = new (std::nothrow) NotificationDoNotDisturbProfile();
2731         if (profile == nullptr) {
2732             ANS_LOGW("Get clone profile failed.");
2733             continue;
2734         }
2735         profile->FromJson(item.second);
2736         profilesInfo.push_back(profile);
2737     }
2738 }
2739 
GetAllCloneBundleInfo(const int32_t & userId,std::vector<NotificationCloneBundleInfo> & cloneBundleInfo)2740 void NotificationPreferencesDatabase::GetAllCloneBundleInfo(const int32_t &userId,
2741     std::vector<NotificationCloneBundleInfo>& cloneBundleInfo)
2742 {
2743     std::unordered_map<std::string, std::string> values;
2744     if (GetBatchKvsFromDb(KEY_CLONE_LABEL + CLONE_BUNDLE, values, userId) != ERR_OK) {
2745         ANS_LOGW("Get clone bundle map info failed %{public}d.", userId);
2746         return;
2747     }
2748 
2749     for (auto item : values) {
2750         NotificationCloneBundleInfo bundleInfo;
2751         if (item.second.empty() || !nlohmann::json::accept(item.second)) {
2752             ANS_LOGE("Invalid accept json");
2753             continue;
2754         }
2755         nlohmann::json jsonObject = nlohmann::json::parse(item.second, nullptr, false);
2756         if (jsonObject.is_null() || !jsonObject.is_object()) {
2757             ANS_LOGE("Invalid JSON object");
2758             continue;
2759         }
2760         bundleInfo.FromJson(jsonObject);
2761         cloneBundleInfo.emplace_back(bundleInfo);
2762     }
2763 }
2764 
DelBatchCloneBundleInfo(const int32_t & userId,const std::vector<NotificationCloneBundleInfo> & cloneBundleInfo)2765 bool NotificationPreferencesDatabase::DelBatchCloneBundleInfo(const int32_t &userId,
2766     const std::vector<NotificationCloneBundleInfo>& cloneBundleInfo)
2767 {
2768     std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE;
2769     if (!CheckRdbStore()) {
2770         ANS_LOGE("null RdbStore");
2771         return false;
2772     }
2773 
2774     std::vector<std::string> keys;
2775     for (auto bundleInfo : cloneBundleInfo) {
2776         std::string key = cloneBundle + bundleInfo.GetBundleName() +
2777             std::to_string(bundleInfo.GetAppIndex());
2778         keys.emplace_back(key);
2779     }
2780     int32_t result = rdbDataManager_->DeleteBatchData(keys, userId);
2781     if (result != NativeRdb::E_OK) {
2782         ANS_LOGE("delete clone bundle Info failed.");
2783         return false;
2784     }
2785     return true;
2786 }
2787 
UpdateBatchCloneBundleInfo(const int32_t & userId,const std::vector<NotificationCloneBundleInfo> & cloneBundleInfo)2788 bool NotificationPreferencesDatabase::UpdateBatchCloneBundleInfo(const int32_t &userId,
2789     const std::vector<NotificationCloneBundleInfo>& cloneBundleInfo)
2790 {
2791     std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE;
2792     std::unordered_map<std::string, std::string> values;
2793     for (auto& info : cloneBundleInfo) {
2794         nlohmann::json jsonNode;
2795         std::string key = cloneBundle + info.GetBundleName() + std::to_string(info.GetAppIndex());
2796         info.ToJson(jsonNode);
2797         values.emplace(key, jsonNode.dump());
2798     }
2799     return UpdateCloneToDisturbeDB(userId, values);
2800 }
2801 
DelCloneBundleInfo(const int32_t & userId,const NotificationCloneBundleInfo & cloneBundleInfo)2802 bool NotificationPreferencesDatabase::DelCloneBundleInfo(const int32_t &userId,
2803     const NotificationCloneBundleInfo& cloneBundleInfo)
2804 {
2805     std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE;
2806     std::string key = cloneBundle + cloneBundleInfo.GetBundleName() +
2807         std::to_string(cloneBundleInfo.GetAppIndex());
2808     if (!CheckRdbStore()) {
2809         ANS_LOGE("null RdbStore");
2810         return false;
2811     }
2812 
2813     int32_t result = rdbDataManager_->DeleteData(key, userId);
2814     if (result != NativeRdb::E_OK) {
2815         ANS_LOGE("delete clone bundle Info failed.");
2816         return false;
2817     }
2818     return true;
2819 }
2820 
UpdateCloneToDisturbeDB(const int32_t & userId,const std::unordered_map<std::string,std::string> values)2821 bool NotificationPreferencesDatabase::UpdateCloneToDisturbeDB(const int32_t &userId,
2822     const std::unordered_map<std::string, std::string> values)
2823 {
2824     if (values.empty() || !CheckRdbStore()) {
2825         ANS_LOGE("null RdbStore");
2826         return false;
2827     }
2828 
2829     int32_t result = rdbDataManager_->InsertBatchData(values, userId);
2830     return (result == NativeRdb::E_OK);
2831 }
2832 
SetDisableNotificationInfo(const sptr<NotificationDisable> & notificationDisable)2833 bool NotificationPreferencesDatabase::SetDisableNotificationInfo(const sptr<NotificationDisable> &notificationDisable)
2834 {
2835     if (notificationDisable == nullptr || !CheckRdbStore()) {
2836         ANS_LOGE("null notificationDisable or rdbStore");
2837         return false;
2838     }
2839     if (notificationDisable->GetBundleList().empty()) {
2840         ANS_LOGE("the bundle list is empty");
2841         return false;
2842     }
2843     std::string value = notificationDisable->ToJson();
2844     int32_t userId = notificationDisable->GetUserId();
2845     if (userId == SUBSCRIBE_USER_INIT) {
2846         userId = ZERO_USER_ID;
2847     }
2848     int32_t result = rdbDataManager_->InsertData(KEY_DISABLE_NOTIFICATION, value, userId);
2849     return (result == NativeRdb::E_OK);
2850 }
2851 
GetDisableNotificationInfo(NotificationDisable & notificationDisable)2852 bool NotificationPreferencesDatabase::GetDisableNotificationInfo(NotificationDisable &notificationDisable)
2853 {
2854     if (!CheckRdbStore()) {
2855         ANS_LOGE("null rdbStore");
2856         return false;
2857     }
2858     std::string value;
2859     int32_t result = rdbDataManager_->QueryData(KEY_DISABLE_NOTIFICATION, value, ZERO_USER_ID);
2860     if (result != NativeRdb::E_OK) {
2861         ANS_LOGE("query data failed");
2862         return false;
2863     }
2864     notificationDisable.FromJson(value);
2865     return true;
2866 }
2867 
GetUserDisableNotificationInfo(int32_t userId,NotificationDisable & notificationDisable)2868 bool NotificationPreferencesDatabase::GetUserDisableNotificationInfo(
2869     int32_t userId, NotificationDisable &notificationDisable)
2870 {
2871     if (!CheckRdbStore()) {
2872         ANS_LOGE("null rdbStore");
2873         return false;
2874     }
2875     std::string value;
2876     int32_t result = rdbDataManager_->QueryData(KEY_DISABLE_NOTIFICATION, value, userId);
2877     if (result != NativeRdb::E_OK) {
2878         ANS_LOGE("query data failed");
2879         return false;
2880     }
2881     notificationDisable.FromJson(value);
2882     return true;
2883 }
2884 
GetDisableNotificationInfo(NotificationPreferencesInfo & info)2885 void NotificationPreferencesDatabase::GetDisableNotificationInfo(NotificationPreferencesInfo &info)
2886 {
2887     if (!CheckRdbStore()) {
2888         ANS_LOGE("null rdbStore");
2889         return;
2890     }
2891     std::string value;
2892     int32_t result = rdbDataManager_->QueryData(KEY_DISABLE_NOTIFICATION, value, ZERO_USER_ID);
2893     if (result != NativeRdb::E_OK) {
2894         ANS_LOGE("query data failed");
2895         return;
2896     }
2897     info.AddDisableNotificationInfo(value);
2898 }
2899 
IsDistributedEnabledEmptyForBundle(const std::string & deviceType,const NotificationPreferencesInfo::BundleInfo & bundleInfo)2900 bool NotificationPreferencesDatabase::IsDistributedEnabledEmptyForBundle(
2901     const std::string& deviceType, const NotificationPreferencesInfo::BundleInfo& bundleInfo)
2902 {
2903     if (bundleInfo.GetBundleName().empty()) {
2904         ANS_LOGE("bundle name is empty.");
2905         return true;
2906     }
2907 
2908     std::string key = GenerateBundleLablel(bundleInfo, deviceType);
2909     bool result = true;
2910     int32_t userId = -1;
2911     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleInfo.GetBundleUid(), userId);
2912     GetValueFromDisturbeDB(key, userId, [&](const int32_t& status, std::string& value) {
2913         if (status == NativeRdb::E_EMPTY_VALUES_BUCKET) {
2914             result = false;
2915         }
2916     });
2917     return result;
2918 }
2919 
GetSmartReminderEnableFromCCM(const std::string & deviceType,bool & enabled)2920 void NotificationPreferencesDatabase::GetSmartReminderEnableFromCCM(const std::string& deviceType, bool& enabled)
2921 {
2922     ANS_LOGD("called");
2923     if (!isCachedSmartReminderEnableList_) {
2924         if (!DelayedSingleton<NotificationConfigParse>::GetInstance()->GetSmartReminderEnableList(
2925             smartReminderEnableList_)) {
2926             ANS_LOGE("GetSmartReminderEnableList failed from json");
2927             enabled = false;
2928             return;
2929         }
2930         isCachedSmartReminderEnableList_ = true;
2931     }
2932 
2933     if (smartReminderEnableList_.empty()) {
2934         ANS_LOGD("smartReminderEnableList_ is empty");
2935         enabled = false;
2936         return;
2937     }
2938 
2939     if (std::find(smartReminderEnableList_.begin(), smartReminderEnableList_.end(), deviceType) !=
2940         smartReminderEnableList_.end()) {
2941         enabled = true;
2942     } else {
2943         enabled = false;
2944     }
2945     ANS_LOGD("get %{public}s smartReminderEnable is %{public}d from json", deviceType.c_str(), enabled);
2946 }
2947 
GenerateSubscriberExistFlagKey(const std::string & deviceType,const int32_t userId) const2948 std::string NotificationPreferencesDatabase::GenerateSubscriberExistFlagKey(
2949     const std::string& deviceType, const int32_t userId) const
2950 {
2951     return std::string(KEY_SUBSCRIBER_EXISTED_FLAG)
2952         .append(KEY_MIDDLE_LINE)
2953         .append(deviceType)
2954         .append(KEY_MIDDLE_LINE)
2955         .append(std::to_string(userId));
2956 }
2957 
SetSubscriberExistFlag(const std::string & deviceType,bool existFlag)2958 bool NotificationPreferencesDatabase::SetSubscriberExistFlag(const std::string& deviceType, bool existFlag)
2959 {
2960     ANS_LOGD("%{public}s, deviceType:%{public}s, existFlag[%{public}d]", __FUNCTION__, deviceType.c_str(), existFlag);
2961     int32_t userId = SUBSCRIBE_USER_INIT;
2962     OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
2963     if (userId == SUBSCRIBE_USER_INIT) {
2964         ANS_LOGE("current user acquisition failed");
2965         return false;
2966     }
2967 
2968     std::string key = GenerateSubscriberExistFlagKey(deviceType, userId);
2969     int32_t result = PutDataToDB(key, existFlag, userId);
2970     return (result == NativeRdb::E_OK);
2971 }
2972 
GetSubscriberExistFlag(const std::string & deviceType,bool & existFlag)2973 bool NotificationPreferencesDatabase::GetSubscriberExistFlag(const std::string& deviceType, bool& existFlag)
2974 {
2975     ANS_LOGD("%{public}s, deviceType:%{public}s, existFlag[%{public}d]", __FUNCTION__, deviceType.c_str(), existFlag);
2976     int32_t userId = SUBSCRIBE_USER_INIT;
2977     OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
2978     if (userId == SUBSCRIBE_USER_INIT) {
2979         ANS_LOGE("current user acquisition failed");
2980         return false;
2981     }
2982 
2983     std::string key = GenerateSubscriberExistFlagKey(deviceType, userId);
2984     bool result = false;
2985     existFlag = false;
2986     GetValueFromDisturbeDB(key, userId, [&](const int32_t& status, std::string& value) {
2987         switch (status) {
2988             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
2989                 result = true;
2990                 break;
2991             }
2992             case NativeRdb::E_OK: {
2993                 result = true;
2994                 existFlag = static_cast<bool>(StringToInt(value));
2995                 break;
2996             }
2997             default:
2998                 result = false;
2999                 break;
3000         }
3001     });
3002     return result;
3003 }
3004 
SetHashCodeRule(const int32_t uid,const uint32_t type)3005 bool NotificationPreferencesDatabase::SetHashCodeRule(const int32_t uid, const uint32_t type)
3006 {
3007     ANS_LOGD("%{public}s, %{public}d,", __FUNCTION__, type);
3008     int32_t userId = SUBSCRIBE_USER_INIT;
3009     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
3010     ANS_LOGI("userId = %{public}d", userId);
3011     if (userId == SUBSCRIBE_USER_INIT) {
3012         ANS_LOGE("Current user acquisition failed");
3013         return false;
3014     }
3015 
3016     std::string key = GenerateHashCodeGenerate(uid);
3017     ANS_LOGD("%{public}s, key:%{public}s,type = %{public}d", __FUNCTION__, key.c_str(), type);
3018     int32_t result = PutDataToDB(key, type, userId);
3019     return (result == NativeRdb::E_OK);
3020 }
3021 
GetHashCodeRule(const int32_t uid)3022 uint32_t NotificationPreferencesDatabase::GetHashCodeRule(const int32_t uid)
3023 {
3024     ANS_LOGD("%{public}s, %{public}d,", __FUNCTION__, uid);
3025     int32_t userId = SUBSCRIBE_USER_INIT;
3026     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
3027     if (userId == SUBSCRIBE_USER_INIT) {
3028         ANS_LOGE("Current user acquisition failed");
3029         return 0;
3030     }
3031 
3032     std::string key = GenerateHashCodeGenerate(uid);
3033     ANS_LOGD("%{public}s, key:%{public}s", __FUNCTION__, key.c_str());
3034     uint32_t result = 0;
3035     GetValueFromDisturbeDB(key, userId, [&](const int32_t &status, std::string &value) {
3036         switch (status) {
3037             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
3038                 break;
3039             }
3040             case NativeRdb::E_OK: {
3041                 result = StringToInt(value);
3042                 break;
3043             }
3044             default:
3045                 break;
3046         }
3047     });
3048     return result;
3049 }
3050 
GetBundleRemoveFlagKey(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,int32_t sourceType)3051 static std::string GetBundleRemoveFlagKey(const sptr<NotificationBundleOption> &bundleOption,
3052     const NotificationConstant::SlotType &slotType, int32_t sourceType)
3053 {
3054     std::string key;
3055     if (sourceType == CLEAR_SLOT_FROM_AVSEESAION) {
3056         key = KEY_REMOVE_SLOT_FLAG + bundleOption->GetBundleName() + std::to_string(bundleOption->GetUid()) +
3057             KEY_UNDER_LINE + std::to_string(slotType);
3058     } else {
3059         key = KEY_REMOVE_SLOT_FLAG + std::to_string(sourceType) + KEY_UNDER_LINE + bundleOption->GetBundleName() +
3060             std::to_string(bundleOption->GetUid()) + KEY_UNDER_LINE + std::to_string(slotType);
3061     }
3062     return key;
3063 }
3064 
SetBundleRemoveFlag(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,int32_t sourceType)3065 bool NotificationPreferencesDatabase::SetBundleRemoveFlag(const sptr<NotificationBundleOption> &bundleOption,
3066     const NotificationConstant::SlotType &slotType, int32_t sourceType)
3067 {
3068     if (bundleOption == nullptr) {
3069         ANS_LOGE("null bundleOption");
3070         return false;
3071     }
3072 
3073     int32_t userId = SUBSCRIBE_USER_INIT;
3074     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
3075     if (userId == SUBSCRIBE_USER_INIT) {
3076         ANS_LOGE("Current user acquisition failed");
3077         return false;
3078     }
3079 
3080     if (!CheckRdbStore()) {
3081         ANS_LOGE("null RdbStore");
3082         return false;
3083     }
3084     std::string key = GetBundleRemoveFlagKey(bundleOption, slotType, sourceType);
3085     int32_t result = rdbDataManager_->InsertData(key, KEY_SECOND_REMOVED_FLAG, userId);
3086     return (result == NativeRdb::E_OK);
3087 }
3088 
GetBundleRemoveFlag(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,int32_t sourceType)3089 bool NotificationPreferencesDatabase::GetBundleRemoveFlag(const sptr<NotificationBundleOption> &bundleOption,
3090     const NotificationConstant::SlotType &slotType, int32_t sourceType)
3091 {
3092     if (bundleOption == nullptr) {
3093         ANS_LOGE("null bundleOption");
3094         return true;
3095     }
3096 
3097     int32_t userId = SUBSCRIBE_USER_INIT;
3098     OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
3099     if (userId == SUBSCRIBE_USER_INIT) {
3100         ANS_LOGW("Current user acquisition failed");
3101         return true;
3102     }
3103 
3104     std::string key = GetBundleRemoveFlagKey(bundleOption, slotType, sourceType);
3105     bool existFlag = true;
3106     std::string result;
3107     GetValueFromDisturbeDB(key, userId, [&](const int32_t& status, std::string& value) {
3108         switch (status) {
3109             case NativeRdb::E_EMPTY_VALUES_BUCKET: {
3110                 existFlag = false;
3111                 break;
3112             }
3113             case NativeRdb::E_OK: {
3114                 result = value;
3115                 break;
3116             }
3117             default:
3118                 break;
3119         }
3120     });
3121 
3122     ANS_LOGI("Get current remove flag %{public}s,%{public}s,%{public}d", key.c_str(), result.c_str(), existFlag);
3123     if (!existFlag || result == KEY_REMOVED_FLAG) {
3124         return false;
3125     }
3126     return true;
3127 }
3128 
GenerateHashCodeGenerate(const int32_t uid)3129 std::string NotificationPreferencesDatabase::GenerateHashCodeGenerate(const int32_t uid)
3130 {
3131     return std::string(KEY_HASH_CODE_RULE).append(KEY_MIDDLE_LINE).append(std::to_string(uid));
3132 }
3133 }  // namespace Notification
3134 }  // namespace OHOS
3135