aboutsummaryrefslogtreecommitdiff
path: root/lib/jobs/basejob.h
blob: c34ba3c39807b91e1d9fd179c7b1d03bcfd31ed6 (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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/******************************************************************************
 * 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
 */

#pragma once

#include "../logging.h"
#include "requestdata.h"

#include <QtCore/QObject>
#include <QtCore/QUrlQuery>
#include <QtCore/QJsonDocument>

class QNetworkReply;
class QSslError;

namespace QMatrixClient
{
    class ConnectionData;

    enum class HttpVerb { Get, Put, Post, Delete };

    struct JobTimeoutConfig
    {
        int jobTimeout;
        int nextRetryInterval;
    };

    class BaseJob: public QObject
    {
            Q_OBJECT
            Q_PROPERTY(QUrl requestUrl READ requestUrl CONSTANT)
            Q_PROPERTY(int maxRetries READ maxRetries WRITE setMaxRetries)
        public:
            /* Just in case, the values are compatible with KJob
             * (which BaseJob used to inherit from). */
            enum StatusCode { NoError = 0 // To be compatible with Qt conventions
                , Success = 0
                , Pending = 1
                , WarningLevel = 20
                , UnexpectedResponseTypeWarning = 21
                , Abandoned = 50 //< A very brief period between abandoning and object deletion
                , ErrorLevel = 100 //< Errors have codes starting from this
                , NetworkError = 100
                , JsonParseError // TODO: Merge into IncorrectResponseError
                , TimeoutError
                , ContentAccessError
                , NotFoundError
                , IncorrectRequestError
                , IncorrectResponseError
                , TooManyRequestsError
                , RequestNotImplementedError
                , NetworkAuthRequiredError
                , UserConsentRequiredError
                , UserDefinedError = 200
            };

            /**
             * A simple wrapper around QUrlQuery that allows its creation from
             * a list of string pairs
             */
            class Query : public QUrlQuery
            {
                public:
                    using QUrlQuery::QUrlQuery;
                    Query() = default;
                    Query(const std::initializer_list< QPair<QString, QString> >& l)
                    {
                        setQueryItems(l);
                    }
            };

            using Data = RequestData;

            /**
             * This structure stores the status of a server call job. The status consists
             * of a code, that is described (but not delimited) by the respective enum,
             * and a freeform message.
             *
             * To extend the list of error codes, define an (anonymous) enum
             * along the lines of StatusCode, with additional values
             * starting at UserDefinedError
             */
            class Status
            {
                public:
                    Status(StatusCode c) : code(c) { }
                    Status(int c, QString m) : code(c), message(std::move(m)) { }

                    bool good() const { return code < ErrorLevel; }
                    friend QDebug operator<<(QDebug dbg, const Status& s)
                    {
                        QDebugStateSaver _s(dbg);
                        return dbg.noquote().nospace()
                                << s.code << ": " << s.message;
                    }

                    bool operator==(const Status& other) const
                    {
                        return code == other.code && message == other.message;
                    }
                    bool operator!=(const Status& other) const
                    {
                        return !operator==(other);
                    }

                    int code;
                    QString message;
            };

            using duration_t = int; // milliseconds

        public:
            BaseJob(HttpVerb verb, const QString& name, const QString& endpoint,
                    bool needsToken = true);
            BaseJob(HttpVerb verb, const QString& name, const QString& endpoint,
                    const Query& query, Data&& data = {},
                    bool needsToken = true);

            QUrl requestUrl() const;
            bool isBackground() const;

            /** Current status of the job */
            Status status() const;
            /** Short human-friendly message on the job status */
            QString statusCaption() const;
            /** Raw response body as received from the server */
            QByteArray rawData() const;

            /** Error (more generally, status) code
             * Equivalent to status().code
             * \sa status
             */
            int error() const;
            /** Error-specific message, as returned by the server */
            virtual QString errorString() const;
            /** A URL to help/clarify the error, if provided by the server */
            QUrl errorUrl() const;

            int maxRetries() const;
            void setMaxRetries(int newMaxRetries);

            Q_INVOKABLE duration_t getCurrentTimeout() const;
            Q_INVOKABLE duration_t getNextRetryInterval() const;
            Q_INVOKABLE duration_t millisToRetry() const;

            friend QDebug operator<<(QDebug dbg, const BaseJob* j)
            {
                return dbg << j->objectName();
            }

        public slots:
            void start(const ConnectionData* connData,
                       bool inBackground = false);

            /**
             * Abandons the result of this job, arrived or unarrived.
             *
             * This aborts waiting for a reply from the server (if there was
             * any pending) and deletes the job object. No result signals
             * (result, success, failure) are emitted.
             */
            void abandon();

        signals:
            /** The job is about to send a network request */
            void aboutToStart();

            /** The job has sent a network request */
            void started();

            /** The job has changed its status */
            void statusChanged(Status newStatus);

            /**
             * The previous network request has failed; the next attempt will
             * be done in the specified time
             * @param nextAttempt the 1-based number of attempt (will always be more than 1)
             * @param inMilliseconds the interval after which the next attempt will be taken
             */
            void retryScheduled(int nextAttempt, int inMilliseconds);

            /**
             * Emitted when the job is finished, in any case. It is used to notify
             * observers that the job is terminated and that progress can be hidden.
             *
             * This should not be emitted directly by subclasses;
             * use finishJob() instead.
             *
             * In general, to be notified of a job's completion, client code
             * should connect to result(), success(), or failure()
             * rather than finished(). However if you store a list of jobs
             * and need to track their lifecycle, then you should connect to this
             * instead of result(), to avoid dangling pointers in your list.
             *
             * @param job the job that emitted this signal
             *
             * @see result, success, failure
             */
            void finished(BaseJob* job);

            /**
             * Emitted when the job is finished (except when abandoned).
             *
             * Use error() to know if the job was finished with error.
             *
             * @param job the job that emitted this signal
             *
             * @see success, failure
             */
            void result(BaseJob* job);

            /**
             * Emitted together with result() in case there's no error.
             *
             * @see result, failure
             */
            void success(BaseJob*);

            /**
             * Emitted together with result() if there's an error.
             * Similar to result(), this won't be emitted in case of abandon().
             *
             * @see result, success
             */
            void failure(BaseJob*);

            void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
            void uploadProgress(qint64 bytesSent, qint64 bytesTotal);

        protected:
            using headers_t = QHash<QByteArray, QByteArray>;

            const QString& apiEndpoint() const;
            void setApiEndpoint(const QString& apiEndpoint);
            const headers_t& requestHeaders() const;
            void setRequestHeader(const headers_t::key_type& headerName,
                                  const headers_t::mapped_type& headerValue);
            void setRequestHeaders(const headers_t& headers);
            const QUrlQuery& query() const;
            void setRequestQuery(const QUrlQuery& query);
            const Data& requestData() const;
            void setRequestData(Data&& data);
            const QByteArrayList& expectedContentTypes() const;
            void addExpectedContentType(const QByteArray& contentType);
            void setExpectedContentTypes(const QByteArrayList& contentTypes);

            /** Construct a URL out of baseUrl, path and query
             * The function automatically adds '/' between baseUrl's path and
             * \p path if necessary. The query component of \p baseUrl
             * is ignored.
             */
            static QUrl makeRequestUrl(QUrl baseUrl, const QString& path,
                                       const QUrlQuery& query = {});

            virtual void beforeStart(const ConnectionData* connData);
            virtual void afterStart(const ConnectionData* connData,
                                    QNetworkReply* reply);
            virtual void beforeAbandon(QNetworkReply*);

            /**
             * Used by gotReply() to check the received reply for general
             * issues such as network errors or access denial.
             * Returning anything except NoError/Success prevents
             * further parseReply()/parseJson() invocation.
             *
             * @param reply the reply received from the server
             * @return the result of checking the reply
             *
             * @see gotReply
             */
            virtual Status doCheckReply(QNetworkReply* reply) const;

            /**
             * Processes the reply. By default, parses the reply into
             * a QJsonDocument and calls parseJson() if it's a valid JSON.
             *
             * @param reply raw contents of a HTTP reply from the server (without headers)
             *
             * @see gotReply, parseJson
             */
            virtual Status parseReply(QNetworkReply* reply);

            /**
             * Processes the JSON document received from the Matrix server.
             * By default returns succesful status without analysing the JSON.
             *
             * @param json valid JSON document received from the server
             *
             * @see parseReply
             */
            virtual Status parseJson(const QJsonDocument&);

            void setStatus(Status s);
            void setStatus(int code, QString message);

            // Q_DECLARE_LOGGING_CATEGORY return different function types
            // in different versions
            using LoggingCategory = decltype(JOBS)*;
            void setLoggingCategory(LoggingCategory lcf);

            // Job objects should only be deleted via QObject::deleteLater
            ~BaseJob() override;

        protected slots:
            void timeout();

        private slots:
            void sendRequest(bool inBackground);
            void checkReply();
            void gotReply();

        private:
            void stop();
            void finishJob();

            class Private;
            QScopedPointer<Private> d;
    };

    inline bool isJobRunning(BaseJob* job)
    {
        return job && job->error() == BaseJob::Pending;
    }
}  // namespace QMatrixClient