File indexing completed on 2024-06-02 05:21:15

0001 /* This file is part of the KDE project
0002 
0003    SPDX-FileCopyrightText: 2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
0004    SPDX-FileContributor: Kevin Ottens <kevin@kdab.com>
0005 
0006    SPDX-FileCopyrightText: 2010 Casey Link <unnamedrambler@gmail.com>
0007    SPDX-FileCopyrightText: 2009-2010 Klaralvdalens Datakonsult AB, a KDAB Group company <info@kdab.net>
0008    SPDX-FileCopyrightText: 2009 Kevin Ottens <ervin@kde.org>
0009    SPDX-FileCopyrightText: 2006-2008 Omat Holding B.V. <info@omat.nl>
0010    SPDX-FileCopyrightText: 2006 Frode M. Døving <frode@lnix.net>
0011 
0012    Original copied from showfoto:
0013     SPDX-FileCopyrightText: 2005 Gilles Caulier <caulier.gilles@free.fr>
0014 
0015    SPDX-License-Identifier: GPL-2.0-or-later
0016 */
0017 
0018 #include "setupserver.h"
0019 #include "folderarchivesettingpage.h"
0020 #include "imapresource.h"
0021 #include "serverinfodialog.h"
0022 #include "settings.h"
0023 #include <config-imap.h>
0024 
0025 #include <KLineEditEventHandler>
0026 #include <MailTransport/ServerTest>
0027 #include <MailTransport/Transport>
0028 
0029 #include <KMime/Message>
0030 
0031 #include "imapresource_debug.h"
0032 #include <Akonadi/CollectionFetchJob>
0033 #include <Akonadi/CollectionModifyJob>
0034 #include <Akonadi/EntityDisplayAttribute>
0035 #include <Akonadi/ResourceSettings>
0036 #include <Akonadi/SpecialMailCollections>
0037 #include <Akonadi/SpecialMailCollectionsRequestJob>
0038 #include <KAuthorized>
0039 #include <KLocalizedString>
0040 #include <KMessageBox>
0041 #include <KUser>
0042 #include <QNetworkInformation>
0043 #include <QPushButton>
0044 
0045 #include <KIdentityManagementCore/IdentityManager>
0046 #include <KIdentityManagementWidgets/IdentityCombo>
0047 #include <QFontDatabase>
0048 #include <QPointer>
0049 #include <QVBoxLayout>
0050 
0051 #include "imapaccount.h"
0052 #include "subscriptiondialog.h"
0053 
0054 #include "ui_setupserverview_desktop.h"
0055 
0056 /** static helper functions **/
0057 static QString authenticationModeString(MailTransport::Transport::EnumAuthenticationType mode)
0058 {
0059     switch (mode) {
0060     case MailTransport::Transport::EnumAuthenticationType::LOGIN:
0061         return QStringLiteral("LOGIN");
0062     case MailTransport::Transport::EnumAuthenticationType::PLAIN:
0063         return QStringLiteral("PLAIN");
0064     case MailTransport::Transport::EnumAuthenticationType::CRAM_MD5:
0065         return QStringLiteral("CRAM-MD5");
0066     case MailTransport::Transport::EnumAuthenticationType::DIGEST_MD5:
0067         return QStringLiteral("DIGEST-MD5");
0068     case MailTransport::Transport::EnumAuthenticationType::GSSAPI:
0069         return QStringLiteral("GSSAPI");
0070     case MailTransport::Transport::EnumAuthenticationType::NTLM:
0071         return QStringLiteral("NTLM");
0072     case MailTransport::Transport::EnumAuthenticationType::CLEAR:
0073         return i18nc("Authentication method", "Clear text");
0074     case MailTransport::Transport::EnumAuthenticationType::ANONYMOUS:
0075         return i18nc("Authentication method", "Anonymous");
0076     case MailTransport::Transport::EnumAuthenticationType::XOAUTH2:
0077         return i18nc("Authentication method", "Gmail");
0078     default:
0079         break;
0080     }
0081     return {};
0082 }
0083 
0084 static void setCurrentAuthMode(QComboBox *authCombo, MailTransport::Transport::EnumAuthenticationType authtype)
0085 {
0086     qCDebug(IMAPRESOURCE_LOG) << "setting authcombo: " << authenticationModeString(authtype);
0087     int index = authCombo->findData(authtype);
0088     if (index == -1) {
0089         qCWarning(IMAPRESOURCE_LOG) << "desired authmode not in the combo";
0090     }
0091     qCDebug(IMAPRESOURCE_LOG) << "found corresponding index: " << index << "with data"
0092                               << authenticationModeString((MailTransport::Transport::EnumAuthenticationType)authCombo->itemData(index).toInt());
0093     authCombo->setCurrentIndex(index);
0094     auto t = static_cast<MailTransport::Transport::EnumAuthenticationType>(authCombo->itemData(authCombo->currentIndex()).toInt());
0095     qCDebug(IMAPRESOURCE_LOG) << "selected auth mode:" << authenticationModeString(t);
0096     Q_ASSERT(t == authtype);
0097 }
0098 
0099 static MailTransport::Transport::EnumAuthenticationType getCurrentAuthMode(QComboBox *authCombo)
0100 {
0101     auto authtype = static_cast<MailTransport::Transport::EnumAuthenticationType>(authCombo->itemData(authCombo->currentIndex()).toInt());
0102     qCDebug(IMAPRESOURCE_LOG) << "current auth mode: " << authenticationModeString(authtype);
0103     return authtype;
0104 }
0105 
0106 static void addAuthenticationItem(QComboBox *authCombo, MailTransport::Transport::EnumAuthenticationType authtype)
0107 {
0108     qCDebug(IMAPRESOURCE_LOG) << "adding auth item " << authenticationModeString(authtype);
0109     authCombo->addItem(authenticationModeString(authtype), QVariant(authtype));
0110 }
0111 
0112 SetupServer::SetupServer(ImapResourceBase *parentResource, WId parent)
0113     : QDialog()
0114     , m_parentResource(parentResource)
0115     , m_ui(new Ui::SetupServerView)
0116     , mValidator(this)
0117 {
0118     m_parentResource->settings()->setWinId(parent);
0119     auto mainWidget = new QWidget(this);
0120     auto mainLayout = new QVBoxLayout(this);
0121     mainLayout->addWidget(mainWidget);
0122     auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
0123     mOkButton = buttonBox->button(QDialogButtonBox::Ok);
0124     mOkButton->setDefault(true);
0125     mOkButton->setShortcut(Qt::CTRL | Qt::Key_Return);
0126     connect(mOkButton, &QPushButton::clicked, this, &SetupServer::applySettings);
0127     connect(buttonBox, &QDialogButtonBox::rejected, this, &SetupServer::reject);
0128     mainLayout->addWidget(buttonBox);
0129 
0130     m_ui->setupUi(mainWidget);
0131     m_ui->password->setRevealPasswordAvailable(KAuthorized::authorize(QStringLiteral("lineedit_reveal_password")));
0132     m_ui->customPassword->setRevealPasswordAvailable(KAuthorized::authorize(QStringLiteral("lineedit_reveal_password")));
0133     KLineEditEventHandler::catchReturnKey(m_ui->accountName);
0134     KLineEditEventHandler::catchReturnKey(m_ui->imapServer);
0135     KLineEditEventHandler::catchReturnKey(m_ui->userName);
0136     KLineEditEventHandler::catchReturnKey(m_ui->alternateURL);
0137     KLineEditEventHandler::catchReturnKey(m_ui->customUsername);
0138 
0139     m_folderArchiveSettingPage = new FolderArchiveSettingPage(m_parentResource->identifier());
0140     m_ui->tabWidget->addTab(m_folderArchiveSettingPage, i18n("Archive Folder"));
0141     m_ui->safeImapGroup->setId(m_ui->noRadio, KIMAP::LoginJob::Unencrypted);
0142     m_ui->safeImapGroup->setId(m_ui->sslRadio, KIMAP::LoginJob::SSLorTLS);
0143     m_ui->safeImapGroup->setId(m_ui->tlsRadio, KIMAP::LoginJob::STARTTLS);
0144 
0145     connect(m_ui->noRadio, &QRadioButton::toggled, this, &SetupServer::slotSafetyChanged);
0146     connect(m_ui->sslRadio, &QRadioButton::toggled, this, &SetupServer::slotSafetyChanged);
0147     connect(m_ui->tlsRadio, &QRadioButton::toggled, this, &SetupServer::slotSafetyChanged);
0148 
0149     m_ui->testInfo->hide();
0150     m_ui->testProgress->hide();
0151     m_ui->accountName->setFocus();
0152     m_ui->checkInterval->setSuffix(ki18np(" minute", " minutes"));
0153     m_ui->checkInterval->setMinimum(Akonadi::ResourceSettings::self()->minimumCheckInterval());
0154     m_ui->checkInterval->setMaximum(10000);
0155     m_ui->checkInterval->setSingleStep(1);
0156     m_ui->imapInfo->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
0157 
0158     // regex for evaluating a valid server name/ip
0159     mValidator.setRegularExpression(QRegularExpression(QStringLiteral("[A-Za-z0-9_:.-]*")));
0160     m_ui->imapServer->setValidator(&mValidator);
0161 
0162     m_ui->folderRequester->setMimeTypeFilter(QStringList() << KMime::Message::mimeType());
0163     m_ui->folderRequester->setAccessRightsFilter(Akonadi::Collection::CanChangeItem | Akonadi::Collection::CanCreateItem | Akonadi::Collection::CanDeleteItem);
0164     m_ui->folderRequester->changeCollectionDialogOptions(Akonadi::CollectionDialog::AllowToCreateNewChildCollection);
0165     m_identityCombobox = new KIdentityManagementWidgets::IdentityCombo(KIdentityManagementCore::IdentityManager::self(), this);
0166     m_identityCombobox->setShowDefault(true);
0167     m_ui->formLayoutAdvanced->insertRow(3, i18n("Identity:"), m_identityCombobox);
0168 
0169     connect(m_ui->testButton, &QPushButton::pressed, this, &SetupServer::slotTest);
0170 
0171     connect(m_ui->imapServer, &QLineEdit::textChanged, this, &SetupServer::slotServerChanged);
0172     connect(m_ui->imapServer, &QLineEdit::textChanged, this, &SetupServer::slotTestChanged);
0173     connect(m_ui->imapServer, &QLineEdit::textChanged, this, &SetupServer::slotComplete);
0174     connect(m_ui->userName, &QLineEdit::textChanged, this, &SetupServer::slotComplete);
0175     connect(m_ui->subscriptionEnabled, &QCheckBox::toggled, this, &SetupServer::slotSubcriptionCheckboxChanged);
0176     connect(m_ui->subscriptionButton, &QPushButton::pressed, this, &SetupServer::slotManageSubscriptions);
0177 
0178     connect(m_ui->managesieveCheck, &QCheckBox::toggled, this, &SetupServer::slotEnableWidgets);
0179     connect(m_ui->sameConfigCheck, &QCheckBox::toggled, this, &SetupServer::slotEnableWidgets);
0180 
0181     connect(m_ui->enableMailCheckBox, &QCheckBox::toggled, this, &SetupServer::slotMailCheckboxChanged);
0182     connect(m_ui->safeImapGroup, &QButtonGroup::buttonClicked, this, &SetupServer::slotEncryptionRadioChanged);
0183     connect(m_ui->customSieveGroup, &QButtonGroup::buttonClicked, this, &SetupServer::slotCustomSieveChanged);
0184     connect(m_ui->showServerInfo, &QPushButton::pressed, this, &SetupServer::slotShowServerInfo);
0185 
0186     readSettings();
0187     slotTestChanged();
0188     slotComplete();
0189     slotCustomSieveChanged();
0190 
0191     QNetworkInformation::instance()->loadBackendByFeatures(QNetworkInformation::Feature::Reachability);
0192     connect(QNetworkInformation::instance(), &QNetworkInformation::reachabilityChanged, this, [this](QNetworkInformation::Reachability newReachability) {
0193         slotTestChanged();
0194     });
0195 }
0196 
0197 SetupServer::~SetupServer()
0198 {
0199     delete m_ui;
0200 }
0201 
0202 bool SetupServer::shouldClearCache() const
0203 {
0204     return m_shouldClearCache;
0205 }
0206 
0207 void SetupServer::slotSubcriptionCheckboxChanged()
0208 {
0209     m_ui->subscriptionButton->setEnabled(m_ui->subscriptionEnabled->isChecked());
0210 }
0211 
0212 void SetupServer::slotMailCheckboxChanged()
0213 {
0214     m_ui->checkInterval->setEnabled(m_ui->enableMailCheckBox->isChecked());
0215 }
0216 
0217 void SetupServer::slotEncryptionRadioChanged()
0218 {
0219     // TODO these really should be defined somewhere else
0220     switch (m_ui->safeImapGroup->checkedId()) {
0221     case KIMAP::LoginJob::Unencrypted:
0222     case KIMAP::LoginJob::STARTTLS:
0223         m_ui->portSpin->setValue(143);
0224         break;
0225     case KIMAP::LoginJob::SSLorTLS:
0226         m_ui->portSpin->setValue(993);
0227         break;
0228     default:
0229         qFatal("Shouldn't happen");
0230     }
0231 }
0232 
0233 void SetupServer::slotCustomSieveChanged()
0234 {
0235     QAbstractButton *checkedButton = m_ui->customSieveGroup->checkedButton();
0236 
0237     if (checkedButton == m_ui->imapUserPassword || checkedButton == m_ui->noAuthentification) {
0238         m_ui->customUsername->setEnabled(false);
0239         m_ui->customPassword->setEnabled(false);
0240     } else if (checkedButton == m_ui->customUserPassword) {
0241         m_ui->customUsername->setEnabled(true);
0242         m_ui->customPassword->setEnabled(true);
0243     }
0244 }
0245 
0246 void SetupServer::applySettings()
0247 {
0248     if (!m_parentResource->settings()->imapServer().isEmpty() && m_ui->imapServer->text() != m_parentResource->settings()->imapServer()) {
0249         if (KMessageBox::warningContinueCancel(this,
0250                                                i18n("You have changed the address of the server. Even if this is the same server as before "
0251                                                     "we will have to re-download all your emails from this account again. "
0252                                                     "Are you sure you want to proceed?"),
0253                                                i18n("Server address change"))
0254             == KMessageBox::Cancel) {
0255             return;
0256         }
0257     }
0258     if (!m_parentResource->settings()->userName().isEmpty() && m_ui->userName->text() != m_parentResource->settings()->userName()) {
0259         if (KMessageBox::warningContinueCancel(this,
0260                                                i18n("You have changed the user name. Even if this is a user name for the same account as before "
0261                                                     "we will have to re-download all your emails from this account again. "
0262                                                     "Are you sure you want to proceed?"),
0263                                                i18n("User name change"))
0264             == KMessageBox::Cancel) {
0265             return;
0266         }
0267     }
0268 
0269     m_folderArchiveSettingPage->writeSettings();
0270     m_shouldClearCache =
0271         (m_parentResource->settings()->imapServer() != m_ui->imapServer->text()) || (m_parentResource->settings()->userName() != m_ui->userName->text());
0272 
0273     const MailTransport::Transport::EnumAuthenticationType authtype = getCurrentAuthMode(m_ui->authenticationCombo);
0274     if (!m_ui->userName->text().contains(QLatin1Char('@')) && authtype == MailTransport::Transport::EnumAuthenticationType::XOAUTH2
0275         && m_ui->imapServer->text().contains(QLatin1StringView("gmail.com"))) {
0276         // Normalize gmail username so that it matches the JSON account info returned by GMail authentication.
0277         // If we don't do this, we will look up cached auth without @gmail.com and save it with @gmail.com => very frequent auth dialog popping up.
0278         qCDebug(IMAPRESOURCE_LOG) << "Fixing up username" << m_ui->userName->text() << "by adding @gmail.com";
0279         m_ui->userName->setText(m_ui->userName->text() + QLatin1StringView("@gmail.com"));
0280     }
0281 
0282     m_parentResource->setName(m_ui->accountName->text());
0283 
0284     m_parentResource->settings()->setImapServer(m_ui->imapServer->text());
0285     m_parentResource->settings()->setImapPort(m_ui->portSpin->value());
0286     m_parentResource->settings()->setUserName(m_ui->userName->text());
0287     QString encryption;
0288     switch (m_ui->safeImapGroup->checkedId()) {
0289     case KIMAP::LoginJob::Unencrypted:
0290         encryption = QStringLiteral("None");
0291         break;
0292     case KIMAP::LoginJob::SSLorTLS:
0293         encryption = QStringLiteral("SSL");
0294         break;
0295     case KIMAP::LoginJob::STARTTLS:
0296         encryption = QStringLiteral("STARTTLS");
0297         break;
0298     default:
0299         qFatal("Shouldn't happen");
0300     }
0301     m_parentResource->settings()->setSafety(encryption);
0302 
0303     qCDebug(IMAPRESOURCE_LOG) << "saving IMAP auth mode: " << authenticationModeString(authtype);
0304     m_parentResource->settings()->setAuthentication(authtype);
0305     m_parentResource->settings()->setPassword(m_ui->password->password());
0306     m_parentResource->settings()->setSubscriptionEnabled(m_ui->subscriptionEnabled->isChecked());
0307     m_parentResource->settings()->setIntervalCheckTime(m_ui->checkInterval->value());
0308     m_parentResource->settings()->setDisconnectedModeEnabled(m_ui->disconnectedModeEnabled->isChecked());
0309     m_parentResource->settings()->setUseProxy(m_ui->useProxyCheck->isChecked());
0310 
0311     MailTransport::Transport::EnumAuthenticationType alternateAuthtype = getCurrentAuthMode(m_ui->authenticationAlternateCombo);
0312     qCDebug(IMAPRESOURCE_LOG) << "saving Alternate server sieve auth mode: " << authenticationModeString(alternateAuthtype);
0313     m_parentResource->settings()->setAlternateAuthentication(alternateAuthtype);
0314     m_parentResource->settings()->setSieveSupport(m_ui->managesieveCheck->isChecked());
0315     m_parentResource->settings()->setSieveReuseConfig(m_ui->sameConfigCheck->isChecked());
0316     m_parentResource->settings()->setSievePort(m_ui->sievePortSpin->value());
0317     m_parentResource->settings()->setSieveAlternateUrl(m_ui->alternateURL->text());
0318     m_parentResource->settings()->setSieveVacationFilename(m_vacationFileName);
0319 
0320     m_parentResource->settings()->setTrashCollection(m_ui->folderRequester->collection().id());
0321     Akonadi::Collection trash = m_ui->folderRequester->collection();
0322     Akonadi::SpecialMailCollections::self()->registerCollection(Akonadi::SpecialMailCollections::Trash, trash);
0323     auto attribute = trash.attribute<Akonadi::EntityDisplayAttribute>(Akonadi::Collection::AddIfMissing);
0324     attribute->setIconName(QStringLiteral("user-trash"));
0325     new Akonadi::CollectionModifyJob(trash);
0326     if (mOldTrash != trash) {
0327         Akonadi::SpecialMailCollections::self()->unregisterCollection(mOldTrash);
0328     }
0329 
0330     m_parentResource->settings()->setAutomaticExpungeEnabled(m_ui->autoExpungeCheck->isChecked());
0331     m_parentResource->settings()->setUseDefaultIdentity(m_identityCombobox->isDefaultIdentity());
0332 
0333     if (!m_identityCombobox->isDefaultIdentity()) {
0334         m_parentResource->settings()->setAccountIdentity(m_identityCombobox->currentIdentity());
0335     }
0336 
0337     m_parentResource->settings()->setIntervalCheckEnabled(m_ui->enableMailCheckBox->isChecked());
0338     if (m_ui->enableMailCheckBox->isChecked()) {
0339         m_parentResource->settings()->setIntervalCheckTime(m_ui->checkInterval->value());
0340     }
0341 
0342     m_parentResource->settings()->setSieveCustomUsername(m_ui->customUsername->text());
0343 
0344     QAbstractButton *checkedButton = m_ui->customSieveGroup->checkedButton();
0345 
0346     if (checkedButton == m_ui->imapUserPassword) {
0347         m_parentResource->settings()->setSieveCustomAuthentification(QStringLiteral("ImapUserPassword"));
0348     } else if (checkedButton == m_ui->noAuthentification) {
0349         m_parentResource->settings()->setSieveCustomAuthentification(QStringLiteral("NoAuthentification"));
0350     } else if (checkedButton == m_ui->customUserPassword) {
0351         m_parentResource->settings()->setSieveCustomAuthentification(QStringLiteral("CustomUserPassword"));
0352     }
0353 
0354     m_parentResource->settings()->setSieveCustomPassword(m_ui->customPassword->password());
0355 
0356     m_parentResource->settings()->save();
0357     qCDebug(IMAPRESOURCE_LOG) << "wrote" << m_ui->imapServer->text() << m_ui->userName->text() << m_ui->safeImapGroup->checkedId();
0358 
0359     if (m_oldResourceName != m_ui->accountName->text() && !m_ui->accountName->text().isEmpty()) {
0360         m_parentResource->settings()->renameRootCollection(m_ui->accountName->text());
0361     }
0362 
0363     accept();
0364 }
0365 
0366 void SetupServer::readSettings()
0367 {
0368     m_folderArchiveSettingPage->loadSettings();
0369     m_ui->accountName->setText(m_parentResource->name());
0370     m_oldResourceName = m_ui->accountName->text();
0371 
0372     auto currentUser = new KUser();
0373 
0374     m_ui->imapServer->setText(m_parentResource->settings()->imapServer());
0375 
0376     m_ui->portSpin->setValue(m_parentResource->settings()->imapPort());
0377 
0378     m_ui->userName->setText(!m_parentResource->settings()->userName().isEmpty() ? m_parentResource->settings()->userName() : currentUser->loginName());
0379 
0380     const QString safety = m_parentResource->settings()->safety();
0381     int i = 0;
0382     if (safety == QLatin1StringView("SSL")) {
0383         i = KIMAP::LoginJob::SSLorTLS;
0384     } else if (safety == QLatin1StringView("STARTTLS")) {
0385         i = KIMAP::LoginJob::STARTTLS;
0386     } else {
0387         i = KIMAP::LoginJob::Unencrypted;
0388     }
0389 
0390     QAbstractButton *safetyButton = m_ui->safeImapGroup->button(i);
0391     if (safetyButton) {
0392         safetyButton->setChecked(true);
0393     }
0394 
0395     populateDefaultAuthenticationOptions();
0396     i = m_parentResource->settings()->authentication();
0397     qCDebug(IMAPRESOURCE_LOG) << "read IMAP auth mode: " << authenticationModeString(static_cast<MailTransport::Transport::EnumAuthenticationType>(i));
0398     setCurrentAuthMode(m_ui->authenticationCombo, (MailTransport::Transport::EnumAuthenticationType)i);
0399 
0400     i = m_parentResource->settings()->alternateAuthentication();
0401     setCurrentAuthMode(m_ui->authenticationAlternateCombo, static_cast<MailTransport::Transport::EnumAuthenticationType>(i));
0402 
0403     bool rejected = false;
0404     const QString password = m_parentResource->settings()->password(&rejected);
0405     if (rejected) {
0406         m_ui->password->setEnabled(false);
0407         KMessageBox::information(nullptr,
0408                                  i18n("Could not access KWallet. "
0409                                       "If you want to store the password permanently then you have to "
0410                                       "activate it. If you do not "
0411                                       "want to use KWallet, check the box below, but note that you will be "
0412                                       "prompted for your password when needed."),
0413                                  i18n("Do not use KWallet"),
0414                                  QStringLiteral("warning_kwallet_disabled"));
0415     } else {
0416         m_ui->password->lineEdit()->insert(password);
0417     }
0418 
0419     m_ui->subscriptionEnabled->setChecked(m_parentResource->settings()->subscriptionEnabled());
0420 
0421     m_ui->checkInterval->setValue(m_parentResource->settings()->intervalCheckTime());
0422     m_ui->disconnectedModeEnabled->setChecked(m_parentResource->settings()->disconnectedModeEnabled());
0423     m_ui->useProxyCheck->setChecked(m_parentResource->settings()->useProxy());
0424 
0425     m_ui->managesieveCheck->setChecked(m_parentResource->settings()->sieveSupport());
0426     m_ui->sameConfigCheck->setChecked(m_parentResource->settings()->sieveReuseConfig());
0427     m_ui->sievePortSpin->setValue(m_parentResource->settings()->sievePort());
0428     m_ui->alternateURL->setText(m_parentResource->settings()->sieveAlternateUrl());
0429     m_vacationFileName = m_parentResource->settings()->sieveVacationFilename();
0430 
0431     Akonadi::Collection trashCollection(m_parentResource->settings()->trashCollection());
0432     if (trashCollection.isValid()) {
0433         auto fetchJob = new Akonadi::CollectionFetchJob(trashCollection, Akonadi::CollectionFetchJob::Base, this);
0434         connect(fetchJob, &Akonadi::CollectionFetchJob::collectionsReceived, this, &SetupServer::targetCollectionReceived);
0435     } else {
0436         auto requestJob = new Akonadi::SpecialMailCollectionsRequestJob(this);
0437         connect(requestJob, &Akonadi::SpecialMailCollectionsRequestJob::result, this, &SetupServer::localFolderRequestJobFinished);
0438         requestJob->requestDefaultCollection(Akonadi::SpecialMailCollections::Trash);
0439         requestJob->start();
0440     }
0441 
0442     m_identityCombobox->setCurrentIdentity(m_parentResource->settings()->accountIdentity());
0443 
0444     m_ui->enableMailCheckBox->setChecked(m_parentResource->settings()->intervalCheckEnabled());
0445     if (m_ui->enableMailCheckBox->isChecked()) {
0446         m_ui->checkInterval->setValue(m_parentResource->settings()->intervalCheckTime());
0447     } else {
0448         m_ui->checkInterval->setEnabled(false);
0449     }
0450 
0451     m_ui->autoExpungeCheck->setChecked(m_parentResource->settings()->automaticExpungeEnabled());
0452 
0453     if (m_vacationFileName.isEmpty()) {
0454         m_vacationFileName = QStringLiteral("kmail-vacation.siv");
0455     }
0456 
0457     m_ui->customUsername->setText(m_parentResource->settings()->sieveCustomUsername());
0458 
0459     rejected = false;
0460     const QString customPassword = m_parentResource->settings()->sieveCustomPassword(&rejected);
0461     if (rejected) {
0462         m_ui->customPassword->setEnabled(false);
0463         KMessageBox::information(nullptr,
0464                                  i18n("Could not access KWallet. "
0465                                       "If you want to store the password permanently then you have to "
0466                                       "activate it. If you do not "
0467                                       "want to use KWallet, check the box below, but note that you will be "
0468                                       "prompted for your password when needed."),
0469                                  i18n("Do not use KWallet"),
0470                                  QStringLiteral("warning_kwallet_disabled"));
0471     } else {
0472         m_ui->customPassword->lineEdit()->insert(customPassword);
0473     }
0474 
0475     const QString sieverCustomAuth(m_parentResource->settings()->sieveCustomAuthentification());
0476     if (sieverCustomAuth == QLatin1StringView("ImapUserPassword")) {
0477         m_ui->imapUserPassword->setChecked(true);
0478     } else if (sieverCustomAuth == QLatin1StringView("NoAuthentification")) {
0479         m_ui->noAuthentification->setChecked(true);
0480     } else if (sieverCustomAuth == QLatin1StringView("CustomUserPassword")) {
0481         m_ui->customUserPassword->setChecked(true);
0482     }
0483 
0484     delete currentUser;
0485 }
0486 
0487 void SetupServer::slotTest()
0488 {
0489     qCDebug(IMAPRESOURCE_LOG) << m_ui->imapServer->text();
0490 
0491     m_ui->testButton->setEnabled(false);
0492     m_ui->advancedTab->setEnabled(false);
0493     m_ui->authenticationCombo->setEnabled(false);
0494 
0495     m_ui->testInfo->clear();
0496     m_ui->testInfo->hide();
0497 
0498     delete m_serverTest;
0499     m_serverTest = new MailTransport::ServerTest(this);
0500 #ifndef QT_NO_CURSOR
0501     qApp->setOverrideCursor(Qt::BusyCursor);
0502 #endif
0503 
0504     const QString server = m_ui->imapServer->text();
0505     const int port = m_ui->portSpin->value();
0506     qCDebug(IMAPRESOURCE_LOG) << "server: " << server << "port: " << port;
0507 
0508     m_serverTest->setServer(server);
0509 
0510     if (port != 143 && port != 993) {
0511         m_serverTest->setPort(MailTransport::Transport::EnumEncryption::None, port);
0512         m_serverTest->setPort(MailTransport::Transport::EnumEncryption::SSL, port);
0513     }
0514 
0515     m_serverTest->setProtocol(QStringLiteral("imap"));
0516     m_serverTest->setProgressBar(m_ui->testProgress);
0517     connect(m_serverTest, &MailTransport::ServerTest::finished, this, &SetupServer::slotFinished);
0518     mOkButton->setEnabled(false);
0519     m_serverTest->start();
0520 }
0521 
0522 void SetupServer::slotFinished(const QList<int> &testResult)
0523 {
0524     qCDebug(IMAPRESOURCE_LOG) << testResult;
0525 
0526 #ifndef QT_NO_CURSOR
0527     qApp->restoreOverrideCursor();
0528 #endif
0529     mOkButton->setEnabled(true);
0530 
0531     using namespace MailTransport;
0532 
0533     if (!m_serverTest->isNormalPossible() && !m_serverTest->isSecurePossible()) {
0534         KMessageBox::error(this, i18n("Unable to connect to the server, please verify the server address."));
0535     }
0536 
0537     m_ui->testInfo->show();
0538 
0539     m_ui->sslRadio->setEnabled(testResult.contains(Transport::EnumEncryption::SSL));
0540     m_ui->tlsRadio->setEnabled(testResult.contains(Transport::EnumEncryption::TLS));
0541     m_ui->noRadio->setEnabled(testResult.contains(Transport::EnumEncryption::None));
0542 
0543     QString text;
0544     if (testResult.contains(Transport::EnumEncryption::TLS)) {
0545         m_ui->tlsRadio->setChecked(true);
0546         text = i18n("<qt><b>STARTTLS is supported and recommended.</b></qt>");
0547     } else if (testResult.contains(Transport::EnumEncryption::SSL)) {
0548         m_ui->sslRadio->setChecked(true);
0549         text = i18n("<qt><b>SSL/TLS is supported and recommended.</b></qt>");
0550     } else if (testResult.contains(Transport::EnumEncryption::None)) {
0551         m_ui->noRadio->setChecked(true);
0552         text = i18n(
0553             "<qt><b>No security is supported. It is not "
0554             "recommended to connect to this server.</b></qt>");
0555     } else {
0556         text = i18n("<qt><b>It is not possible to use this server.</b></qt>");
0557     }
0558     m_ui->testInfo->setText(text);
0559 
0560     m_ui->testButton->setEnabled(true);
0561     m_ui->advancedTab->setEnabled(true);
0562     m_ui->authenticationCombo->setEnabled(true);
0563     slotEncryptionRadioChanged();
0564     slotSafetyChanged();
0565 }
0566 
0567 void SetupServer::slotTestChanged()
0568 {
0569     delete m_serverTest;
0570     m_serverTest = nullptr;
0571     slotSafetyChanged();
0572 
0573     // do not use imapConnectionPossible, as the data is not yet saved.
0574     m_ui->testButton->setEnabled(true /* TODO && Global::connectionPossible() ||
0575                                                 m_ui->imapServer->text() == "localhost"*/);
0576 }
0577 
0578 void SetupServer::slotEnableWidgets()
0579 {
0580     const bool haveSieve = m_ui->managesieveCheck->isChecked();
0581     const bool reuseConfig = m_ui->sameConfigCheck->isChecked();
0582 
0583     m_ui->sameConfigCheck->setEnabled(haveSieve);
0584     m_ui->sievePortSpin->setEnabled(haveSieve);
0585     m_ui->alternateURL->setEnabled(haveSieve && !reuseConfig);
0586     m_ui->authentication->setEnabled(haveSieve && !reuseConfig);
0587 }
0588 
0589 void SetupServer::slotComplete()
0590 {
0591     const bool ok = !m_ui->imapServer->text().isEmpty() && !m_ui->userName->text().isEmpty();
0592     mOkButton->setEnabled(ok);
0593 }
0594 
0595 void SetupServer::slotSafetyChanged()
0596 {
0597     if (m_serverTest == nullptr) {
0598         return;
0599     }
0600     QList<int> protocols;
0601 
0602     switch (m_ui->safeImapGroup->checkedId()) {
0603     case KIMAP::LoginJob::Unencrypted:
0604         qCDebug(IMAPRESOURCE_LOG) << "safeImapGroup: unencrypted";
0605         protocols = m_serverTest->normalProtocols();
0606         break;
0607     case KIMAP::LoginJob::SSLorTLS:
0608         protocols = m_serverTest->secureProtocols();
0609         qCDebug(IMAPRESOURCE_LOG) << "safeImapGroup: SSL";
0610         break;
0611     case KIMAP::LoginJob::STARTTLS:
0612         protocols = m_serverTest->tlsProtocols();
0613         qCDebug(IMAPRESOURCE_LOG) << "safeImapGroup: starttls";
0614         break;
0615     default:
0616         qFatal("Shouldn't happen");
0617     }
0618 
0619     m_ui->authenticationCombo->clear();
0620     addAuthenticationItem(m_ui->authenticationCombo, MailTransport::Transport::EnumAuthenticationType::CLEAR);
0621     for (int prot : std::as_const(protocols)) {
0622         addAuthenticationItem(m_ui->authenticationCombo, (MailTransport::Transport::EnumAuthenticationType)prot);
0623     }
0624     if (protocols.isEmpty()) {
0625         qCDebug(IMAPRESOURCE_LOG) << "no authmodes found";
0626     } else {
0627         setCurrentAuthMode(m_ui->authenticationCombo, (MailTransport::Transport::EnumAuthenticationType)protocols.first());
0628     }
0629 }
0630 
0631 void SetupServer::slotManageSubscriptions()
0632 {
0633     qCDebug(IMAPRESOURCE_LOG) << "manage subscripts";
0634     ImapAccount account;
0635 
0636     account.setServer(m_ui->imapServer->text());
0637     account.setPort(m_ui->portSpin->value());
0638 
0639     account.setUserName(m_ui->userName->text());
0640     account.setSubscriptionEnabled(m_ui->subscriptionEnabled->isChecked());
0641 
0642     account.setEncryptionMode(static_cast<KIMAP::LoginJob::EncryptionMode>(m_ui->safeImapGroup->checkedId()));
0643 
0644     account.setAuthenticationMode(Settings::mapTransportAuthToKimap(getCurrentAuthMode(m_ui->authenticationCombo)));
0645 
0646     QPointer<SubscriptionDialog> subscriptions = new SubscriptionDialog(this);
0647     subscriptions->setWindowTitle(i18nc("@title:window", "Serverside Subscription"));
0648     subscriptions->setWindowIcon(QIcon::fromTheme(QStringLiteral("network-server")));
0649     subscriptions->connectAccount(account, m_ui->password->password());
0650     m_subscriptionsChanged = subscriptions->isSubscriptionChanged();
0651 
0652     subscriptions->exec();
0653     delete subscriptions;
0654 
0655     m_ui->subscriptionEnabled->setChecked(account.isSubscriptionEnabled());
0656 }
0657 
0658 void SetupServer::slotShowServerInfo()
0659 {
0660     auto dialog = new ServerInfoDialog(m_parentResource, this);
0661     dialog->show();
0662 }
0663 
0664 void SetupServer::targetCollectionReceived(const Akonadi::Collection::List &collections)
0665 {
0666     m_ui->folderRequester->setCollection(collections.first());
0667     mOldTrash = collections.first();
0668 }
0669 
0670 void SetupServer::localFolderRequestJobFinished(KJob *job)
0671 {
0672     if (!job->error()) {
0673         Akonadi::Collection targetCollection = Akonadi::SpecialMailCollections::self()->defaultCollection(Akonadi::SpecialMailCollections::Trash);
0674         Q_ASSERT(targetCollection.isValid());
0675         m_ui->folderRequester->setCollection(targetCollection);
0676         mOldTrash = targetCollection;
0677     }
0678 }
0679 
0680 void SetupServer::populateDefaultAuthenticationOptions()
0681 {
0682     populateDefaultAuthenticationOptions(m_ui->authenticationCombo);
0683     populateDefaultAuthenticationOptions(m_ui->authenticationAlternateCombo);
0684 }
0685 
0686 void SetupServer::populateDefaultAuthenticationOptions(QComboBox *combo)
0687 {
0688     combo->clear();
0689     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::CLEAR);
0690     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::LOGIN);
0691     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::PLAIN);
0692     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::CRAM_MD5);
0693     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::DIGEST_MD5);
0694     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::NTLM);
0695     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::GSSAPI);
0696     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::ANONYMOUS);
0697     addAuthenticationItem(combo, MailTransport::Transport::EnumAuthenticationType::XOAUTH2);
0698 }
0699 
0700 void SetupServer::slotServerChanged()
0701 {
0702     populateDefaultAuthenticationOptions(m_ui->authenticationCombo);
0703 }
0704 
0705 #include "moc_setupserver.cpp"