Debian Codegraph @

src/librssguard/core/feedsmodel.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "core/feedsmodel.h"
4
5 #include "3rd-party/boolinq/boolinq.h"
6 #include "database/databasefactory.h"
7 #include "database/databasequeries.h"
8 #include "definitions/definitions.h"
9 #include "gui/dialogs/formmain.h"
10 #include "gui/messagebox.h"
11 #include "miscellaneous/feedreader.h"
12 #include "miscellaneous/iconfactory.h"
13 #include "miscellaneous/settings.h"
14 #include "services/abstract/feed.h"
15 #include "services/abstract/recyclebin.h"
16 #include "services/abstract/serviceentrypoint.h"
17 #include "services/abstract/serviceroot.h"
18
19 #include <QMimeData>
20 #include <QPair>
21 #include <QSqlError>
22 #include <QStack>
23 #include <QTimer>
24
25 FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent), m_rootItem(new RootItem()) {
26 setObjectName(QSL("FeedsModel"));
27
28 // Create root item.
29
30 // : Name of root item of feed list which can be seen in feed add/edit dialog.
31 m_rootItem->setTitle(tr("Root"));
32 m_rootItem->setIcon(qApp->icons()->fromTheme(QSL("folder")));
33
34 // Setup icons.
35 m_countsIcon = qApp->icons()->fromTheme(QSL("mail-mark-unread"));
36
37 // : Title text in the feed list header.
38 m_headerData << tr("Title");
39 m_tooltipData << /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.")
40 << /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages.");
41
42 setupFonts();
43 setupBehaviorDuringFetching();
44 }
45
46 FeedsModel::~FeedsModel() {
47 qDebugNN << LOGSEC_FEEDMODEL << "Destroying FeedsModel instance.";
48 delete m_rootItem;
49 }
50
51 QMimeData* FeedsModel::mimeData(const QModelIndexList& indexes) const {
52 auto* mime_data = new QMimeData();
53 QByteArray encoded_data;
54 QDataStream stream(&encoded_data, QIODevice::OpenModeFlag::WriteOnly);
55
56 for (const QModelIndex& index : indexes) {
57 if (index.column() != 0) {
58 continue;
59 }
60
61 RootItem* item_for_index = itemForIndex(index);
62
63 if (item_for_index->kind() != RootItem::Kind::Root) {
64 stream << quintptr(item_for_index);
65 }
66 }
67
68 mime_data->setData(QSL(MIME_TYPE_ITEM_POINTER), encoded_data);
69
70 return mime_data;
71 }
72
73 QStringList FeedsModel::mimeTypes() const {
74 return QStringList() << QSL(MIME_TYPE_ITEM_POINTER);
75 }
76
77 Qt::DropActions FeedsModel::supportedDropActions() const {
78 return Qt::DropAction::MoveAction;
79 }
80
81 Qt::ItemFlags FeedsModel::flags(const QModelIndex& index) const {
82 const RootItem* item_for_index = itemForIndex(index);
83
84 Qt::ItemFlags base_flags = QAbstractItemModel::flags(index);
85 Qt::ItemFlags additional_flags = item_for_index->additionalFlags();
86
87 return base_flags | additional_flags;
88 }
89
90 QVariant FeedsModel::headerData(int section, Qt::Orientation orientation, int role) const {
91 if (orientation != Qt::Horizontal) {
92 return QVariant();
93 }
94
95 switch (role) {
96 case Qt::ItemDataRole::DisplayRole:
97 if (section == FDS_MODEL_TITLE_INDEX) {
98 return m_headerData.at(FDS_MODEL_TITLE_INDEX);
99 }
100 else {
101 return QVariant();
102 }
103
104 case Qt::ItemDataRole::ToolTipRole:
105 return m_tooltipData.at(section);
106
107 case Qt::ItemDataRole::DecorationRole:
108 if (section == FDS_MODEL_COUNTS_INDEX) {
109 return m_countsIcon;
110 }
111 else {
112 return QVariant();
113 }
114
115 default:
116 return QVariant();
117 }
118 }
119
120 QModelIndex FeedsModel::index(int row, int column, const QModelIndex& parent) const {
121 if (!hasIndex(row, column, parent)) {
122 return QModelIndex();
123 }
124
125 RootItem* parent_item = itemForIndex(parent);
126 RootItem* child_item = parent_item->child(row);
127
128 if (child_item != nullptr) {
129 return createIndex(row, column, child_item);
130 }
131 else {
132 return QModelIndex();
133 }
134 }
135
136 QModelIndex FeedsModel::parent(const QModelIndex& child) const {
137 if (!child.isValid()) {
138 return QModelIndex();
139 }
140
141 RootItem* child_item = itemForIndex(child);
142 RootItem* parent_item = child_item->parent();
143
144 if (parent_item == m_rootItem) {
145 return QModelIndex();
146 }
147 else {
148 return createIndex(parent_item->row(), 0, parent_item);
149 }
150 }
151
152 int FeedsModel::rowCount(const QModelIndex& parent) const {
153 if (parent.column() > 0) {
154 return 0;
155 }
156 else {
157 return itemForIndex(parent)->childCount();
158 }
159 }
160
161 int FeedsModel::countOfAllMessages() const {
162 return m_rootItem->countOfAllMessages();
163 }
164
165 int FeedsModel::countOfUnreadMessages() const {
166 return m_rootItem->countOfUnreadMessages();
167 }
168
169 void FeedsModel::reloadCountsOfWholeModel() {
170 m_rootItem->updateCounts(true);
171 reloadWholeLayout();
172 notifyWithCounts();
173 }
174
175 void FeedsModel::removeItem(const QModelIndex& index) {
176 if (index.isValid()) {
177 RootItem* deleting_item = itemForIndex(index);
178 QModelIndex parent_index = index.parent();
179 RootItem* parent_item = deleting_item->parent();
180
181 beginRemoveRows(parent_index, index.row(), index.row());
182 parent_item->removeChild(deleting_item);
183 endRemoveRows();
184 deleting_item->deleteLater();
185 notifyWithCounts();
186 }
187 }
188
189 void FeedsModel::removeItem(RootItem* deleting_item) {
190 if (deleting_item != nullptr) {
191 QModelIndex index = indexForItem(deleting_item);
192 QModelIndex parent_index = index.parent();
193 RootItem* parent_item = deleting_item->parent();
194
195 beginRemoveRows(parent_index, index.row(), index.row());
196 parent_item->removeChild(deleting_item);
197 endRemoveRows();
198
199 if (deleting_item->kind() != RootItem::Kind::ServiceRoot) {
200 deleting_item->getParentServiceRoot()->updateCounts(true);
201 }
202
203 delete deleting_item;
204 // deleting_item->deleteLater();
205
206 notifyWithCounts();
207 }
208 }
209
210 void FeedsModel::reassignNodeToNewParent(RootItem* original_node, RootItem* new_parent) {
211 RootItem* original_parent = original_node->parent();
212
213 if (original_parent != new_parent) {
214 if (original_parent != nullptr) {
215 int original_index_of_item = original_parent->childItems().indexOf(original_node);
216
217 if (original_index_of_item >= 0) {
218 // Remove the original item from the model...
219 beginRemoveRows(indexForItem(original_parent), original_index_of_item, original_index_of_item);
220 original_parent->removeChild(original_node);
221 endRemoveRows();
222 }
223 }
224
225 int new_index_of_item = new_parent->childCount();
226
227 // ... and insert it under the new parent.
228 beginInsertRows(indexForItem(new_parent), new_index_of_item, new_index_of_item);
229 new_parent->appendChild(original_node);
230 endInsertRows();
231 }
232 }
233
234 QList<ServiceRoot*> FeedsModel::serviceRoots() const {
235 QList<ServiceRoot*> roots;
236 auto ch = m_rootItem->childItems();
237
238 for (RootItem* root : std::as_const(ch)) {
239 if (root->kind() == RootItem::Kind::ServiceRoot) {
240 roots.append(root->toServiceRoot());
241 }
242 }
243
244 return roots;
245 }
246
247 QList<Feed*> FeedsModel::feedsForScheduledUpdate(bool auto_update_now) {
248 QList<Feed*> feeds_for_update;
249 auto stf = m_rootItem->getSubTreeFeeds();
250 auto cur_date = QDateTime::currentDateTimeUtc();
251
252 for (Feed* feed : std::as_const(stf)) {
253 switch (feed->autoUpdateType()) {
254 case Feed::AutoUpdateType::DontAutoUpdate:
255 // Do not auto-update this feed ever.
256 continue;
257
258 case Feed::AutoUpdateType::DefaultAutoUpdate:
259 if (auto_update_now) {
260 feeds_for_update.append(feed);
261 }
262
263 break;
264
265 case Feed::AutoUpdateType::SpecificAutoUpdate:
266 default:
267 if (feed->lastUpdated().addSecs(feed->autoUpdateInterval()) < cur_date) {
268 feeds_for_update.append(feed);
269 }
270
271 break;
272 }
273 }
274
275 return feeds_for_update;
276 }
277
278 int FeedsModel::columnCount(const QModelIndex& parent) const {
279 Q_UNUSED(parent)
280 return FEEDS_VIEW_COLUMN_COUNT;
281 }
282
283 RootItem* FeedsModel::itemForIndex(const QModelIndex& index) const {
284 if (index.isValid() && index.model() == this) {
285 return static_cast<RootItem*>(index.internalPointer());
286 }
287 else {
288 return m_rootItem;
289 }
290 }
291
292 QModelIndex FeedsModel::indexForItem(const RootItem* item) const {
293 if (item == nullptr || item->kind() == RootItem::Kind::Root) {
294 // Root item lies on invalid index.
295 return QModelIndex();
296 }
297
298 QStack<const RootItem*> chain;
299
300 while (item->kind() != RootItem::Kind::Root) {
301 chain.push(item);
302 item = item->parent();
303 }
304
305 // Now, we have complete chain list: parent --- ..... --- parent --- leaf (item).
306 QModelIndex target_index = indexForItem(m_rootItem);
307
308 // We go through the stack and create our target index.
309 while (!chain.isEmpty()) {
310 const RootItem* parent_item = chain.pop();
311
312 target_index =
313 index(parent_item->parent()->childItems().indexOf(const_cast<RootItem* const>(parent_item)), 0, target_index);
314 }
315
316 return target_index;
317 }
318
319 bool FeedsModel::hasAnyFeedNewMessages() const {
320 return boolinq::from(m_rootItem->getSubTreeFeeds()).any([](const Feed* feed) {
321 return feed->status() == Feed::Status::NewMessages;
322 });
323 }
324
325 RootItem* FeedsModel::rootItem() const {
326 return m_rootItem;
327 }
328
329 void FeedsModel::setupBehaviorDuringFetching() {
330 m_updateDuringFetching = qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::UpdateFeedListDuringFetching)).toBool();
331
332 if (m_updateDuringFetching) {
333 m_updateItemIcon = qApp->icons()->fromTheme(QSL("view-refresh"));
334 }
335 }
336
337 void FeedsModel::reloadChangedLayout(QModelIndexList list) {
338 while (!list.isEmpty()) {
339 QModelIndex indx = list.takeFirst();
340
341 if (indx.isValid()) {
342 QModelIndex indx_parent = indx.parent();
343
344 // Underlying data are changed.
345 emit dataChanged(index(indx.row(), 0, indx_parent), index(indx.row(), FDS_MODEL_COUNTS_INDEX, indx_parent));
346
347 list.append(indx_parent);
348 }
349 }
350 }
351
352 void FeedsModel::reloadChangedItem(RootItem* item) {
353 reloadChangedLayout({indexForItem(item)});
354 }
355
356 void FeedsModel::notifyWithCounts() {
357 emit messageCountsChanged(countOfUnreadMessages(), hasAnyFeedNewMessages());
358 }
359
360 void FeedsModel::onItemDataChanged(const QList<RootItem*>& items) {
361 if (items.size() > RELOAD_MODEL_BORDER_NUM) {
362 qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model for more than " << RELOAD_MODEL_BORDER_NUM
363 << " items, reloading model fully.";
364 reloadWholeLayout();
365 }
366 else {
367 qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model, reloading the " << items.size()
368 << " items individually.";
369
370 for (RootItem* item : items) {
371 reloadChangedItem(item);
372 }
373 }
374
375 notifyWithCounts();
376 }
377
378 void FeedsModel::setupFonts() {
379 QFont fon;
380
381 if (qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::CustomizeListFont)).toBool()) {
382 fon.fromString(qApp->settings()
383 ->value(GROUP(Feeds), Feeds::ListFont, Application::font("FeedsView").toString())
384 .toString());
385 }
386 else {
387 fon = Application::font("FeedsView");
388 }
389
390 m_normalFont = fon;
391
392 m_boldFont = m_normalFont;
393 m_boldFont.setBold(true);
394
395 m_normalStrikedFont = m_normalFont;
396 m_normalStrikedFont.setStrikeOut(true);
397
398 m_boldStrikedFont = m_boldFont;
399 m_boldStrikedFont.setStrikeOut(true);
400 }
401
402 void FeedsModel::informAboutDatabaseCleanup() {
403 for (ServiceRoot* acc : serviceRoots()) {
404 acc->onDatabaseCleanup();
405 }
406 }
407
408 void FeedsModel::reloadWholeLayout() {
409 emit layoutAboutToBeChanged();
410 emit layoutChanged();
411 }
412
413 bool FeedsModel::addServiceAccount(ServiceRoot* root, bool freshly_activated) {
414 int new_row_index = m_rootItem->childCount();
415
416 beginInsertRows(indexForItem(m_rootItem), new_row_index, new_row_index);
417 m_rootItem->appendChild(root);
418 endInsertRows();
419
420 // Connect.
421 connect(root,
422 &ServiceRoot::itemRemovalRequested,
423 this,
424 static_cast<void (FeedsModel::*)(RootItem*)>(&FeedsModel::removeItem));
425 connect(root, &ServiceRoot::itemReassignmentRequested, this, &FeedsModel::reassignNodeToNewParent);
426 connect(root, &ServiceRoot::dataChanged, this, &FeedsModel::onItemDataChanged);
427 connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested);
428 connect(root, &ServiceRoot::itemExpandRequested, this, &FeedsModel::itemExpandRequested);
429 connect(root, &ServiceRoot::itemExpandStateSaveRequested, this, &FeedsModel::itemExpandStateSaveRequested);
430
431 root->start(freshly_activated);
432
433 return true;
434 }
435
436 bool FeedsModel::restoreAllBins() {
437 bool result = true;
438 auto srts = serviceRoots();
439
440 for (ServiceRoot* root : std::as_const(srts)) {
441 RecycleBin* bin_of_root = root->recycleBin();
442
443 if (bin_of_root != nullptr) {
444 result &= bin_of_root->restore();
445 }
446 }
447
448 return result;
449 }
450
451 bool FeedsModel::emptyAllBins() {
452 bool result = true;
453 auto srts = serviceRoots();
454
455 for (ServiceRoot* root : std::as_const(srts)) {
456 RecycleBin* bin_of_root = root->recycleBin();
457
458 if (bin_of_root != nullptr) {
459 result &= bin_of_root->empty();
460 }
461 }
462
463 return result;
464 }
465
466 void FeedsModel::changeSortOrder(RootItem* item, bool move_top, bool move_bottom, int new_sort_order) {
467 QSqlDatabase db = qApp->database()->driver()->connection(metaObject()->className());
468
469 DatabaseQueries::moveItem(item, move_top, move_bottom, new_sort_order, db);
470 }
471
472 void FeedsModel::sortDirectDescendants(RootItem* item, RootItem::Kind kind_to_sort) {
473 auto childs = item->childItems(kind_to_sort);
474
475 std::sort(childs.begin(), childs.end(), [](RootItem* lhs, RootItem* rhs) {
476 return lhs->title().compare(rhs->title(), Qt::CaseSensitivity::CaseInsensitive) < 0;
477 });
478
479 for (RootItem* it : childs) {
480 changeSortOrder(it, false, true);
481 }
482 }
483
484 void FeedsModel::loadActivatedServiceAccounts() {
485 auto serv = qApp->feedReader()->feedServices();
486
487 // Iterate all globally available feed "service plugins".
488 for (const ServiceEntryPoint* entry_point : std::as_const(serv)) {
489 // Load all stored root nodes from the entry point and add those to the model.
490 QList<ServiceRoot*> roots = entry_point->initializeSubtree();
491
492 for (ServiceRoot* root : roots) {
493 addServiceAccount(root, false);
494 }
495 }
496
497 if (serviceRoots().isEmpty()) {
498 QTimer::singleShot(2000, qApp->mainForm(), []() {
499 qApp->mainForm()->showAddAccountDialog();
500 });
501 }
502 }
503
504 void FeedsModel::stopServiceAccounts() {
505 auto serv = serviceRoots();
506
507 for (ServiceRoot* account : std::as_const(serv)) {
508 account->stop();
509 }
510 }
511
512 QList<Feed*> FeedsModel::feedsForIndex(const QModelIndex& index) const {
513 return itemForIndex(index)->getSubTreeFeeds();
514 }
515
516 bool FeedsModel::markItemRead(RootItem* item, RootItem::ReadStatus read) {
517 if (item != nullptr) {
518 return item->markAsReadUnread(read);
519 }
520
521 return true;
522 }
523
524 bool FeedsModel::markItemCleared(RootItem* item, bool clean_read_only) {
525 if (item != nullptr) {
526 return item->cleanMessages(clean_read_only);
527 }
528
529 return true;
530 }
531
532 bool FeedsModel::purgeArticles(const QList<Feed*>& feeds) {
533 auto database = qApp->database()->driver()->connection(metaObject()->className());
534
535 try {
536 bool anything_purged = DatabaseQueries::purgeFeedArticles(database, feeds);
537
538 if (anything_purged) {
539 QMultiHash<ServiceRoot*, Feed*> feeds_per_root;
540
541 for (auto* fd : feeds) {
542 feeds_per_root.insert(fd->getParentServiceRoot(), fd);
543 }
544
545 for (auto* acc : feeds_per_root.uniqueKeys()) {
546 acc->onAfterFeedsPurged(feeds_per_root.values(acc));
547 }
548
549 reloadCountsOfWholeModel();
550 emit reloadMessageListRequested(false);
551 return true;
552 }
553 }
554 catch (const ApplicationException& ex) {
555 qCriticalNN << LOGSEC_CORE
556 << "Purging of articles from feeds failed with error:" << QUOTE_W_SPACE_DOT(ex.message());
557 }
558
559 return false;
560 }
561
562 QVariant FeedsModel::data(const QModelIndex& index, int role) const {
563 switch (role) {
564 case Qt::ItemDataRole::FontRole: {
565 RootItem* it = itemForIndex(index);
566 bool is_bold = it->countOfUnreadMessages() > 0;
567 bool is_striked = it->kind() == RootItem::Kind::Feed && it->toFeed()->isSwitchedOff() &&
568 qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::StrikethroughDisabledFeeds)).toBool();
569
570 return is_bold ? (is_striked ? m_boldStrikedFont : m_boldFont)
571 : (is_striked ? m_normalStrikedFont : m_normalFont);
572 }
573
574 case Qt::ItemDataRole::DecorationRole: {
575 if (index.column() == FDS_MODEL_TITLE_INDEX && m_updateDuringFetching) {
576 RootItem* it = itemForIndex(index);
577
578 if (it->isFetching()) {
579 return m_updateItemIcon;
580 }
581 }
582
583 return itemForIndex(index)->data(index.column(), role);
584 }
585
586 case Qt::ItemDataRole::ToolTipRole:
587 // NOTE: Fall-down to "default" if condition not met.
588 if (!qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::EnableTooltipsFeedsMessages)).toBool()) {
589 return QVariant();
590 }
591
592 default:
593 return itemForIndex(index)->data(index.column(), role);
594 }
595 }