forked from anttiko/Quickddit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickdditmanager.cpp
279 lines (232 loc) · 9.6 KB
/
quickdditmanager.cpp
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
/*
Quickddit - Reddit client for mobile phones
Copyright (C) 2014 Dickson Leong
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see [http://www.gnu.org/licenses/].
*/
#include "quickdditmanager.h"
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <qt-json/json.h>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QtCore/QUrlQuery>
#endif
#include "appsettings.h"
#include "utils.h"
#if !defined(REDDIT_CLIENT_ID) || !defined(REDDIT_CLIENT_SECRET) || !defined(REDDIT_REDIRECT_URL)
// fill these up with your own Reddit client id, secret and redirect url
#define REDDIT_CLIENT_ID ""
#define REDDIT_CLIENT_SECRET ""
#define REDDIT_REDIRECT_URL ""
#endif
#define REDDIT_OAUTH_SCOPE "read,mysubreddits,subscribe,vote,submit,edit,identity,privatemessages,history,save"
QuickdditManager::QuickdditManager(QObject *parent) :
QObject(parent), m_netManager(new QNetworkAccessManager(this)), m_settings(0),
m_accessTokenRequest(0), m_pendingRequest(0), m_userInfoReply(0)
{
}
bool QuickdditManager::isSignedIn() const
{
return m_settings->hasRefreshToken();
}
AppSettings *QuickdditManager::settings() const
{
return m_settings;
}
void QuickdditManager::setSettings(AppSettings *settings)
{
m_settings = settings;
}
APIRequest *QuickdditManager::createGetRequest(QObject *parent, const QUrl &url, const QByteArray &authHeader)
{
APIRequest *request = new APIRequest(APIRequest::NormalRequest, m_netManager, parent);
request->setRequestMethod(APIRequest::GET);
request->setBaseUrl(url);
request->setAuthHeader(authHeader);
request->send();
return request;
}
APIRequest *QuickdditManager::createRedditRequest(QObject *parent, APIRequest::HttpMethod method,
const QString &relativeUrl, const QHash<QString, QString> ¶meters)
{
APIRequest *request;
if (m_settings->hasRefreshToken()) {
request = new APIRequest(APIRequest::OAuthRequest, m_netManager, parent);
request->setRequestMethod(method);
request->setRelativeUrl(relativeUrl);
request->setParameters(parameters);
if (!m_accessToken.isEmpty() && m_accessTokenExpiry.elapsed() < 3600000) {
request->setAccessToken(m_accessToken);
} else {
if (m_pendingRequest != 0) {
m_pendingRequest->forceFailure();
m_pendingRequest = 0;
}
m_pendingRequest = request;
connect(this, SIGNAL(accessTokenSuccess()), SLOT(onRefreshTokenFinished()));
connect(this, SIGNAL(accessTokenFailure(QString)), SLOT(onRefreshTokenFinished()));
refreshAccessToken();
return request;
}
} else {
request = new APIRequest(APIRequest::NormalRequest, m_netManager, parent);
request->setRequestMethod(method);
request->setRelativeUrl(relativeUrl);
request->setParameters(parameters);
}
request->send();
return request;
}
QUrl QuickdditManager::generateAuthorizationUrl()
{
QUrl url("https://ssl.reddit.com/api/v1/authorize.compact");
QHash<QString, QString> parameters;
parameters.insert("response_type", "code");
parameters.insert("client_id", REDDIT_CLIENT_ID);
parameters.insert("redirect_uri", REDDIT_REDIRECT_URL);
parameters.insert("scope", REDDIT_OAUTH_SCOPE);
parameters.insert("duration", "permanent");
m_state = QString::number(qrand());
parameters.insert("state", m_state);
Utils::setUrlQuery(&url, parameters);
return url;
}
void QuickdditManager::getAccessToken(const QUrl &signedInUrl)
{
// if m_state is empty means generateAuthorizationUrl() is not called first
Q_ASSERT(!m_state.isEmpty());
if (m_accessTokenRequest != 0) {
qWarning("QuickdditManager::getAccessToken(): Aborting active network request (Try to avoid!)");
m_accessTokenRequest->disconnect();
m_accessTokenRequest->deleteLater();
m_accessTokenRequest = 0;
}
// check state
QString state;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
QUrlQuery signedInUrlQuery(signedInUrl.query());
state = signedInUrlQuery.queryItemValue("state");
#else
state = signedInUrl.queryItemValue("state");
#endif
if (m_state != state) {
qCritical("QuickdditManager::getAccessToken(): (OAuth2) state is not matched");
emit accessTokenFailure("Error: state not match");
return;
}
m_state.clear();
QString code;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
code = signedInUrlQuery.queryItemValue("code");
#else
code = signedInUrl.queryItemValue("code");
#endif
m_accessTokenRequest = new APIRequest(APIRequest::AccessTokenRequest, m_netManager, this);
m_accessTokenRequest->setClientId(REDDIT_CLIENT_ID);
m_accessTokenRequest->setClientSecret(REDDIT_CLIENT_SECRET);
m_accessTokenRequest->setRedirectUrl(REDDIT_REDIRECT_URL);
m_accessTokenRequest->setCode(code);
m_accessTokenRequest->send();
connect(m_accessTokenRequest, SIGNAL(finished(QNetworkReply*)), SLOT(onAccessTokenRequestFinished(QNetworkReply*)));
}
void QuickdditManager::refreshAccessToken()
{
if (m_accessTokenRequest != 0) {
qWarning("QuickdditManager::refreshAccessToken(): Aborting active network request (Try to avoid!)");
m_accessTokenRequest->disconnect();
m_accessTokenRequest->deleteLater();
m_accessTokenRequest = 0;
}
QByteArray refreshToken = m_settings->refreshToken();
Q_ASSERT(!refreshToken.isEmpty());
m_accessTokenRequest = new APIRequest(APIRequest::RefreshAccessTokenRequest, m_netManager, this);
m_accessTokenRequest->setClientId(REDDIT_CLIENT_ID);
m_accessTokenRequest->setClientSecret(REDDIT_CLIENT_SECRET);
m_accessTokenRequest->setRedirectUrl(REDDIT_REDIRECT_URL);
m_accessTokenRequest->setRefreshToken(refreshToken);
m_accessTokenRequest->send();
connect(m_accessTokenRequest, SIGNAL(finished(QNetworkReply*)), SLOT(onAccessTokenRequestFinished(QNetworkReply*)));
}
void QuickdditManager::signOut()
{
m_accessToken.clear();
m_settings->setRefreshToken(QByteArray());
m_settings->setRedditUsername(QString());
emit signedInChanged();
}
void QuickdditManager::onAccessTokenRequestFinished(QNetworkReply *reply)
{
if (reply->error() == QNetworkReply::NoError) {
const QString replyString = QString::fromUtf8(reply->readAll());
bool ok;
const QVariantMap replyJson = QtJson::parse(replyString, ok).toMap();
Q_ASSERT_X(ok, Q_FUNC_INFO, "Error parsing JSON");
const QString accessToken = replyJson.value("access_token").toString();
const QString refreshToken = replyJson.value("refresh_token").toString();
if (!accessToken.isEmpty()) {
m_accessToken = accessToken;
m_accessTokenExpiry.start();
if (!refreshToken.isEmpty())
m_settings->setRefreshToken(refreshToken.toLatin1());
emit accessTokenSuccess();
emit signedInChanged();
} else {
emit accessTokenFailure("Error: access token not found. Please sign in again.");
qDebug("QuickdditManager::onAccessTokenRequestFinished(): "
"Unable to get access token from the following data:\n%s", qPrintable(replyString));
}
} else {
emit accessTokenFailure(reply->errorString());
}
m_accessTokenRequest->deleteLater();
m_accessTokenRequest = 0;
if (!m_accessToken.isEmpty() && m_settings->redditUsername().isEmpty())
updateRedditUsername();
}
void QuickdditManager::onRefreshTokenFinished()
{
disconnect(this, 0, this, SLOT(onRefreshTokenFinished()));
if (!m_accessToken.isEmpty() && m_accessTokenExpiry.elapsed() < 3600000) {
m_pendingRequest->setAccessToken(m_accessToken);
m_pendingRequest->send();
} else {
m_pendingRequest->forceFailure();
}
m_pendingRequest = 0;
}
void QuickdditManager::updateRedditUsername()
{
if (m_userInfoReply != 0) {
qWarning("QuickdditManager::updateRedditUsername(): Aborting active network request (Try to avoid!)");
m_userInfoReply->disconnect();
m_userInfoReply->deleteLater();
m_userInfoReply = 0;
}
m_userInfoReply = new APIRequest(APIRequest::OAuthRequest, m_netManager, this);
m_userInfoReply->setRequestMethod(APIRequest::GET);
m_userInfoReply->setRelativeUrl("/api/v1/me");
m_userInfoReply->setAccessToken(m_accessToken);
m_userInfoReply->send();
connect(m_userInfoReply, SIGNAL(finished(QNetworkReply*)), SLOT(onUserInfoFinished(QNetworkReply*)));
}
void QuickdditManager::onUserInfoFinished(QNetworkReply *reply)
{
if (reply->error() == QNetworkReply::NoError) {
bool ok;
QVariantMap userJson = QtJson::parse(reply->readAll(), ok).toMap();
Q_ASSERT_X(ok, Q_FUNC_INFO, "Error parsing JSON");
m_settings->setRedditUsername(userJson.value("name").toString());
} else {
qDebug("QuickdditManager::onUserInfoFinished(): Network error: %s", qPrintable(reply->errorString()));
}
m_userInfoReply->deleteLater();
m_userInfoReply = 0;
}