1/*
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.h"
17
18#include <fstream>
19#include <memory>
20#include <mutex>
21
22#include "access_token_helper.h"
23#include "ans_const_define.h"
24#include "ans_inner_errors.h"
25#include "ans_log_wrapper.h"
26#include "ans_permission_def.h"
27#include "bundle_manager_helper.h"
28#include "hitrace_meter_adapter.h"
29#include "nlohmann/json.hpp"
30#include "os_account_manager_helper.h"
31#include "notification_analytics_util.h"
32#include "notification_config_parse.h"
33
34namespace OHOS {
35namespace Notification {
36namespace {
37const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_";
38}
39std::mutex NotificationPreferences::instanceMutex_;
40std::shared_ptr<NotificationPreferences> NotificationPreferences::instance_;
41
42NotificationPreferences::NotificationPreferences()
43{
44    preferncesDB_ = std::make_unique<NotificationPreferencesDatabase>();
45    if (preferncesDB_ == nullptr) {
46        HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1)
47           .Message("preferncesDB is null.");
48        NotificationAnalyticsUtil::ReportModifyEvent(message);
49    }
50    InitSettingFromDisturbDB();
51}
52
53std::shared_ptr<NotificationPreferences> NotificationPreferences::GetInstance()
54{
55    if (instance_ == nullptr) {
56        std::lock_guard<std::mutex> lock(instanceMutex_);
57        if (instance_ == nullptr) {
58            auto instance = std::make_shared<NotificationPreferences>();
59            instance_ = instance;
60        }
61    }
62    return instance_;
63}
64
65ErrCode NotificationPreferences::AddNotificationSlots(
66    const sptr<NotificationBundleOption> &bundleOption, const std::vector<sptr<NotificationSlot>> &slots)
67{
68    HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
69    ANS_LOGD("%{public}s", __FUNCTION__);
70    HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1)
71        .BundleName(bundleOption == nullptr ? "" : bundleOption->GetBundleName());
72    if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || slots.empty()) {
73        message.Message("Invalid param.");
74        NotificationAnalyticsUtil::ReportModifyEvent(message);
75        return ERR_ANS_INVALID_PARAM;
76    }
77    std::lock_guard<std::mutex> lock(preferenceMutex_);
78    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
79    ErrCode result = ERR_OK;
80    for (auto slot : slots) {
81        result = CheckSlotForCreateSlot(bundleOption, slot, preferencesInfo);
82        if (result != ERR_OK) {
83            return result;
84        }
85    }
86
87    ANS_LOGD("ffrt: add slot to db!");
88    if (result == ERR_OK &&
89        (!preferncesDB_->PutSlotsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), slots))) {
90        message.Message("put slot for to db failed.");
91        NotificationAnalyticsUtil::ReportModifyEvent(message);
92        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
93    }
94
95    if (result == ERR_OK) {
96        preferencesInfo_ = preferencesInfo;
97    }
98    return result;
99}
100
101ErrCode NotificationPreferences::AddNotificationBundleProperty(const sptr<NotificationBundleOption> &bundleOption)
102{
103    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
104        return ERR_ANS_INVALID_PARAM;
105    }
106    std::lock_guard<std::mutex> lock(preferenceMutex_);
107    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
108    NotificationPreferencesInfo::BundleInfo bundleInfo;
109    preferencesInfo.SetBundleInfo(bundleInfo);
110    ErrCode result = ERR_OK;
111    if (preferncesDB_->PutBundlePropertyToDisturbeDB(bundleInfo)) {
112        preferencesInfo_ = preferencesInfo;
113    } else {
114        result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
115    }
116    ANS_LOGD("AddNotificationBundleProperty.result: %{public}d", result);
117    return result;
118}
119
120ErrCode NotificationPreferences::RemoveNotificationSlot(
121    const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType)
122{
123    HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
124    ANS_LOGD("%{public}s", __FUNCTION__);
125    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
126        return ERR_ANS_INVALID_PARAM;
127    }
128    HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1)
129        .BundleName(bundleOption->GetBundleName());
130    message.SlotType(static_cast<uint32_t>(slotType));
131    std::lock_guard<std::mutex> lock(preferenceMutex_);
132    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
133    ErrCode result = ERR_OK;
134    result = CheckSlotForRemoveSlot(bundleOption, slotType, preferencesInfo);
135    if (result == ERR_OK &&
136        (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType, bundleOption->GetUid()))) {
137        message.Message("Remove slot failed: " + std::to_string(result));
138        NotificationAnalyticsUtil::ReportModifyEvent(message);
139        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
140    }
141
142    if (result == ERR_OK) {
143        preferencesInfo_ = preferencesInfo;
144    }
145    message.Message("Remove slot successful");
146    NotificationAnalyticsUtil::ReportModifyEvent(message);
147    return result;
148}
149
150ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptr<NotificationBundleOption> &bundleOption)
151{
152    ANS_LOGD("%{public}s", __FUNCTION__);
153    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
154        return ERR_ANS_INVALID_PARAM;
155    }
156    HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1)
157        .BundleName(bundleOption->GetBundleName());
158    std::lock_guard<std::mutex> lock(preferenceMutex_);
159    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
160    ErrCode result = ERR_OK;
161    NotificationPreferencesInfo::BundleInfo bundleInfo;
162    if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) {
163        bundleInfo.RemoveAllSlots();
164        preferencesInfo.SetBundleInfo(bundleInfo);
165        if (!preferncesDB_->RemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) {
166            result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
167        }
168    } else {
169        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
170    }
171
172    if (result == ERR_OK) {
173        ANS_LOGD("result is ERR_OK");
174        preferencesInfo_ = preferencesInfo;
175    }
176    message.Message("Remove all slot: " + std::to_string(result));
177    NotificationAnalyticsUtil::ReportModifyEvent(message);
178    return result;
179}
180
181ErrCode NotificationPreferences::RemoveNotificationForBundle(const sptr<NotificationBundleOption> &bundleOption)
182{
183    ANS_LOGD("%{public}s", __FUNCTION__);
184    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
185        return ERR_ANS_INVALID_PARAM;
186    }
187    std::lock_guard<std::mutex> lock(preferenceMutex_);
188    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
189
190    ErrCode result = ERR_OK;
191    if (preferencesInfo.IsExsitBundleInfo(bundleOption)) {
192        preferencesInfo.RemoveBundleInfo(bundleOption);
193        if (!preferncesDB_->RemoveBundleFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) {
194            result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
195        }
196    } else {
197        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
198    }
199
200    if (result == ERR_OK) {
201        preferencesInfo_ = preferencesInfo;
202    }
203
204    return result;
205}
206
207ErrCode NotificationPreferences::UpdateNotificationSlots(
208    const sptr<NotificationBundleOption> &bundleOption, const std::vector<sptr<NotificationSlot>> &slots)
209{
210    ANS_LOGD("%{public}s", __FUNCTION__);
211    if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || slots.empty()) {
212        return ERR_ANS_INVALID_PARAM;
213    }
214    HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_2)
215        .BundleName(bundleOption->GetBundleName());
216    std::lock_guard<std::mutex> lock(preferenceMutex_);
217    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
218    ErrCode result = ERR_OK;
219    for (auto slotIter : slots) {
220        result = CheckSlotForUpdateSlot(bundleOption, slotIter, preferencesInfo);
221        if (result != ERR_OK) {
222            message.Message("Check slot for update failed." + std::to_string(result));
223            NotificationAnalyticsUtil::ReportModifyEvent(message);
224            return result;
225        }
226    }
227
228    if ((result == ERR_OK) &&
229        (!preferncesDB_->PutSlotsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), slots))) {
230        message.Message("Update put slot for to db failed.");
231        NotificationAnalyticsUtil::ReportModifyEvent(message);
232        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
233    }
234
235    if (result == ERR_OK) {
236        preferencesInfo_ = preferencesInfo;
237    }
238
239    return result;
240}
241
242ErrCode NotificationPreferences::GetNotificationSlot(const sptr<NotificationBundleOption> &bundleOption,
243    const NotificationConstant::SlotType &type, sptr<NotificationSlot> &slot)
244{
245    ANS_LOGD("%{public}s", __FUNCTION__);
246    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
247        return ERR_ANS_INVALID_PARAM;
248    }
249
250    ErrCode result = ERR_OK;
251    NotificationPreferencesInfo::BundleInfo bundleInfo;
252    std::lock_guard<std::mutex> lock(preferenceMutex_);
253    if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) {
254        if (!bundleInfo.GetSlot(type, slot)) {
255            result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
256        }
257    } else {
258        ANS_LOGW("bundle not exist");
259        result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
260    }
261    ANS_LOGD("%{public}s status  = %{public}d ", __FUNCTION__, result);
262    return result;
263}
264
265ErrCode NotificationPreferences::GetNotificationAllSlots(
266    const sptr<NotificationBundleOption> &bundleOption, std::vector<sptr<NotificationSlot>> &slots)
267{
268    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
269        return ERR_ANS_INVALID_PARAM;
270    }
271
272    ErrCode result = ERR_OK;
273    NotificationPreferencesInfo::BundleInfo bundleInfo;
274    std::lock_guard<std::mutex> lock(preferenceMutex_);
275    if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) {
276        bundleInfo.GetAllSlots(slots);
277    } else {
278        ANS_LOGW("Notification bundle does not exsit.");
279        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
280    }
281
282    return result;
283}
284
285ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle(
286    const sptr<NotificationBundleOption> &bundleOption, uint64_t &num)
287{
288    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
289        return ERR_ANS_INVALID_PARAM;
290    }
291
292    ErrCode result = ERR_OK;
293    NotificationPreferencesInfo::BundleInfo bundleInfo;
294    std::lock_guard<std::mutex> lock(preferenceMutex_);
295    if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) {
296        num = static_cast<uint64_t>(bundleInfo.GetAllSlotsSize());
297    } else {
298        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
299    }
300    return result;
301}
302
303ErrCode NotificationPreferences::GetNotificationSlotFlagsForBundle(
304    const sptr<NotificationBundleOption> &bundleOption, uint32_t &slotFlags)
305{
306    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
307        return ERR_ANS_INVALID_PARAM;
308    }
309
310    return GetBundleProperty(bundleOption, BundleType::BUNDLE_SLOTFLGS_TYPE, slotFlags);
311}
312
313
314ErrCode NotificationPreferences::SetNotificationSlotFlagsForBundle(
315    const sptr<NotificationBundleOption> &bundleOption, uint32_t slotFlags)
316{
317    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
318        return ERR_ANS_INVALID_PARAM;
319    }
320
321    std::lock_guard<std::mutex> lock(preferenceMutex_);
322    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
323    ErrCode result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_SLOTFLGS_TYPE, slotFlags);
324    if (result == ERR_OK) {
325        preferencesInfo_ = preferencesInfo;
326    }
327    return result;
328}
329
330ErrCode NotificationPreferences::IsShowBadge(const sptr<NotificationBundleOption> &bundleOption, bool &enable)
331{
332    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
333        return ERR_ANS_INVALID_PARAM;
334    }
335    return GetBundleProperty(bundleOption, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable);
336}
337
338ErrCode NotificationPreferences::SetShowBadge(const sptr<NotificationBundleOption> &bundleOption, const bool enable)
339{
340    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
341        return ERR_ANS_INVALID_PARAM;
342    }
343    std::lock_guard<std::mutex> lock(preferenceMutex_);
344    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
345    ErrCode result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable);
346    if (result == ERR_OK) {
347        preferencesInfo_ = preferencesInfo;
348    }
349    return result;
350}
351
352ErrCode NotificationPreferences::GetImportance(const sptr<NotificationBundleOption> &bundleOption, int32_t &importance)
353{
354    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
355        return ERR_ANS_INVALID_PARAM;
356    }
357
358    return GetBundleProperty(bundleOption, BundleType::BUNDLE_IMPORTANCE_TYPE, importance);
359}
360
361
362ErrCode NotificationPreferences::SetImportance(
363    const sptr<NotificationBundleOption> &bundleOption, const int32_t &importance)
364{
365    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
366        return ERR_ANS_INVALID_PARAM;
367    }
368    std::lock_guard<std::mutex> lock(preferenceMutex_);
369    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
370    ErrCode result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_IMPORTANCE_TYPE, importance);
371    if (result == ERR_OK) {
372        preferencesInfo_ = preferencesInfo;
373    }
374    return result;
375}
376
377ErrCode NotificationPreferences::GetTotalBadgeNums(
378    const sptr<NotificationBundleOption> &bundleOption, int32_t &totalBadgeNum)
379{
380    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
381        return ERR_ANS_INVALID_PARAM;
382    }
383    return GetBundleProperty(bundleOption, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum);
384}
385
386ErrCode NotificationPreferences::SetTotalBadgeNums(
387    const sptr<NotificationBundleOption> &bundleOption, const int32_t num)
388{
389    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
390        return ERR_ANS_INVALID_PARAM;
391    }
392    std::lock_guard<std::mutex> lock(preferenceMutex_);
393    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
394    ErrCode result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, num);
395    if (result == ERR_OK) {
396        preferencesInfo_ = preferencesInfo;
397    }
398    return result;
399}
400
401ErrCode NotificationPreferences::GetNotificationsEnabledForBundle(
402    const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
403{
404    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
405        return ERR_ANS_INVALID_PARAM;
406    }
407    return GetBundleProperty(bundleOption, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled);
408}
409
410ErrCode NotificationPreferences::SetNotificationsEnabledForBundle(
411    const sptr<NotificationBundleOption> &bundleOption, const bool enabled)
412{
413    HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
414    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
415        return ERR_ANS_INVALID_PARAM;
416    }
417
418    std::lock_guard<std::mutex> lock(preferenceMutex_);
419    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
420    ErrCode result =
421        SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled);
422    if (result == ERR_OK) {
423        preferencesInfo_ = preferencesInfo;
424    }
425    return result;
426}
427
428ErrCode NotificationPreferences::GetNotificationsEnabled(const int32_t &userId, bool &enabled)
429{
430    if (userId <= SUBSCRIBE_USER_INIT) {
431        return ERR_ANS_INVALID_PARAM;
432    }
433
434    ErrCode result = ERR_OK;
435    std::lock_guard<std::mutex> lock(preferenceMutex_);
436    if (!preferencesInfo_.GetEnabledAllNotification(userId, enabled)) {
437        result = ERR_ANS_INVALID_PARAM;
438    }
439    return result;
440}
441
442ErrCode NotificationPreferences::SetNotificationsEnabled(const int32_t &userId, const bool &enabled)
443{
444    if (userId <= SUBSCRIBE_USER_INIT) {
445        return ERR_ANS_INVALID_PARAM;
446    }
447    std::lock_guard<std::mutex> lock(preferenceMutex_);
448    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
449    preferencesInfo.SetEnabledAllNotification(userId, enabled);
450    ErrCode result = ERR_OK;
451    if (!preferncesDB_->PutNotificationsEnabled(userId, enabled)) {
452        result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
453    }
454
455    if (result == ERR_OK) {
456        preferencesInfo_ = preferencesInfo;
457    }
458    return result;
459}
460
461ErrCode NotificationPreferences::GetHasPoppedDialog(const sptr<NotificationBundleOption> &bundleOption, bool &hasPopped)
462{
463    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
464        return ERR_ANS_INVALID_PARAM;
465    }
466    return GetBundleProperty(bundleOption, BundleType::BUNDLE_POPPED_DIALOG_TYPE, hasPopped);
467}
468
469ErrCode NotificationPreferences::SetHasPoppedDialog(const sptr<NotificationBundleOption> &bundleOption, bool hasPopped)
470{
471    if (bundleOption == nullptr) {
472        return ERR_ANS_INVALID_PARAM;
473    }
474    std::lock_guard<std::mutex> lock(preferenceMutex_);
475    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
476    ErrCode result = ERR_OK;
477    result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_POPPED_DIALOG_TYPE, hasPopped);
478    if (result == ERR_OK) {
479        preferencesInfo_ = preferencesInfo;
480    }
481    return result;
482}
483
484ErrCode NotificationPreferences::GetDoNotDisturbDate(const int32_t &userId,
485    sptr<NotificationDoNotDisturbDate> &date)
486{
487    if (userId <= SUBSCRIBE_USER_INIT) {
488        return ERR_ANS_INVALID_PARAM;
489    }
490
491    ErrCode result = ERR_OK;
492    std::lock_guard<std::mutex> lock(preferenceMutex_);
493    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
494    if (!preferencesInfo.GetDoNotDisturbDate(userId, date)) {
495        result = ERR_ANS_INVALID_PARAM;
496    }
497    return result;
498}
499
500ErrCode NotificationPreferences::SetDoNotDisturbDate(const int32_t &userId,
501    const sptr<NotificationDoNotDisturbDate> date)
502{
503    ANS_LOGE("enter.");
504    if (userId <= SUBSCRIBE_USER_INIT) {
505        return ERR_ANS_INVALID_PARAM;
506    }
507    std::lock_guard<std::mutex> lock(preferenceMutex_);
508    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
509    preferencesInfo.SetDoNotDisturbDate(userId, date);
510
511    ErrCode result = ERR_OK;
512    if (!preferncesDB_->PutDoNotDisturbDate(userId, date)) {
513        result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
514    }
515
516    if (result == ERR_OK) {
517        preferencesInfo_ = preferencesInfo;
518    }
519    return result;
520}
521
522bool NotificationPreferences::CheckDoNotDisturbProfileID(int32_t profileId)
523{
524    if (profileId < DO_NOT_DISTURB_PROFILE_MIN_ID || profileId > DO_NOT_DISTURB_PROFILE_MAX_ID) {
525        ANS_LOGE("The profile id is out of range.");
526        return false;
527    }
528    return true;
529}
530
531ErrCode NotificationPreferences::AddDoNotDisturbProfiles(
532    int32_t userId, std::vector<sptr<NotificationDoNotDisturbProfile>> profiles)
533{
534    ANS_LOGD("Called.");
535    for (auto profile : profiles) {
536        if (profile == nullptr) {
537            ANS_LOGE("The profile is nullptr.");
538            return ERR_ANS_INVALID_PARAM;
539        }
540        if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) {
541            return ERR_ANS_INVALID_PARAM;
542        }
543        auto trustList = profile->GetProfileTrustList();
544        for (auto& bundleInfo : trustList) {
545            int32_t index = BundleManagerHelper::GetInstance()->GetAppIndexByUid(bundleInfo.GetUid());
546            bundleInfo.SetAppIndex(index);
547            ANS_LOGI("Get app index by uid %{public}d %{public}s %{public}d", bundleInfo.GetUid(),
548                bundleInfo.GetBundleName().c_str(), index);
549        }
550        profile->SetProfileTrustList(trustList);
551    }
552    std::lock_guard<std::mutex> lock(preferenceMutex_);
553    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
554    preferencesInfo.AddDoNotDisturbProfiles(userId, profiles);
555    if (preferncesDB_ == nullptr) {
556        ANS_LOGE("The prefernces db is nullptr.");
557        return ERR_ANS_SERVICE_NOT_READY;
558    }
559    if (!preferncesDB_->AddDoNotDisturbProfiles(userId, profiles)) {
560        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
561    }
562    preferencesInfo_ = preferencesInfo;
563    return ERR_OK;
564}
565
566ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles(
567    int32_t userId, const std::vector<sptr<NotificationDoNotDisturbProfile>> profiles)
568{
569    ANS_LOGE("Called.");
570    for (auto profile : profiles) {
571        if (profile == nullptr) {
572            ANS_LOGE("The profile is nullptr.");
573            return ERR_ANS_INVALID_PARAM;
574        }
575        if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) {
576            return ERR_ANS_INVALID_PARAM;
577        }
578    }
579    std::lock_guard<std::mutex> lock(preferenceMutex_);
580    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
581    preferencesInfo.RemoveDoNotDisturbProfiles(userId, profiles);
582    if (preferncesDB_ == nullptr) {
583        ANS_LOGE("The prefernces db is nullptr.");
584        return ERR_ANS_SERVICE_NOT_READY;
585    }
586    if (!preferncesDB_->RemoveDoNotDisturbProfiles(userId, profiles)) {
587        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
588    }
589    preferencesInfo_ = preferencesInfo;
590    return ERR_OK;
591}
592
593void NotificationPreferences::UpdateProfilesUtil(std::vector<NotificationBundleOption>& trustList,
594    const std::vector<NotificationBundleOption> bundleList)
595{
596    for (auto& item : bundleList) {
597        bool exit = false;
598        for (auto& bundle: trustList) {
599            if (item.GetUid() == bundle.GetUid()) {
600                exit = true;
601                break;
602            }
603        }
604        if (!exit) {
605            trustList.push_back(item);
606        }
607    }
608}
609
610ErrCode NotificationPreferences::UpdateDoNotDisturbProfiles(int32_t userId, int32_t profileId,
611    const std::string& name, const std::vector<NotificationBundleOption>& bundleList)
612{
613    ANS_LOGI("Called update Profile %{public}d %{public}d %{public}zu.", userId, profileId, bundleList.size());
614    if (!CheckDoNotDisturbProfileID(profileId) || bundleList.empty()) {
615        return ERR_ANS_INVALID_PARAM;
616    }
617
618    sptr<NotificationDoNotDisturbProfile> profile = new (std::nothrow) NotificationDoNotDisturbProfile();
619    std::lock_guard<std::mutex> lock(preferenceMutex_);
620    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
621    if (preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) {
622        auto trustList = profile->GetProfileTrustList();
623        UpdateProfilesUtil(trustList, bundleList);
624        profile->SetProfileTrustList(trustList);
625    } else {
626        profile->SetProfileId(profileId);
627        profile->SetProfileName(name);
628        profile->SetProfileTrustList(bundleList);
629    }
630    ANS_LOGI("Update profile %{public}d %{public}d %{public}zu", userId, profile->GetProfileId(),
631        profile->GetProfileTrustList().size());
632    preferencesInfo.AddDoNotDisturbProfiles(userId, {profile});
633    if (preferncesDB_ == nullptr) {
634        ANS_LOGE("The prefernces db is nullptr.");
635        return ERR_ANS_SERVICE_NOT_READY;
636    }
637    if (!preferncesDB_->AddDoNotDisturbProfiles(userId, {profile})) {
638        return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
639    }
640    preferencesInfo_ = preferencesInfo;
641    return ERR_OK;
642}
643
644void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId,
645    const NotificationCloneBundleInfo& cloneBundleInfo)
646{
647    ANS_LOGI("Event bundle update %{public}s.", cloneBundleInfo.Dump().c_str());
648    NotificationPreferencesInfo::BundleInfo bundleInfo;
649    sptr<NotificationBundleOption> bundleOption = new NotificationBundleOption();
650    bundleOption->SetBundleName(cloneBundleInfo.GetBundleName());
651    bundleOption->SetUid(cloneBundleInfo.GetUid());
652    std::lock_guard<std::mutex> lock(preferenceMutex_);
653    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
654    if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) {
655        bundleInfo.SetBundleName(cloneBundleInfo.GetBundleName());
656        bundleInfo.SetBundleUid(cloneBundleInfo.GetUid());
657    }
658
659    /* after clone, override these witch */
660    bundleInfo.SetSlotFlags(cloneBundleInfo.GetSlotFlags());
661    bundleInfo.SetIsShowBadge(cloneBundleInfo.GetIsShowBadge());
662    bundleInfo.SetEnableNotification(cloneBundleInfo.GetEnableNotification());
663    /* update property to db */
664    if (!preferncesDB_->UpdateBundlePropertyToDisturbeDB(userId, bundleInfo)) {
665        ANS_LOGW("Clone bundle info failed %{public}s.", cloneBundleInfo.Dump().c_str());
666        return;
667    }
668    preferencesInfo.SetBundleInfo(bundleInfo);
669
670    /* update slot info */
671    std::vector<sptr<NotificationSlot>> slots;
672    for (auto& cloneSlot : cloneBundleInfo.GetSlotInfo()) {
673        sptr<NotificationSlot> slotInfo = new (std::nothrow) NotificationSlot(cloneSlot.slotType_);
674        uint32_t slotFlags = bundleInfo.GetSlotFlags();
675        auto configSlotReminderMode = DelayedSingleton<NotificationConfigParse>::GetInstance()->
676            GetConfigSlotReminderModeByType(slotInfo->GetType());
677        slotInfo->SetReminderMode(configSlotReminderMode & slotFlags);
678        slotInfo->SetEnable(cloneSlot.enable_);
679        slotInfo->SetForceControl(cloneSlot.isForceControl_);
680        slotInfo->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
681        slots.push_back(slotInfo);
682        bundleInfo.SetSlot(slotInfo);
683    }
684
685    if (!preferncesDB_->UpdateBundleSlotToDisturbeDB(userId, cloneBundleInfo.GetBundleName(),
686        cloneBundleInfo.GetUid(), slots)) {
687        ANS_LOGW("Clone bundle slot failed %{public}s.", cloneBundleInfo.Dump().c_str());
688        preferencesInfo_ = preferencesInfo;
689        return;
690    }
691    preferencesInfo.SetBundleInfo(bundleInfo);
692    preferencesInfo_ = preferencesInfo;
693}
694
695void NotificationPreferences::GetAllCLoneBundlesInfo(int32_t userId,
696    std::vector<NotificationCloneBundleInfo> &cloneBundles)
697{
698    std::lock_guard<std::mutex> lock(preferenceMutex_);
699    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
700    std::unordered_map<std::string, std::string> bundlesMap;
701    if (GetBatchKvsFromDb(KEY_BUNDLE_LABEL, bundlesMap, userId) != ERR_OK) {
702        ANS_LOGE("Get bundle map info failed.");
703        return;
704    }
705    preferencesInfo.GetAllCLoneBundlesInfo(userId, bundlesMap, cloneBundles);
706    preferencesInfo_ = preferencesInfo;
707}
708
709void NotificationPreferences::GetDoNotDisturbProfileListByUserId(int32_t userId,
710    std::vector<sptr<NotificationDoNotDisturbProfile>> &profiles)
711{
712    std::lock_guard<std::mutex> lock(preferenceMutex_);
713    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
714    preferencesInfo.GetAllDoNotDisturbProfiles(userId, profiles);
715    preferencesInfo_ = preferencesInfo;
716}
717
718ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector<NotificationBundleOption> &bundleOption)
719{
720    ANS_LOGD("Called.");
721    std::lock_guard<std::mutex> lock(preferenceMutex_);
722    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
723    ErrCode result = ERR_OK;
724    if (preferncesDB_ == nullptr) {
725        return ERR_ANS_SERVICE_NOT_READY;
726    }
727    if (preferncesDB_->GetAllNotificationEnabledBundles(bundleOption)) {
728        preferencesInfo_ = preferencesInfo;
729    } else {
730        result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
731    }
732    return result;
733}
734
735ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings()
736{
737    ErrCode result = ERR_OK;
738    std::lock_guard<std::mutex> lock(preferenceMutex_);
739    if (!preferncesDB_->RemoveAllDataFromDisturbeDB()) {
740        result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
741    }
742
743    if (result == ERR_OK) {
744        preferencesInfo_ = NotificationPreferencesInfo();
745    }
746    return result;
747}
748
749ErrCode NotificationPreferences::GetDoNotDisturbProfile(
750    int32_t profileId, int32_t userId, sptr<NotificationDoNotDisturbProfile> &profile)
751{
752    if (!CheckDoNotDisturbProfileID(profileId)) {
753        return ERR_ANS_INVALID_PARAM;
754    }
755    std::lock_guard<std::mutex> lock(preferenceMutex_);
756    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
757    if (!preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) {
758        return ERR_ANS_NO_PROFILE_TEMPLATE;
759    }
760    return ERR_OK;
761}
762
763void NotificationPreferences::RemoveDoNotDisturbProfileTrustList(
764    int32_t userId, const sptr<NotificationBundleOption> &bundleOption)
765{
766    if (bundleOption == nullptr) {
767        ANS_LOGE("The bundle option is nullptr.");
768        return;
769    }
770    int32_t uid = bundleOption->GetUid();
771    int32_t appIndex = bundleOption->GetAppIndex();
772    auto bundleName = bundleOption->GetBundleName();
773    ANS_LOGI("Remove %{public}s %{public}d %{public}d.", bundleName.c_str(), uid, appIndex);
774    std::lock_guard<std::mutex> lock(preferenceMutex_);
775    NotificationPreferencesInfo preferencesInfo = preferencesInfo_;
776
777    std::vector<sptr<NotificationDoNotDisturbProfile>> profiles;
778    preferencesInfo.GetAllDoNotDisturbProfiles(userId, profiles);
779    for (auto profile : profiles) {
780        if (profile == nullptr) {
781            ANS_LOGE("The profile is nullptr.");
782            continue;
783        }
784        auto trustList = profile->GetProfileTrustList();
785        for (auto it = trustList.begin(); it != trustList.end(); it++) {
786            if (it->GetUid() == uid) {
787                trustList.erase(it);
788                break;
789            }
790        }
791        profile->SetProfileTrustList(trustList);
792    }
793    preferencesInfo.AddDoNotDisturbProfiles(userId, profiles);
794    if (preferncesDB_ == nullptr) {
795        ANS_LOGE("The prefernces db is nullptr.");
796        return;
797    }
798    if (!preferncesDB_->AddDoNotDisturbProfiles(userId, profiles)) {
799        return;
800    }
801    preferencesInfo_ = preferencesInfo;
802}
803
804ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptr<NotificationBundleOption> &bundleOption,
805    const sptr<NotificationSlot> &slot, NotificationPreferencesInfo &preferencesInfo) const
806{
807    if (slot == nullptr) {
808        ANS_LOGE("Notification slot is nullptr.");
809        return ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST;
810    }
811
812    NotificationPreferencesInfo::BundleInfo bundleInfo;
813    if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) {
814        bundleInfo.SetBundleName(bundleOption->GetBundleName());
815        bundleInfo.SetBundleUid(bundleOption->GetUid());
816        bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption));
817    }
818    bundleInfo.SetSlot(slot);
819    preferencesInfo.SetBundleInfo(bundleInfo);
820
821    return ERR_OK;
822}
823
824ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptr<NotificationBundleOption> &bundleOption,
825    const NotificationConstant::SlotType &slotType, NotificationPreferencesInfo &preferencesInfo) const
826{
827    ErrCode result = ERR_OK;
828    NotificationPreferencesInfo::BundleInfo bundleInfo;
829    if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) {
830        if (bundleInfo.IsExsitSlot(slotType)) {
831            bundleInfo.RemoveSlot(slotType);
832            preferencesInfo.SetBundleInfo(bundleInfo);
833        } else {
834            ANS_LOGE("Notification slot type does not exsited.");
835            result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
836        }
837    } else {
838        ANS_LOGW("Notification bundle does not exsit.");
839        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
840    }
841    return result;
842}
843
844ErrCode NotificationPreferences::CheckSlotForUpdateSlot(const sptr<NotificationBundleOption> &bundleOption,
845    const sptr<NotificationSlot> &slot, NotificationPreferencesInfo &preferencesInfo) const
846{
847    if (slot == nullptr) {
848        ANS_LOGE("Notification slot is nullptr.");
849        return ERR_ANS_INVALID_PARAM;
850    }
851
852    ErrCode result = ERR_OK;
853    NotificationPreferencesInfo::BundleInfo bundleInfo;
854    if (preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) {
855        if (bundleInfo.IsExsitSlot(slot->GetType())) {
856            bundleInfo.SetBundleName(bundleOption->GetBundleName());
857            bundleInfo.SetBundleUid(bundleOption->GetUid());
858            bundleInfo.SetSlot(slot);
859            preferencesInfo.SetBundleInfo(bundleInfo);
860        } else {
861            ANS_LOGE("Notification slot type does not exist.");
862            result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
863        }
864    } else {
865        ANS_LOGW("Notification bundle does not exsit.");
866        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
867    }
868
869    return result;
870}
871
872template <typename T>
873ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo &preferencesInfo,
874    const sptr<NotificationBundleOption> &bundleOption, const BundleType &type, const T &value)
875{
876    ErrCode result = ERR_OK;
877    NotificationPreferencesInfo::BundleInfo bundleInfo;
878    if (!preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) {
879        bundleInfo.SetBundleName(bundleOption->GetBundleName());
880        bundleInfo.SetBundleUid(bundleOption->GetUid());
881        bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption));
882    }
883    result = SaveBundleProperty(bundleInfo, bundleOption, type, value);
884    if (result == ERR_OK) {
885        preferencesInfo.SetBundleInfo(bundleInfo);
886    }
887
888    return result;
889}
890
891template <typename T>
892ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo,
893    const sptr<NotificationBundleOption> &bundleOption, const BundleType &type, const T &value)
894{
895    HaMetaMessage message = HaMetaMessage().BundleName(bundleInfo.GetBundleName());
896    bool storeDBResult = true;
897    switch (type) {
898        case BundleType::BUNDLE_IMPORTANCE_TYPE:
899            bundleInfo.SetImportance(value);
900            storeDBResult = preferncesDB_->PutImportance(bundleInfo, value);
901            break;
902        case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE:
903            bundleInfo.SetBadgeTotalNum(value);
904            storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleInfo, value);
905            break;
906        case BundleType::BUNDLE_SHOW_BADGE_TYPE:
907            bundleInfo.SetIsShowBadge(value);
908            storeDBResult = preferncesDB_->PutShowBadge(bundleInfo, value);
909            break;
910        case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE:
911            bundleInfo.SetEnableNotification(value);
912            storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, value);
913            break;
914        case BundleType::BUNDLE_POPPED_DIALOG_TYPE:
915            ANS_LOGI("Into BUNDLE_POPPED_DIALOG_TYPE:SetHasPoppedDialog.");
916            bundleInfo.SetHasPoppedDialog(value);
917            storeDBResult = preferncesDB_->PutHasPoppedDialog(bundleInfo, value);
918            break;
919        case BundleType::BUNDLE_SLOTFLGS_TYPE:
920            ANS_LOGI("Into BUNDLE_SLOTFLGS_TYPE:SetSlotFlags.");
921            bundleInfo.SetSlotFlags(value);
922            storeDBResult = preferncesDB_->PutSlotFlags(bundleInfo, value);
923            break;
924        default:
925            break;
926    }
927    message.Message("Save:" + std::to_string(static_cast<int32_t>(type)) +
928        " : " + std::to_string(value) + " : " + std::to_string(storeDBResult));
929    NotificationAnalyticsUtil::ReportModifyEvent(message);
930    return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
931}
932
933template <typename T>
934ErrCode NotificationPreferences::GetBundleProperty(
935    const sptr<NotificationBundleOption> &bundleOption, const BundleType &type, T &value)
936{
937    ErrCode result = ERR_OK;
938    NotificationPreferencesInfo::BundleInfo bundleInfo;
939    std::lock_guard<std::mutex> lock(preferenceMutex_);
940    if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) {
941        switch (type) {
942            case BundleType::BUNDLE_IMPORTANCE_TYPE:
943                value = bundleInfo.GetImportance();
944                break;
945            case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE:
946                value = bundleInfo.GetBadgeTotalNum();
947                break;
948            case BundleType::BUNDLE_SHOW_BADGE_TYPE:
949                value = bundleInfo.GetIsShowBadge();
950                break;
951            case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE:
952                value = bundleInfo.GetEnableNotification();
953                break;
954            case BundleType::BUNDLE_POPPED_DIALOG_TYPE:
955                ANS_LOGD("Into BUNDLE_POPPED_DIALOG_TYPE:GetHasPoppedDialog.");
956                value = bundleInfo.GetHasPoppedDialog();
957                break;
958            case BundleType::BUNDLE_SLOTFLGS_TYPE:
959                value = bundleInfo.GetSlotFlags();
960                ANS_LOGD("Into BUNDLE_SLOTFLGS_TYPE:GetSlotFlags.");
961                break;
962            default:
963                result = ERR_ANS_INVALID_PARAM;
964                break;
965        }
966    } else {
967        ANS_LOGW("Notification bundle does not exsit.");
968        result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST;
969    }
970    return result;
971}
972
973std::string NotificationPreferences::GenerateBundleKey(const sptr<NotificationBundleOption> &bundleOption) const
974{
975    return bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid()));
976}
977
978ErrCode NotificationPreferences::GetTemplateSupported(const std::string& templateName, bool &support)
979{
980    if (templateName.length() == 0) {
981        ANS_LOGE("template name is null.");
982        return ERR_ANS_INVALID_PARAM;
983    }
984
985    std::ifstream inFile;
986    inFile.open(DEFAULT_TEMPLATE_PATH.c_str(), std::ios::in);
987    if (!inFile.is_open()) {
988        ANS_LOGE("read template config error.");
989        return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED;
990    }
991
992    nlohmann::json jsonObj;
993    inFile >> jsonObj;
994    if (jsonObj.is_null() || !jsonObj.is_object()) {
995        ANS_LOGE("Invalid JSON object");
996        return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED;
997    }
998    if (jsonObj.is_discarded()) {
999        ANS_LOGE("template json discarded error.");
1000        inFile.close();
1001        return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED;
1002    }
1003
1004    if (jsonObj.contains(templateName)) {
1005        support = true;
1006    }
1007
1008    jsonObj.clear();
1009    inFile.close();
1010    return ERR_OK;
1011}
1012
1013ErrCode NotificationPreferences::SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
1014    const std::string &deviceType, const bool enabled)
1015{
1016    ANS_LOGD("%{public}s", __FUNCTION__);
1017    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
1018        return ERR_ANS_INVALID_PARAM;
1019    }
1020
1021    std::lock_guard<std::mutex> lock(preferenceMutex_);
1022    NotificationPreferencesInfo::BundleInfo bundleInfo;
1023    bundleInfo.SetBundleName(bundleOption->GetBundleName());
1024    bundleInfo.SetBundleUid(bundleOption->GetUid());
1025    bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption));
1026    bool storeDBResult = true;
1027    storeDBResult = preferncesDB_->PutDistributedEnabledForBundle(deviceType, bundleInfo, enabled);
1028    return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
1029}
1030
1031ErrCode NotificationPreferences::IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
1032    const std::string &deviceType, bool &enabled)
1033{
1034    ANS_LOGD("%{public}s", __FUNCTION__);
1035    if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
1036        return ERR_ANS_INVALID_PARAM;
1037    }
1038
1039    std::lock_guard<std::mutex> lock(preferenceMutex_);
1040    NotificationPreferencesInfo::BundleInfo bundleInfo;
1041    bundleInfo.SetBundleName(bundleOption->GetBundleName());
1042    bundleInfo.SetBundleUid(bundleOption->GetUid());
1043    bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption));
1044    bool storeDBResult = true;
1045    storeDBResult = preferncesDB_->GetDistributedEnabledForBundle(deviceType, bundleInfo, enabled);
1046    return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
1047}
1048
1049ErrCode NotificationPreferences::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled)
1050{
1051    ANS_LOGD("%{public}s", __FUNCTION__);
1052    if (deviceType.empty()) {
1053        return ERR_ANS_INVALID_PARAM;
1054    }
1055
1056    std::lock_guard<std::mutex> lock(preferenceMutex_);
1057    bool storeDBResult = true;
1058    storeDBResult = preferncesDB_->SetSmartReminderEnabled(deviceType, enabled);
1059    return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
1060}
1061
1062ErrCode NotificationPreferences::IsSmartReminderEnabled(const std::string &deviceType, bool &enabled)
1063{
1064    ANS_LOGD("%{public}s", __FUNCTION__);
1065    if (deviceType.empty()) {
1066        return ERR_ANS_INVALID_PARAM;
1067    }
1068
1069    std::lock_guard<std::mutex> lock(preferenceMutex_);
1070    bool storeDBResult = true;
1071    storeDBResult = preferncesDB_->IsSmartReminderEnabled(deviceType, enabled);
1072    return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED;
1073}
1074
1075void NotificationPreferences::InitSettingFromDisturbDB(int32_t userId)
1076{
1077    ANS_LOGI("%{public}s userId is %{public}d", __FUNCTION__, userId);
1078    std::lock_guard<std::mutex> lock(preferenceMutex_);
1079    if (preferncesDB_ != nullptr) {
1080        preferncesDB_->ParseFromDisturbeDB(preferencesInfo_, userId);
1081    }
1082}
1083
1084void NotificationPreferences::RemoveSettings(int32_t userId)
1085{
1086    ANS_LOGD("%{public}s", __FUNCTION__);
1087
1088    {
1089        std::lock_guard<std::mutex> lock(preferenceMutex_);
1090        preferencesInfo_.RemoveNotificationEnable(userId);
1091        preferencesInfo_.RemoveDoNotDisturbDate(userId);
1092    }
1093
1094    if (preferncesDB_ != nullptr) {
1095        preferncesDB_->RemoveNotificationEnable(userId);
1096        preferncesDB_->RemoveDoNotDisturbDate(userId);
1097        preferncesDB_->DropUserTable(userId);
1098    }
1099}
1100
1101bool NotificationPreferences::CheckApiCompatibility(const sptr<NotificationBundleOption> &bundleOption) const
1102{
1103    ANS_LOGD("%{public}s", __FUNCTION__);
1104    std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1105    if (bundleManager == nullptr) {
1106        return false;
1107    }
1108    return bundleManager->CheckApiCompatibility(bundleOption);
1109}
1110
1111void NotificationPreferences::RemoveAnsBundleDbInfo(const sptr<NotificationBundleOption> &bundleOption)
1112{
1113    ANS_LOGE("%{public}s", __FUNCTION__);
1114    if (preferncesDB_ != nullptr && bundleOption != nullptr) {
1115        preferncesDB_->RemoveAnsBundleDbInfo(bundleOption->GetBundleName(), bundleOption->GetUid());
1116    }
1117}
1118
1119void NotificationPreferences::RemoveEnabledDbByBundle(const sptr<NotificationBundleOption> &bundleOption)
1120{
1121    ANS_LOGE("%{public}s", __FUNCTION__);
1122    if (preferncesDB_ != nullptr && bundleOption != nullptr) {
1123        std::lock_guard<std::mutex> lock(preferenceMutex_);
1124        preferncesDB_->RemoveEnabledDbByBundleName(bundleOption->GetBundleName(), bundleOption->GetUid());
1125    }
1126}
1127
1128bool NotificationPreferences::GetBundleSoundPermission(bool &allPackage, std::set<std::string> &bundleNames)
1129{
1130    ANS_LOGD("%{public}s", __FUNCTION__);
1131    std::string value = "";
1132    int32_t userId = -1;
1133    OsAccountManagerHelper::GetInstance().GetCurrentCallingUserId(userId);
1134    if (GetKvFromDb("RING_TRUSTLIST_PKG", value, userId) != ERR_OK) {
1135        ANS_LOGD("Get bundle sound permission failed.");
1136        return false;
1137    }
1138
1139    ANS_LOGD("The bundle permission is :%{public}s.", value.c_str());
1140    nlohmann::json jsonPermission = nlohmann::json::parse(value, nullptr, false);
1141    if (jsonPermission.is_null() || jsonPermission.empty()) {
1142        ANS_LOGE("Invalid JSON object");
1143        return false;
1144    }
1145    if (jsonPermission.is_discarded() || !jsonPermission.is_array()) {
1146        ANS_LOGE("Parse bundle permission failed due to data is discarded or not array");
1147        return false;
1148    }
1149
1150    for (const auto &item : jsonPermission) {
1151        bundleNames.insert(item);
1152        if (item == "ALL_PKG") {
1153            allPackage = true;
1154        }
1155    }
1156    return true;
1157}
1158
1159int32_t NotificationPreferences::SetKvToDb(
1160    const std::string &key, const std::string &value, const int32_t &userId)
1161{
1162    if (preferncesDB_ == nullptr) {
1163        return ERR_ANS_SERVICE_NOT_READY;
1164    }
1165    return preferncesDB_->SetKvToDb(key, value, userId);
1166}
1167
1168int32_t NotificationPreferences::SetByteToDb(
1169    const std::string &key, const std::vector<uint8_t> &value, const int32_t &userId)
1170{
1171    if (preferncesDB_ == nullptr) {
1172        return ERR_ANS_SERVICE_NOT_READY;
1173    }
1174    return preferncesDB_->SetByteToDb(key, value, userId);
1175}
1176
1177int32_t NotificationPreferences::GetKvFromDb(
1178    const std::string &key, std::string &value, const int32_t &userId)
1179{
1180    if (preferncesDB_ == nullptr) {
1181        return ERR_ANS_SERVICE_NOT_READY;
1182    }
1183    return preferncesDB_->GetKvFromDb(key, value, userId);
1184}
1185
1186int32_t NotificationPreferences::GetByteFromDb(
1187    const std::string &key, std::vector<uint8_t> &value, const int32_t &userId)
1188{
1189    if (preferncesDB_ == nullptr) {
1190        return ERR_ANS_SERVICE_NOT_READY;
1191    }
1192    return preferncesDB_->GetByteFromDb(key, value, userId);
1193}
1194
1195int32_t NotificationPreferences::GetBatchKvsFromDb(
1196    const std::string &key, std::unordered_map<std::string, std::string> &values, const int32_t &userId)
1197{
1198    if (preferncesDB_ == nullptr) {
1199        return ERR_ANS_SERVICE_NOT_READY;
1200    }
1201    return preferncesDB_->GetBatchKvsFromDb(key, values, userId);
1202}
1203
1204int32_t NotificationPreferences::DeleteKvFromDb(const std::string &key, const int32_t &userId)
1205{
1206    if (preferncesDB_ == nullptr) {
1207        return ERR_ANS_SERVICE_NOT_READY;
1208    }
1209    return preferncesDB_->DeleteKvFromDb(key, userId);
1210}
1211
1212bool NotificationPreferences::IsAgentRelationship(const std::string &agentBundleName,
1213    const std::string &sourceBundleName)
1214{
1215    if (AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
1216        ANS_LOGD("Client has agent permission.");
1217        return true;
1218    }
1219
1220    if (preferncesDB_ == nullptr) {
1221        ANS_LOGD("perferencdDb is null.");
1222        return false;
1223    }
1224
1225    return preferncesDB_->IsAgentRelationship(agentBundleName, sourceBundleName);
1226}
1227
1228std::string NotificationPreferences::GetAdditionalConfig(const std::string &key)
1229{
1230    if (preferncesDB_ == nullptr) {
1231        return "";
1232    }
1233    return preferncesDB_->GetAdditionalConfig(key);
1234}
1235}  // namespace Notification
1236}  // namespace OHOS
1237