| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "core/feeddownloader.h" |
| 4 | |
| 5 | #include "3rd-party/boolinq/boolinq.h" |
| 6 | #include "core/messagefilter.h" |
| 7 | #include "database/databasequeries.h" |
| 8 | #include "definitions/definitions.h" |
| 9 | #include "exceptions/feedfetchexception.h" |
| 10 | #include "exceptions/filteringexception.h" |
| 11 | #include "miscellaneous/application.h" |
| 12 | #include "miscellaneous/settings.h" |
| 13 | #include "miscellaneous/thread.h" |
| 14 | #include "services/abstract/cacheforserviceroot.h" |
| 15 | #include "services/abstract/feed.h" |
| 16 | #include "services/abstract/labelsnode.h" |
| 17 | |
| 18 | #include <QDebug> |
| 19 | #include <QJSEngine> |
| 20 | #include <QString> |
| 21 | #include <QtConcurrentMap> |
| 22 | |
| 23 | FeedDownloader::FeedDownloader() |
| 24 | : QObject(), m_isCacheSynchronizationRunning(false), m_stopCacheSynchronization(false) { |
| 25 | qRegisterMetaType<FeedDownloadResults>("FeedDownloadResults"); |
| 26 | |
| 27 | connect(&m_watcherLookup, &QFutureWatcher<FeedUpdateResult>::resultReadyAt, this, [=](int idx) { |
| 28 | FeedUpdateResult res = m_watcherLookup.resultAt(idx); |
| 29 | |
| 30 | emit updateProgress(res.feed, m_watcherLookup.progressValue(), m_watcherLookup.progressMaximum()); |
| 31 | }); |
| 32 | connect(&m_watcherLookup, &QFutureWatcher<FeedUpdateResult>::finished, this, [=]() { |
| 33 | finalizeUpdate(); |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | FeedDownloader::~FeedDownloader() { |
| 38 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Destroying FeedDownloader instance."; |
| 39 | } |
| 40 | |
| 41 | bool FeedDownloader::isUpdateRunning() const { |
| 42 | return !m_feeds.isEmpty(); |
| 43 | } |
| 44 | |
| 45 | void FeedDownloader::synchronizeAccountCaches(const QList<CacheForServiceRoot*>& caches, bool emit_signals) { |
| 46 | m_isCacheSynchronizationRunning = true; |
| 47 | |
| 48 | for (CacheForServiceRoot* cache : caches) { |
| 49 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Synchronizing cache back to server on thread" |
| 50 | << QUOTE_W_SPACE_DOT(getThreadID()); |
| 51 | cache->saveAllCachedData(false); |
| 52 | |
| 53 | if (m_stopCacheSynchronization) { |
| 54 | qWarningNN << LOGSEC_FEEDDOWNLOADER << "Aborting cache synchronization."; |
| 55 | |
| 56 | m_stopCacheSynchronization = false; |
| 57 | break; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | m_isCacheSynchronizationRunning = false; |
| 62 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "All caches synchronized."; |
| 63 | |
| 64 | if (emit_signals) { |
| 65 | emit cachesSynchronized(); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | void FeedDownloader::updateFeeds(const QList<Feed*>& feeds) { |
| 70 | m_erroredAccounts.clear(); |
| 71 | m_results.clear(); |
| 72 | m_feeds.clear(); |
| 73 | |
| 74 | if (feeds.isEmpty()) { |
| 75 | qWarningNN << LOGSEC_FEEDDOWNLOADER << "No feeds to update in worker thread, aborting update."; |
| 76 | finalizeUpdate(); |
| 77 | } |
| 78 | else { |
| 79 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Starting feed updates from worker in thread" |
| 80 | << QUOTE_W_SPACE_DOT(getThreadID()); |
| 81 | |
| 82 | // Job starts now. |
| 83 | emit updateStarted(); |
| 84 | QSet<CacheForServiceRoot*> caches; |
| 85 | QMultiHash<ServiceRoot*, Feed*> feeds_per_root; |
| 86 | |
| 87 | for (auto* fd : feeds) { |
| 88 | CacheForServiceRoot* fd_cache = fd->getParentServiceRoot()->toCache(); |
| 89 | |
| 90 | if (fd_cache != nullptr) { |
| 91 | caches.insert(fd_cache); |
| 92 | } |
| 93 | |
| 94 | feeds_per_root.insert(fd->getParentServiceRoot(), fd); |
| 95 | } |
| 96 | |
| 97 | synchronizeAccountCaches(caches.values(), false); |
| 98 | |
| 99 | auto roots = feeds_per_root.uniqueKeys(); |
| 100 | QSqlDatabase database = qApp->database()->driver()->threadSafeConnection(metaObject()->className()); |
| 101 | |
| 102 | for (auto* rt : roots) { |
| 103 | auto fds = scrambleFeedsWithSameHost(feeds_per_root.values(rt)); |
| 104 | |
| 105 | QHash<QString, QStringList> per_acc_tags; |
| 106 | QHash<QString, QHash<ServiceRoot::BagOfMessages, QStringList>> per_acc_states; |
| 107 | |
| 108 | // Obtain lists of local IDs. |
| 109 | if (rt->wantsBaggedIdsOfExistingMessages()) { |
| 110 | // Tags per account. |
| 111 | per_acc_tags = DatabaseQueries::bagsOfMessages(database, rt->labelsNode()->labels()); |
| 112 | |
| 113 | // This account has activated intelligent downloading of messages. |
| 114 | // Prepare bags. |
| 115 | for (Feed* fd : fds) { |
| 116 | QHash<ServiceRoot::BagOfMessages, QStringList> per_feed_states; |
| 117 | |
| 118 | per_feed_states.insert(ServiceRoot::BagOfMessages::Read, |
| 119 | DatabaseQueries::bagOfMessages(database, ServiceRoot::BagOfMessages::Read, fd)); |
| 120 | per_feed_states.insert(ServiceRoot::BagOfMessages::Unread, |
| 121 | DatabaseQueries::bagOfMessages(database, ServiceRoot::BagOfMessages::Unread, fd)); |
| 122 | per_feed_states.insert(ServiceRoot::BagOfMessages::Starred, |
| 123 | DatabaseQueries::bagOfMessages(database, ServiceRoot::BagOfMessages::Starred, fd)); |
| 124 | |
| 125 | per_acc_states.insert(fd->customId(), per_feed_states); |
| 126 | |
| 127 | FeedUpdateRequest fu; |
| 128 | |
| 129 | fu.account = rt; |
| 130 | fu.feed = fd; |
| 131 | fu.stated_messages = per_feed_states; |
| 132 | fu.tagged_messages = per_acc_tags; |
| 133 | |
| 134 | m_feeds.append(fu); |
| 135 | } |
| 136 | } |
| 137 | else { |
| 138 | for (Feed* fd : fds) { |
| 139 | FeedUpdateRequest fu; |
| 140 | |
| 141 | fu.account = rt; |
| 142 | fu.feed = fd; |
| 143 | |
| 144 | m_feeds.append(fu); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | try { |
| 149 | rt->aboutToBeginFeedFetching(fds, per_acc_states, per_acc_tags); |
| 150 | } |
| 151 | catch (const ApplicationException& ex) { |
| 152 | // Common error showed, all feeds from the root are errored now! |
| 153 | m_erroredAccounts.insert(rt, ex); |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | std::function<FeedUpdateResult(const FeedUpdateRequest&)> func = |
| 158 | [=](const FeedUpdateRequest& fd) -> FeedUpdateResult { |
| 159 | #if defined(Q_OS_LINUX) |
| 160 | setThreadPriority(Priority::Lowest); |
| 161 | #endif |
| 162 | return updateThreadedFeed(fd); |
| 163 | }; |
| 164 | |
| 165 | m_watcherLookup.setFuture(QtConcurrent::mapped( |
| 166 | #if QT_VERSION_MAJOR > 5 |
| 167 | qApp->workHorsePool(), |
| 168 | #endif |
| 169 | m_feeds, |
| 170 | func)); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | void FeedDownloader::clearFeedOverload(Feed* feed) { |
| 175 | m_overloadedHosts.remove(QUrl(feed->source()).host()); |
| 176 | } |
| 177 | |
| 178 | bool FeedDownloader::checkIfFeedOverloaded(Feed* feed) const { |
| 179 | QString hostname = QUrl(feed->source()).host(); |
| 180 | QDateTime retry_after = m_overloadedHosts.value(hostname); |
| 181 | |
| 182 | return retry_after.isValid() && retry_after > QDateTime::currentDateTimeUtc(); |
| 183 | } |
| 184 | |
| 185 | FeedUpdateResult FeedDownloader::updateThreadedFeed(const FeedUpdateRequest& fd) { |
| 186 | if (m_erroredAccounts.contains(fd.account)) { |
| 187 | // This feed is errored because its account errored when preparing feed update. |
| 188 | ApplicationException root_ex = m_erroredAccounts.value(fd.account); |
| 189 | |
| 190 | skipFeedUpdateWithError(fd.account, fd.feed, root_ex); |
| 191 | } |
| 192 | else { |
| 193 | updateOneFeed(fd.account, fd.feed, fd.stated_messages, fd.tagged_messages); |
| 194 | } |
| 195 | |
| 196 | fd.feed->setLastUpdated(QDateTime::currentDateTimeUtc()); |
| 197 | |
| 198 | FeedUpdateResult res; |
| 199 | |
| 200 | res.feed = fd.feed; |
| 201 | |
| 202 | return res; |
| 203 | } |
| 204 | |
| 205 | void FeedDownloader::skipFeedUpdateWithError(ServiceRoot* acc, Feed* feed, const ApplicationException& ex) { |
| 206 | const FeedFetchException* fetch_ex = dynamic_cast<const FeedFetchException*>(&ex); |
| 207 | |
| 208 | if (fetch_ex != nullptr) { |
| 209 | feed->setStatus(fetch_ex->feedStatus(), fetch_ex->message()); |
| 210 | } |
| 211 | else { |
| 212 | feed->setStatus(Feed::Status::OtherError, ex.message()); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | void FeedDownloader::stopRunningUpdate() { |
| 217 | m_stopCacheSynchronization = true; |
| 218 | |
| 219 | m_watcherLookup.cancel(); |
| 220 | m_watcherLookup.waitForFinished(); |
| 221 | |
| 222 | m_feeds.clear(); |
| 223 | } |
| 224 | |
| 225 | void FeedDownloader::updateOneFeed(ServiceRoot* acc, |
| 226 | Feed* feed, |
| 227 | const QHash<ServiceRoot::BagOfMessages, QStringList>& stated_messages, |
| 228 | const QHash<QString, QStringList>& tagged_messages) { |
| 229 | const bool update_feed_list = |
| 230 | qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::UpdateFeedListDuringFetching)).toBool(); |
| 231 | |
| 232 | if (checkIfFeedOverloaded(feed)) { |
| 233 | qWarningNN << LOGSEC_CORE << "Feed with source" << QUOTE_W_SPACE(feed->source()) |
| 234 | << "was signalled temporarily being down. Returning no articles for now."; |
| 235 | |
| 236 | feed->setStatus(Feed::Status::NetworkError, |
| 237 | tr("feed is in network cooldown mode due to making too many network requests")); |
| 238 | |
| 239 | if (update_feed_list) { |
| 240 | acc->itemChanged({feed}); |
| 241 | } |
| 242 | |
| 243 | return; |
| 244 | } |
| 245 | |
| 246 | feed->setStatus(Feed::Status::Fetching); |
| 247 | |
| 248 | if (update_feed_list) { |
| 249 | acc->itemChanged({feed}); |
| 250 | } |
| 251 | |
| 252 | qlonglong thread_id = getThreadID(); |
| 253 | |
| 254 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Downloading new messages for feed ID" << QUOTE_W_SPACE(feed->customId()) |
| 255 | << "URL:" << QUOTE_W_SPACE(feed->source()) << "title:" << QUOTE_W_SPACE(feed->title()) << "in thread " |
| 256 | << QUOTE_W_SPACE_DOT(thread_id); |
| 257 | |
| 258 | int acc_id = acc->accountId(); |
| 259 | QElapsedTimer tmr; |
| 260 | tmr.start(); |
| 261 | |
| 262 | try { |
| 263 | QSqlDatabase database = qApp->database()->driver()->threadSafeConnection(metaObject()->className()); |
| 264 | QList<Message> msgs = feed->getParentServiceRoot()->obtainNewMessages(feed, stated_messages, tagged_messages); |
| 265 | |
| 266 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Downloaded" << NONQUOTE_W_SPACE(msgs.size()) << "messages for feed ID" |
| 267 | << QUOTE_W_SPACE_COMMA(feed->customId()) << "operation took" << NONQUOTE_W_SPACE(tmr.nsecsElapsed() / 1000) |
| 268 | << "microseconds."; |
| 269 | |
| 270 | clearFeedOverload(feed); |
| 271 | |
| 272 | bool fix_future_datetimes = |
| 273 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::FixupFutureArticleDateTimes)).toBool(); |
| 274 | |
| 275 | // Now, sanitize messages (tweak encoding etc.). |
| 276 | for (auto& msg : msgs) { |
| 277 | msg.m_accountId = acc_id; |
| 278 | msg.sanitize(feed, fix_future_datetimes); |
| 279 | } |
| 280 | |
| 281 | QMutexLocker lck(&m_mutexDb); |
| 282 | |
| 283 | if (!feed->messageFilters().isEmpty()) { |
| 284 | tmr.restart(); |
| 285 | |
| 286 | // Perform per-message filtering. |
| 287 | QJSEngine filter_engine; |
| 288 | |
| 289 | // Create JavaScript communication wrapper for the message. |
| 290 | MessageObject msg_obj(&database, feed, feed->getParentServiceRoot(), true); |
| 291 | |
| 292 | MessageFilter::initializeFilteringEngine(filter_engine, &msg_obj); |
| 293 | |
| 294 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Setting up JS evaluation took " << tmr.nsecsElapsed() / 1000 |
| 295 | << " microseconds."; |
| 296 | |
| 297 | QList<Message> read_msgs, important_msgs; |
| 298 | |
| 299 | for (int i = 0; i < msgs.size(); i++) { |
| 300 | Message msg_original(msgs[i]); |
| 301 | Message* msg_tweaked_by_filter = &msgs[i]; |
| 302 | |
| 303 | // Attach live message object to wrapper. |
| 304 | tmr.restart(); |
| 305 | msg_obj.setMessage(msg_tweaked_by_filter); |
| 306 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Hooking message took " << tmr.nsecsElapsed() / 1000 << " microseconds."; |
| 307 | |
| 308 | auto feed_filters = feed->messageFilters(); |
| 309 | bool remove_msg = false; |
| 310 | |
| 311 | for (int j = 0; j < feed_filters.size(); j++) { |
| 312 | QPointer<MessageFilter> filter = feed_filters.at(j); |
| 313 | |
| 314 | if (filter.isNull()) { |
| 315 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 316 | << "Article filter was probably deleted, removing its pointer from list of filters."; |
| 317 | feed_filters.removeAt(j--); |
| 318 | continue; |
| 319 | } |
| 320 | |
| 321 | MessageFilter* msg_filter = filter.data(); |
| 322 | |
| 323 | tmr.restart(); |
| 324 | |
| 325 | try { |
| 326 | MessageObject::FilteringAction decision = msg_filter->filterMessage(&filter_engine); |
| 327 | |
| 328 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Running filter script, it took " << tmr.nsecsElapsed() / 1000 |
| 329 | << " microseconds."; |
| 330 | |
| 331 | switch (decision) { |
| 332 | case MessageObject::FilteringAction::Accept: |
| 333 | // Message is normally accepted, it could be tweaked by the filter. |
| 334 | continue; |
| 335 | |
| 336 | case MessageObject::FilteringAction::Ignore: |
| 337 | case MessageObject::FilteringAction::Purge: |
| 338 | default: |
| 339 | // Remove the message, we do not want it. |
| 340 | remove_msg = true; |
| 341 | break; |
| 342 | } |
| 343 | } |
| 344 | catch (const FilteringException& ex) { |
| 345 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 346 | << "Error when evaluating filtering JS function: " << QUOTE_W_SPACE_DOT(ex.message()) |
| 347 | << " Accepting message."; |
| 348 | continue; |
| 349 | } |
| 350 | |
| 351 | // If we reach this point. Then we ignore the message which is by now |
| 352 | // already removed, go to next message. |
| 353 | break; |
| 354 | } |
| 355 | |
| 356 | if (!msg_original.m_isRead && msg_tweaked_by_filter->m_isRead) { |
| 357 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Message with custom ID:" << QUOTE_W_SPACE(msg_original.m_customId) |
| 358 | << "was marked as read by message scripts."; |
| 359 | |
| 360 | read_msgs << *msg_tweaked_by_filter; |
| 361 | } |
| 362 | |
| 363 | if (!msg_original.m_isImportant && msg_tweaked_by_filter->m_isImportant) { |
| 364 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Message with custom ID:" << QUOTE_W_SPACE(msg_original.m_customId) |
| 365 | << "was marked as important by message scripts."; |
| 366 | |
| 367 | important_msgs << *msg_tweaked_by_filter; |
| 368 | } |
| 369 | |
| 370 | // NOTE: We only remember what labels were added/removed in filters |
| 371 | // and store the fact to server (of synchronized) and local DB later. |
| 372 | // This is mainly because articles might not even be in DB yet. |
| 373 | // So first insert articles, then update their label assignments etc. |
| 374 | for (Label* lbl : std::as_const(msg_original.m_assignedLabels)) { |
| 375 | if (!msg_tweaked_by_filter->m_assignedLabels.contains(lbl)) { |
| 376 | // Label is not there anymore, it was deassigned. |
| 377 | msg_tweaked_by_filter->m_deassignedLabelsByFilter << lbl; |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | for (Label* lbl : std::as_const(msg_tweaked_by_filter->m_assignedLabels)) { |
| 382 | if (!msg_original.m_assignedLabels.contains(lbl)) { |
| 383 | // Label is in new message, but is not in old message, it |
| 384 | // was newly assigned. |
| 385 | msg_tweaked_by_filter->m_assignedLabelsByFilter << lbl; |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | if (remove_msg) { |
| 390 | msgs.removeAt(i--); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | if (!read_msgs.isEmpty()) { |
| 395 | // Now we push new read states to the service. |
| 396 | if (feed->getParentServiceRoot()->onBeforeSetMessagesRead(feed, read_msgs, RootItem::ReadStatus::Read)) { |
| 397 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Notified services about messages marked as read by message filters."; |
| 398 | } |
| 399 | else { |
| 400 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 401 | << "Notification of services about messages marked as read by message filters FAILED."; |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | if (!important_msgs.isEmpty()) { |
| 406 | // Now we push new read states to the service. |
| 407 | auto list = boolinq::from(important_msgs) |
| 408 | .select([](const Message& msg) { |
| 409 | return ImportanceChange(msg, RootItem::Importance::Important); |
| 410 | }) |
| 411 | .toStdList(); |
| 412 | QList<ImportanceChange> chngs = FROM_STD_LIST(QList<ImportanceChange>, list); |
| 413 | |
| 414 | if (feed->getParentServiceRoot()->onBeforeSwitchMessageImportance(feed, chngs)) { |
| 415 | qDebugNN << LOGSEC_FEEDDOWNLOADER |
| 416 | << "Notified services about messages marked as important by message filters."; |
| 417 | } |
| 418 | else { |
| 419 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 420 | << "Notification of services about messages marked as important by message filters FAILED."; |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | removeDuplicateMessages(msgs); |
| 426 | removeTooOldMessages(feed, msgs); |
| 427 | |
| 428 | tmr.restart(); |
| 429 | auto updated_messages = acc->updateMessages(msgs, feed, false, nullptr); |
| 430 | |
| 431 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Updating messages in DB took" << NONQUOTE_W_SPACE(tmr.nsecsElapsed() / 1000) |
| 432 | << "microseconds."; |
| 433 | |
| 434 | if (feed->status() != Feed::Status::NewMessages) { |
| 435 | feed->setStatus((!updated_messages.m_all.isEmpty() || !updated_messages.m_unread.isEmpty()) |
| 436 | ? Feed::Status::NewMessages |
| 437 | : Feed::Status::Normal); |
| 438 | } |
| 439 | |
| 440 | qDebugNN << LOGSEC_FEEDDOWNLOADER << updated_messages.m_unread.size() << " unread messages and" |
| 441 | << NONQUOTE_W_SPACE(updated_messages.m_all.size()) "total messages for feed" |
| 442 | << QUOTE_W_SPACE(feed->customId()) << "stored in DB."; |
| 443 | |
| 444 | m_results.appendUpdatedFeed(feed, updated_messages.m_unread); |
| 445 | } |
| 446 | catch (const FeedFetchException& feed_ex) { |
| 447 | qCriticalNN << LOGSEC_NETWORK << "Error when fetching feed:" << QUOTE_W_SPACE(feed_ex.feedStatus()) |
| 448 | << "message:" << QUOTE_W_SPACE_DOT(feed_ex.message()); |
| 449 | |
| 450 | m_results.appendErroredFeed(feed, feed_ex.message()); |
| 451 | feed->setStatus(feed_ex.feedStatus(), feed_ex.message()); |
| 452 | |
| 453 | if (feed_ex.feedStatus() == Feed::Status::NetworkError && !feed_ex.data().isNull()) { |
| 454 | NetworkResult network_result = feed_ex.data().value<NetworkResult>(); |
| 455 | |
| 456 | if (network_result.m_httpCode == HTTP_CODE_TOO_MANY_REQUESTS || |
| 457 | network_result.m_httpCode == HTTP_CODE_UNAVAILABLE) { |
| 458 | QDateTime safe_dt = NetworkFactory::extractRetryAfter(network_result.m_headers.value(QSL("retry-after"))); |
| 459 | |
| 460 | m_overloadedHosts.insert(QUrl(feed->source()).host(), safe_dt); |
| 461 | |
| 462 | qDebugNN << LOGSEC_CORE << "Extracted Retry-After value is" << QUOTE_W_SPACE_DOT(safe_dt); |
| 463 | qWarningNN << LOGSEC_CORE << "Feed" << QUOTE_W_SPACE_DOT(feed->source()) |
| 464 | << "indicates that there is too many requests right now on the same host."; |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | catch (const ApplicationException& app_ex) { |
| 469 | qCriticalNN << LOGSEC_NETWORK << "Unknown error when fetching feed:" |
| 470 | << "message:" << QUOTE_W_SPACE_DOT(app_ex.message()); |
| 471 | |
| 472 | m_results.appendErroredFeed(feed, app_ex.message()); |
| 473 | feed->setStatus(Feed::Status::OtherError, app_ex.message()); |
| 474 | } |
| 475 | |
| 476 | if (update_feed_list) { |
| 477 | acc->itemChanged({feed}); |
| 478 | } |
| 479 | |
| 480 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Made progress in feed updates, total feeds count " |
| 481 | << m_watcherLookup.progressValue() + 1 << "/" << m_feeds.size() << " (id of feed is " << feed->id() << ")."; |
| 482 | } |
| 483 | |
| 484 | void FeedDownloader::finalizeUpdate() { |
| 485 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Finished feed updates in thread" << QUOTE_W_SPACE_DOT(getThreadID()); |
| 486 | |
| 487 | m_feeds.clear(); |
| 488 | |
| 489 | if (!m_results.erroredFeeds().isEmpty()) { |
| 490 | qApp->showGuiMessage(Notification::Event::ArticlesFetchingError, |
| 491 | {QObject::tr("Some feeds have error"), |
| 492 | QObject::tr("Some feeds threw an error when fetching articles."), |
| 493 | QSystemTrayIcon::MessageIcon::Warning}); |
| 494 | } |
| 495 | |
| 496 | // Update of feeds has finished. |
| 497 | // NOTE: This means that now "update lock" can be unlocked |
| 498 | // and feeds can be added/edited/deleted and application |
| 499 | // can eventually quit. |
| 500 | emit updateFinished(m_results); |
| 501 | } |
| 502 | |
| 503 | bool FeedDownloader::isCacheSynchronizationRunning() const { |
| 504 | return m_isCacheSynchronizationRunning; |
| 505 | } |
| 506 | |
| 507 | void FeedDownloader::removeDuplicateMessages(QList<Message>& messages) { |
| 508 | auto idx = 0; |
| 509 | |
| 510 | while (idx < messages.size()) { |
| 511 | Message& message = messages[idx]; |
| 512 | std::function<bool(const Message& a, const Message& b)> is_duplicate; |
| 513 | |
| 514 | if (message.m_id > 0) { |
| 515 | is_duplicate = [](const Message& a, const Message& b) { |
| 516 | return a.m_id == b.m_id; |
| 517 | }; |
| 518 | } |
| 519 | else if (message.m_customId.isEmpty()) { |
| 520 | is_duplicate = [](const Message& a, const Message& b) { |
| 521 | return std::tie(a.m_title, a.m_url, a.m_author) == std::tie(b.m_title, b.m_url, b.m_author); |
| 522 | }; |
| 523 | } |
| 524 | else { |
| 525 | is_duplicate = [](const Message& a, const Message& b) { |
| 526 | return a.m_customId == b.m_customId; |
| 527 | }; |
| 528 | } |
| 529 | |
| 530 | auto next_idx = idx + 1; // Index of next message to check after removing all duplicates. |
| 531 | auto last_idx = idx; // Index of the last kept duplicate. |
| 532 | |
| 533 | idx = next_idx; |
| 534 | |
| 535 | // Remove all duplicate messages, and keep the message with the latest created date. |
| 536 | // If the created date is identical for all duplicate messages then keep the last message in the list. |
| 537 | while (idx < messages.size()) { |
| 538 | auto& last_duplicate = messages[last_idx]; |
| 539 | |
| 540 | if (is_duplicate(last_duplicate, messages[idx])) { |
| 541 | if (last_duplicate.m_created <= messages[idx].m_created) { |
| 542 | // The last seen message was created earlier or at the same date -- keep the current, and remove the last. |
| 543 | qWarningNN << LOGSEC_CORE << "Removing article" << QUOTE_W_SPACE(last_duplicate.m_title) |
| 544 | << "before saving articles to DB, because it is duplicate."; |
| 545 | |
| 546 | messages.removeAt(last_idx); |
| 547 | if (last_idx + 1 == next_idx) { |
| 548 | // The `next_idx` was pointing to the message following the duplicate. With that duplicate removed the |
| 549 | // next index needs to be adjusted. |
| 550 | next_idx = last_idx; |
| 551 | } |
| 552 | |
| 553 | last_idx = idx; |
| 554 | ++idx; |
| 555 | } |
| 556 | else { |
| 557 | qWarningNN << LOGSEC_CORE << "Removing article" << QUOTE_W_SPACE(messages[idx].m_title) |
| 558 | << "before saving articles to DB, because it is duplicate."; |
| 559 | |
| 560 | messages.removeAt(idx); |
| 561 | } |
| 562 | } |
| 563 | else { |
| 564 | ++idx; |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | idx = next_idx; |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | void FeedDownloader::removeTooOldMessages(Feed* feed, QList<Message>& msgs) { |
| 573 | const Feed::ArticleIgnoreLimit art = feed->articleIgnoreLimit(); |
| 574 | |
| 575 | if (!art.m_addAnyArticlesToDb) { |
| 576 | QDateTime dt_to_avoid; |
| 577 | |
| 578 | if (art.m_dtToAvoid.isValid() && art.m_dtToAvoid.toMSecsSinceEpoch() > 0) { |
| 579 | dt_to_avoid = art.m_dtToAvoid; |
| 580 | } |
| 581 | else if (art.m_hoursToAvoid > 0) { |
| 582 | dt_to_avoid = QDateTime::currentDateTimeUtc().addSecs((art.m_hoursToAvoid * -3600)); |
| 583 | } |
| 584 | else if (qApp->settings()->value(GROUP(Messages), SETTING(Messages::AvoidOldArticles)).toBool()) { |
| 585 | QDateTime global_dt_to_avoid = |
| 586 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::DateTimeToAvoidArticle)).toDateTime(); |
| 587 | int global_hours_to_avoid = |
| 588 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::HoursToAvoidArticle)).toInt(); |
| 589 | |
| 590 | if (global_dt_to_avoid.isValid() && global_dt_to_avoid.toMSecsSinceEpoch() > 0) { |
| 591 | dt_to_avoid = global_dt_to_avoid; |
| 592 | } |
| 593 | else if (global_hours_to_avoid > 0) { |
| 594 | dt_to_avoid = QDateTime::currentDateTimeUtc().addSecs(global_hours_to_avoid * -3600); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | if (dt_to_avoid.isValid()) { |
| 599 | for (int i = 0; i < msgs.size(); i++) { |
| 600 | const auto& mss = msgs.at(i); |
| 601 | |
| 602 | if (mss.m_createdFromFeed && mss.m_created < dt_to_avoid) { |
| 603 | qDebugNN << LOGSEC_CORE << "Removing message" << QUOTE_W_SPACE(mss.m_title) << "for being too old."; |
| 604 | msgs.removeAt(i--); |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | QList<Feed*> FeedDownloader::scrambleFeedsWithSameHost(const QList<Feed*>& feeds) const { |
| 612 | return feeds; |
| 613 | } |
| 614 | |
| 615 | QString FeedDownloadResults::overview(int how_many_feeds) const { |
| 616 | QStringList result; |
| 617 | |
| 618 | for (int i = 0, number_items_output = qMin(how_many_feeds, m_updatedFeeds.size()); i < number_items_output; i++) { |
| 619 | auto* fd = m_updatedFeeds.keys().at(i); |
| 620 | auto msgs = m_updatedFeeds.value(fd); |
| 621 | |
| 622 | if (fd->isQuiet()) { |
| 623 | continue; |
| 624 | } |
| 625 | |
| 626 | result.append(fd->title() + QSL(": ") + QString::number(msgs.size())); |
| 627 | } |
| 628 | |
| 629 | QString res_str = result.join(QSL("\n")); |
| 630 | |
| 631 | if (m_updatedFeeds.size() > how_many_feeds) { |
| 632 | res_str += QObject::tr("\n\n+ %n other feeds.", nullptr, m_updatedFeeds.size() - how_many_feeds); |
| 633 | } |
| 634 | |
| 635 | return res_str; |
| 636 | } |
| 637 | |
| 638 | void FeedDownloadResults::appendUpdatedFeed(Feed* feed, const QList<Message>& updated_unread_msgs) { |
| 639 | if (!updated_unread_msgs.isEmpty()) { |
| 640 | m_updatedFeeds.insert(feed, updated_unread_msgs); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | void FeedDownloadResults::appendErroredFeed(Feed* feed, const QString& error) { |
| 645 | m_erroredFeeds.insert(feed, error); |
| 646 | } |
| 647 | |
| 648 | void FeedDownloadResults::clear() { |
| 649 | m_updatedFeeds.clear(); |
| 650 | m_erroredFeeds.clear(); |
| 651 | } |
| 652 | |
| 653 | QHash<Feed*, QString> FeedDownloadResults::erroredFeeds() const { |
| 654 | return m_erroredFeeds; |
| 655 | } |
| 656 | |
| 657 | QHash<Feed*, QList<Message>> FeedDownloadResults::updatedFeeds() const { |
| 658 | return m_updatedFeeds; |
| 659 | } |