-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.cpp
66 lines (55 loc) · 1.58 KB
/
api.cpp
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
#include "api.h"
#include <QtNetwork/QNetworkAccessManager>
#include <QUrl>
#include <QtNetwork/QNetworkRequest>
#include <QString>
#include <QEventLoop>
#include <memory>
#include <iostream>
#include "mainwindow.h"
using namespace std;
shared_ptr<API> API::api_ = std::shared_ptr<API>();
std::ostream& operator<< (ostream& os, const std::weak_ptr<API>& m) {
auto access = m.lock();
if(access){
return os << "adr: " << access->adress_.toStdString() << " key: " << access->api_key_.toStdString() << " available: " << access->isAvailable();
}
return os;
}
API::API(QString adress, QString api_key)
: adress_(adress), api_key_(api_key)
{
}
QString API::url()
{
return QString(adress_+ "/api/" + api_key_);
}
bool API::isAvailable() const
{
QEventLoop loop;
QNetworkAccessManager *manager = new QNetworkAccessManager();
bool success = false;
MainWindow::connect(
manager,
&QNetworkAccessManager::finished,
[&success, &loop](QNetworkReply* reply) mutable {
success = !reply->readAll().trimmed().isEmpty();
loop.quit();
}
);
manager->get(QNetworkRequest(QUrl(adress_+ "/api/" + api_key_)));
loop.exec();
manager->deleteLater();
return success;
}
weak_ptr<API> API::get() {
if(API::api_) return weak_ptr<API> (API::api_);
return weak_ptr<API>();
}
weak_ptr<API> API::api(QString adress, QString api_key) {
API::api_ = make_shared<API>(API(adress, api_key));
if(!API::api_->isAvailable()){
API::api_ = shared_ptr<API> ();
}
return weak_ptr<API> (API::api_);
}