1 /*
2  * Copyright (c) 2023 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 "service_db_helper.h"
17 #include "intell_voice_log.h"
18 
19 using namespace OHOS::DistributedKv;
20 #define LOG_TAG "ServiceDbHelper"
21 
22 namespace OHOS {
23 namespace IntellVoiceEngine {
ServiceDbHelper(const std::string & inAppId,const std::string & inStoreId)24 ServiceDbHelper::ServiceDbHelper(const std::string &inAppId, const std::string &inStoreId)
25 {
26     AppId appId = { inAppId };
27     StoreId storeId = { inStoreId };
28 
29     Options options = {
30         .createIfMissing = true,
31         .encrypt = false,
32         .autoSync = false,
33         .securityLevel = SecurityLevel::S1,
34         .area = Area::EL1,
35         .kvStoreType = KvStoreType::SINGLE_VERSION,
36         .baseDir = "/data/service/el1/public/database/" + appId.appId
37     };
38 
39     INTELL_VOICE_LOG_INFO("inAppId:%{public}s, inStoreId:%{public}s, options.baseDir:%{public}s",
40         inAppId.c_str(), appId.appId.c_str(), options.baseDir.c_str());
41 
42     DistributedKvDataManager manager;
43     Status status = manager.GetSingleKvStore(options, appId, storeId, kvStore_);
44     if (status != Status::SUCCESS) {
45         INTELL_VOICE_LOG_INFO("GetSingleKvStore failed, status: %{public}d.", status);
46     } else {
47         INTELL_VOICE_LOG_INFO("GetSingleKvStore success");
48     }
49 }
50 
~ServiceDbHelper()51 ServiceDbHelper::~ServiceDbHelper()
52 {
53     kvStore_ = nullptr;
54 }
55 
SetValue(const std::string & key,const std::string & value)56 void ServiceDbHelper::SetValue(const std::string &key, const std::string &value)
57 {
58     if (kvStore_ == nullptr) {
59         INTELL_VOICE_LOG_ERROR("kvStore_ is nullptr");
60         return;
61     }
62     kvStore_->Put(key, value);
63 }
64 
GetValue(const std::string & key)65 std::string ServiceDbHelper::GetValue(const std::string &key)
66 {
67     if (kvStore_ == nullptr) {
68         INTELL_VOICE_LOG_ERROR("kvStore_ is nullptr");
69         return "";
70     }
71     Value value;
72     kvStore_->Get(key, value);
73     return value.ToString();
74 }
75 
Delete(const std::string & key)76 void ServiceDbHelper::Delete(const std::string &key)
77 {
78     if (kvStore_ == nullptr) {
79         INTELL_VOICE_LOG_ERROR("kvStore_ is nullptr");
80     }
81     kvStore_->Delete(key);
82 }
83 }
84 }
85