Debian Codegraph @

src/librssguard/database/databasequeries.h

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #ifndef DATABASEQUERIES_H
4 #define DATABASEQUERIES_H
5
6 #include "core/messagefilter.h"
7 #include "definitions/typedefs.h"
8 #include "miscellaneous/application.h"
9 #include "miscellaneous/iconfactory.h"
10 #include "miscellaneous/textfactory.h"
11 #include "services/abstract/category.h"
12 #include "services/abstract/label.h"
13 #include "services/abstract/rootitem.h"
14 #include "services/abstract/search.h"
15 #include "services/abstract/serviceroot.h"
16
17 #include <QJsonDocument>
18 #include <QJsonObject>
19 #include <QMultiMap>
20 #include <QSqlError>
21 #include <QSqlQuery>
22
23 class RSSGUARD_DLLSPEC DatabaseQueries {
24 public:
25 static QMap<int, QString> messageTableAttributes(bool only_msg_table, bool is_sqlite);
26
27 // Custom data serializers.
28 static QString serializeCustomData(const QVariantHash& data);
29 static QVariantHash deserializeCustomData(const QString& data);
30
31 // Label operators.
32 static bool isLabelAssignedToMessage(const QSqlDatabase& db, Label* label, const Message& msg);
33 static bool deassignLabelFromMessage(const QSqlDatabase& db, Label* label, const Message& msg);
34 static bool assignLabelToMessage(const QSqlDatabase& db, Label* label, const Message& msg);
35 static bool setLabelsForMessage(const QSqlDatabase& db, const QList<Label*>& labels, const Message& msg);
36 static QList<Label*> getLabelsForAccount(const QSqlDatabase& db, int account_id);
37 static QList<Label*> getLabelsForMessage(const QSqlDatabase& db,
38 const Message& msg,
39 const QList<Label*>& installed_labels);
40 static bool updateLabel(const QSqlDatabase& db, Label* label);
41 static bool deleteLabel(const QSqlDatabase& db, Label* label);
42 static bool createLabel(const QSqlDatabase& db, Label* label, int account_id);
43
44 // Probe operators.
45 static void createProbe(const QSqlDatabase& db, Search* probe, int account_id);
46 static QList<Search*> getProbesForAccount(const QSqlDatabase& db, int account_id);
47 static void deleteProbe(const QSqlDatabase& db, Search* probe);
48 static void updateProbe(const QSqlDatabase& db, Search* probe);
49
50 // Message operators.
51 static void markProbeReadUnread(const QSqlDatabase& db, Search* probe, RootItem::ReadStatus read);
52 static bool markLabelledMessagesReadUnread(const QSqlDatabase& db, Label* label, RootItem::ReadStatus read);
53 static bool markImportantMessagesReadUnread(const QSqlDatabase& db, int account_id, RootItem::ReadStatus read);
54 static bool markUnreadMessagesRead(const QSqlDatabase& db, int account_id);
55 static bool markMessagesReadUnread(const QSqlDatabase& db, const QStringList& ids, RootItem::ReadStatus read);
56 static void markMessagesReadUnreadImportant(const QSqlDatabase& db,
57 int account_id,
58 const QStringList& custom_ids,
59 RootItem::ReadStatus read,
60 RootItem::Importance important);
61 static bool markMessageImportant(const QSqlDatabase& db, int id, RootItem::Importance importance);
62 static bool markFeedsReadUnread(const QSqlDatabase& db,
63 const QStringList& ids,
64 int account_id,
65 RootItem::ReadStatus read);
66 static bool markBinReadUnread(const QSqlDatabase& db, int account_id, RootItem::ReadStatus read);
67 static bool markAccountReadUnread(const QSqlDatabase& db, int account_id, RootItem::ReadStatus read);
68 static bool switchMessagesImportance(const QSqlDatabase& db, const QStringList& ids);
69 static bool permanentlyDeleteMessages(const QSqlDatabase& db, const QStringList& ids);
70 static bool deleteOrRestoreMessagesToFromBin(const QSqlDatabase& db, const QStringList& ids, bool deleted);
71 static bool restoreBin(const QSqlDatabase& db, int account_id);
72
73 // Purge database.
74 static bool removeUnwantedArticlesFromFeed(const QSqlDatabase& db,
75 const Feed* feed,
76 const Feed::ArticleIgnoreLimit& feed_setup,
77 const Feed::ArticleIgnoreLimit& app_setup);
78
79 static bool purgeFeedArticles(const QSqlDatabase& database, const QList<Feed*>& feeds);
80 static bool purgeMessage(const QSqlDatabase& db, int message_id);
81 static bool purgeImportantMessages(const QSqlDatabase& db);
82 static bool purgeReadMessages(const QSqlDatabase& db);
83 static bool purgeOldMessages(const QSqlDatabase& db, int older_than_days);
84 static bool purgeRecycleBin(const QSqlDatabase& db);
85 static bool purgeMessagesFromBin(const QSqlDatabase& db, bool clear_only_read, int account_id);
86 static bool purgeLeftoverMessages(const QSqlDatabase& db, int account_id);
87
88 // Counts of unread/all messages.
89 static QMap<QString, ArticleCounts> getMessageCountsForCategory(const QSqlDatabase& db,
90 const QString& custom_id,
91 int account_id,
92 bool include_total_counts,
93 bool* ok = nullptr);
94 static QMap<QString, ArticleCounts> getMessageCountsForAccount(const QSqlDatabase& db,
95 int account_id,
96 bool include_total_counts,
97 bool* ok = nullptr);
98 static ArticleCounts getMessageCountsForFeed(const QSqlDatabase& db,
99 const QString& feed_custom_id,
100 int account_id,
101 bool* ok = nullptr);
102 static ArticleCounts getMessageCountsForLabel(const QSqlDatabase& db,
103 Label* label,
104 int account_id,
105 bool* ok = nullptr);
106 static ArticleCounts getMessageCountsForProbe(const QSqlDatabase& db, Search* probe, int account_id);
107 static QMap<QString, ArticleCounts> getMessageCountsForAllLabels(const QSqlDatabase& db,
108 int account_id,
109 bool* ok = nullptr);
110 static QMap<QString, ArticleCounts> getCountOfAssignedLabelsToMessages(const QSqlDatabase& db,
111 const QList<Message>& messages,
112 int account_id,
113 bool* ok = nullptr);
114 static ArticleCounts getImportantMessageCounts(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
115 static int getUnreadMessageCounts(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
116 static ArticleCounts getMessageCountsForBin(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
117
118 // Get messages (for newspaper view for example).
119 static QList<Message> getUndeletedMessagesForProbe(const QSqlDatabase& db, const Search* probe);
120 static QList<Message> getUndeletedMessagesWithLabel(const QSqlDatabase& db, const Label* label, bool* ok = nullptr);
121 static QList<Message> getUndeletedLabelledMessages(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
122 static QList<Message> getUndeletedImportantMessages(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
123 static QList<Message> getUndeletedUnreadMessages(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
124 static QList<Message> getUndeletedMessagesForFeed(const QSqlDatabase& db,
125 const QString& feed_custom_id,
126 int account_id,
127 bool* ok = nullptr);
128 static QList<Message> getUndeletedMessagesForBin(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
129 static QList<Message> getUndeletedMessagesForAccount(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
130
131 static QList<Message> getArticlesSlice(const QSqlDatabase& db,
132 const QString& feed_custom_id,
133 int account_id,
134 bool newest_first,
135 bool unread_only,
136 bool starred_only,
137 qint64 start_after_article_date,
138 int row_offset,
139 int row_limit);
140
141 // Custom ID accumulators.
142 static QStringList bagOfMessages(const QSqlDatabase& db, ServiceRoot::BagOfMessages bag, const Feed* feed);
143 static QHash<QString, QStringList> bagsOfMessages(const QSqlDatabase& db, const QList<Label*>& labels);
144 static QStringList customIdsOfMessagesFromLabel(const QSqlDatabase& db,
145 Label* label,
146 RootItem::ReadStatus target_read,
147 bool* ok = nullptr);
148 static QStringList customIdsOfMessagesFromProbe(const QSqlDatabase& db,
149 Search* probe,
150 RootItem::ReadStatus target_read);
151 static QStringList customIdsOfImportantMessages(const QSqlDatabase& db,
152 RootItem::ReadStatus target_read,
153 int account_id,
154 bool* ok = nullptr);
155 static QStringList customIdsOfUnreadMessages(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
156 static QStringList customIdsOfMessagesFromAccount(const QSqlDatabase& db,
157 RootItem::ReadStatus target_read,
158 int account_id,
159 bool* ok = nullptr);
160 static QStringList customIdsOfMessagesFromBin(const QSqlDatabase& db,
161 RootItem::ReadStatus target_read,
162 int account_id,
163 bool* ok = nullptr);
164 static QStringList customIdsOfMessagesFromFeed(const QSqlDatabase& db,
165 const QString& feed_custom_id,
166 RootItem::ReadStatus target_read,
167 int account_id,
168 bool* ok = nullptr);
169
170 // Common account methods.
171 template <typename T>
172 static QList<ServiceRoot*> getAccounts(const QSqlDatabase& db, const QString& code, bool* ok = nullptr);
173
174 template <typename Categ, typename Fee>
175 static void loadRootFromDatabase(ServiceRoot* root);
176 static bool storeNewOauthTokens(const QSqlDatabase& db, const QString& refresh_token, int account_id);
177 static void createOverwriteAccount(const QSqlDatabase& db, ServiceRoot* account);
178
179 // Returns counts of updated messages <unread, all>.
180 static UpdatedArticles updateMessages(const QSqlDatabase& db,
181 QList<Message>& messages,
182 Feed* feed,
183 bool force_update,
184 QMutex* db_mutex,
185 bool* ok = nullptr);
186 static bool deleteAccount(const QSqlDatabase& db, ServiceRoot* account);
187 static bool deleteAccountData(const QSqlDatabase& db,
188 int account_id,
189 bool delete_messages_too,
190 bool delete_labels_too);
191 static bool cleanLabelledMessages(const QSqlDatabase& db, bool clean_read_only, Label* label);
192 static void cleanProbedMessages(const QSqlDatabase& db, bool clean_read_only, Search* probe);
193 static bool cleanImportantMessages(const QSqlDatabase& db, bool clean_read_only, int account_id);
194 static bool cleanUnreadMessages(const QSqlDatabase& db, int account_id);
195 static bool cleanFeeds(const QSqlDatabase& db, const QStringList& ids, bool clean_read_only, int account_id);
196 static void storeAccountTree(const QSqlDatabase& db, RootItem* tree_root, int account_id);
197 static void createOverwriteFeed(const QSqlDatabase& db, Feed* feed, int account_id, int new_parent_id);
198 static void createOverwriteCategory(const QSqlDatabase& db, Category* category, int account_id, int new_parent_id);
199 static bool deleteFeed(const QSqlDatabase& db, Feed* feed, int account_id);
200 static bool deleteCategory(const QSqlDatabase& db, Category* category);
201
202 template <typename T>
203 static Assignment getCategories(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
204
205 template <typename T>
206 static Assignment getFeeds(const QSqlDatabase& db,
207 const QList<MessageFilter*>& global_filters,
208 int account_id,
209 bool* ok = nullptr);
210
211 // Item order methods.
212 static void moveItem(RootItem* item, bool move_top, bool move_bottom, int move_index, const QSqlDatabase& db);
213
214 // Message filters operators.
215 static bool purgeLeftoverMessageFilterAssignments(const QSqlDatabase& db, int account_id);
216 static MessageFilter* addMessageFilter(const QSqlDatabase& db, const QString& title, const QString& script);
217 static void removeMessageFilter(const QSqlDatabase& db, int filter_id, bool* ok = nullptr);
218 static void removeMessageFilterAssignments(const QSqlDatabase& db, int filter_id, bool* ok = nullptr);
219 static QList<MessageFilter*> getMessageFilters(const QSqlDatabase& db, bool* ok = nullptr);
220 static QMultiMap<QString, int> messageFiltersInFeeds(const QSqlDatabase& db, int account_id, bool* ok = nullptr);
221 static void assignMessageFilterToFeed(const QSqlDatabase& db,
222 const QString& feed_custom_id,
223 int filter_id,
224 int account_id,
225 bool* ok = nullptr);
226 static void updateMessageFilter(const QSqlDatabase& db, MessageFilter* filter, bool* ok = nullptr);
227 static void removeMessageFilterFromFeed(const QSqlDatabase& db,
228 const QString& feed_custom_id,
229 int filter_id,
230 int account_id,
231 bool* ok = nullptr);
232
233 // Gmail account.
234 static QStringList getAllGmailRecipients(const QSqlDatabase& db, int account_id);
235
236 private:
237 static QString unnulifyString(const QString& str);
238
239 explicit DatabaseQueries() = default;
240 };
241
242 template <typename T>
243 QList<ServiceRoot*> DatabaseQueries::getAccounts(const QSqlDatabase& db, const QString& code, bool* ok) {
244 QSqlQuery query(db);
245 QList<ServiceRoot*> roots;
246
247 if (query.exec(QSL("SELECT * FROM Accounts WHERE type = '%1';").arg(code))) {
248 while (query.next()) {
249 ServiceRoot* root = new T();
250
251 // Load common data.
252 root->setAccountId(query.value(QSL("id")).toInt());
253 root->setSortOrder(query.value(QSL("ordr")).toInt());
254
255 QNetworkProxy proxy(QNetworkProxy::ProxyType(query.value(QSL("proxy_type")).toInt()),
256 query.value(QSL("proxy_host")).toString(),
257 query.value(QSL("proxy_port")).toInt(),
258 query.value(QSL("proxy_username")).toString(),
259 TextFactory::decrypt(query.value(QSL("proxy_password")).toString()));
260
261 root->setNetworkProxy(proxy);
262 root->setCustomDatabaseData(deserializeCustomData(query.value(QSL("custom_data")).toString()));
263
264 roots.append(root);
265 }
266
267 if (ok != nullptr) {
268 *ok = true;
269 }
270 }
271 else {
272 qWarningNN << LOGSEC_DB << "Loading of accounts with code" << QUOTE_W_SPACE(code)
273 << "failed with error:" << QUOTE_W_SPACE_DOT(query.lastError().text());
274
275 if (ok != nullptr) {
276 *ok = false;
277 }
278 }
279
280 return roots;
281 }
282
283 template <typename T>
284 Assignment DatabaseQueries::getCategories(const QSqlDatabase& db, int account_id, bool* ok) {
285 Assignment categories;
286
287 // Obtain data for categories from the database.
288 QSqlQuery query_categories(db);
289
290 query_categories.setForwardOnly(true);
291 query_categories.prepare(QSL("SELECT * FROM Categories WHERE account_id = :account_id;"));
292 query_categories.bindValue(QSL(":account_id"), account_id);
293
294 if (!query_categories.exec()) {
295 qFatal("Query for obtaining categories failed. Error message: '%s'.",
296 qPrintable(query_categories.lastError().text()));
297
298 if (ok != nullptr) {
299 *ok = false;
300 }
301 }
302 else {
303 if (ok != nullptr) {
304 *ok = true;
305 }
306 }
307
308 while (query_categories.next()) {
309 AssignmentItem pair;
310
311 pair.first = query_categories.value(CAT_DB_PARENT_ID_INDEX).toInt();
312 pair.second = new T();
313
314 auto* cat = static_cast<Category*>(pair.second);
315
316 cat->setId(query_categories.value(CAT_DB_ID_INDEX).toInt());
317 cat->setSortOrder(query_categories.value(CAT_DB_ORDER_INDEX).toInt());
318 cat->setCustomId(query_categories.value(CAT_DB_CUSTOM_ID_INDEX).toString());
319
320 if (cat->customId().isEmpty()) {
321 cat->setCustomId(QString::number(cat->id()));
322 }
323
324 cat->setTitle(query_categories.value(CAT_DB_TITLE_INDEX).toString());
325 cat->setDescription(query_categories.value(CAT_DB_DESCRIPTION_INDEX).toString());
326 cat->setCreationDate(TextFactory::parseDateTime(query_categories.value(CAT_DB_DCREATED_INDEX).value<qint64>()));
327 cat->setIcon(qApp->icons()->fromByteArray(query_categories.value(CAT_DB_ICON_INDEX).toByteArray()));
328
329 categories << pair;
330 }
331
332 return categories;
333 }
334
335 template <typename T>
336 Assignment DatabaseQueries::getFeeds(const QSqlDatabase& db,
337 const QList<MessageFilter*>& global_filters,
338 int account_id,
339 bool* ok) {
340 Assignment feeds;
341
342 // All categories are now loaded.
343 QSqlQuery query(db);
344 auto filters_in_feeds = messageFiltersInFeeds(db, account_id);
345
346 query.setForwardOnly(true);
347 query.prepare(QSL("SELECT * FROM Feeds WHERE account_id = :account_id;"));
348 query.bindValue(QSL(":account_id"), account_id);
349
350 if (!query.exec()) {
351 qFatal("Query for obtaining feeds failed. Error message: '%s'.", qPrintable(query.lastError().text()));
352
353 if (ok != nullptr) {
354 *ok = false;
355 }
356 }
357 else {
358 if (ok != nullptr) {
359 *ok = true;
360 }
361 }
362
363 while (query.next()) {
364 AssignmentItem pair;
365
366 pair.first = query.value(FDS_DB_CATEGORY_INDEX).toInt();
367
368 Feed* feed = new T();
369
370 // Load common data.
371 feed->setTitle(query.value(FDS_DB_TITLE_INDEX).toString());
372 feed->setId(query.value(FDS_DB_ID_INDEX).toInt());
373 feed->setSortOrder(query.value(FDS_DB_ORDER_INDEX).toInt());
374 feed->setSource(query.value(FDS_DB_SOURCE_INDEX).toString());
375 feed->setCustomId(query.value(FDS_DB_CUSTOM_ID_INDEX).toString());
376
377 if (feed->customId().isEmpty()) {
378 feed->setCustomId(QString::number(feed->id()));
379 }
380
381 feed->setDescription(QString::fromUtf8(query.value(FDS_DB_DESCRIPTION_INDEX).toByteArray()));
382 feed->setCreationDate(TextFactory::parseDateTime(query.value(FDS_DB_DCREATED_INDEX).value<qint64>()));
383 feed->setIcon(qApp->icons()->fromByteArray(query.value(FDS_DB_ICON_INDEX).toByteArray()));
384 feed->setAutoUpdateType(static_cast<Feed::AutoUpdateType>(query.value(FDS_DB_UPDATE_TYPE_INDEX).toInt()));
385 feed->setAutoUpdateInterval(query.value(FDS_DB_UPDATE_INTERVAL_INDEX).toInt());
386 feed->setIsSwitchedOff(query.value(FDS_DB_IS_OFF_INDEX).toBool());
387 feed->setIsQuiet(query.value(FDS_DB_IS_QUIET_INDEX).toBool());
388 feed->setRtlBehavior(query.value(FDS_DB_IS_RTL_INDEX).value<RtlBehavior>());
389
390 Feed::ArticleIgnoreLimit art;
391
392 art.m_addAnyArticlesToDb = query.value(FDS_DB_ADD_ANY_DATETIME_ARTICLES_INDEX).toBool();
393
394 qint64 time_to_avoid = query.value(FDS_DB_DATETIME_TO_AVOID_INDEX).value<qint64>();
395
396 if (time_to_avoid > 10000) {
397 art.m_dtToAvoid = TextFactory::parseDateTime(time_to_avoid);
398 }
399 else {
400 art.m_hoursToAvoid = time_to_avoid;
401 }
402
403 art.m_customizeLimitting = query.value(FDS_DB_KEEP_CUSTOMIZE).toBool();
404 art.m_keepCountOfArticles = query.value(FDS_DB_KEEP_ARTICLES_COUNT).toInt();
405 art.m_doNotRemoveUnread = query.value(FDS_DB_KEEP_UNREAD_ARTICLES).toBool();
406 art.m_doNotRemoveStarred = query.value(FDS_DB_KEEP_STARRED_ARTICLES).toBool();
407 art.m_moveToBinDontPurge = query.value(RECYCLE_ARTICLE_DONT_PURGE).toBool();
408
409 feed->setArticleIgnoreLimit(art);
410 feed->setOpenArticlesDirectly(query.value(FDS_DB_OPEN_ARTICLES_INDEX).toBool());
411
412 qDebugNN << LOGSEC_CORE << "Custom ID of feed when loading from DB is" << QUOTE_W_SPACE_DOT(feed->customId());
413
414 // Load custom data.
415 feed->setCustomDatabaseData(deserializeCustomData(query.value(FDS_DB_CUSTOM_DATA_INDEX).toString()));
416
417 if (filters_in_feeds.contains(feed->customId())) {
418 auto all_filters_for_this_feed = filters_in_feeds.values(feed->customId());
419
420 for (MessageFilter* fltr : global_filters) {
421 if (all_filters_for_this_feed.contains(fltr->id())) {
422 feed->appendMessageFilter(fltr);
423 }
424 }
425 }
426
427 pair.second = feed;
428
429 feeds << pair;
430 }
431
432 return feeds;
433 }
434
435 template <typename Categ, typename Fee>
436 void DatabaseQueries::loadRootFromDatabase(ServiceRoot* root) {
437 QSqlDatabase database = qApp->database()->driver()->connection(root->metaObject()->className());
438 Assignment categories = DatabaseQueries::getCategories<Categ>(database, root->accountId());
439 Assignment feeds = DatabaseQueries::getFeeds<Fee>(database, qApp->feedReader()->messageFilters(), root->accountId());
440 auto labels = DatabaseQueries::getLabelsForAccount(database, root->accountId());
441 auto probes = DatabaseQueries::getProbesForAccount(database, root->accountId());
442
443 root->performInitialAssembly(categories, feeds, labels, probes);
444 }
445
446 #endif // DATABASEQUERIES_H