File indexing completed on 2024-12-29 05:00:27
0001 /* 0002 * SPDX-FileCopyrightText: 2007 Tobias Koenig <tokoe@kde.org> 0003 * SPDX-FileCopyrightText: 2008 Anne-Marie Mahfouf <annma@kde.org> 0004 * 0005 * SPDX-License-Identifier: GPL-2.0-or-later 0006 */ 0007 0008 #include "apodprovider.h" 0009 0010 #include <QRegularExpression> 0011 #include <QTextDocumentFragment> 0012 0013 #include <KIO/StoredTransferJob> 0014 #include <KPluginFactory> 0015 0016 ApodProvider::ApodProvider(QObject *parent, const KPluginMetaData &data, const QVariantList &args) 0017 : PotdProvider(parent, data, args) 0018 { 0019 m_infoUrl = QUrl(QStringLiteral("https://antwrp.gsfc.nasa.gov/apod/")); 0020 0021 KIO::StoredTransferJob *job = KIO::storedGet(m_infoUrl, KIO::NoReload, KIO::HideProgressInfo); 0022 connect(job, &KIO::StoredTransferJob::finished, this, &ApodProvider::pageRequestFinished); 0023 } 0024 0025 void ApodProvider::pageRequestFinished(KJob *_job) 0026 { 0027 KIO::StoredTransferJob *job = static_cast<KIO::StoredTransferJob *>(_job); 0028 if (job->error()) { 0029 Q_EMIT error(this); 0030 return; 0031 } 0032 0033 const QString data = QString::fromUtf8(job->data()).simplified(); // Join lines so title match can work 0034 0035 const QString pattern = QStringLiteral("<a href=\"(image/.*?)\""); 0036 QRegularExpression exp(pattern); 0037 const auto expMatch = exp.match(data); 0038 0039 if (expMatch.hasMatch()) { 0040 const QString sub = expMatch.captured(1); 0041 m_remoteUrl = QUrl(QStringLiteral("https://antwrp.gsfc.nasa.gov/apod/") + sub); 0042 0043 /** 0044 * Match title and author 0045 * Example: 0046 * <b> The Full Moon and the Dancer </b> <br> 0047 * 0048 * <b>Image Credit & 0049 * <a href="lib/about_apod.html#srapply">Copyright</a>:</b> 0050 * 0051 * <a href="https://www.instagram.com/through_my_lens_84/">Elena Pinna</a> 0052 */ 0053 const QRegularExpression infoRegEx(QStringLiteral("<center>.*?<b>(.+?)</b>.*?Credit.*?</b>(.+?)</center>")); 0054 const QRegularExpressionMatch match = infoRegEx.match(data); 0055 0056 if (match.hasMatch()) { 0057 m_title = QTextDocumentFragment::fromHtml(match.captured(1).trimmed()).toPlainText(); 0058 m_author = QTextDocumentFragment::fromHtml(match.captured(2).trimmed()).toPlainText(); 0059 } 0060 0061 KIO::StoredTransferJob *imageJob = KIO::storedGet(m_remoteUrl, KIO::NoReload, KIO::HideProgressInfo); 0062 connect(imageJob, &KIO::StoredTransferJob::finished, this, &ApodProvider::imageRequestFinished); 0063 } else { 0064 Q_EMIT error(this); 0065 } 0066 } 0067 0068 void ApodProvider::imageRequestFinished(KJob *_job) 0069 { 0070 KIO::StoredTransferJob *job = static_cast<KIO::StoredTransferJob *>(_job); 0071 if (job->error()) { 0072 Q_EMIT error(this); 0073 return; 0074 } 0075 0076 Q_EMIT finished(this, QImage::fromData(job->data())); 0077 } 0078 0079 K_PLUGIN_CLASS_WITH_JSON(ApodProvider, "apodprovider.json") 0080 0081 #include "apodprovider.moc"