Debian Codegraph @

src/librssguard/miscellaneous/feedreader.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "miscellaneous/feedreader.h"
4
5 #include "3rd-party/boolinq/boolinq.h"
6 #include "core/feeddownloader.h"
7 #include "core/feedsmodel.h"
8 #include "core/feedsproxymodel.h"
9 #include "core/messagesmodel.h"
10 #include "core/messagesproxymodel.h"
11 #include "database/databasequeries.h"
12 #include "gui/dialogs/formmessagefiltersmanager.h"
13 #include "miscellaneous/application.h"
14 #include "miscellaneous/mutex.h"
15 #include "miscellaneous/pluginfactory.h"
16 #include "miscellaneous/settings.h"
17 #include "services/abstract/cacheforserviceroot.h"
18 #include "services/abstract/serviceentrypoint.h"
19 #include "services/abstract/serviceroot.h"
20
21 #include <QThread>
22 #include <QTimer>
23
24 FeedReader::FeedReader(QObject* parent)
25 : QObject(parent), m_autoUpdateTimer(new QTimer(this)), m_feedDownloader(nullptr), m_feedFetchingPaused(false) {
26 m_feedsModel = new FeedsModel(this);
27 m_feedsProxyModel = new FeedsProxyModel(m_feedsModel, this);
28 m_messagesModel = new MessagesModel(this);
29 m_messagesProxyModel = new MessagesProxyModel(m_messagesModel, this);
30
31 updateAutoUpdateStatus();
32 initializeFeedDownloader();
33
34 if (qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::FeedsUpdateOnStartup)).toBool()) {
35 qDebugNN << LOGSEC_CORE << "Requesting update for all feeds on application startup.";
36 QTimer::singleShot(qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::FeedsUpdateStartupDelay)).toDouble() * 1000,
37 this,
38 [this]() {
39 updateFeeds(m_feedsModel->rootItem()->getSubAutoFetchingEnabledFeeds());
40 connect(m_autoUpdateTimer, &QTimer::timeout, this, &FeedReader::executeNextAutoUpdate);
41 });
42 }
43 else {
44 connect(m_autoUpdateTimer, &QTimer::timeout, this, &FeedReader::executeNextAutoUpdate);
45 }
46 }
47
48 FeedReader::~FeedReader() {
49 qDebugNN << LOGSEC_CORE << "Destroying FeedReader instance.";
50
51 for (ServiceEntryPoint* service : m_feedServices) {
52 if (!service->isDynamicallyLoaded()) {
53 qDebugNN << LOGSEC_CORE << "Deleting service" << QUOTE_W_SPACE_DOT(service->code());
54 delete service;
55 }
56 else {
57 qDebugNN << LOGSEC_CORE << "Service" << QUOTE_W_SPACE(service->code()) << "will be deleted by runtime.";
58 }
59 }
60 // qDeleteAll(m_feedServices);
61
62 qDeleteAll(m_messageFilters);
63 }
64
65 QList<ServiceEntryPoint*> FeedReader::feedServices() {
66 if (m_feedServices.isEmpty()) {
67 PluginFactory plugin_loader;
68
69 // Add dynamically loaded plugins.
70 m_feedServices.append(plugin_loader.loadPlugins());
71 }
72
73 return m_feedServices;
74 }
75
76 void FeedReader::updateFeeds(const QList<Feed*>& feeds, bool update_switched_off_too) {
77 auto my_feeds = feeds;
78
79 if (!update_switched_off_too) {
80 for (int i = 0; i < my_feeds.size(); i++) {
81 if (my_feeds.at(i)->isSwitchedOff()) {
82 my_feeds.removeAt(i--);
83 }
84 }
85 }
86
87 if (my_feeds.isEmpty()) {
88 return;
89 }
90
91 if (!qApp->feedUpdateLock()->tryLock()) {
92 qApp->showGuiMessage(Notification::Event::GeneralEvent,
93 {tr("Cannot fetch articles at this point"),
94 tr("You cannot fetch new articles now because another critical operation is ongoing."),
95 QSystemTrayIcon::MessageIcon::Warning});
96 return;
97 }
98
99 QMetaObject::invokeMethod(m_feedDownloader,
100 "updateFeeds",
101 Qt::ConnectionType::QueuedConnection,
102 Q_ARG(QList<Feed*>, my_feeds));
103 }
104
105 void FeedReader::synchronizeMessageData(const QList<CacheForServiceRoot*>& caches) {
106 QMetaObject::invokeMethod(m_feedDownloader,
107 "synchronizeAccountCaches",
108 Qt::ConnectionType::QueuedConnection,
109 Q_ARG(QList<CacheForServiceRoot*>, caches),
110 Q_ARG(bool, true));
111 }
112
113 void FeedReader::initializeFeedDownloader() {
114 if (m_feedDownloader == nullptr) {
115 qDebugNN << LOGSEC_CORE << "Creating FeedDownloader singleton.";
116
117 m_feedDownloader = new FeedDownloader();
118 m_feedDownloaderThread = new QThread();
119
120 // Downloader setup.
121 qRegisterMetaType<QList<Feed*>>("QList<Feed*>");
122 qRegisterMetaType<QList<CacheForServiceRoot*>>("QList<CacheForServiceRoot*>");
123
124 m_feedDownloader->moveToThread(m_feedDownloaderThread);
125
126 connect(m_feedDownloaderThread, &QThread::finished, m_feedDownloaderThread, &QThread::deleteLater);
127 connect(m_feedDownloaderThread, &QThread::finished, m_feedDownloader, &FeedDownloader::deleteLater);
128 connect(m_feedDownloader, &FeedDownloader::updateFinished, this, &FeedReader::onFeedUpdatesFinished);
129 connect(m_feedDownloader, &FeedDownloader::updateProgress, this, &FeedReader::feedUpdatesProgress);
130 connect(m_feedDownloader, &FeedDownloader::updateStarted, this, &FeedReader::feedUpdatesStarted);
131 connect(m_feedDownloader, &FeedDownloader::updateFinished, qApp->feedUpdateLock(), &Mutex::unlock);
132
133 m_feedDownloaderThread->start(QThread::Priority::LowPriority);
134 }
135 }
136
137 QDateTime FeedReader::lastAutoUpdate() const {
138 return m_lastAutoUpdate;
139 }
140
141 void FeedReader::showMessageFiltersManager() {
142 FormMessageFiltersManager manager(qApp->feedReader(),
143 qApp->feedReader()->feedsModel()->serviceRoots(),
144 qApp->mainFormWidget());
145
146 manager.exec();
147
148 m_feedsModel->reloadCountsOfWholeModel();
149 m_messagesModel->reloadWholeLayout();
150 }
151
152 void FeedReader::updateAutoUpdateStatus() {
153 // Restore global intervals.
154 // NOTE: Specific per-feed interval are left intact.
155 m_globalAutoUpdateInterval = qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::AutoUpdateInterval)).toInt();
156 m_globalAutoUpdateFast = qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::FastAutoUpdate)).toBool();
157
158 if (m_lastAutoUpdate.isNull()) {
159 m_lastAutoUpdate = QDateTime::currentDateTimeUtc();
160 }
161
162 m_globalAutoUpdateEnabled = qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::AutoUpdateEnabled)).toBool();
163 m_globalAutoUpdateOnlyUnfocused =
164 qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::AutoUpdateOnlyUnfocused)).toBool();
165
166 if (m_globalAutoUpdateFast) {
167 // NOTE: In "fast" mode, we set interval to 1 second.
168 // This might have some performance consequences.
169 m_autoUpdateTimer->setInterval(1000);
170 qDebugNN << LOGSEC_CORE
171 << "Enabling support for very small auto-fetching intervals. This might have performance consequences.";
172 }
173 else {
174 m_autoUpdateTimer->setInterval(AUTO_UPDATE_INTERVAL * 1000);
175 }
176
177 // Start global auto-update timer if it is not running yet.
178 // NOTE: The timer must run even if global auto-update
179 // is not enabled because user can still enable auto-update
180 // for individual feeds.
181 if (!m_autoUpdateTimer->isActive()) {
182 m_autoUpdateTimer->start();
183 qDebugNN << LOGSEC_CORE << "Auto-download timer started with interval " << m_autoUpdateTimer->interval() << " ms.";
184 }
185 else {
186 qDebugNN << LOGSEC_CORE << "Auto-download timer is already running.";
187 }
188 }
189
190 bool FeedReader::autoUpdateEnabled() const {
191 return m_globalAutoUpdateEnabled;
192 }
193
194 int FeedReader::autoUpdateInterval() const {
195 return m_globalAutoUpdateInterval;
196 }
197
198 void FeedReader::loadSavedMessageFilters() {
199 // Load all message filters from database.
200 // All plugin services will hook active filters to
201 // all feeds.
202 m_messageFilters =
203 DatabaseQueries::getMessageFilters(qApp->database()->driver()->connection(metaObject()->className()));
204
205 for (auto* filter : std::as_const(m_messageFilters)) {
206 filter->setParent(this);
207 }
208 }
209
210 MessageFilter* FeedReader::addMessageFilter(const QString& title, const QString& script) {
211 auto* fltr =
212 DatabaseQueries::addMessageFilter(qApp->database()->driver()->connection(metaObject()->className()), title, script);
213
214 m_messageFilters.append(fltr);
215 return fltr;
216 }
217
218 void FeedReader::removeMessageFilter(MessageFilter* filter) {
219 m_messageFilters.removeAll(filter);
220
221 // Now, remove all references from all feeds.
222 auto all_feeds = m_feedsModel->feedsForIndex();
223
224 for (auto* feed : all_feeds) {
225 feed->removeMessageFilter(filter);
226 }
227
228 // Remove from DB.
229 DatabaseQueries::removeMessageFilterAssignments(qApp->database()->driver()->connection(metaObject()->className()),
230 filter->id());
231 DatabaseQueries::removeMessageFilter(qApp->database()->driver()->connection(metaObject()->className()), filter->id());
232
233 // Free from memory as last step.
234 filter->deleteLater();
235 }
236
237 void FeedReader::updateMessageFilter(MessageFilter* filter) {
238 DatabaseQueries::updateMessageFilter(qApp->database()->driver()->connection(metaObject()->className()), filter);
239 }
240
241 void FeedReader::assignMessageFilterToFeed(Feed* feed, MessageFilter* filter) {
242 feed->appendMessageFilter(filter);
243 DatabaseQueries::assignMessageFilterToFeed(qApp->database()->driver()->connection(metaObject()->className()),
244 feed->customId(),
245 filter->id(),
246 feed->getParentServiceRoot()->accountId());
247 }
248
249 void FeedReader::removeMessageFilterToFeedAssignment(Feed* feed, MessageFilter* filter) {
250 feed->removeMessageFilter(filter);
251 DatabaseQueries::removeMessageFilterFromFeed(qApp->database()->driver()->connection(metaObject()->className()),
252 feed->customId(),
253 filter->id(),
254 feed->getParentServiceRoot()->accountId());
255 }
256
257 void FeedReader::updateAllFeeds() {
258 updateFeeds(m_feedsModel->rootItem()->getSubTreeFeeds());
259 }
260
261 void FeedReader::updateManuallyIntervaledFeeds() {
262 updateFeeds(m_feedsModel->rootItem()->getSubTreeAutoFetchingWithManualIntervalsFeeds());
263 }
264
265 void FeedReader::stopRunningFeedUpdate() {
266 if (m_feedDownloader != nullptr) {
267 m_feedDownloader->stopRunningUpdate();
268 }
269 }
270
271 void FeedReader::pauseUnpaseFeedFetching(bool pause) {
272 m_feedFetchingPaused = pause;
273 qApp->settings()->setValue(GROUP(Feeds), Feeds::PauseFeedFetching, pause);
274 }
275
276 bool FeedReader::isFeedUpdateRunning() const {
277 return m_feedDownloader != nullptr && m_feedDownloader->isUpdateRunning();
278 }
279
280 FeedDownloader* FeedReader::feedDownloader() const {
281 return m_feedDownloader;
282 }
283
284 FeedsModel* FeedReader::feedsModel() const {
285 return m_feedsModel;
286 }
287
288 MessagesModel* FeedReader::messagesModel() const {
289 return m_messagesModel;
290 }
291
292 void FeedReader::executeNextAutoUpdate() {
293 bool disable_update_with_window =
294 (qApp->mainFormWidget()->isActiveWindow() || QApplication::activeModalWidget() != nullptr) &&
295 m_globalAutoUpdateOnlyUnfocused;
296 auto roots = qApp->feedReader()->feedsModel()->serviceRoots();
297 std::list<CacheForServiceRoot*> full_caches = boolinq::from(roots)
298 .select([](ServiceRoot* root) -> CacheForServiceRoot* {
299 auto* cache = root->toCache();
300
301 if (cache != nullptr) {
302 return cache;
303 }
304 else {
305 return nullptr;
306 }
307 })
308 .where([](CacheForServiceRoot* cache) {
309 return cache != nullptr && !cache->isEmpty();
310 })
311 .toStdList();
312
313 // Skip this round of auto-updating, but only if user disabled it when main window is active
314 // and there are no caches to synchronize.
315 if ((m_feedFetchingPaused || disable_update_with_window) && full_caches.empty()) {
316 qDebugNN << LOGSEC_CORE << "Delaying scheduled feed auto-download for some time since window "
317 << "is focused and updates while focused are disabled by the "
318 << "user (or paused) and all account caches are empty.";
319
320 // Cannot update, quit.
321 return;
322 }
323
324 if (!qApp->feedUpdateLock()->tryLock()) {
325 qDebugNN << LOGSEC_CORE << "Delaying scheduled feed auto-downloads and message state synchronization for "
326 << "some time due to another running update.";
327 // Cannot update, quit.
328 return;
329 }
330
331 qApp->feedUpdateLock()->unlock();
332
333 // Resynchronize caches.
334 if (!full_caches.empty()) {
335 QList<CacheForServiceRoot*> caches = FROM_STD_LIST(QList<CacheForServiceRoot*>, full_caches);
336
337 synchronizeMessageData(caches);
338 }
339
340 if (m_feedFetchingPaused || disable_update_with_window) {
341 qDebugNN << LOGSEC_CORE << "Delaying scheduled feed auto-download for some time since window "
342 << "is focused or feed fetching is paused. Article cache was synchronised nonetheless.";
343 return;
344 }
345
346 // Pass needed interval data and lets the model decide which feeds
347 // should be updated in this pass.
348 QDateTime current_time = QDateTime::currentDateTimeUtc();
349 bool auto_update_now =
350 m_globalAutoUpdateEnabled && m_lastAutoUpdate.addSecs(m_globalAutoUpdateInterval) < current_time;
351
352 if (auto_update_now) {
353 qDebugNN << LOGSEC_CORE << "Now it's time to auto-fetch articles because last auto-fetch was on"
354 << QUOTE_W_SPACE(m_lastAutoUpdate) << "and next should be in"
355 << NONQUOTE_W_SPACE(m_globalAutoUpdateInterval) << "seconds.";
356
357 m_lastAutoUpdate = current_time;
358 }
359
360 QList<Feed*> feeds_for_update = m_feedsModel->feedsForScheduledUpdate(auto_update_now);
361
362 if (!feeds_for_update.isEmpty()) {
363 // Request update for given feeds.
364 updateFeeds(feeds_for_update);
365
366 if (boolinq::from(feeds_for_update).any([](const Feed* fd) {
367 return !fd->isQuiet();
368 })) {
369 // NOTE: OSD/bubble informing about performing of scheduled update can be shown now.
370 qApp->showGuiMessage(Notification::Event::ArticlesFetchingStarted,
371 {tr("Starting auto-download of some feeds' articles"),
372 tr("I will auto-download new articles for %n feed(s).", nullptr, feeds_for_update.size()),
373 QSystemTrayIcon::MessageIcon::Information});
374 }
375 }
376 }
377
378 void FeedReader::onFeedUpdatesFinished(FeedDownloadResults updated_feeds) {
379 m_feedsModel->reloadWholeLayout();
380 m_feedsModel->notifyWithCounts();
381
382 emit feedUpdatesFinished(updated_feeds);
383 }
384
385 QList<MessageFilter*> FeedReader::messageFilters() const {
386 return m_messageFilters;
387 }
388
389 void FeedReader::quit() {
390 if (m_autoUpdateTimer->isActive()) {
391 m_autoUpdateTimer->stop();
392 }
393
394 // Stop running updates.
395 if (m_feedDownloader != nullptr) {
396 m_feedDownloader->stopRunningUpdate();
397
398 if (m_feedDownloader->isUpdateRunning() || m_feedDownloader->isCacheSynchronizationRunning()) {
399 QEventLoop loop(this);
400
401 connect(m_feedDownloader, &FeedDownloader::cachesSynchronized, &loop, &QEventLoop::quit);
402 connect(m_feedDownloader, &FeedDownloader::updateFinished, &loop, &QEventLoop::quit);
403 loop.exec();
404 }
405
406 // Both thread and downloader are auto-deleted when worker thread exits.
407 m_feedDownloaderThread->quit();
408 }
409
410 if (qApp->settings()->value(GROUP(Messages), SETTING(Messages::ClearReadOnExit)).toBool()) {
411 m_feedsModel->markItemCleared(m_feedsModel->rootItem(), true);
412 }
413
414 m_feedsModel->stopServiceAccounts();
415 }
416
417 MessagesProxyModel* FeedReader::messagesProxyModel() const {
418 return m_messagesProxyModel;
419 }
420
421 FeedsProxyModel* FeedReader::feedsProxyModel() const {
422 return m_feedsProxyModel;
423 }