31#include <QRegularExpression>
35#include "moc_qgsnewsfeedparser.cpp"
37using namespace Qt::StringLiterals;
56 , mBaseUrl( feedUrl.toString() )
67 QUrlQuery query( feedUrl );
74 if ( feedLanguage.isEmpty() )
78 if ( !feedLanguage.isEmpty() && feedLanguage !=
"C"_L1 )
79 query.addQueryItem( u
"lang"_s, feedLanguage.mid( 0, 2 ) );
87 if ( feedUrl.isLocalFile() )
89 query.addQueryItem( u
"lat"_s, QString::number(
static_cast< int >( feedLat ) ) );
90 query.addQueryItem( u
"lon"_s, QString::number(
static_cast< int >( feedLong ) ) );
100 if ( feedUrl.isLocalFile() )
102 if ( !query.toString().isEmpty() )
103 mFeedUrl = QUrl( mFeedUrl.toString() +
'_' + query.toString() );
107 mFeedUrl.setQuery( query );
132 const int beforeSize = mEntries.size();
133 mEntries.erase( std::remove_if( mEntries.begin(), mEntries.end(),
134 [key, &dismissed](
const Entry & entry )
136 if ( entry.key == key )
142 } ), mEntries.end() );
143 if ( beforeSize == mEntries.size() )
148 sTreeNewsFeedEntries->deleteItem( QString::number( key ), {mFeedKey} );
156 if ( !dismissed.imageUrl.isEmpty() )
159 const QString imagePath = u
"%1/%2.png"_s.arg( previewDir ).arg( key );
160 if ( QFile::exists( imagePath ) )
162 QFile::remove( imagePath );
166 if ( !mBlockSignals )
167 emit entryDismissed( dismissed );
172 const QList< QgsNewsFeedParser::Entry >
entries = mEntries;
191 QNetworkRequest req( mFeedUrl );
194 mFetchStartTime = QDateTime::currentDateTimeUtc().toSecsSinceEpoch();
204 QNetworkReply *reply = task->
reply();
211 if ( reply->error() != QNetworkReply::NoError )
218 QMetaObject::invokeMethod(
this,
"onFetch", Qt::QueuedConnection, Q_ARG( QString, task->
contentAsString() ) );
227void QgsNewsFeedParser::onFetch(
const QString &content )
233 const QVariantList
entries = json.toList();
234 QList< QgsNewsFeedParser::Entry > fetchedEntries;
235 fetchedEntries.reserve(
entries.size() );
236 for (
const QVariant &e :
entries )
239 const QVariantMap entryMap = e.toMap();
240 incomingEntry.key = entryMap.value( u
"pk"_s ).toInt();
241 incomingEntry.title = entryMap.value( u
"title"_s ).toString();
242 incomingEntry.imageUrl = entryMap.value( u
"image"_s ).toString();
243 incomingEntry.content = entryMap.value( u
"content"_s ).toString();
244 incomingEntry.link = entryMap.value( u
"url"_s ).toString();
245 incomingEntry.sticky = entryMap.value( u
"sticky"_s ).toBool();
246 bool hasExpiry =
false;
247 const qlonglong expiry = entryMap.value( u
"publish_to"_s ).toLongLong( &hasExpiry );
249 incomingEntry.expiry.setSecsSinceEpoch( expiry );
251 fetchedEntries.append( incomingEntry );
254 const auto entryIter { std::find_if( mEntries.begin(), mEntries.end(), [incomingEntry](
const QgsNewsFeedParser::Entry & candidate )
256 return candidate.key == incomingEntry.key;
258 const bool entryExists { entryIter != mEntries.end() };
261 if ( hasExpiry && expiry < mFetchStartTime )
266 else if ( entryExists )
268 const bool imageNeedsUpdate = ( entryIter->imageUrl != incomingEntry.imageUrl );
270 if ( imageNeedsUpdate && ! entryIter->imageUrl.isEmpty() )
273 const QString imagePath = u
"%1/%2.png"_s.arg( previewDir ).arg( entryIter->key );
274 if ( QFile::exists( imagePath ) )
276 QFile::remove( imagePath );
279 *entryIter = incomingEntry;
280 if ( imageNeedsUpdate && ! incomingEntry.imageUrl.isEmpty() )
281 fetchImageForEntry( incomingEntry );
284 storeEntryInSettings( incomingEntry );
288 else if ( !hasExpiry || expiry >= mFetchStartTime )
290 if ( !incomingEntry.imageUrl.isEmpty() )
291 fetchImageForEntry( incomingEntry );
293 mEntries.append( incomingEntry );
294 storeEntryInSettings( incomingEntry );
300 emit
fetched( fetchedEntries );
303void QgsNewsFeedParser::readStoredEntries()
305 QStringList existing;
310 catch ( QgsSettingsException &e )
315 std::sort( existing.begin(), existing.end(), [](
const QString & a,
const QString & b )
317 return a.toInt() < b.toInt();
319 mEntries.reserve( existing.size() );
320 for (
const QString &entry : existing )
322 const Entry e = readEntryFromSettings( entry.toInt() );
323 if ( !e.expiry.isValid() || e.expiry > QDateTime::currentDateTime() )
324 mEntries.append( e );
328 mBlockSignals =
true;
330 mBlockSignals =
false;
345 if ( !entry.imageUrl.isEmpty() )
348 const QString imagePath = u
"%1/%2.png"_s.arg( previewDir ).arg( entry.key );
349 if ( QFile::exists( imagePath ) )
351 const QImage img( imagePath );
352 entry.image = QPixmap::fromImage( img );
356 fetchImageForEntry( entry );
369 if ( entry.
expiry.isValid() )
376 QgsNetworkContentFetcher *fetcher =
new QgsNetworkContentFetcher();
379 const auto findIter = std::find_if( mEntries.begin(), mEntries.end(), [entry](
const QgsNewsFeedParser::Entry & candidate )
381 return candidate.key == entry.key;
383 if ( findIter != mEntries.end() )
385 const int entryIndex =
static_cast< int >( std::distance( mEntries.begin(), findIter ) );
387 QImage img = QImage::fromData( fetcher->
reply()->readAll() );
389 QSize size = img.size();
391 if ( size.width() > 250 )
393 size.setHeight(
static_cast< int >( size.height() *
static_cast< double >( 250 ) / size.width() ) );
394 size.setWidth( 250 );
397 if ( size.height() > 177 )
399 size.setWidth(
static_cast< int >( size.width() *
static_cast< double >( 177 ) / size.height() ) );
400 size.setHeight( 177 );
404 img = img.scaled( size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );
407 QImage previewImage( size, QImage::Format_ARGB32 );
408 previewImage.fill( Qt::transparent );
409 QPainter previewPainter( &previewImage );
410 previewPainter.setRenderHint( QPainter::Antialiasing,
true );
411 previewPainter.setRenderHint( QPainter::SmoothPixmapTransform,
true );
412 previewPainter.setPen( Qt::NoPen );
413 previewPainter.setBrush( Qt::black );
414 previewPainter.drawRoundedRect( 0, 0, size.width(), size.height(), 8, 8 );
415 previewPainter.setCompositionMode( QPainter::CompositionMode_SourceIn );
416 previewPainter.drawImage( 0, 0, img );
417 previewPainter.end();
421 QDir().mkdir( previewDir );
422 const QString imagePath = u
"%1/%2.png"_s.arg( previewDir ).arg( entry.
key );
423 previewImage.save( imagePath );
425 mEntries[ entryIndex ].image = QPixmap::fromImage( previewImage );
428 fetcher->deleteLater();
435 static const QRegularExpression sRegexp( u
"[^a-zA-Z0-9]"_s );
436 QString res = baseUrl;
437 res = res.replace( sRegexp, QString() );
QFlags< SettingsOption > SettingsOptions
static const QgsSettingsEntryString * settingsLocaleUserLocale
Settings entry locale user locale.
static QString qgisSettingsDirPath()
Returns the path to the settings directory in user's home dir.
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
Handles HTTP network content fetching in a background task.
QString contentAsString() const
Returns the fetched content as a string.
void fetched()
Emitted when the network content has been fetched, regardless of whether the fetch was successful or ...
QNetworkReply * reply()
Returns the network reply.
void fetchContent(const QUrl &url, const QString &authcfg=QString(), const QgsHttpHeaders &headers=QgsHttpHeaders())
Fetches content from a remote URL and handles redirects.
void finished()
Emitted when content has loaded.
QNetworkReply * reply()
Returns a reference to the network reply.
Represents a single entry from a news feed.
QString content
HTML content of news entry.
bool sticky
true if entry is "sticky" and should always be shown at the top
QUrl link
Optional URL link for entry.
QString imageUrl
Optional URL for image associated with entry.
QDateTime expiry
Optional auto-expiry time for entry.
int key
Unique entry identifier.
QString title
Entry title.
static QgsSettingsTreeNamedListNode * sTreeNewsFeedEntries
void enabledChanged()
Emitted when the enabled/disabled state of the feed URL associated to the news parser changes.
static const QgsSettingsEntryString * settingsFeedEntryTitle
Q_INVOKABLE void dismissEntry(int key)
Dismisses an entry with matching key.
static const QgsSettingsEntryString * settingsFeedEntryLink
void fetch()
Fetches new entries from the feed's URL.
void fetched(const QList< QgsNewsFeedParser::Entry > &entries)
Emitted when entries have been fetched from the feed.
void isFetchingChanged()
Emitted when the news parser's fetching state changes.
static const QgsSettingsEntryString * settingsFeedEntryImageUrl
static const QgsSettingsEntryDouble * settingsFeedLatitude
QString authcfg() const
Returns the authentication configuration for the parser.
static const QgsSettingsEntryInteger64 * settingsFeedLastFetchTime
QgsNewsFeedParser(const QUrl &feedUrl, const QString &authcfg=QString(), QObject *parent=nullptr)
Constructor for QgsNewsFeedParser, parsing the specified feedUrl.
static const QgsSettingsEntryBool * settingsFeedEntrySticky
Q_INVOKABLE void dismissAll()
Dismisses all current news items.
static const QgsSettingsEntryDouble * settingsFeedLongitude
static const QgsSettingsEntryString * settingsFeedLanguage
static const QgsSettingsEntryString * settingsFeedEntryContent
void entryUpdated(const QgsNewsFeedParser::Entry &entry)
Emitted whenever an existing entry is available from the feed (as a result of a call to fetch()).
static const QgsSettingsEntryVariant * settingsFeedEntryExpiry
static QString keyForFeed(const QString &baseUrl)
Returns the settings key used for a feed with the given baseUrl.
void entryAdded(const QgsNewsFeedParser::Entry &entry)
Emitted whenever a new entry is available from the feed (as a result of a call to fetch()).
void imageFetched(int key, const QPixmap &pixmap)
Emitted when the image attached to the entry with the specified key has been fetched and is now avail...
QList< QgsNewsFeedParser::Entry > entries() const
Returns a list of existing entries in the feed.
void setEnabled(bool enabled)
Sets whether the feed URL associated with the news parser is enabled.
bool setValue(const T &value, const QString &dynamicKeyPart=QString()) const
Set settings value.
A boolean settings entry.
A 64 bits integer (long long) settings entry.
A variant settings entry.
Custom exception class for settings related exceptions.
Stores settings for use within QGIS.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
@ CanCancel
Task can be canceled.
@ CancelWithoutPrompt
Task can be canceled without any users prompts, e.g. when closing a project or QGIS.
@ Silent
Don't show task updates (such as completion/failure messages) as operating-system level notifications...
void setDescription(const QString &description)
Sets the task's description.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
#define QgsDebugError(str)
#define QgsSetRequestInitiatorClass(request, _class)