File indexing completed on 2024-04-28 04:55:43

0001 /*
0002     This file is part of Choqok, the KDE micro-blogging client
0003 
0004     SPDX-FileCopyrightText: 2016 Andrea Scarpino <scarpino@kde.org>
0005 
0006     SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0007 */
0008 
0009 #include "friendicaeditaccount.h"
0010 
0011 #include <QJsonDocument>
0012 #include <QLineEdit>
0013 
0014 #include <KIO/StoredTransferJob>
0015 #include <KJobWidgets>
0016 
0017 #include "accountmanager.h"
0018 #include "choqoktools.h"
0019 
0020 #include "gnusocialapiaccount.h"
0021 
0022 #include "friendicadebug.h"
0023 #include "friendicamicroblog.h"
0024 
0025 FriendicaEditAccountWidget::FriendicaEditAccountWidget(FriendicaMicroBlog *microblog,
0026         GNUSocialApiAccount *account, QWidget *parent)
0027     : ChoqokEditAccountWidget(account, parent), mAccount(account), progress(nullptr), isAuthenticated(false)
0028 {
0029     setupUi(this);
0030 //     setAuthenticated(false);
0031 //     connect(kcfg_authorize, SIGNAL(clicked(bool)), SLOT(authorizeUser()));
0032 //     connect(kcfg_authMethod, SIGNAL(currentIndexChanged(int)), SLOT(slotAuthMethodChanged(int)));
0033 //     slotAuthMethodChanged(kcfg_authMethod->currentIndex());
0034     connect(kcfg_host, &QLineEdit::editingFinished, this,
0035             &FriendicaEditAccountWidget::slotCheckHostUrl);
0036     if (mAccount) {
0037         kcfg_alias->setText(mAccount->alias());
0038         kcfg_host->setText(mAccount->host());
0039         kcfg_api->setText(mAccount->api());
0040 //         kcfg_oauthUsername->setText( mAccount->username() );
0041         kcfg_basicUsername->setText(mAccount->username());
0042         kcfg_basicPassword->setText(mAccount->password());
0043         kcfg_changeExclamationMark->setChecked(mAccount->isChangeExclamationMark());
0044         kcfg_changeToString->setText(mAccount->changeExclamationMarkToText());
0045 //         if(mAccount->usingOAuth()){
0046 //             if( !mAccount->oauthConsumerKey().isEmpty() &&
0047 //                 !mAccount->oauthConsumerSecret().isEmpty() &&
0048 //                 !mAccount->oauthToken().isEmpty() &&
0049 //                 !mAccount->oauthTokenSecret().isEmpty() ) {
0050 //                 setAuthenticated(true);
0051 //                 oauthConsumerKey = mAccount->oauthConsumerKey();
0052 //                 oauthConsumerSecret = mAccount->oauthConsumerSecret();
0053 //                 token = mAccount->oauthToken();
0054 //                 tokenSecret = mAccount->oauthTokenSecret();
0055 //             } else {
0056 //                 setAuthenticated(false);
0057 //             }
0058 //              kcfg_authMethod->setCurrentIndex(0);
0059 //         } else {
0060 //             kcfg_authMethod->setCurrentIndex(1);
0061 //         }
0062     } else {
0063 //         kcfg_authMethod->setCurrentIndex(0);
0064         QString newAccountAlias = microblog->serviceName();
0065         QString servName = newAccountAlias;
0066         int counter = 1;
0067         while (Choqok::AccountManager::self()->findAccount(newAccountAlias)) {
0068             newAccountAlias = QStringLiteral("%1%2").arg(servName).arg(counter);
0069             counter++;
0070         }
0071         setAccount(mAccount = new GNUSocialApiAccount(microblog, newAccountAlias));
0072         kcfg_alias->setText(newAccountAlias);
0073         const QRegExp userRegExp(QLatin1String("([a-z0-9]){1,64}"), Qt::CaseInsensitive);
0074         QValidator *userVal = new QRegExpValidator(userRegExp, nullptr);
0075         kcfg_basicUsername->setValidator(userVal);
0076     }
0077     loadTimelinesTableState();
0078     kcfg_alias->setFocus(Qt::OtherFocusReason);
0079 }
0080 
0081 FriendicaEditAccountWidget::~FriendicaEditAccountWidget()
0082 {
0083 }
0084 
0085 bool FriendicaEditAccountWidget::validateData()
0086 {
0087 //     if( kcfg_authMethod->currentIndex()==0 ) {//OAuth
0088 //         if(kcfg_alias->text().isEmpty() || kcfg_oauthUsername->text().isEmpty() || !isAuthenticated)
0089 //             return false;
0090 //     } else {//Basic
0091     if (kcfg_alias->text().isEmpty() || kcfg_basicUsername->text().isEmpty() ||
0092             kcfg_basicPassword->text().isEmpty()) {
0093         return false;
0094     }
0095 //     }
0096     return true;
0097 }
0098 
0099 Choqok::Account *FriendicaEditAccountWidget::apply()
0100 {
0101     qCDebug(CHOQOK);
0102     /*if(kcfg_authMethod->currentIndex() == 0){
0103         mAccount->setUsername( kcfg_oauthUsername->text() );
0104         mAccount->setOauthToken( token );
0105         mAccount->setOauthConsumerKey( oauthConsumerKey );
0106         mAccount->setOauthConsumerSecret( oauthConsumerSecret );
0107         mAccount->setOauthTokenSecret( tokenSecret );
0108         mAccount->setUsingOAuth(true);
0109     } else*/ {
0110         mAccount->setUsername(kcfg_basicUsername->text());
0111         mAccount->setPassword(kcfg_basicPassword->text());
0112         mAccount->setUsingOAuth(false);
0113     }
0114     mAccount->setHost(kcfg_host->text());
0115     mAccount->setApi(kcfg_api->text());
0116     mAccount->setAlias(kcfg_alias->text());
0117     mAccount->setChangeExclamationMark(kcfg_changeExclamationMark->isChecked());
0118     mAccount->setChangeExclamationMarkToText(kcfg_changeToString->text());
0119     saveTimelinesTableState();
0120     setTextLimit();
0121     mAccount->writeConfig();
0122     return mAccount;
0123 }
0124 
0125 // void FriendicaEditAccountWidget::authorizeUser()
0126 // {
0127 //     qCDebug(CHOQOK);
0128 //     slotCheckHostUrl();
0129 //     if(QUrl(kcfg_host->text()).host()!="identi.ca"){
0130 //         KMessageBox::sorry(this, i18n("Sorry, OAuth Method just works with Identi.ca server. You have to use basic authentication for other StatusNet servers."));
0131 //         kcfg_authMethod->setCurrentIndex(1);
0132 //         return;
0133 //     }
0134 //     qoauth = new QOAuth::Interface(new KIO::Integration::AccessManager(this), this);
0135 //     //TODO change this to have support for self hosted StatusNets
0136 //     qoauth->setConsumerKey( oauthConsumerKey );
0137 //     qoauth->setConsumerSecret( oauthConsumerSecret );
0138 //     qoauth->setRequestTimeout( 10000 );
0139 //
0140 //     // send a request for an unauthorized token
0141 //     QString oauthReqTokenUrl = QString("%1/%2/oauth/request_token").arg(kcfg_host->text()).arg(kcfg_api->text());
0142 // //     qCDebug(CHOQOK)<<oauthReqTokenUrl;
0143 //     QOAuth::ParamMap params;
0144 //     params.insert("oauth_callback", "oob");
0145 //     QOAuth::ParamMap reply =
0146 //         qoauth->requestToken( oauthReqTokenUrl, QOAuth::GET, QOAuth::HMAC_SHA1, params );
0147 //     setAuthenticated(false);
0148 //     kcfg_authorize->setIcon(QIcon::fromTheme("object-locked"));
0149 //
0150 //     // if no error occurred, read the received token and token secret
0151 //     if ( qoauth->error() == QOAuth::NoError ) {
0152 //         token = reply.value( QOAuth::tokenParameterName() );
0153 //         tokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
0154 //         qCDebug(CHOQOK)<<"token: "<<token;
0155 //         QUrl url(QString("%1/%2/oauth/authorize").arg(kcfg_host->text()).arg(kcfg_api->text()));
0156 //         url.addQueryItem( QOAuth::tokenParameterName(), token );
0157 //         url.addQueryItem( "oauth_token", token );
0158 //         Choqok::openUrl(url);
0159 //         kcfg_authorize->setEnabled(false);
0160 //         getPinCode();
0161 //     } else {
0162 //         qCDebug(CHOQOK)<<"ERROR:" <<qoauth->error()<<Choqok::qoauthErrorText(qoauth->error());
0163 //         KMessageBox::detailedError(this, i18n("Authentication Error"),
0164 //                                    Choqok::qoauthErrorText(qoauth->error()));
0165 //     }
0166 // }
0167 //
0168 // void FriendicaEditAccountWidget::getPinCode()
0169 // {
0170 //     isAuthenticated = false;
0171 //     while(!isAuthenticated){
0172 //         QString verifier = KInputDialog::getText( i18n("Security code"),
0173 //                                                   i18nc("Security code received from StatusNet",
0174 //                                                         "Enter security code:"));
0175 //         if(verifier.isEmpty())
0176 //             return;
0177 //         QOAuth::ParamMap otherArgs;
0178 //         otherArgs.insert( "oauth_verifier", verifier.toUtf8() );
0179 //
0180 //         QOAuth::ParamMap reply =
0181 //         qoauth->accessToken( QString("%1/%2/oauth/access_token").arg(kcfg_host->text()).arg(kcfg_api->text()),
0182 //                              QOAuth::GET, token, tokenSecret, QOAuth::HMAC_SHA1, otherArgs );
0183 //         // if no error occurred, read the Access Token (and other arguments, if applicable)
0184 //         if ( qoauth->error() == QOAuth::NoError ) {
0185 //             sender()->deleteLater();
0186 //             kcfg_authorize->setEnabled(true);
0187 //             token = reply.value( QOAuth::tokenParameterName() );
0188 //             tokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
0189 //             qCDebug(CHOQOK)<<"token: "<<token;
0190 //             setAuthenticated(true);
0191 //             KMessageBox::information(this, i18n("Choqok is authorized successfully."),
0192 //                                      i18n("Authorized"));
0193 //         } else {
0194 //             setAuthenticated(false);
0195 //             qCDebug(CHOQOK)<<"ERROR: "<<qoauth->error()<<' '<<Choqok::qoauthErrorText(qoauth->error());
0196 //             KMessageBox::detailedError(this, i18n("Authentication Error"),
0197 //             Choqok::qoauthErrorText(qoauth->error()));
0198 //         }
0199 //     }
0200 // }
0201 
0202 void FriendicaEditAccountWidget::setTextLimit()
0203 {
0204     QString url = mAccount->host() + QLatin1Char('/') + mAccount->api() + QLatin1String("/statusnet/config.json");
0205     KIO::StoredTransferJob *job = KIO::storedGet(QUrl(url), KIO::Reload, KIO::HideProgressInfo);
0206     job->exec();
0207     if (job->error()) {
0208         qCCritical(CHOQOK) << "Job error:" << job->errorString();
0209         return;
0210     }
0211 
0212     const QJsonDocument json = QJsonDocument::fromJson(job->data());
0213     if (!json.isNull()) {
0214         const QVariantMap siteInfos = json.toVariant().toMap()[QLatin1String("site")].toMap();
0215         bool ok;
0216         mAccount->setPostCharLimit(siteInfos[QLatin1String("textlimit")].toUInt(&ok));
0217         if (!ok) {
0218             qCDebug(CHOQOK) << "Cannot parse text limit value";
0219             mAccount->setPostCharLimit(140);
0220         }
0221     } else {
0222         qCDebug(CHOQOK) << "Cannot parse JSON reply";
0223     }
0224 }
0225 
0226 void FriendicaEditAccountWidget::loadTimelinesTableState()
0227 {
0228     for (const QString &timeline: mAccount->microblog()->timelineNames()) {
0229         int newRow = timelinesTable->rowCount();
0230         timelinesTable->insertRow(newRow);
0231         Choqok::TimelineInfo *info = mAccount->microblog()->timelineInfo(timeline);
0232         QTableWidgetItem *item = new QTableWidgetItem(info->name);
0233         item->setData(32, timeline);
0234         item->setToolTip(info->description);
0235         timelinesTable->setItem(newRow, 0, item);
0236 
0237         QCheckBox *enable = new QCheckBox(timelinesTable);
0238         enable->setChecked(mAccount->timelineNames().contains(timeline));
0239         timelinesTable->setCellWidget(newRow, 1, enable);
0240     }
0241 }
0242 
0243 void FriendicaEditAccountWidget::saveTimelinesTableState()
0244 {
0245     QStringList timelines;
0246     int rowCount = timelinesTable->rowCount();
0247     for (int i = 0; i < rowCount; ++i) {
0248         QCheckBox *enable = qobject_cast<QCheckBox *>(timelinesTable->cellWidget(i, 1));
0249         if (enable && enable->isChecked()) {
0250             timelines << timelinesTable->item(i, 0)->data(32).toString();
0251         }
0252     }
0253     timelines.removeDuplicates();
0254     mAccount->setTimelineNames(timelines);
0255 }
0256 
0257 // void FriendicaEditAccountWidget::slotAuthMethodChanged(int index)
0258 // {
0259 //     if(index == 0){
0260 //         kcfg_BasicBox->hide();
0261 //         kcfg_OAuthBox->show();
0262 //     } else {
0263 //         kcfg_BasicBox->show();
0264 //         kcfg_OAuthBox->hide();
0265 //     }
0266 // }
0267 
0268 // void FriendicaEditAccountWidget::setAuthenticated(bool authenticated)
0269 // {
0270 //     isAuthenticated = authenticated;
0271 //     if(authenticated){
0272 //         kcfg_authorize->setIcon(QIcon::fromTheme("object-unlocked"));
0273 //         kcfg_authenticateLed->on();
0274 //         kcfg_authenticateStatus->setText(i18n("Authenticated"));
0275 //     } else {
0276 //         kcfg_authorize->setIcon(QIcon::fromTheme("object-locked"));
0277 //         kcfg_authenticateLed->off();
0278 //         kcfg_authenticateStatus->setText(i18n("Not Authenticated"));
0279 //     }
0280 // }
0281 
0282 void FriendicaEditAccountWidget::slotCheckHostUrl()
0283 {
0284     if (!kcfg_host->text().isEmpty() && !kcfg_host->text().startsWith(QLatin1String("http"),
0285             Qt::CaseInsensitive) && !kcfg_host->text().startsWith(QLatin1String("https"))) {
0286         kcfg_host->setText(kcfg_host->text().prepend(QLatin1String("https://")));
0287     }
0288 }
0289 
0290 #include "moc_friendicaeditaccount.cpp"