about summary refs log tree commit diff stats
path: root/src/invapi.cpp
blob: f53c06b6ac77342c17de7164bec0b3ef7cb87c9f (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <string>
#include <vector>
#include <iostream>

#include <cpr/cpr.h>
#include <nlohmann/json.hpp>

#include "invapi.hpp"
#include "video.hpp"
#include "sqliteinterface.hpp"

using namespace std;
using json = nlohmann::json;

InvidiousApi::InvidiousApi(const string& url) {

    instanceUrl = url;
    
}

vector<string> InvidiousApi::getInstances() {

    vector<string> result;
    cpr::Response r = cpr::Get(cpr::Url{"https://api.invidious.io/instances.json"}, 
        cpr::Parameters{{"sort_by", "health"}},
        cpr::Timeout{5000});

    if (r.status_code > 299) {
        
        cerr << "invidious.io returned error code " << r.status_code << "!!" << endl;
        throw runtime_error("bad response");
    }

    json j = json::parse(r.text);
    for ( json i: j ) {
        if ( i.at(1).at("api") != json::value_t::null && i.at(1).at("api")) {

            result.push_back( i[1]["uri"] );
        }
    }
    return result;
}

void InvidiousApi::saveInstancesToDb(SqliteInterface& sqldb) {

    cpr::Response r = cpr::Get(cpr::Url{"https://api.invidious.io/instances.json"}, 
        cpr::Parameters{{"sort_by", "health"}}, 
        cpr::Timeout{5000});

    if (r.status_code > 299) {
        
        cerr << "invidious.io returned error code " << r.status_code << "!!" << endl;
        throw runtime_error("bad response");
    }

    json j = json::parse(r.text);
    for ( json i: j ) {
        if ( i.at(1).at("api") != json::value_t::null && i.at(1).at("api") 
            && i.at(1).at("monitor") != json::value_t::null
            && i.at(1).at("monitor").at("30dRatio") != json::value_t::null
            && i.at(1).at("monitor").at("30dRatio").at("ratio") != json::value_t::null
            && i.at(1).at("uri") != json::value_t::null
            && i.at(1).at("region") != json::value_t::null) {

                string uri = i[1]["uri"];
                string health = i[1]["monitor"]["30dRatio"]["ratio"];
                string region = i[1]["region"];
                sqldb.saveInstance(uri.c_str(), stof(health), region.c_str());
        }
    }    
}

void InvidiousApi::test() {

    session.SetUrl(cpr::Url{instanceUrl});
    session.SetParameters(cpr::Parameters{{"hello", "world"}});
    cpr::Response new_r = session.Get();

    cout << new_r.url << endl;
    cout << new_r.text << endl;
}

std::string InvidiousApi::getInstance() {

    return instanceUrl;
}

void InvidiousApi::setInstance(const std::string& newUrl) {

    instanceUrl = newUrl;
}