about summary refs log tree commit diff stats
path: root/src/YtdlpWrapper.cpp
blob: cabe4737dca4b70359630e610a7b373990b06589 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "video.hpp"
#include "YtdlpWrapper.hpp"

using json = nlohmann::json;
namespace py = pybind11;
using namespace py::literals;

std::string pyDictToJsonString(const py::dict& dict) {

    pybind11::object json = py::module::import("json");
    return json.attr("dumps")(dict).cast<std::string>();
}

py::object YtdlpWrapper::get_ytdl() {

    // pybind11::object ytdl = pybind11::none();     
    // if (ytdl.is_none()) {
    //     ytdl = py::module::import("yt_dlp");
    // }

    return py::module::import("yt_dlp");
}

json YtdlpWrapper::getJsonSearch(const std::string& searchTerm, int limit) {

    pybind11::scoped_interpreter guard{};
    py::dict info = get_ytdl()
        .attr("YoutubeDL")(py::dict("ignoreerrors"_a=py::bool_(true)))
        .attr("extract_info")("ytsearch"+std::to_string(limit)+":"+searchTerm, "download"_a=py::bool_(false));
    return json::parse(pyDictToJsonString(info));
}

std::vector<Video::video> YtdlpWrapper::searchVideos(const std::string& searchTerm, int limit) {

    pybind11::scoped_interpreter guard{};
    std::vector<Video::video> resp;

    json info = json::parse(pyDictToJsonString(
        get_ytdl().attr("YoutubeDL")(py::dict("ignoreerrors"_a=py::bool_(true)))
        .attr("extract_info")("ytsearch"+std::to_string(limit)+":"+searchTerm, "download"_a=py::bool_(false))
    ));

    for (json i: info.at("entries")) {
        Video::video entry = i.get<Video::video>();

        resp.push_back(entry);
    }

    return resp;
}


Video::video YtdlpWrapper::getVideoByUrl(const std::string& url) {

    pybind11::scoped_interpreter guard{};
    json info = json::parse(pyDictToJsonString(
        get_ytdl().attr("YoutubeDL")(py::dict("ignoreerrors"_a=py::bool_(true), "noplaylist"_a=py::bool_(true)))
        .attr("extract_info")(url, "download"_a=py::bool_(false))
    ));
    
    return info.get<Video::video>();
}