forked from transmission/transmission
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRpcClient.cc
321 lines (251 loc) · 8.09 KB
/
RpcClient.cc
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
/*
* This file Copyright (C) 2014-2016 Mnemosyne LLC
*
* It may be used under the GNU GPL versions 2 or 3
* or any future license endorsed by Mnemosyne LLC.
*
*/
#include <cstring>
#include <iostream>
#include <QApplication>
#include <QHostAddress>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <event2/buffer.h>
#include <libtransmission/transmission.h>
#include <libtransmission/rpcimpl.h>
#include <libtransmission/utils.h> // tr_free
#include <libtransmission/version.h> // LONG_VERSION_STRING
#include "RpcClient.h"
// #define DEBUG_HTTP
#define REQUEST_DATA_PROPERTY_KEY "requestData"
#define REQUEST_FUTUREINTERFACE_PROPERTY_KEY "requestReplyFutureInterface"
namespace
{
void destroyVariant(tr_variant* json)
{
tr_variantFree(json);
tr_free(json);
}
TrVariantPtr createVariant()
{
return TrVariantPtr(tr_new0(tr_variant, 1), &destroyVariant);
}
} // namespace
RpcClient::RpcClient(QObject* parent) :
QObject(parent),
mySession(nullptr),
myNAM(nullptr),
myNextTag(0)
{
qRegisterMetaType<TrVariantPtr>("TrVariantPtr");
}
void RpcClient::stop()
{
mySession = nullptr;
mySessionId.clear();
myUrl.clear();
if (myNAM != nullptr)
{
myNAM->deleteLater();
myNAM = nullptr;
}
}
void RpcClient::start(tr_session* session)
{
mySession = session;
}
void RpcClient::start(QUrl const& url)
{
myUrl = url;
}
bool RpcClient::isLocal() const
{
if (mySession != nullptr)
{
return true;
}
if (QHostAddress(myUrl.host()).isLoopback())
{
return true;
}
return false;
}
QUrl const& RpcClient::url() const
{
return myUrl;
}
RpcResponseFuture RpcClient::exec(tr_quark method, tr_variant* args)
{
return exec(tr_quark_get_string(method, nullptr), args);
}
RpcResponseFuture RpcClient::exec(char const* method, tr_variant* args)
{
TrVariantPtr json = createVariant();
tr_variantInitDict(json.get(), 3);
tr_variantDictAddStr(json.get(), TR_KEY_method, method);
if (args != nullptr)
{
tr_variantDictSteal(json.get(), TR_KEY_arguments, args);
}
return sendRequest(json);
}
int64_t RpcClient::getNextTag()
{
return myNextTag++;
}
void RpcClient::sendNetworkRequest(TrVariantPtr json, QFutureInterface<RpcResponse> const& promise)
{
QNetworkRequest request;
request.setUrl(myUrl);
request.setRawHeader("User-Agent", (qApp->applicationName() + QLatin1Char('/') +
QString::fromUtf8(LONG_VERSION_STRING)).toUtf8());
request.setRawHeader("Content-Type", "application/json; charset=UTF-8");
if (!mySessionId.isEmpty())
{
request.setRawHeader(TR_RPC_SESSION_ID_HEADER, mySessionId.toUtf8());
}
size_t rawJsonDataLength;
char* rawJsonData = tr_variantToStr(json.get(), TR_VARIANT_FMT_JSON_LEAN, &rawJsonDataLength);
QByteArray jsonData(rawJsonData, rawJsonDataLength);
tr_free(rawJsonData);
QNetworkReply* reply = networkAccessManager()->post(request, jsonData);
reply->setProperty(REQUEST_DATA_PROPERTY_KEY, QVariant::fromValue(json));
reply->setProperty(REQUEST_FUTUREINTERFACE_PROPERTY_KEY, QVariant::fromValue(promise));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(dataReadProgress()));
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SIGNAL(dataSendProgress()));
#ifdef DEBUG_HTTP
std::cerr << "sending " << "POST " << qPrintable(myUrl.path()) << std::endl;
for (QByteArray const& b : request.rawHeaderList())
{
std::cerr << b.constData() << ": " << request.rawHeader(b).constData() << std::endl;
}
std::cerr << "Body:\n" << jsonData.constData() << std::endl;
#endif
}
void RpcClient::sendLocalRequest(TrVariantPtr json, QFutureInterface<RpcResponse> const& promise, int64_t tag)
{
myLocalRequests.insert(tag, promise);
tr_rpc_request_exec_json(mySession, json.get(), localSessionCallback, this);
}
RpcResponseFuture RpcClient::sendRequest(TrVariantPtr json)
{
int64_t tag = getNextTag();
tr_variantDictAddInt(json.get(), TR_KEY_tag, tag);
QFutureInterface<RpcResponse> promise;
promise.setExpectedResultCount(1);
promise.setProgressRange(0, 1);
promise.setProgressValue(0);
promise.reportStarted();
if (mySession != nullptr)
{
sendLocalRequest(json, promise, tag);
}
else if (!myUrl.isEmpty())
{
sendNetworkRequest(json, promise);
}
return promise.future();
}
QNetworkAccessManager* RpcClient::networkAccessManager()
{
if (myNAM == nullptr)
{
myNAM = new QNetworkAccessManager();
connect(myNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(networkRequestFinished(QNetworkReply*)));
connect(myNAM, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), this,
SIGNAL(httpAuthenticationRequired()));
}
return myNAM;
}
void RpcClient::localSessionCallback(tr_session* s, tr_variant* response, void* vself)
{
Q_UNUSED(s);
RpcClient* self = static_cast<RpcClient*>(vself);
TrVariantPtr json = createVariant();
*json = *response;
tr_variantInitBool(response, false);
// this callback is invoked in the libtransmission thread, so we don't want
// to process the response here... let's push it over to the Qt thread.
QMetaObject::invokeMethod(self, "localRequestFinished", Qt::QueuedConnection, Q_ARG(TrVariantPtr, json));
}
void RpcClient::networkRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
QFutureInterface<RpcResponse> promise = reply->property(REQUEST_FUTUREINTERFACE_PROPERTY_KEY).
value<QFutureInterface<RpcResponse>>();
#ifdef DEBUG_HTTP
std::cerr << "http response header: " << std::endl;
for (QByteArray const& b : reply->rawHeaderList())
{
std::cerr << b.constData() << ": " << reply->rawHeader(b).constData() << std::endl;
}
std::cerr << "json:\n" << reply->peek(reply->bytesAvailable()).constData() << std::endl;
#endif
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 409 &&
reply->hasRawHeader(TR_RPC_SESSION_ID_HEADER))
{
// we got a 409 telling us our session id has expired.
// update it and resubmit the request.
mySessionId = QString::fromUtf8(reply->rawHeader(TR_RPC_SESSION_ID_HEADER));
sendNetworkRequest(reply->property(REQUEST_DATA_PROPERTY_KEY).value<TrVariantPtr>(), promise);
return;
}
emit networkResponse(reply->error(), reply->errorString());
if (reply->error() != QNetworkReply::NoError)
{
RpcResponse result;
result.networkError = reply->error();
promise.setProgressValueAndText(1, reply->errorString());
promise.reportFinished(&result);
}
else
{
RpcResponse result;
QByteArray const jsonData = reply->readAll().trimmed();
TrVariantPtr json = createVariant();
if (tr_variantFromJson(json.get(), jsonData.constData(), jsonData.size()) == 0)
{
result = parseResponseData(*json);
}
promise.setProgressValue(1);
promise.reportFinished(&result);
}
}
void RpcClient::localRequestFinished(TrVariantPtr response)
{
int64_t tag = parseResponseTag(*response);
RpcResponse result = parseResponseData(*response);
QFutureInterface<RpcResponse> promise = myLocalRequests.take(tag);
promise.setProgressRange(0, 1);
promise.setProgressValue(1);
promise.reportFinished(&result);
}
int64_t RpcClient::parseResponseTag(tr_variant& json)
{
int64_t tag;
if (!tr_variantDictFindInt(&json, TR_KEY_tag, &tag))
{
tag = -1;
}
return tag;
}
RpcResponse RpcClient::parseResponseData(tr_variant& json)
{
RpcResponse ret;
char const* result;
if (tr_variantDictFindStr(&json, TR_KEY_result, &result, nullptr))
{
ret.result = QString::fromUtf8(result);
ret.success = std::strcmp(result, "success") == 0;
}
tr_variant* args;
if (tr_variantDictFindDict(&json, TR_KEY_arguments, &args))
{
ret.args = createVariant();
*ret.args = *args;
tr_variantInitBool(args, false);
}
return ret;
}