File indexing completed on 2024-12-15 03:45:00

0001 /*
0002     SPDX-FileCopyrightText: 2017 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: MIT
0005 */
0006 
0007 #include "handshakejob.h"
0008 
0009 #include <rest/restapi.h>
0010 #include <rest/restclient.h>
0011 
0012 #include <QDebug>
0013 #include <QJsonDocument>
0014 #include <QJsonObject>
0015 #include <QNetworkReply>
0016 
0017 using namespace KUserFeedback::Console;
0018 
0019 HandshakeJob::HandshakeJob(RESTClient* restClient, QObject* parent)
0020     : Job(parent)
0021     , m_restClient(restClient)
0022 {
0023     auto reply = RESTApi::checkSchema(restClient);
0024     connect(reply, &QNetworkReply::finished, this, [this, reply]() {
0025         if (reply->error() == QNetworkReply::NoError) {
0026             Q_EMIT info(tr("Connected to %1.").arg(m_restClient->serverInfo().url().toString()));
0027             processResponse(reply);
0028         } else {
0029             emitError(reply->errorString());
0030         }
0031         reply->deleteLater();
0032     });
0033     connect(reply, &QNetworkReply::redirected, this, [this](const auto &url) {
0034         auto s = m_restClient->serverInfo();
0035         auto u = url;
0036         auto p = u.path();
0037         p.remove(QLatin1String("analytics/check_schema"));
0038         u.setPath(p);
0039         s.setUrl(u);
0040         m_restClient->setServerInfo(s);
0041     });
0042 }
0043 
0044 HandshakeJob::~HandshakeJob()
0045 {
0046 }
0047 
0048 void HandshakeJob::processResponse(QNetworkReply* reply)
0049 {
0050     const auto doc = QJsonDocument::fromJson(reply->readAll());
0051     const auto obj = doc.object();
0052 
0053     const auto protoVer = obj.value(QLatin1String("protocolVersion")).toInt();
0054     if (protoVer != 2) {
0055         emitError(tr("Incompatible protocol: %1.").arg(protoVer));
0056         return;
0057     }
0058 
0059     const auto prevSchema = obj.value(QLatin1String("previousSchemaVersion")).toInt();
0060     const auto curSchema = obj.value(QLatin1String("currentSchemaVersion")).toInt();
0061     if (prevSchema != curSchema)
0062         Q_EMIT info(tr("Updated database schema from version %1 to %2.").arg(prevSchema).arg(curSchema));
0063 
0064     m_restClient->setConnected(true);
0065     emitFinished();
0066 }
0067 
0068 #include "moc_handshakejob.cpp"