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