1 /*
2 SPDX-FileCopyrightText: 2015-2021 Laurent Montel <montel@kde.org>
3
4 SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "ur1cashorturlengineinterface.h"
8 #include "../shorturlengineplugin.h"
9 #include "ur1cashorturlengineplugin_debug.h"
10
11 #include <QNetworkReply>
12 #include <QNetworkRequest>
13 #include <QUrlQuery>
14
Ur1CaShortUrlEngineInterface(ShortUrlEnginePlugin * plugin,QObject * parent)15 Ur1CaShortUrlEngineInterface::Ur1CaShortUrlEngineInterface(ShortUrlEnginePlugin *plugin, QObject *parent)
16 : ShortUrlEngineInterface(plugin, parent)
17 {
18 connect(mNetworkAccessManager, &QNetworkAccessManager::sslErrors, this, &Ur1CaShortUrlEngineInterface::slotSslErrors);
19 connect(mNetworkAccessManager, &QNetworkAccessManager::finished, this, &Ur1CaShortUrlEngineInterface::slotShortUrlFinished);
20 }
21
~Ur1CaShortUrlEngineInterface()22 Ur1CaShortUrlEngineInterface::~Ur1CaShortUrlEngineInterface()
23 {
24 }
25
engineName() const26 QString Ur1CaShortUrlEngineInterface::engineName() const
27 {
28 return mEnginePlugin->engineName();
29 }
30
generateShortUrl()31 void Ur1CaShortUrlEngineInterface::generateShortUrl()
32 {
33 QUrl url(QStringLiteral("http://ur1.ca/"));
34 QUrlQuery query;
35 query.addQueryItem(QStringLiteral("longurl"), mOriginalUrl);
36
37 url.setQuery(query);
38 QByteArray postData;
39
40 postData = query.query().toLatin1();
41 QNetworkRequest request(url);
42 request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("text/plain"));
43
44 QNetworkReply *reply = mNetworkAccessManager->post(request, postData);
45 connect(reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error), this, &Ur1CaShortUrlEngineInterface::slotErrorFound);
46 }
47
slotSslErrors(QNetworkReply * reply,const QList<QSslError> & error)48 void Ur1CaShortUrlEngineInterface::slotSslErrors(QNetworkReply *reply, const QList<QSslError> &error)
49 {
50 reply->ignoreSslErrors(error);
51 }
52
slotShortUrlFinished(QNetworkReply * reply)53 void Ur1CaShortUrlEngineInterface::slotShortUrlFinished(QNetworkReply *reply)
54 {
55 if (!mErrorFound) {
56 QString output = QLatin1String(reply->readAll());
57 qCDebug(UR1CASHORTURLENGINEPLUGIN_LOG) << "void Ur1CaShortUrl::slotShortUrlFinished(QNetworkReply *reply) " << output;
58 QRegExp rx(QStringLiteral("<p class=[\'\"]success[\'\"]>(.*)</p>"));
59 rx.setMinimal(true);
60 output = rx.cap(1);
61 rx.setPattern(QStringLiteral("href=[\'\"](.*)[\'\"]"));
62 rx.indexIn(output);
63 output = rx.cap(1);
64 qCDebug(UR1CASHORTURLENGINEPLUGIN_LOG) << "Short url is: " << output;
65 if (!output.isEmpty()) {
66 mTextCursor.insertText(output);
67 } else {
68 Q_EMIT shortUrlFailed(QString());
69 }
70 }
71 reply->deleteLater();
72 }
73