| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "src/standardserviceroot.h" |
| 4 | |
| 5 | #include "src/definitions.h" |
| 6 | #include "src/gui/formdiscoverfeeds.h" |
| 7 | #include "src/gui/formeditstandardaccount.h" |
| 8 | #include "src/gui/formstandardfeeddetails.h" |
| 9 | #include "src/gui/formstandardimportexport.h" |
| 10 | #include "src/parsers/atomparser.h" |
| 11 | #include "src/parsers/icalparser.h" |
| 12 | #include "src/parsers/jsonparser.h" |
| 13 | #include "src/parsers/rdfparser.h" |
| 14 | #include "src/parsers/rssparser.h" |
| 15 | #include "src/parsers/sitemapparser.h" |
| 16 | #include "src/standardcategory.h" |
| 17 | #include "src/standardfeed.h" |
| 18 | #include "src/standardfeedsimportexportmodel.h" |
| 19 | #include "src/standardserviceentrypoint.h" |
| 20 | |
| 21 | #include <librssguard/database/databasequeries.h> |
| 22 | #include <librssguard/definitions/definitions.h> |
| 23 | #include <librssguard/exceptions/applicationexception.h> |
| 24 | #include <librssguard/exceptions/feedfetchexception.h> |
| 25 | #include <librssguard/exceptions/scriptexception.h> |
| 26 | #include <librssguard/gui/messagebox.h> |
| 27 | #include <librssguard/miscellaneous/application.h> |
| 28 | #include <librssguard/miscellaneous/iconfactory.h> |
| 29 | #include <librssguard/miscellaneous/mutex.h> |
| 30 | #include <librssguard/miscellaneous/settings.h> |
| 31 | #include <librssguard/network-web/networkfactory.h> |
| 32 | #include <librssguard/services/abstract/gui/formcategorydetails.h> |
| 33 | |
| 34 | #if defined(NO_LITE) |
| 35 | #include <librssguard/gui/webviewers/webengine/webengineviewer.h> |
| 36 | #include <librssguard/network-web/webengine/webenginepage.h> |
| 37 | #endif |
| 38 | |
| 39 | #if defined(ENABLE_COMPRESSED_SITEMAP) |
| 40 | #include "src/3rd-party/qcompressor/qcompressor.h" |
| 41 | #endif |
| 42 | |
| 43 | #include <QAction> |
| 44 | #include <QSqlTableModel> |
| 45 | #include <QStack> |
| 46 | #include <QTextCodec> |
| 47 | #include <QThread> |
| 48 | |
| 49 | StandardServiceRoot::StandardServiceRoot(RootItem* parent) : ServiceRoot(parent), m_spacingSameHostsRequests(0) { |
| 50 | setIcon(StandardServiceEntryPoint().icon()); |
| 51 | setDescription(tr("This is the obligatory service account for standard RSS/RDF/ATOM feeds.")); |
| 52 | } |
| 53 | |
| 54 | StandardServiceRoot::~StandardServiceRoot() { |
| 55 | qDeleteAll(m_feedContextMenu); |
| 56 | } |
| 57 | |
| 58 | void StandardServiceRoot::onDatabaseCleanup() { |
| 59 | for (Feed* fd : getSubTreeFeeds()) { |
| 60 | qobject_cast<StandardFeed*>(fd)->setLastEtag({}); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | void StandardServiceRoot::onAfterFeedsPurged(const QList<Feed*>& feeds) { |
| 65 | for (Feed* fd : feeds) { |
| 66 | static_cast<StandardFeed*>(fd)->setLastEtag(QString()); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | void StandardServiceRoot::start(bool freshly_activated) { |
| 71 | DatabaseQueries::loadRootFromDatabase<StandardCategory, StandardFeed>(this); |
| 72 | |
| 73 | if (freshly_activated && getSubTreeFeeds().isEmpty()) { |
| 74 | // In other words, if there are no feeds or categories added. |
| 75 | if (MsgBox::show(qApp->mainFormWidget(), |
| 76 | QMessageBox::Question, |
| 77 | QObject::tr("Load initial set of feeds"), |
| 78 | tr("This new account does not include any feeds. You can now add default set of feeds."), |
| 79 | tr("Do you want to load initial set of feeds?"), |
| 80 | QString(), |
| 81 | QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { |
| 82 | QString target_opml_file = APP_INITIAL_FEEDS_PATH + QDir::separator() + FEED_INITIAL_OPML_PATTERN; |
| 83 | QString current_locale = qApp->localization()->loadedLanguage(); |
| 84 | QString file_to_load; |
| 85 | |
| 86 | if (QFile::exists(target_opml_file.arg(current_locale))) { |
| 87 | file_to_load = target_opml_file.arg(current_locale); |
| 88 | } |
| 89 | else if (QFile::exists(target_opml_file.arg(QSL(DEFAULT_LOCALE)))) { |
| 90 | file_to_load = target_opml_file.arg(QSL(DEFAULT_LOCALE)); |
| 91 | } |
| 92 | |
| 93 | FeedsImportExportModel model(this); |
| 94 | QString output_msg; |
| 95 | |
| 96 | try { |
| 97 | model.importAsOPML20(IOFactory::readFile(file_to_load), false, false, false); |
| 98 | model.checkAllItems(); |
| 99 | |
| 100 | if (mergeImportExportModel(&model, this, output_msg)) { |
| 101 | requestItemExpand(getSubTree<RootItem>(), true); |
| 102 | } |
| 103 | } |
| 104 | catch (ApplicationException& ex) { |
| 105 | MsgBox::show(qApp->mainFormWidget(), |
| 106 | QMessageBox::Critical, |
| 107 | tr("Error when loading initial feeds"), |
| 108 | ex.message()); |
| 109 | } |
| 110 | } |
| 111 | else { |
| 112 | requestItemExpand({this}, true); |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | void StandardServiceRoot::stop() { |
| 118 | qDebugNN << LOGSEC_STANDARD << "Stopping StandardServiceRoot instance."; |
| 119 | } |
| 120 | |
| 121 | QString StandardServiceRoot::code() const { |
| 122 | return StandardServiceEntryPoint().code(); |
| 123 | } |
| 124 | |
| 125 | bool StandardServiceRoot::canBeEdited() const { |
| 126 | return true; |
| 127 | } |
| 128 | |
| 129 | FormAccountDetails* StandardServiceRoot::accountSetupDialog() const { |
| 130 | return new FormEditStandardAccount(qApp->mainFormWidget()); |
| 131 | } |
| 132 | |
| 133 | void StandardServiceRoot::editItems(const QList<RootItem*>& items) { |
| 134 | auto std_feeds = boolinq::from(items) |
| 135 | .select([](RootItem* it) { |
| 136 | return qobject_cast<Feed*>(it); |
| 137 | }) |
| 138 | .where([](Feed* fd) { |
| 139 | return fd != nullptr; |
| 140 | }) |
| 141 | .toStdList(); |
| 142 | |
| 143 | if (!std_feeds.empty()) { |
| 144 | QScopedPointer<FormStandardFeedDetails> form_pointer(new FormStandardFeedDetails(this, |
| 145 | nullptr, |
| 146 | {}, |
| 147 | qApp->mainFormWidget())); |
| 148 | |
| 149 | form_pointer->addEditFeed<StandardFeed>(FROM_STD_LIST(QList<Feed*>, std_feeds)); |
| 150 | return; |
| 151 | } |
| 152 | |
| 153 | if (items.first()->kind() == RootItem::Kind::ServiceRoot) { |
| 154 | QScopedPointer<FormEditStandardAccount> p(qobject_cast<FormEditStandardAccount*>(accountSetupDialog())); |
| 155 | |
| 156 | p->addEditAccount(this); |
| 157 | return; |
| 158 | } |
| 159 | |
| 160 | ServiceRoot::editItems(items); |
| 161 | } |
| 162 | |
| 163 | bool StandardServiceRoot::supportsFeedAdding() const { |
| 164 | return true; |
| 165 | } |
| 166 | |
| 167 | bool StandardServiceRoot::supportsCategoryAdding() const { |
| 168 | return true; |
| 169 | } |
| 170 | |
| 171 | void StandardServiceRoot::addNewFeed(RootItem* selected_item, const QString& url) { |
| 172 | if (!qApp->feedUpdateLock()->tryLock()) { |
| 173 | // Lock was not obtained because |
| 174 | // it is used probably by feed updater or application |
| 175 | // is quitting. |
| 176 | qApp->showGuiMessage(Notification::Event::GeneralEvent, |
| 177 | {tr("Cannot add item"), |
| 178 | tr("Cannot add feed because another critical operation is ongoing."), |
| 179 | QSystemTrayIcon::MessageIcon::Warning}); |
| 180 | |
| 181 | return; |
| 182 | } |
| 183 | |
| 184 | QScopedPointer<FormDiscoverFeeds> form_discover(new FormDiscoverFeeds(this, |
| 185 | selected_item, |
| 186 | url, |
| 187 | qApp->mainFormWidget())); |
| 188 | |
| 189 | if (form_discover->exec() == ADVANCED_FEED_ADD_DIALOG_CODE) { |
| 190 | QScopedPointer<FormStandardFeedDetails> form_pointer(new FormStandardFeedDetails(this, |
| 191 | selected_item, |
| 192 | url, |
| 193 | qApp->mainFormWidget())); |
| 194 | |
| 195 | form_pointer->addEditFeed<StandardFeed>(); |
| 196 | } |
| 197 | |
| 198 | qApp->feedUpdateLock()->unlock(); |
| 199 | } |
| 200 | |
| 201 | Qt::ItemFlags StandardServiceRoot::additionalFlags() const { |
| 202 | return ServiceRoot::additionalFlags() | Qt::ItemFlag::ItemIsDragEnabled | Qt::ItemFlag::ItemIsDropEnabled; |
| 203 | } |
| 204 | |
| 205 | void StandardServiceRoot::spaceHost(const QString& host, const QString& url) { |
| 206 | if (m_spacingSameHostsRequests <= 0 || host.simplified().isEmpty()) { |
| 207 | // Spacing not enabled or host information unavailable. |
| 208 | return; |
| 209 | } |
| 210 | |
| 211 | m_spacingMutex.lock(); |
| 212 | |
| 213 | QDateTime host_last_fetched = m_spacingHosts.value(host); |
| 214 | QDateTime now = QDateTime::currentDateTimeUtc(); |
| 215 | int secs_to_wait = 0; |
| 216 | |
| 217 | if (host_last_fetched.isValid()) { |
| 218 | // No last fetch time saved yet. |
| 219 | QDateTime last = host_last_fetched.addSecs(m_spacingSameHostsRequests); |
| 220 | |
| 221 | if (last < now) { |
| 222 | // This host was last fetched sometimes in the past and not within the critical spacing window. |
| 223 | // We can therefore fetch now. |
| 224 | secs_to_wait = 0; |
| 225 | } |
| 226 | else { |
| 227 | secs_to_wait = now.secsTo(last); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | resetHostSpacing(host, now.addSecs(secs_to_wait)); |
| 232 | |
| 233 | m_spacingMutex.unlock(); |
| 234 | |
| 235 | if (secs_to_wait > 0) { |
| 236 | qDebugNN << LOGSEC_STANDARD << "Freezing feed with URL" << QUOTE_W_SPACE(url) << "for" |
| 237 | << NONQUOTE_W_SPACE(secs_to_wait) |
| 238 | << "seconds, because its host was used for fetching another feed during the spacing period."; |
| 239 | QThread::sleep(ulong(secs_to_wait)); |
| 240 | qDebugNN << LOGSEC_STANDARD << "Freezing feed with URL" << QUOTE_W_SPACE(url) << "is done."; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | void StandardServiceRoot::resetHostSpacing(const QString& host, const QDateTime& next_dt) { |
| 245 | m_spacingHosts.insert(host, next_dt); |
| 246 | qDebugNN << LOGSEC_STANDARD << "Setting spacing for" << QUOTE_W_SPACE(host) << "to" << QUOTE_W_SPACE_DOT(next_dt); |
| 247 | } |
| 248 | |
| 249 | QList<Message> StandardServiceRoot::obtainNewMessages(Feed* feed, |
| 250 | const QHash<ServiceRoot::BagOfMessages, QStringList>& |
| 251 | stated_messages, |
| 252 | const QHash<QString, QStringList>& tagged_messages) { |
| 253 | Q_UNUSED(stated_messages) |
| 254 | Q_UNUSED(tagged_messages) |
| 255 | |
| 256 | StandardFeed* f = static_cast<StandardFeed*>(feed); |
| 257 | QString host = QUrl(f->source()).host(); |
| 258 | QByteArray feed_contents; |
| 259 | QString formatted_feed_contents; |
| 260 | int download_timeout = qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::UpdateTimeout)).toInt(); |
| 261 | |
| 262 | if (f->sourceType() == StandardFeed::SourceType::Url) { |
| 263 | spaceHost(host, f->source()); |
| 264 | |
| 265 | qDebugNN << LOGSEC_STANDARD << "Downloading URL" << QUOTE_W_SPACE(feed->source()) << "to obtain feed data."; |
| 266 | |
| 267 | QList<QPair<QByteArray, QByteArray>> headers = StandardFeed::httpHeadersToList(f->httpHeaders()); |
| 268 | |
| 269 | headers << NetworkFactory::generateBasicAuthHeader(f->protection(), f->username(), f->password()); |
| 270 | |
| 271 | if (!f->lastEtag().isEmpty()) { |
| 272 | headers.append({QSL("If-None-Match").toLocal8Bit(), f->lastEtag().toLocal8Bit()}); |
| 273 | |
| 274 | qDebugNN << "Using ETag value:" << QUOTE_W_SPACE_DOT(f->lastEtag()); |
| 275 | } |
| 276 | |
| 277 | auto network_result = NetworkFactory::performNetworkOperation(f->source(), |
| 278 | download_timeout, |
| 279 | {}, |
| 280 | feed_contents, |
| 281 | QNetworkAccessManager::Operation::GetOperation, |
| 282 | headers, |
| 283 | false, |
| 284 | {}, |
| 285 | {}, |
| 286 | networkProxy(), |
| 287 | f->http2Status()); |
| 288 | |
| 289 | // Update last datetime this host was used. |
| 290 | // resetHostSpacing(host); |
| 291 | |
| 292 | if (network_result.m_networkError != QNetworkReply::NetworkError::NoError) { |
| 293 | qWarningNN << LOGSEC_STANDARD << "Error" << QUOTE_W_SPACE(network_result.m_networkError) |
| 294 | << "during fetching of new messages for feed" << QUOTE_W_SPACE_DOT(feed->source()); |
| 295 | throw FeedFetchException(Feed::Status::NetworkError, |
| 296 | NetworkFactory::networkErrorText(network_result.m_networkError), |
| 297 | QVariant::fromValue(network_result)); |
| 298 | } |
| 299 | else { |
| 300 | f->setLastEtag(network_result.m_headers.value(QSL("etag"))); |
| 301 | |
| 302 | if (network_result.m_httpCode == HTTP_CODE_NOT_MODIFIED && feed_contents.trimmed().isEmpty()) { |
| 303 | // We very likely used "eTag" before and server reports that |
| 304 | // content was not modified since. |
| 305 | qWarningNN << LOGSEC_STANDARD << QUOTE_W_SPACE(feed->source()) |
| 306 | << "reported HTTP/304, meaning that the remote file did not change since last time we checked it."; |
| 307 | return {}; |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | else if (f->sourceType() == StandardFeed::SourceType::EmbeddedBrowser) { |
| 312 | #if defined(NO_LITE) |
| 313 | feed_contents = WebEngineViewer::getJsEnabledHtml(f->source(), true); |
| 314 | #else |
| 315 | throw ApplicationException(tr("this source type cannot be used on 'lite' %1 build").arg(QSL(APP_NAME))); |
| 316 | #endif |
| 317 | } |
| 318 | else if (f->sourceType() == StandardFeed::SourceType::LocalFile) { |
| 319 | feed_contents = IOFactory::readFile(feed->source()); |
| 320 | } |
| 321 | else { |
| 322 | qDebugNN << LOGSEC_STANDARD << "Running custom script" << QUOTE_W_SPACE(feed->source()) << "to obtain feed data."; |
| 323 | |
| 324 | // Use script to generate feed file. |
| 325 | try { |
| 326 | feed_contents = StandardFeed::generateFeedFileWithScript(feed->source(), download_timeout); |
| 327 | } |
| 328 | catch (const ScriptException& ex) { |
| 329 | qCriticalNN << LOGSEC_STANDARD |
| 330 | << "Custom script for generating feed file failed:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 331 | |
| 332 | throw FeedFetchException(Feed::Status::OtherError, ex.message()); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // Sitemap parser supports gzip-encoded data too. |
| 337 | // We need to decode it here before encoding |
| 338 | // stuff kicks in. |
| 339 | if (SitemapParser::isGzip(feed_contents)) { |
| 340 | #if defined(ENABLE_COMPRESSED_SITEMAP) |
| 341 | qWarningNN << LOGSEC_STANDARD << "Decompressing gzipped feed data."; |
| 342 | |
| 343 | QByteArray uncompressed_feed_contents; |
| 344 | |
| 345 | if (!QCompressor::gzipDecompress(feed_contents, uncompressed_feed_contents)) { |
| 346 | throw ApplicationException("gzip decompression failed"); |
| 347 | } |
| 348 | |
| 349 | feed_contents = uncompressed_feed_contents; |
| 350 | #else |
| 351 | qWarningNN << LOGSEC_STANDARD << "This feed is gzipped."; |
| 352 | #endif |
| 353 | } |
| 354 | |
| 355 | if (!f->postProcessScript().simplified().isEmpty()) { |
| 356 | qDebugNN << LOGSEC_STANDARD << "We will process feed data with post-process script" |
| 357 | << QUOTE_W_SPACE_DOT(f->postProcessScript()); |
| 358 | |
| 359 | try { |
| 360 | feed_contents = |
| 361 | StandardFeed::postProcessFeedFileWithScript(f->postProcessScript(), feed_contents, download_timeout); |
| 362 | } |
| 363 | catch (const ScriptException& ex) { |
| 364 | qCriticalNN << LOGSEC_STANDARD |
| 365 | << "Post-processing script for feed file failed:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 366 | |
| 367 | throw FeedFetchException(Feed::Status::OtherError, ex.message()); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | // Encode obtained data for further parsing. |
| 372 | QTextCodec* codec = QTextCodec::codecForName(f->encoding().toLocal8Bit()); |
| 373 | |
| 374 | if (codec == nullptr) { |
| 375 | // No suitable codec for this encoding was found. |
| 376 | // Use UTF-8. |
| 377 | formatted_feed_contents = QString::fromUtf8(feed_contents); |
| 378 | } |
| 379 | else { |
| 380 | formatted_feed_contents = codec->toUnicode(feed_contents); |
| 381 | } |
| 382 | |
| 383 | // Feed data are downloaded and encoded. |
| 384 | // Parse data and obtain messages. |
| 385 | QList<Message> messages; |
| 386 | FeedParser* parser; |
| 387 | QElapsedTimer tmr; |
| 388 | |
| 389 | tmr.start(); |
| 390 | |
| 391 | switch (f->type()) { |
| 392 | case StandardFeed::Type::Rss0X: |
| 393 | case StandardFeed::Type::Rss2X: |
| 394 | parser = new RssParser(formatted_feed_contents); |
| 395 | break; |
| 396 | |
| 397 | case StandardFeed::Type::Rdf: |
| 398 | parser = new RdfParser(formatted_feed_contents); |
| 399 | break; |
| 400 | |
| 401 | case StandardFeed::Type::Atom10: |
| 402 | parser = new AtomParser(formatted_feed_contents); |
| 403 | break; |
| 404 | |
| 405 | case StandardFeed::Type::Json: |
| 406 | parser = new JsonParser(formatted_feed_contents); |
| 407 | break; |
| 408 | |
| 409 | case StandardFeed::Type::iCalendar: |
| 410 | parser = new IcalParser(formatted_feed_contents); |
| 411 | break; |
| 412 | |
| 413 | case StandardFeed::Type::Sitemap: |
| 414 | parser = new SitemapParser(formatted_feed_contents); |
| 415 | break; |
| 416 | |
| 417 | default: |
| 418 | break; |
| 419 | } |
| 420 | |
| 421 | if (!f->dateTimeFormat().isEmpty()) { |
| 422 | parser->setDateTimeFormat(f->dateTimeFormat()); |
| 423 | } |
| 424 | |
| 425 | parser->setDontUseRawXmlSaving(f->dontUseRawXmlSaving()); |
| 426 | messages = parser->messages(); |
| 427 | |
| 428 | qDebugNN << LOGSEC_STANDARD << "XML parsing for feed" << QUOTE_W_SPACE(f->title()) << "took" |
| 429 | << NONQUOTE_W_SPACE(tmr.elapsed()) << "ms."; |
| 430 | |
| 431 | if (!parser->dateTimeFormat().isEmpty()) { |
| 432 | f->setDateTimeFormat(parser->dateTimeFormat()); |
| 433 | } |
| 434 | |
| 435 | delete parser; |
| 436 | |
| 437 | for (Message& mess : messages) { |
| 438 | mess.m_feedId = feed->customId(); |
| 439 | } |
| 440 | |
| 441 | return messages; |
| 442 | } |
| 443 | |
| 444 | QList<QAction*> StandardServiceRoot::getContextMenuForFeed(StandardFeed* feed) { |
| 445 | if (m_feedContextMenu.isEmpty()) { |
| 446 | // Initialize. |
| 447 | auto* action_metadata = |
| 448 | new QAction(qApp->icons()->fromTheme(QSL("download"), QSL("emblem-downloads")), tr("Fetch metadata"), this); |
| 449 | |
| 450 | m_feedContextMenu.append(action_metadata); |
| 451 | |
| 452 | connect(action_metadata, &QAction::triggered, this, [this]() { |
| 453 | m_feedForMetadata->fetchMetadataForItself(); |
| 454 | }); |
| 455 | } |
| 456 | |
| 457 | m_feedForMetadata = feed; |
| 458 | |
| 459 | return m_feedContextMenu; |
| 460 | } |
| 461 | |
| 462 | QVariantHash StandardServiceRoot::customDatabaseData() const { |
| 463 | QVariantHash data = ServiceRoot::customDatabaseData(); |
| 464 | |
| 465 | data[QSL("title")] = title(); |
| 466 | data[QSL("icon")] = IconFactory::toByteArray(icon()); |
| 467 | data[QSL("requests_spacing")] = spacingSameHostsRequests(); |
| 468 | |
| 469 | return data; |
| 470 | } |
| 471 | |
| 472 | void StandardServiceRoot::setCustomDatabaseData(const QVariantHash& data) { |
| 473 | ServiceRoot::setCustomDatabaseData(data); |
| 474 | |
| 475 | setTitle(data.value(QSL("title"), defaultTitle()).toString()); |
| 476 | |
| 477 | QByteArray icon_data = data.value(QSL("icon")).toByteArray(); |
| 478 | |
| 479 | if (!icon_data.isEmpty()) { |
| 480 | setIcon(IconFactory::fromByteArray(icon_data)); |
| 481 | } |
| 482 | |
| 483 | setSpacingSameHostsRequests(data.value(QSL("requests_spacing")).toInt()); |
| 484 | } |
| 485 | |
| 486 | QString StandardServiceRoot::defaultTitle() { |
| 487 | return qApp->system()->loggedInUser() + QSL(" (RSS/ATOM/JSON)"); |
| 488 | } |
| 489 | |
| 490 | bool StandardServiceRoot::mergeImportExportModel(FeedsImportExportModel* model, |
| 491 | RootItem* target_root_node, |
| 492 | QString& output_message) { |
| 493 | QStack<RootItem*> original_parents; |
| 494 | |
| 495 | original_parents.push(target_root_node); |
| 496 | QStack<RootItem*> new_parents; |
| 497 | |
| 498 | new_parents.push(model->sourceModel()->rootItem()); |
| 499 | bool some_feed_category_error = false; |
| 500 | |
| 501 | QSqlDatabase database = qApp->database()->driver()->connection(metaObject()->className()); |
| 502 | |
| 503 | // Iterate all new items we would like to merge into current model. |
| 504 | while (!new_parents.isEmpty()) { |
| 505 | RootItem* target_parent = original_parents.pop(); |
| 506 | RootItem* source_parent = new_parents.pop(); |
| 507 | auto sour_chi = source_parent->childItems(); |
| 508 | |
| 509 | for (RootItem* source_item : std::as_const(sour_chi)) { |
| 510 | if (!model->sourceModel()->isItemChecked(source_item)) { |
| 511 | // We can skip this item, because it is not checked and should not be imported. |
| 512 | // NOTE: All descendants are thus skipped too. |
| 513 | continue; |
| 514 | } |
| 515 | |
| 516 | if (source_item->kind() == RootItem::Kind::Category) { |
| 517 | auto* source_category = qobject_cast<StandardCategory*>(source_item); |
| 518 | auto* new_category = new StandardCategory(*source_category); |
| 519 | QString new_category_title = new_category->title(); |
| 520 | |
| 521 | // Add category to model. |
| 522 | new_category->clearChildren(); |
| 523 | |
| 524 | try { |
| 525 | DatabaseQueries::createOverwriteCategory(database, |
| 526 | new_category, |
| 527 | target_root_node->getParentServiceRoot()->accountId(), |
| 528 | target_parent->id()); |
| 529 | requestItemReassignment(new_category, target_parent); |
| 530 | |
| 531 | original_parents.push(new_category); |
| 532 | new_parents.push(source_category); |
| 533 | } |
| 534 | catch (ApplicationException& ex) { |
| 535 | // Add category failed, but this can mean that the same category (with same title) |
| 536 | // already exists. If such a category exists in current parent, then find it and |
| 537 | // add descendants to it. |
| 538 | RootItem* existing_category = nullptr; |
| 539 | auto tar_chi = target_parent->childItems(); |
| 540 | |
| 541 | for (RootItem* child : std::as_const(tar_chi)) { |
| 542 | if (child->kind() == RootItem::Kind::Category && child->title() == new_category_title) { |
| 543 | existing_category = child; |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | if (existing_category != nullptr) { |
| 548 | original_parents.push(existing_category); |
| 549 | new_parents.push(source_category); |
| 550 | } |
| 551 | else { |
| 552 | some_feed_category_error = true; |
| 553 | |
| 554 | qCriticalNN << LOGSEC_STANDARD << "Cannot import category:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | else if (source_item->kind() == RootItem::Kind::Feed) { |
| 559 | auto* source_feed = qobject_cast<StandardFeed*>(source_item); |
| 560 | const auto* feed_with_same_url = target_root_node->getItemFromSubTree([source_feed](const RootItem* it) { |
| 561 | return it->kind() == RootItem::Kind::Feed && |
| 562 | it->toFeed()->source().toLower() == source_feed->source().toLower(); |
| 563 | }); |
| 564 | |
| 565 | if (feed_with_same_url != nullptr) { |
| 566 | continue; |
| 567 | } |
| 568 | |
| 569 | auto* new_feed = new StandardFeed(*source_feed); |
| 570 | |
| 571 | try { |
| 572 | DatabaseQueries::createOverwriteFeed(database, |
| 573 | new_feed, |
| 574 | target_root_node->getParentServiceRoot()->accountId(), |
| 575 | target_parent->id()); |
| 576 | requestItemReassignment(new_feed, target_parent); |
| 577 | } |
| 578 | catch (const ApplicationException& ex) { |
| 579 | qCriticalNN << LOGSEC_STANDARD << "Cannot import feed:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 580 | some_feed_category_error = true; |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | if (some_feed_category_error) { |
| 587 | output_message = tr("Some feeds/categories were not imported due to error, check debug log for more details."); |
| 588 | } |
| 589 | else { |
| 590 | output_message = tr("Import was completely successful."); |
| 591 | } |
| 592 | |
| 593 | return !some_feed_category_error; |
| 594 | } |
| 595 | |
| 596 | int StandardServiceRoot::spacingSameHostsRequests() const { |
| 597 | return m_spacingSameHostsRequests; |
| 598 | } |
| 599 | |
| 600 | void StandardServiceRoot::setSpacingSameHostsRequests(int spacing) { |
| 601 | m_spacingSameHostsRequests = spacing; |
| 602 | } |
| 603 | |
| 604 | void StandardServiceRoot::addNewCategory(RootItem* selected_item) { |
| 605 | if (!qApp->feedUpdateLock()->tryLock()) { |
| 606 | // Lock was not obtained because |
| 607 | // it is used probably by feed updater or application |
| 608 | // is quitting. |
| 609 | qApp->showGuiMessage(Notification::Event::GeneralEvent, |
| 610 | {tr("Cannot add category"), |
| 611 | tr("Cannot add category because another critical operation is ongoing."), |
| 612 | QSystemTrayIcon::MessageIcon::Warning}); |
| 613 | |
| 614 | // Thus, cannot delete and quit the method. |
| 615 | return; |
| 616 | } |
| 617 | |
| 618 | QScopedPointer<FormCategoryDetails> form_pointer(new FormCategoryDetails(this, |
| 619 | selected_item, |
| 620 | qApp->mainFormWidget())); |
| 621 | |
| 622 | form_pointer->addEditCategory<StandardCategory>(); |
| 623 | qApp->feedUpdateLock()->unlock(); |
| 624 | } |
| 625 | |
| 626 | void StandardServiceRoot::importFeeds() { |
| 627 | QScopedPointer<FormStandardImportExport> form(new FormStandardImportExport(this, qApp->mainFormWidget())); |
| 628 | |
| 629 | form.data()->setMode(FeedsImportExportModel::Mode::Import); |
| 630 | form.data()->exec(); |
| 631 | } |
| 632 | |
| 633 | void StandardServiceRoot::exportFeeds() { |
| 634 | QScopedPointer<FormStandardImportExport> form(new FormStandardImportExport(this, qApp->mainFormWidget())); |
| 635 | |
| 636 | form.data()->setMode(FeedsImportExportModel::Mode::Export); |
| 637 | form.data()->exec(); |
| 638 | } |
| 639 | |
| 640 | QList<QAction*> StandardServiceRoot::serviceMenu() { |
| 641 | if (m_serviceMenu.isEmpty()) { |
| 642 | ServiceRoot::serviceMenu(); |
| 643 | |
| 644 | auto* action_export_feeds = new QAction(qApp->icons()->fromTheme(QSL("document-export")), tr("Export feeds"), this); |
| 645 | auto* action_import_feeds = new QAction(qApp->icons()->fromTheme(QSL("document-import")), tr("Import feeds"), this); |
| 646 | |
| 647 | connect(action_export_feeds, &QAction::triggered, this, &StandardServiceRoot::exportFeeds); |
| 648 | connect(action_import_feeds, &QAction::triggered, this, &StandardServiceRoot::importFeeds); |
| 649 | |
| 650 | m_serviceMenu.append(action_export_feeds); |
| 651 | m_serviceMenu.append(action_import_feeds); |
| 652 | } |
| 653 | |
| 654 | return m_serviceMenu; |
| 655 | } |