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 #define MLOG_TAG "BundleManager"
17
18 #include "medialibrary_bundle_manager.h"
19
20 #include <memory>
21 #include <mutex>
22
23 #include "ipc_skeleton.h"
24 #include "permission_utils.h"
25
26 using namespace std;
27
28 namespace OHOS {
29 namespace Media {
30
31 shared_ptr<MediaLibraryBundleManager> MediaLibraryBundleManager::instance_ = nullptr;
32 mutex MediaLibraryBundleManager::mutex_;
GetInstance()33 shared_ptr<MediaLibraryBundleManager> MediaLibraryBundleManager::GetInstance()
34 {
35 if (instance_ == nullptr) {
36 lock_guard<mutex> lock(mutex_);
37 if (instance_ == nullptr) {
38 instance_ = make_shared<MediaLibraryBundleManager>();
39 }
40 }
41 return instance_;
42 }
43
GetBundleNameByUID(const int32_t uid,string & bundleName)44 void MediaLibraryBundleManager::GetBundleNameByUID(const int32_t uid, string &bundleName)
45 {
46 PermissionUtils::GetClientBundle(uid, bundleName);
47 if (bundleName.empty()) {
48 return;
49 }
50
51 auto it = cacheMap_.find(uid);
52 if (it != cacheMap_.end()) {
53 cacheList_.erase(it->second);
54 }
55 cacheList_.push_front(make_pair(uid, bundleName));
56 cacheMap_[uid] = cacheList_.begin();
57 if (cacheMap_.size() > CAPACITY) {
58 int32_t deleteKey = cacheList_.back().first;
59 cacheMap_.erase(deleteKey);
60 cacheList_.pop_back();
61 }
62 }
63
64 /**
65 * if it is called by SA, bundlename is null. we should not log everytime
66 */
GetClientBundleName()67 std::string MediaLibraryBundleManager::GetClientBundleName()
68 {
69 lock_guard<mutex> lock(uninstallMutex_);
70 int32_t uid = IPCSkeleton::GetCallingUid();
71 auto iter = cacheMap_.find(uid);
72 if (iter == cacheMap_.end()) {
73 string bundleName;
74 GetBundleNameByUID(uid, bundleName);
75 return bundleName;
76 }
77 cacheList_.splice(cacheList_.begin(), cacheList_, iter->second);
78 return iter->second->second;
79 }
80
Clear()81 void MediaLibraryBundleManager::Clear()
82 {
83 lock_guard<mutex> lock(uninstallMutex_);
84 cacheList_.clear();
85 cacheMap_.clear();
86 }
87 } // Media
88 } // OHOS
89