aboutsummaryrefslogtreecommitdiff
path: root/jobs/basejob.cpp
blob: 074a262916a992222536b6b4b9abcbc1fb226433 (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/******************************************************************************
 * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "basejob.h"

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtCore/QTimer>

#include "../connectiondata.h"

using namespace QMatrixClient;

class BaseJob::Private
{
    public:
        Private(ConnectionData* c, JobHttpType t, bool nt)
            : connection(c), reply(nullptr), type(t), needsToken(nt) {}
        
        ConnectionData* connection;
        QNetworkReply* reply;
        JobHttpType type;
        bool needsToken;
};

BaseJob::BaseJob(ConnectionData* connection, JobHttpType type, bool needsToken)
    : d(new Private(connection, type, needsToken))
{
    // Work around KJob inability to separate success and failure signals
    connect(this, &BaseJob::result, [this]() {
        if (error() == NoError)
            emit success(this);
        else
            emit failure(this);
    });
}

BaseJob::~BaseJob()
{
    if( d->reply )
    {
        if( d->reply->isRunning() )
            d->reply->abort();
        d->reply->deleteLater();
    }
    delete d;
}

ConnectionData* BaseJob::connection() const
{
    return d->connection;
}

QJsonObject BaseJob::data()
{
    return QJsonObject();
}

QUrlQuery BaseJob::query()
{
    return QUrlQuery();
}

void BaseJob::parseJson(const QJsonDocument& data)
{
}

void BaseJob::start()
{
    QUrl url = d->connection->baseUrl();
    url.setPath( url.path() + "/" + apiPath() );
    QUrlQuery query = this->query();
    if( d->needsToken )
        query.addQueryItem("access_token", connection()->token());
    url.setQuery(query);
    QNetworkRequest req = QNetworkRequest(url);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    req.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    req.setMaximumRedirectsAllowed(10);
#endif
    QJsonDocument data = QJsonDocument(this->data());
    switch( d->type )
    {
        case JobHttpType::GetJob:
            d->reply = d->connection->nam()->get(req);
            break;
        case JobHttpType::PostJob:
            d->reply = d->connection->nam()->post(req, data.toJson());
            break;
        case JobHttpType::PutJob:
            d->reply = d->connection->nam()->put(req, data.toJson());
            break;
    }
    connect( d->reply, &QNetworkReply::sslErrors, this, &BaseJob::sslErrors );
    connect( d->reply, &QNetworkReply::finished, this, &BaseJob::gotReply );
    QTimer::singleShot( 120*1000, this, SLOT(timeout()) );
//     connect( d->reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
//              this, &BaseJob::networkError ); // http://doc.qt.io/qt-5/qnetworkreply.html#error-1
}

void BaseJob::fail(int errorCode, QString errorString)
{
    setError( errorCode );
    setErrorText( errorString );
    if( d->reply->isRunning() )
        d->reply->abort();
    qWarning() << this << "failed:" << errorString;
    emitResult();
}

QNetworkReply* BaseJob::networkReply() const
{
    return d->reply;
}

// void BaseJob::networkError(QNetworkReply::NetworkError code)
// {
//     fail( KJob::UserDefinedError+1, d->reply->errorString() );
// }

void BaseJob::gotReply()
{
    if( d->reply->error() != QNetworkReply::NoError )
    {
        qDebug() << "NetworkError:" << d->reply->error();
        fail( NetworkError, d->reply->errorString() );
        return;
    }
    QJsonParseError error;
    QJsonDocument data = QJsonDocument::fromJson(d->reply->readAll(), &error);
    if( error.error != QJsonParseError::NoError )
    {
        fail( JsonParseError, error.errorString() );
        return;
    }
    parseJson(data);
}

void BaseJob::timeout()
{
    qDebug() << "Timeout!";
    fail( TimeoutError, "The job has timed out" );
}

void BaseJob::sslErrors(const QList<QSslError>& errors)
{
    foreach (const QSslError &error, errors) {
        qWarning() << "SSL ERROR" << error.errorString();
    }
    d->reply->ignoreSslErrors(); // TODO: insecure! should prompt user first
}