| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "gui/dialogs/formmessagefiltersmanager.h" |
| 4 | |
| 5 | #include "3rd-party/boolinq/boolinq.h" |
| 6 | #include "core/messagefilter.h" |
| 7 | #include "core/messagesforfiltersmodel.h" |
| 8 | #include "database/databasequeries.h" |
| 9 | #include "exceptions/filteringexception.h" |
| 10 | #include "gui/guiutilities.h" |
| 11 | #include "gui/messagebox.h" |
| 12 | #include "gui/reusable/jssyntaxhighlighter.h" |
| 13 | #include "miscellaneous/application.h" |
| 14 | #include "miscellaneous/feedreader.h" |
| 15 | #include "miscellaneous/iconfactory.h" |
| 16 | #include "network-web/webfactory.h" |
| 17 | #include "services/abstract/accountcheckmodel.h" |
| 18 | #include "services/abstract/feed.h" |
| 19 | |
| 20 | #include <QDateTime> |
| 21 | #include <QJSEngine> |
| 22 | #include <QProcess> |
| 23 | |
| 24 | FormMessageFiltersManager::FormMessageFiltersManager(FeedReader* reader, |
| 25 | const QList<ServiceRoot*>& accounts, |
| 26 | QWidget* parent) |
| 27 | : QDialog(parent), m_feedsModel(new AccountCheckSortedModel(this)), m_rootItem(new RootItem()), m_accounts(accounts), |
| 28 | m_reader(reader), m_loadingFilter(false), m_msgModel(new MessagesForFiltersModel(this)) { |
| 29 | m_ui.setupUi(this); |
| 30 | |
| 31 | m_highlighter = new JsSyntaxHighlighter(m_ui.m_txtScript->document()); |
| 32 | |
| 33 | std::sort(m_accounts.begin(), m_accounts.end(), [](const ServiceRoot* lhs, const ServiceRoot* rhs) { |
| 34 | return lhs->title().compare(rhs->title(), Qt::CaseSensitivity::CaseInsensitive) < 0; |
| 35 | }); |
| 36 | |
| 37 | // TODO: Add sorting. |
| 38 | m_ui.m_treeExistingMessages->setModel(m_msgModel); |
| 39 | |
| 40 | GuiUtilities::applyDialogProperties(*this, qApp->icons()->fromTheme(QSL("view-list-details"))); |
| 41 | |
| 42 | m_ui.m_treeFeeds->setIndentation(FEEDS_VIEW_INDENTATION); |
| 43 | m_ui.m_treeFeeds->setModel(m_feedsModel); |
| 44 | m_ui.m_btnCheckAll->setIcon(qApp->icons()->fromTheme(QSL("dialog-yes"), QSL("edit-select-all"))); |
| 45 | m_ui.m_btnUncheckAll->setIcon(qApp->icons()->fromTheme(QSL("dialog-no"), QSL("edit-select-none"))); |
| 46 | m_ui.m_btnAddNew->setIcon(qApp->icons()->fromTheme(QSL("list-add"))); |
| 47 | m_ui.m_btnRemoveSelected->setIcon(qApp->icons()->fromTheme(QSL("list-remove"))); |
| 48 | m_ui.m_btnBeautify->setIcon(qApp->icons()->fromTheme(QSL("format-justify-fill"))); |
| 49 | m_ui.m_btnTest->setIcon(qApp->icons()->fromTheme(QSL("media-playback-start"))); |
| 50 | m_ui.m_btnRunOnMessages->setIcon(qApp->icons()->fromTheme(QSL("media-playback-start"))); |
| 51 | m_ui.m_btnDetailedHelp->setIcon(qApp->icons()->fromTheme(QSL("help-contents"))); |
| 52 | m_ui.m_txtScript->setFont(QFontDatabase::systemFont(QFontDatabase::SystemFont::FixedFont)); |
| 53 | m_ui.m_treeExistingMessages->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); |
| 54 | |
| 55 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_ISREAD, |
| 56 | QHeaderView::ResizeMode::ResizeToContents); |
| 57 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_ISIMPORTANT, |
| 58 | QHeaderView::ResizeMode::ResizeToContents); |
| 59 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_ISDELETED, |
| 60 | QHeaderView::ResizeMode::ResizeToContents); |
| 61 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_AUTHOR, |
| 62 | QHeaderView::ResizeMode::ResizeToContents); |
| 63 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_CREATED, |
| 64 | QHeaderView::ResizeMode::ResizeToContents); |
| 65 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_SCORE, |
| 66 | QHeaderView::ResizeMode::ResizeToContents); |
| 67 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_TITLE, QHeaderView::ResizeMode::Interactive); |
| 68 | m_ui.m_treeExistingMessages->header()->setSectionResizeMode(MFM_MODEL_URL, QHeaderView::ResizeMode::Interactive); |
| 69 | |
| 70 | connect(m_ui.m_btnDetailedHelp, &QPushButton::clicked, this, []() { |
| 71 | qApp->web()->openUrlInExternalBrowser(QSL(MSG_FILTERING_HELP)); |
| 72 | }); |
| 73 | connect(m_ui.m_listFilters, &QListWidget::currentRowChanged, this, &FormMessageFiltersManager::loadFilter); |
| 74 | connect(m_ui.m_btnAddNew, &QPushButton::clicked, this, [this]() { |
| 75 | addNewFilter(); |
| 76 | }); |
| 77 | connect(m_ui.m_btnRemoveSelected, &QPushButton::clicked, this, &FormMessageFiltersManager::removeSelectedFilter); |
| 78 | connect(m_ui.m_txtTitle, &QLineEdit::textChanged, this, &FormMessageFiltersManager::saveSelectedFilter); |
| 79 | connect(m_ui.m_txtScript, &QPlainTextEdit::textChanged, this, &FormMessageFiltersManager::saveSelectedFilter); |
| 80 | connect(m_ui.m_btnTest, &QPushButton::clicked, this, &FormMessageFiltersManager::testFilter); |
| 81 | connect(m_ui.m_btnBeautify, &QPushButton::clicked, this, &FormMessageFiltersManager::beautifyScript); |
| 82 | connect(m_ui.m_cmbAccounts, |
| 83 | static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), |
| 84 | this, |
| 85 | &FormMessageFiltersManager::onAccountChanged); |
| 86 | connect(m_ui.m_btnCheckAll, &QPushButton::clicked, m_feedsModel->sourceModel(), &AccountCheckModel::checkAllItems); |
| 87 | connect(m_ui.m_btnUncheckAll, |
| 88 | &QPushButton::clicked, |
| 89 | m_feedsModel->sourceModel(), |
| 90 | &AccountCheckModel::uncheckAllItems); |
| 91 | connect(m_feedsModel->sourceModel(), |
| 92 | &AccountCheckModel::checkStateChanged, |
| 93 | this, |
| 94 | &FormMessageFiltersManager::onFeedChecked); |
| 95 | connect(m_ui.m_treeFeeds->selectionModel(), |
| 96 | &QItemSelectionModel::selectionChanged, |
| 97 | this, |
| 98 | &FormMessageFiltersManager::displayMessagesOfFeed); |
| 99 | connect(m_ui.m_btnRunOnMessages, &QPushButton::clicked, this, &FormMessageFiltersManager::processCheckedFeeds); |
| 100 | connect(m_ui.m_treeExistingMessages, |
| 101 | &QTreeView::customContextMenuRequested, |
| 102 | this, |
| 103 | &FormMessageFiltersManager::showMessageContextMenu); |
| 104 | |
| 105 | connect(m_ui.m_searchWidget, &SearchTextWidget::searchCancelled, this, [this]() { |
| 106 | m_ui.m_txtScript->find(QString()); |
| 107 | }); |
| 108 | connect(m_ui.m_searchWidget, &SearchTextWidget::searchForText, this, [this](const QString& text, bool backwards) { |
| 109 | m_ui.m_txtScript->find(text, backwards ? QTextDocument::FindFlag::FindBackward : QTextDocument::FindFlags()); |
| 110 | m_ui.m_searchWidget->setFocus(); |
| 111 | }); |
| 112 | |
| 113 | m_ui.m_txtScript->installEventFilter(this); |
| 114 | m_ui.m_searchWidget->hide(); |
| 115 | |
| 116 | initializeTestingMessage(); |
| 117 | initializePremadeFilters(); |
| 118 | loadFilters(); |
| 119 | loadFilter(); |
| 120 | loadAccounts(); |
| 121 | } |
| 122 | |
| 123 | FormMessageFiltersManager::~FormMessageFiltersManager() { |
| 124 | delete m_rootItem; |
| 125 | } |
| 126 | |
| 127 | MessageFilter* FormMessageFiltersManager::selectedFilter() const { |
| 128 | if (m_ui.m_listFilters->currentItem() == nullptr) { |
| 129 | return nullptr; |
| 130 | } |
| 131 | else { |
| 132 | return m_ui.m_listFilters->currentItem()->data(Qt::ItemDataRole::UserRole).value<MessageFilter*>(); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | bool FormMessageFiltersManager::eventFilter(QObject* watched, QEvent* event) { |
| 137 | Q_UNUSED(watched) |
| 138 | |
| 139 | if (event->type() == QEvent::KeyPress) { |
| 140 | QKeyEvent* key_event = static_cast<QKeyEvent*>(event); |
| 141 | |
| 142 | // Find text. |
| 143 | if (key_event->matches(QKeySequence::StandardKey::Find)) { |
| 144 | m_ui.m_searchWidget->clear(); |
| 145 | m_ui.m_searchWidget->show(); |
| 146 | m_ui.m_searchWidget->setFocus(); |
| 147 | return true; |
| 148 | } |
| 149 | |
| 150 | // Hide visible search box. |
| 151 | if (key_event->key() == Qt::Key::Key_Escape && m_ui.m_searchWidget->isVisible()) { |
| 152 | m_ui.m_searchWidget->hide(); |
| 153 | return true; |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | return false; |
| 158 | } |
| 159 | |
| 160 | ServiceRoot* FormMessageFiltersManager::selectedAccount() const { |
| 161 | auto dat = m_ui.m_cmbAccounts->currentData(Qt::ItemDataRole::UserRole); |
| 162 | |
| 163 | return dat.isNull() ? nullptr : dat.value<ServiceRoot*>(); |
| 164 | } |
| 165 | |
| 166 | void FormMessageFiltersManager::filterMessagesLikeThis(const Message& msg) { |
| 167 | QString filter_script = |
| 168 | QSL("function filterMessage() {\n" |
| 169 | " // Adjust the condition to suit your needs.\n" |
| 170 | " var is_message_same =\n" |
| 171 | " msg.isRead == %1 &&\n" |
| 172 | " msg.isImportant == %2 &&\n" |
| 173 | " msg.title == '%3' &&\n" |
| 174 | " msg.url == '%4';\n" |
| 175 | "\n" |
| 176 | " if (is_message_same) {\n" |
| 177 | " return MessageObject.Accept;\n" |
| 178 | " }\n" |
| 179 | " else {\n" |
| 180 | " return MessageObject.Ignore;\n" |
| 181 | " }\n" |
| 182 | "}") |
| 183 | .arg(QString::number(int(msg.m_isRead)), QString::number(int(msg.m_isImportant)), msg.m_title, msg.m_url); |
| 184 | |
| 185 | addNewFilter(filter_script); |
| 186 | } |
| 187 | |
| 188 | void FormMessageFiltersManager::showMessageContextMenu(QPoint pos) { |
| 189 | Message* msg = m_msgModel->messageForRow(m_ui.m_treeExistingMessages->indexAt(pos).row()); |
| 190 | |
| 191 | if (msg != nullptr) { |
| 192 | QMenu menu(tr("Context menu"), m_ui.m_treeExistingMessages); |
| 193 | |
| 194 | menu.addAction(tr("Filter articles like this"), this, [=]() { |
| 195 | filterMessagesLikeThis(*msg); |
| 196 | }); |
| 197 | menu.exec(m_ui.m_treeExistingMessages->mapToGlobal(pos)); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | void FormMessageFiltersManager::removeSelectedFilter() { |
| 202 | auto* fltr = selectedFilter(); |
| 203 | |
| 204 | if (fltr == nullptr) { |
| 205 | return; |
| 206 | } |
| 207 | |
| 208 | if (MsgBox::show(this, |
| 209 | QMessageBox::Icon::Question, |
| 210 | tr("Are you sure?"), |
| 211 | tr("Do you really want to remove selected filter?"), |
| 212 | {}, |
| 213 | fltr->name(), |
| 214 | QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No, |
| 215 | QMessageBox::StandardButton::No) == QMessageBox::StandardButton::Yes) { |
| 216 | m_reader->removeMessageFilter(fltr); |
| 217 | delete m_ui.m_listFilters->currentItem(); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | void FormMessageFiltersManager::loadFilters() { |
| 222 | auto flt = m_reader->messageFilters(); |
| 223 | |
| 224 | for (auto* fltr : std::as_const(flt)) { |
| 225 | auto* it = new QListWidgetItem(fltr->name(), m_ui.m_listFilters); |
| 226 | |
| 227 | it->setData(Qt::ItemDataRole::UserRole, QVariant::fromValue<MessageFilter*>(fltr)); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | void FormMessageFiltersManager::addNewFilter(const QString& filter_script) { |
| 232 | try { |
| 233 | auto* fltr = m_reader->addMessageFilter(tr("New article filter"), |
| 234 | filter_script.isEmpty() |
| 235 | ? QSL("function filterMessage() { return MessageObject.Accept; }") |
| 236 | : filter_script); |
| 237 | auto* it = new QListWidgetItem(fltr->name(), m_ui.m_listFilters); |
| 238 | |
| 239 | it->setData(Qt::ItemDataRole::UserRole, QVariant::fromValue<MessageFilter*>(fltr)); |
| 240 | |
| 241 | m_ui.m_listFilters->setCurrentRow(m_ui.m_listFilters->count() - 1); |
| 242 | } |
| 243 | catch (const ApplicationException& ex) { |
| 244 | MsgBox::show(this, |
| 245 | QMessageBox::Icon::Critical, |
| 246 | tr("Error"), |
| 247 | tr("Cannot save new filter, error: '%1'.").arg(ex.message())); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | void FormMessageFiltersManager::saveSelectedFilter() { |
| 252 | if (m_loadingFilter) { |
| 253 | return; |
| 254 | } |
| 255 | |
| 256 | auto* fltr = selectedFilter(); |
| 257 | |
| 258 | if (fltr == nullptr || m_ui.m_txtTitle->text().isEmpty() || m_ui.m_txtScript->toPlainText().isEmpty()) { |
| 259 | return; |
| 260 | } |
| 261 | |
| 262 | fltr->setName(m_ui.m_txtTitle->text()); |
| 263 | fltr->setScript(m_ui.m_txtScript->toPlainText()); |
| 264 | m_ui.m_listFilters->currentItem()->setText(fltr->name()); |
| 265 | |
| 266 | m_reader->updateMessageFilter(fltr); |
| 267 | } |
| 268 | |
| 269 | void FormMessageFiltersManager::loadFilter() { |
| 270 | auto* filter = selectedFilter(); |
| 271 | auto* acc = selectedAccount(); |
| 272 | |
| 273 | loadAccount(acc); |
| 274 | showFilter(filter); |
| 275 | loadFilterFeedAssignments(filter, acc); |
| 276 | } |
| 277 | |
| 278 | void FormMessageFiltersManager::testFilter() { |
| 279 | m_ui.m_txtErrors->clear(); |
| 280 | |
| 281 | // Perform per-message filtering. |
| 282 | auto* selected_fd_cat = selectedCategoryFeed(); |
| 283 | QJSEngine filter_engine; |
| 284 | QSqlDatabase database = qApp->database()->driver()->connection(metaObject()->className()); |
| 285 | MessageObject msg_obj(&database, |
| 286 | selected_fd_cat->kind() == RootItem::Kind::Feed ? selected_fd_cat->toFeed() : nullptr, |
| 287 | selectedAccount(), |
| 288 | false); |
| 289 | auto* fltr = selectedFilter(); |
| 290 | |
| 291 | MessageFilter::initializeFilteringEngine(filter_engine, &msg_obj); |
| 292 | |
| 293 | // Test real messages. |
| 294 | try { |
| 295 | m_msgModel->testFilter(fltr, &filter_engine, &msg_obj); |
| 296 | } |
| 297 | catch (const FilteringException& ex) { |
| 298 | m_ui.m_txtErrors->setTextColor(Qt::GlobalColor::red); |
| 299 | m_ui.m_txtErrors->insertPlainText(tr("EXISTING articles filtering error: '%1'.\n").arg(ex.message())); |
| 300 | |
| 301 | // See output. |
| 302 | m_ui.m_twMessages->setCurrentIndex(2); |
| 303 | } |
| 304 | |
| 305 | // Test sample message. |
| 306 | Message msg = testingMessage(); |
| 307 | |
| 308 | msg_obj.setMessage(&msg); |
| 309 | |
| 310 | try { |
| 311 | MessageObject::FilteringAction decision = fltr->filterMessage(&filter_engine); |
| 312 | |
| 313 | m_ui.m_txtErrors->setTextColor(decision == MessageObject::FilteringAction::Accept ? Qt::GlobalColor::darkGreen |
| 314 | : Qt::GlobalColor::red); |
| 315 | |
| 316 | QString answer = tr("Article will be %1.\n\n") |
| 317 | .arg(decision == MessageObject::FilteringAction::Accept ? tr("ACCEPTED") : tr("REJECTED")); |
| 318 | |
| 319 | answer += tr("Output (modified) article is:\n" |
| 320 | " Title = '%1'\n" |
| 321 | " URL = '%2'\n" |
| 322 | " Author = '%3'\n" |
| 323 | " Is read/important = '%4/%5'\n" |
| 324 | " Created on = '%6'\n" |
| 325 | " Contents = '%7'\n" |
| 326 | " RAW contents = '%8'") |
| 327 | .arg(msg.m_title, |
| 328 | msg.m_url, |
| 329 | msg.m_author, |
| 330 | msg.m_isRead ? tr("yes") : tr("no"), |
| 331 | msg.m_isImportant ? tr("yes") : tr("no"), |
| 332 | QString::number(msg.m_created.toMSecsSinceEpoch()), |
| 333 | msg.m_contents, |
| 334 | msg.m_rawContents); |
| 335 | |
| 336 | m_ui.m_txtErrors->insertPlainText(answer); |
| 337 | } |
| 338 | catch (const FilteringException& ex) { |
| 339 | m_ui.m_txtErrors->setTextColor(Qt::GlobalColor::red); |
| 340 | m_ui.m_txtErrors->insertPlainText(tr("SAMPLE article filtering error: '%1'.\n").arg(ex.message())); |
| 341 | |
| 342 | // See output. |
| 343 | m_ui.m_twMessages->setCurrentIndex(2); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | void FormMessageFiltersManager::displayMessagesOfFeed() { |
| 348 | auto* item = selectedCategoryFeed(); |
| 349 | |
| 350 | if (item != nullptr) { |
| 351 | m_msgModel->setMessages(item->undeletedMessages()); |
| 352 | } |
| 353 | else { |
| 354 | m_msgModel->setMessages({}); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | void FormMessageFiltersManager::processCheckedFeeds() { |
| 359 | QList<RootItem*> checked = m_feedsModel->sourceModel()->checkedItems(); |
| 360 | auto* fltr = selectedFilter(); |
| 361 | QSqlDatabase database = qApp->database()->driver()->connection(metaObject()->className()); |
| 362 | |
| 363 | for (RootItem* it : checked) { |
| 364 | if (it->kind() == RootItem::Kind::Feed) { |
| 365 | QJSEngine filter_engine; |
| 366 | MessageObject msg_obj(&database, it->toFeed(), selectedAccount(), false); |
| 367 | |
| 368 | MessageFilter::initializeFilteringEngine(filter_engine, &msg_obj); |
| 369 | |
| 370 | // We process messages of the feed. |
| 371 | QList<Message> msgs = it->undeletedMessages(); |
| 372 | QList<Message> read_msgs, important_msgs; |
| 373 | |
| 374 | for (int i = 0; i < msgs.size(); i++) { |
| 375 | auto labels_in_message = DatabaseQueries::getLabelsForMessage(database, msgs[i], msg_obj.availableLabels()); |
| 376 | |
| 377 | // Create backup of message. |
| 378 | Message* msg = &msgs[i]; |
| 379 | |
| 380 | msg->m_assignedLabels = labels_in_message; |
| 381 | msg->m_rawContents = Message::generateRawAtomContents(*msg); |
| 382 | |
| 383 | Message msg_backup(*msg); |
| 384 | |
| 385 | msg_obj.setMessage(msg); |
| 386 | |
| 387 | bool remove_from_list = false; |
| 388 | |
| 389 | try { |
| 390 | MessageObject::FilteringAction result = fltr->filterMessage(&filter_engine); |
| 391 | |
| 392 | if (result == MessageObject::FilteringAction::Purge) { |
| 393 | remove_from_list = true; |
| 394 | |
| 395 | // Purge the message completely and remove leftovers. |
| 396 | DatabaseQueries::purgeMessage(database, msg->m_id); |
| 397 | } |
| 398 | else if (result == MessageObject::FilteringAction::Ignore) { |
| 399 | remove_from_list = true; |
| 400 | } |
| 401 | } |
| 402 | catch (const FilteringException& ex) { |
| 403 | qCriticalNN << LOGSEC_CORE << "Error when running script when processing existing messages:" |
| 404 | << QUOTE_W_SPACE_DOT(ex.message()); |
| 405 | |
| 406 | continue; |
| 407 | } |
| 408 | |
| 409 | if (!msg_backup.m_isRead && msg->m_isRead) { |
| 410 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Message with custom ID: '" << msg_backup.m_customId |
| 411 | << "' was marked as read by message scripts."; |
| 412 | |
| 413 | read_msgs << *msg; |
| 414 | } |
| 415 | |
| 416 | if (!msg_backup.m_isImportant && msg->m_isImportant) { |
| 417 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Message with custom ID: '" << msg_backup.m_customId |
| 418 | << "' was marked as important by message scripts."; |
| 419 | |
| 420 | important_msgs << *msg; |
| 421 | } |
| 422 | |
| 423 | // Process changed labels. |
| 424 | for (Label* lbl : std::as_const(msg_backup.m_assignedLabels)) { |
| 425 | if (!msg->m_assignedLabels.contains(lbl)) { |
| 426 | // Label is not there anymore, it was deassigned. |
| 427 | lbl->deassignFromMessage(*msg); |
| 428 | |
| 429 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "It was detected that label" << QUOTE_W_SPACE(lbl->customId()) |
| 430 | << "was DEASSIGNED from message" << QUOTE_W_SPACE(msg->m_customId) << "by message filter(s)."; |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | for (Label* lbl : std::as_const(msg->m_assignedLabels)) { |
| 435 | if (!msg_backup.m_assignedLabels.contains(lbl)) { |
| 436 | // Label is in new message, but is not in old message, it |
| 437 | // was newly assigned. |
| 438 | lbl->assignToMessage(*msg); |
| 439 | |
| 440 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "It was detected that label" << QUOTE_W_SPACE(lbl->customId()) |
| 441 | << "was ASSIGNED to message" << QUOTE_W_SPACE(msg->m_customId) << "by message filter(s)."; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | if (remove_from_list) { |
| 446 | // Do not update message. |
| 447 | msgs.removeAt(i--); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | if (!read_msgs.isEmpty()) { |
| 452 | // Now we push new read states to the service. |
| 453 | if (it->getParentServiceRoot()->onBeforeSetMessagesRead(it, read_msgs, RootItem::ReadStatus::Read)) { |
| 454 | qDebugNN << LOGSEC_FEEDDOWNLOADER << "Notified services about messages marked as read by message filters."; |
| 455 | } |
| 456 | else { |
| 457 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 458 | << "Notification of services about messages marked as read by message filters FAILED."; |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | if (!important_msgs.isEmpty()) { |
| 463 | // Now we push new read states to the service. |
| 464 | auto list = boolinq::from(important_msgs) |
| 465 | .select([](const Message& msg) { |
| 466 | return ImportanceChange(msg, RootItem::Importance::Important); |
| 467 | }) |
| 468 | .toStdList(); |
| 469 | QList<ImportanceChange> chngs = FROM_STD_LIST(QList<ImportanceChange>, list); |
| 470 | |
| 471 | if (it->getParentServiceRoot()->onBeforeSwitchMessageImportance(it, chngs)) { |
| 472 | qDebugNN << LOGSEC_FEEDDOWNLOADER |
| 473 | << "Notified services about messages marked as important by message filters."; |
| 474 | } |
| 475 | else { |
| 476 | qCriticalNN << LOGSEC_FEEDDOWNLOADER |
| 477 | << "Notification of services about messages marked as important by message filters FAILED."; |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | // Update messages in DB and reload selection. |
| 482 | it->getParentServiceRoot()->updateMessages(msgs, it->toFeed(), true, nullptr); |
| 483 | displayMessagesOfFeed(); |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | void FormMessageFiltersManager::loadAccount(ServiceRoot* account) { |
| 489 | m_feedsModel->setRootItem(account, false, true); |
| 490 | |
| 491 | if (account != nullptr) { |
| 492 | m_msgModel->setMessages(account->undeletedMessages()); |
| 493 | } |
| 494 | else { |
| 495 | m_msgModel->setMessages({}); |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | void FormMessageFiltersManager::loadFilterFeedAssignments(MessageFilter* filter, ServiceRoot* account) { |
| 500 | if (account == nullptr || filter == nullptr) { |
| 501 | return; |
| 502 | } |
| 503 | |
| 504 | m_loadingFilter = true; |
| 505 | auto stf = account->getSubTreeFeeds(); |
| 506 | |
| 507 | for (auto* feed : std::as_const(stf)) { |
| 508 | if (feed->messageFilters().contains(filter)) { |
| 509 | m_feedsModel->sourceModel()->setItemChecked(feed, Qt::CheckState::Checked); |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | m_loadingFilter = false; |
| 514 | } |
| 515 | |
| 516 | void FormMessageFiltersManager::onAccountChanged() { |
| 517 | // Load feeds/categories of the account and check marks. |
| 518 | auto* filter = selectedFilter(); |
| 519 | auto* acc = selectedAccount(); |
| 520 | |
| 521 | loadAccount(acc); |
| 522 | loadFilterFeedAssignments(filter, acc); |
| 523 | } |
| 524 | |
| 525 | void FormMessageFiltersManager::onFeedChecked(RootItem* item, Qt::CheckState state) { |
| 526 | if (m_loadingFilter) { |
| 527 | return; |
| 528 | } |
| 529 | |
| 530 | auto* feed = qobject_cast<Feed*>(item); |
| 531 | |
| 532 | if (feed == nullptr) { |
| 533 | return; |
| 534 | } |
| 535 | |
| 536 | // Update feed/filter assignemnts. |
| 537 | switch (state) { |
| 538 | case Qt::CheckState::Checked: |
| 539 | m_reader->assignMessageFilterToFeed(feed, selectedFilter()); |
| 540 | break; |
| 541 | |
| 542 | case Qt::CheckState::Unchecked: |
| 543 | m_reader->removeMessageFilterToFeedAssignment(feed, selectedFilter()); |
| 544 | break; |
| 545 | |
| 546 | case Qt::CheckState::PartiallyChecked: |
| 547 | break; |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | void FormMessageFiltersManager::showFilter(MessageFilter* filter) { |
| 552 | m_loadingFilter = true; |
| 553 | |
| 554 | if (filter == nullptr) { |
| 555 | m_ui.m_txtTitle->clear(); |
| 556 | m_ui.m_txtScript->clear(); |
| 557 | m_ui.m_gbDetails->setEnabled(false); |
| 558 | |
| 559 | m_ui.m_treeFeeds->setEnabled(false); |
| 560 | m_ui.m_btnCheckAll->setEnabled(false); |
| 561 | m_ui.m_btnUncheckAll->setEnabled(false); |
| 562 | m_ui.m_cmbAccounts->setEnabled(false); |
| 563 | } |
| 564 | else { |
| 565 | m_ui.m_txtTitle->setText(filter->name()); |
| 566 | m_ui.m_txtScript->setPlainText(filter->script()); |
| 567 | m_ui.m_gbDetails->setEnabled(true); |
| 568 | |
| 569 | m_ui.m_treeFeeds->setEnabled(true); |
| 570 | m_ui.m_btnCheckAll->setEnabled(true); |
| 571 | m_ui.m_btnUncheckAll->setEnabled(true); |
| 572 | m_ui.m_cmbAccounts->setEnabled(true); |
| 573 | } |
| 574 | |
| 575 | // See message. |
| 576 | m_ui.m_twMessages->setCurrentIndex(0); |
| 577 | m_loadingFilter = false; |
| 578 | } |
| 579 | |
| 580 | void FormMessageFiltersManager::loadAccounts() { |
| 581 | for (auto* acc : std::as_const(m_accounts)) { |
| 582 | m_ui.m_cmbAccounts->addItem(acc->icon(), acc->title(), QVariant::fromValue(acc)); |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | void FormMessageFiltersManager::beautifyScript() { |
| 587 | QProcess proc_clang_format(this); |
| 588 | |
| 589 | proc_clang_format.setInputChannelMode(QProcess::InputChannelMode::ManagedInputChannel); |
| 590 | proc_clang_format.setArguments({"--assume-filename=script.js", "--style=Chromium"}); |
| 591 | |
| 592 | #if defined(Q_OS_WIN) |
| 593 | proc_clang_format.setProgram(qApp->applicationDirPath() + QDir::separator() + QSL("clang-format.exe")); |
| 594 | #else |
| 595 | proc_clang_format.setProgram(QSL("clang-format")); |
| 596 | #endif |
| 597 | |
| 598 | if (!proc_clang_format.open() || proc_clang_format.error() == QProcess::ProcessError::FailedToStart) { |
| 599 | MsgBox::show(this, |
| 600 | QMessageBox::Icon::Critical, |
| 601 | tr("Cannot find 'clang-format'"), |
| 602 | tr("Script was not beautified, because 'clang-format' tool was not found.")); |
| 603 | return; |
| 604 | } |
| 605 | |
| 606 | proc_clang_format.write(m_ui.m_txtScript->toPlainText().toUtf8()); |
| 607 | proc_clang_format.closeWriteChannel(); |
| 608 | |
| 609 | if (proc_clang_format.waitForFinished(3000)) { |
| 610 | if (proc_clang_format.exitCode() == 0) { |
| 611 | auto script = proc_clang_format.readAllStandardOutput(); |
| 612 | |
| 613 | m_ui.m_txtScript->setPlainText(script); |
| 614 | } |
| 615 | else { |
| 616 | auto err = proc_clang_format.readAllStandardError(); |
| 617 | |
| 618 | MsgBox::show(this, |
| 619 | QMessageBox::Icon::Critical, |
| 620 | tr("Error"), |
| 621 | tr("Script was not beautified, because 'clang-format' tool thrown error."), |
| 622 | QString(), |
| 623 | err); |
| 624 | } |
| 625 | } |
| 626 | else { |
| 627 | proc_clang_format.kill(); |
| 628 | MsgBox::show(this, |
| 629 | QMessageBox::Icon::Critical, |
| 630 | tr("Beautifier was running for too long time"), |
| 631 | tr("Script was not beautified, is 'clang-format' installed?")); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | void FormMessageFiltersManager::insertPremadeFilter(QAction* act_filter) { |
| 636 | QString filter_path = QSL(":/scripts/filters/") + act_filter->text(); |
| 637 | |
| 638 | try { |
| 639 | m_ui.m_txtScript->setPlainText(QString::fromUtf8(IOFactory::readFile(filter_path))); |
| 640 | } |
| 641 | catch (...) { |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | void FormMessageFiltersManager::initializePremadeFilters() { |
| 646 | QMenu* mn_filters = new QMenu(this); |
| 647 | |
| 648 | connect(mn_filters, &QMenu::triggered, this, &FormMessageFiltersManager::insertPremadeFilter); |
| 649 | |
| 650 | auto js_files = QDir(QSL(":/scripts/filters")).entryList(); |
| 651 | |
| 652 | for (const QString& js_file : js_files) { |
| 653 | mn_filters->addAction(js_file); |
| 654 | } |
| 655 | |
| 656 | m_ui.m_btnPremadeFilters->setMenu(mn_filters); |
| 657 | } |
| 658 | |
| 659 | void FormMessageFiltersManager::initializeTestingMessage() { |
| 660 | m_ui.m_cbSampleImportant->setChecked(true); |
| 661 | m_ui.m_txtSampleUrl->setText(QSL("https://mynews.com/news/5")); |
| 662 | m_ui.m_txtSampleTitle->setText(QSL("Year of Linux Desktop")); |
| 663 | m_ui.m_txtSampleAuthor->setText(QSL("Napoleon Bonaparte")); |
| 664 | m_ui.m_txtSampleContents->setPlainText(QSL("<p>Browsers usually insert quotation marks around the q element.</p>" |
| 665 | "<p>WWF's goal is to: <q>Build a future where people live in harmony " |
| 666 | "with nature.</q></p>")); |
| 667 | m_ui.m_txtSampleCreatedOn->setText(QString::number(QDateTime::currentDateTimeUtc().toMSecsSinceEpoch())); |
| 668 | } |
| 669 | |
| 670 | RootItem* FormMessageFiltersManager::selectedCategoryFeed() const { |
| 671 | return m_feedsModel->sourceModel()->itemForIndex(m_feedsModel->mapToSource(m_ui.m_treeFeeds->currentIndex())); |
| 672 | } |
| 673 | |
| 674 | Message FormMessageFiltersManager::testingMessage() const { |
| 675 | Message msg; |
| 676 | |
| 677 | msg.m_feedId = QString::number(NO_PARENT_CATEGORY); |
| 678 | msg.m_url = m_ui.m_txtSampleUrl->text(); |
| 679 | msg.m_customId = m_ui.m_txtSampleUrl->text(); |
| 680 | msg.m_title = m_ui.m_txtSampleTitle->text(); |
| 681 | msg.m_author = m_ui.m_txtSampleAuthor->text(); |
| 682 | msg.m_isRead = m_ui.m_cbSampleRead->isChecked(); |
| 683 | msg.m_isImportant = m_ui.m_cbSampleImportant->isChecked(); |
| 684 | msg.m_created = QDateTime::fromMSecsSinceEpoch(m_ui.m_txtSampleCreatedOn->text().toLongLong()); |
| 685 | msg.m_contents = m_ui.m_txtSampleContents->toPlainText(); |
| 686 | msg.m_rawContents = Message::generateRawAtomContents(msg); |
| 687 | |
| 688 | return msg; |
| 689 | } |