| 1 | /* |
| 2 | * Copyright (C) 2016 Damir Porobic <https://github.com/damirporobic> |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; either version 2 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, |
| 17 | * Boston, MA 02110-1301, USA. |
| 18 | * |
| 19 | */ |
| 20 | |
| 21 | #include "ImgurWrapper.h" |
| 22 | |
| 23 | ImgurWrapper::ImgurWrapper(const QString &imgurUrl, QObject *parent) : |
| 24 | mBaseImgurUrl(imgurUrl), |
| 25 | QObject(parent), |
| 26 | mAccessManager(new QNetworkAccessManager(this)) |
| 27 | { |
| 28 | connect(mAccessManager, &QNetworkAccessManager::finished, this, &ImgurWrapper::handleReply); |
| 29 | |
| 30 | // Client ID that will only be used for anonymous upload |
| 31 | mClientId = "16d41e28a3ba71e"; |
| 32 | } |
| 33 | |
| 34 | /* |
| 35 | * This function starts the upload, depending if an access token was provided |
| 36 | * this will be either an account upload on an anonymous upload. If the upload |
| 37 | * was successful the upload Fished signal will be emitted which holds the url |
| 38 | * to the image. |
| 39 | */ |
| 40 | void ImgurWrapper::startUpload(const QImage& image, const QString &title, const QString &description, const QByteArray& accessToken) const |
| 41 | { |
| 42 | // Convert the image into a byteArray |
| 43 | QByteArray imageByteArray; |
| 44 | QBuffer buffer(&imageByteArray); |
| 45 | image.save(&buffer, "PNG"); |
| 46 | |
| 47 | // Create the network request for posting the image |
| 48 | QUrl url(mBaseImgurUrl + QLatin1String("/3/upload.xml")); |
| 49 | QUrlQuery urlQuery; |
| 50 | |
| 51 | // Add params that we send with the picture |
| 52 | urlQuery.addQueryItem(QLatin1String("title"), title); |
| 53 | urlQuery.addQueryItem(QLatin1String("description"), description); |
| 54 | |
| 55 | url.setQuery(urlQuery); |
| 56 | QNetworkRequest request; |
| 57 | request.setUrl(url); |
| 58 | request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded")); |
| 59 | |
| 60 | // If an access token was sent, we upload to account, otherwise we upload |
| 61 | // anonymously |
| 62 | if (accessToken.isEmpty()) { |
| 63 | request.setRawHeader("Authorization", "Client-ID " + mClientId); |
| 64 | } else { |
| 65 | request.setRawHeader("Authorization", "Bearer " + accessToken); |
| 66 | } |
| 67 | |
| 68 | // Post the image |
| 69 | mAccessManager->post(request, imageByteArray); |
| 70 | } |
| 71 | |
| 72 | /* |
| 73 | * This functions requests an access token, it only starts the request, the |
| 74 | * tokenUpdate signal will be emitted if the request was successful or otherwise |
| 75 | * the tokenError. |
| 76 | */ |
| 77 | void ImgurWrapper::getAccessToken(const QByteArray& pin, const QByteArray& clientId, const QByteArray& clientSecret) const |
| 78 | { |
| 79 | QNetworkRequest request; |
| 80 | |
| 81 | // Build the URL that we will request the token from. The XML indicates we |
| 82 | // want the response in XML format. |
| 83 | request.setUrl(QUrl(mBaseImgurUrl + QLatin1String("/oauth2/token.xml"))); |
| 84 | request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded")); |
| 85 | |
| 86 | // Prepare the params that we send with the request |
| 87 | QByteArray params; |
| 88 | params.append("client_id=" + clientId); |
| 89 | params.append("&client_secret=" + clientSecret); |
| 90 | params.append("&grant_type=pin"); |
| 91 | params.append("&pin=" + pin); |
| 92 | |
| 93 | // Request the token |
| 94 | mAccessManager->post(request, params); |
| 95 | } |
| 96 | |
| 97 | /* |
| 98 | * The imgur token expires after some time, when this happens, and you try to |
| 99 | * post an image the server responds with 403, and we emit the |
| 100 | * tokenRefreshRequired signal, after which this function should be called to |
| 101 | * refresh the token. |
| 102 | */ |
| 103 | void ImgurWrapper::refreshToken(const QByteArray& refreshToken, const QByteArray& clientId, const QByteArray& clientSecret) const |
| 104 | { |
| 105 | QNetworkRequest request; |
| 106 | |
| 107 | // Build the URL that we will request the token from. The XML indicates we |
| 108 | // want the response in XML format |
| 109 | request.setUrl(QUrl(mBaseImgurUrl + QLatin1String("/oauth2/token.xml"))); |
| 110 | request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded")); |
| 111 | |
| 112 | // Prepare the params |
| 113 | QByteArray params; |
| 114 | params.append("refresh_token=" + refreshToken); |
| 115 | params.append("&client_id=" + clientId); |
| 116 | params.append("&client_secret=" + clientSecret); |
| 117 | params.append("&grant_type=refresh_token"); |
| 118 | |
| 119 | // Request the token |
| 120 | mAccessManager->post(request, params); |
| 121 | } |
| 122 | |
| 123 | /* |
| 124 | * Returns a URL that can be opened in a browser to request the pin. The |
| 125 | * function is not opening the pin window in the browser, it only returns the |
| 126 | * correct url to it. |
| 127 | */ |
| 128 | QUrl ImgurWrapper::pinRequestUrl(const QString& clientId) const |
| 129 | { |
| 130 | QUrl url(mBaseImgurUrl + QLatin1String("/oauth2/authorize")); |
| 131 | QUrlQuery urlQuery; |
| 132 | urlQuery.addQueryItem(QLatin1String("client_id"), clientId); |
| 133 | urlQuery.addQueryItem(QLatin1String("response_type"), QLatin1String("pin")); |
| 134 | |
| 135 | url.setQuery(urlQuery); |
| 136 | return url; |
| 137 | } |
| 138 | |
| 139 | /* |
| 140 | * This function handles the default response, a 200OK and any error message is |
| 141 | * returned in a data root element. 200OK is returned when posting an image was |
| 142 | * successful, 403 is mostly returned when a token has expired, anything else is |
| 143 | * an error that we currently cannot handle |
| 144 | */ |
| 145 | void ImgurWrapper::handleDataResponse(const QDomElement& element) const |
| 146 | { |
| 147 | if (element.attribute(QLatin1String("status")) == QLatin1String("200") && !element.elementsByTagName(QLatin1String("link")).isEmpty()) { |
| 148 | auto link = element.elementsByTagName(QLatin1String("link")).at(0).toElement().text(); |
| 149 | auto deleteHash = element.elementsByTagName(QLatin1String("deletehash")).at(0).toElement().text(); |
| 150 | |
| 151 | emit uploadFinished(ImgurResponse(link, deleteHash)); |
| 152 | } else if (element.attribute(QLatin1String("status")) == QLatin1String("403")) { |
| 153 | emit tokenRefreshRequired(); |
| 154 | } else { |
| 155 | if (element.elementsByTagName(QLatin1String("error")).isEmpty()) { |
| 156 | emit error(QNetworkReply::ProtocolFailure, QLatin1String("Server responded with ") + element.attribute(QLatin1String("status"))); |
| 157 | } else { |
| 158 | emit error(QNetworkReply::ProtocolFailure, QLatin1String("Server responded with ") + element.attribute(QLatin1String("status")) + QLatin1String(": ") + |
| 159 | element.elementsByTagName(QLatin1String("error")).at(0).toElement().text()); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /* |
| 165 | * Called when a new token was received, either when first time getting access |
| 166 | * or refreshing a token |
| 167 | */ |
| 168 | void ImgurWrapper::handleTokenResponse(const QDomElement& element) const |
| 169 | { |
| 170 | if (!element.elementsByTagName(QLatin1String("access_token")).isEmpty() && |
| 171 | !element.elementsByTagName(QLatin1String("refresh_token")).isEmpty() && |
| 172 | !element.elementsByTagName(QLatin1String("account_username")).isEmpty() |
| 173 | ) { |
| 174 | emit tokenUpdated(element.elementsByTagName(QLatin1String("access_token")).at(0).toElement().text(), |
| 175 | element.elementsByTagName(QLatin1String("refresh_token")).at(0).toElement().text(), |
| 176 | element.elementsByTagName(QLatin1String("account_username")).at(0).toElement().text() |
| 177 | ); |
| 178 | } else { |
| 179 | emit error(QNetworkReply::ProtocolFailure, QLatin1String("Expected token response was received, something went wrong.")); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /* |
| 184 | * This function will be called when we've got the reply from imgur |
| 185 | */ |
| 186 | void ImgurWrapper::handleReply(QNetworkReply* reply) |
| 187 | { |
| 188 | // Only for troubleshooting, if reply->readAll is called the parser will fail! |
| 189 | // qDebug("----------------------------------------------------------------"); |
| 190 | // qDebug("Reply code:\n%s", qPrintable(reply->readAll())); |
| 191 | // qDebug("----------------------------------------------------------------"); |
| 192 | |
| 193 | // Check network return code, if we get no error or if we get a status 202, |
| 194 | // proceed, the 202 is returned for invalid token, we will request a new |
| 195 | // token. |
| 196 | if (reply->error() != QNetworkReply::NoError && reply->error() != QNetworkReply::ContentOperationNotPermittedError) { |
| 197 | emit error(reply->error(), QLatin1String("Network Error(") + QString::number(reply->error()) + QLatin1String("): ") + reply->errorString()); |
| 198 | reply->deleteLater(); |
| 199 | return; |
| 200 | } |
| 201 | |
| 202 | QDomDocument doc; |
| 203 | QString errorMessage; |
| 204 | int errorLine; |
| 205 | int errorColumn; |
| 206 | |
| 207 | // Try to parse reply into xml reader |
| 208 | if (!doc.setContent(reply->readAll(), false, &errorMessage, &errorLine, &errorColumn)) { |
| 209 | emit error(QNetworkReply::ProtocolFailure, |
| 210 | QLatin1String("Parse error: ") + errorMessage + QLatin1String(", line:") + QString::number(errorLine) + |
| 211 | QLatin1String(", column:") + QString::number(errorColumn)); |
| 212 | reply->deleteLater(); |
| 213 | return; |
| 214 | } |
| 215 | |
| 216 | // See if we have an upload reply, token response or error |
| 217 | auto rootElement = doc.documentElement(); |
| 218 | |
| 219 | if (rootElement.tagName() == QLatin1String("data")) { |
| 220 | handleDataResponse(rootElement); |
| 221 | } else if (rootElement.tagName() == QLatin1String("response")) { |
| 222 | handleTokenResponse(rootElement); |
| 223 | } |
| 224 | else { |
| 225 | emit error(QNetworkReply::ProtocolFailure, QLatin1String("Received unexpected reply from imgur server.")); |
| 226 | } |
| 227 | |
| 228 | reply->deleteLater(); |
| 229 | } |