| 1 | #include "IFetcher.h" |
| 2 | |
| 3 | #include <QNetworkAccessManager> |
| 4 | #include <QNetworkReply> |
| 5 | #include <QNetworkRequest> |
| 6 | #include <QJsonDocument> |
| 7 | |
| 8 | #include <QLogger.h> |
| 9 | |
| 10 | #include <QUrlQuery> |
| 11 | |
| 12 | using namespace QLogger; |
| 13 | |
| 14 | namespace Jenkins |
| 15 | { |
| 16 | IFetcher::IFetcher(const Config &config, QObject *parent) |
| 17 | : QObject(parent) |
| 18 | , mConfig(config) |
| 19 | { |
| 20 | } |
| 21 | |
| 22 | IFetcher::~IFetcher() |
| 23 | { |
| 24 | QLog_Debug("Jenkins" , "Destroying repo fetcher object." ); |
| 25 | } |
| 26 | |
| 27 | void IFetcher::get(const QString &urlStr, bool customUrl) |
| 28 | { |
| 29 | const auto apiUrl = urlStr.endsWith("api/json" ) || customUrl ? urlStr : urlStr + "api/json" ; |
| 30 | |
| 31 | QUrl url(apiUrl); |
| 32 | |
| 33 | if (!customUrl) |
| 34 | { |
| 35 | QUrlQuery query; |
| 36 | query.addQueryItem("tree" , "views[*[*]]" ); |
| 37 | url.setQuery(query); |
| 38 | } |
| 39 | |
| 40 | QNetworkRequest request(url); |
| 41 | |
| 42 | if (!mConfig.user.isEmpty() && !mConfig.token.isEmpty()) |
| 43 | { |
| 44 | const auto data = QString("%1:%2" ).arg(mConfig.user, mConfig.token).toLocal8Bit().toBase64(); |
| 45 | request.setRawHeader("Authorization" , QString(QString::fromUtf8("Basic " ) + data).toLocal8Bit()); |
| 46 | } |
| 47 | |
| 48 | const auto reply = mConfig.accessManager->get(request); |
| 49 | connect(reply, &QNetworkReply::finished, this, &IFetcher::processReply); |
| 50 | } |
| 51 | |
| 52 | void IFetcher::processReply() |
| 53 | { |
| 54 | const auto reply = qobject_cast<QNetworkReply *>(sender()); |
| 55 | const auto data = reply->readAll(); |
| 56 | |
| 57 | if (data.isEmpty()) |
| 58 | QLog_Warning("Jenkins" , QString("Reply from {%1} is empty." ).arg(reply->url().toString())); |
| 59 | |
| 60 | const auto json = QJsonDocument::fromJson(data); |
| 61 | |
| 62 | if (json.isNull()) |
| 63 | { |
| 64 | QLog_Error("Jenkins" , QString("Data from {%1} is not a valid JSON" ).arg(reply->url().toString())); |
| 65 | QLog_Trace("Jenkins" , QString("Data received:\n%1" ).arg(QString::fromUtf8(data))); |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | processData(json); |
| 70 | } |
| 71 | } |
| 72 | |