1/*
2 * Copyright (c) 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 <dlfcn.h>
17
18#include "base/log/log_wrapper.h"
19#include "base/network/download_manager.h"
20
21namespace OHOS::Ace {
22using CreateDownloadManagerFunc = DownloadManager* (*)();
23std::unique_ptr<DownloadManager> DownloadManager::instance_ = nullptr;
24std::mutex DownloadManager::mutex_;
25constexpr char CREATE_DOWNLOAD_MANAGER_FUNC[] = "OHOS_ACE_CreateDownloadManager";
26constexpr char ACE_NET_WORK_NAME[] = "libace_network.z.so";
27
28DownloadManager* CreateDownloadManager()
29{
30    void* handle = dlopen(ACE_NET_WORK_NAME, RTLD_LAZY | RTLD_LOCAL);
31    if (handle == nullptr) {
32        TAG_LOGW(AceLogTag::ACE_DOWNLOAD_MANAGER, "load libace_network failed");
33        return nullptr;
34    }
35
36    auto entry = reinterpret_cast<CreateDownloadManagerFunc>(dlsym(handle, CREATE_DOWNLOAD_MANAGER_FUNC));
37    if (entry == nullptr) {
38        dlclose(handle);
39        return nullptr;
40    }
41
42    auto* manager = entry();
43    return manager;
44}
45
46DownloadManager* DownloadManager::GetInstance()
47{
48    TAG_LOGI(AceLogTag::ACE_DOWNLOAD_MANAGER, "DownloadManager GetInstance");
49    if (!instance_) {
50        std::lock_guard<std::mutex> lock(mutex_);
51        if (!instance_) {
52            auto* manager = CreateDownloadManager();
53            instance_.reset(manager);
54        }
55    }
56    return instance_.get();
57}
58} // namespace OHOS::Ace