File indexing completed on 2024-10-13 12:15:21
0001 /* 0002 SPDX-FileCopyrightText: 2003 Malte Starostik <malte@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #include "downloader.h" 0008 #include <kio/transferjob.h> 0009 0010 #include <cstdlib> 0011 #include <cstring> 0012 0013 #include <QTextCodec> 0014 0015 #include <KLocalizedString> 0016 0017 namespace KPAC 0018 { 0019 Downloader::Downloader(QObject *parent) 0020 : QObject(parent) 0021 { 0022 } 0023 0024 void Downloader::download(const QUrl &url) 0025 { 0026 m_data.resize(0); 0027 m_script.clear(); 0028 m_scriptURL = url; 0029 0030 KIO::TransferJob *job = KIO::get(url, KIO::NoReload, KIO::HideProgressInfo); 0031 connect(job, &KIO::TransferJob::data, this, &Downloader::data); 0032 connect(job, &KIO::TransferJob::redirection, this, &Downloader::redirection); 0033 connect(job, &KJob::result, this, qOverload<KJob *>(&Downloader::result)); 0034 } 0035 0036 void Downloader::failed() 0037 { 0038 Q_EMIT result(false); 0039 } 0040 0041 void Downloader::setError(const QString &error) 0042 { 0043 m_error = error; 0044 } 0045 0046 void Downloader::redirection(KIO::Job *, const QUrl &url) 0047 { 0048 m_scriptURL = url; 0049 } 0050 0051 void Downloader::data(KIO::Job *, const QByteArray &data) 0052 { 0053 unsigned offset = m_data.size(); 0054 m_data.resize(offset + data.size()); 0055 std::memcpy(m_data.data() + offset, data.data(), data.size()); 0056 } 0057 0058 static bool hasErrorPage(KJob *job) 0059 { 0060 KIO::TransferJob *tJob = qobject_cast<KIO::TransferJob *>(job); 0061 return (tJob && tJob->isErrorPage()); 0062 } 0063 0064 void Downloader::result(KJob *job) 0065 { 0066 if (!job->error() && !hasErrorPage(job)) { 0067 const QString charset = static_cast<KIO::Job *>(job)->queryMetaData(QStringLiteral("charset")); 0068 QTextCodec *codec = QTextCodec::codecForName(charset.toLatin1()); 0069 if (!codec) { 0070 codec = QTextCodec::codecForUtfText(m_data); 0071 Q_ASSERT(codec); 0072 } 0073 m_script = codec->toUnicode(m_data); 0074 Q_EMIT result(true); 0075 } else { 0076 if (job->error()) { 0077 setError(i18n("Could not download the proxy configuration script:\n%1", job->errorString())); 0078 } else { 0079 setError(i18n("Could not download the proxy configuration script")); // error page 0080 } 0081 failed(); 0082 } 0083 } 0084 } 0085 0086 #include "moc_downloader.cpp"