File indexing completed on 2025-01-19 04:46:39

0001 /*
0002    SPDX-FileCopyrightText: 2015-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "tinyurlengineinterface.h"
0008 #include "../shorturlengineplugin.h"
0009 #include <KLocalizedString>
0010 
0011 #include <QNetworkAccessManager>
0012 
0013 TinyUrlEngineInterface::TinyUrlEngineInterface(ShortUrlEnginePlugin *plugin, QObject *parent)
0014     : ShortUrlEngineInterface(plugin, parent)
0015 {
0016     connect(mNetworkAccessManager, &QNetworkAccessManager::finished, this, &TinyUrlEngineInterface::slotShortUrlFinished);
0017 }
0018 
0019 TinyUrlEngineInterface::~TinyUrlEngineInterface() = default;
0020 
0021 QString TinyUrlEngineInterface::engineName() const
0022 {
0023     return mEnginePlugin->engineName();
0024 }
0025 
0026 void TinyUrlEngineInterface::generateShortUrl()
0027 {
0028     const QString requestUrl = QStringLiteral("https://tinyurl.com/api-create.php?url=%1").arg(mOriginalUrl);
0029     QNetworkReply *reply = mNetworkAccessManager->get(QNetworkRequest(QUrl(requestUrl)));
0030     connect(reply, &QNetworkReply::errorOccurred, this, &TinyUrlEngineInterface::slotErrorFound);
0031 }
0032 
0033 void TinyUrlEngineInterface::slotShortUrlFinished(QNetworkReply *reply)
0034 {
0035     if (!mErrorFound) {
0036         const QString data = QString::fromUtf8(reply->readAll());
0037         if (!data.isEmpty()) {
0038             mTextCursor.insertText(data);
0039         }
0040     }
0041     reply->deleteLater();
0042 }
0043 
0044 void TinyUrlEngineInterface::slotErrorFound(QNetworkReply::NetworkError error)
0045 {
0046     mErrorFound = true;
0047     auto reply = qobject_cast<QNetworkReply *>(sender());
0048     Q_EMIT shortUrlFailed(i18n("Error reported by server:\n\'%1\'", (reply ? reply->errorString() : QString::number(error))));
0049 }
0050 
0051 #include "moc_tinyurlengineinterface.cpp"