void TwitterEditAccountWidget::authorizeUser()
{
    kDebug();
    qoauth = new QOAuth::Interface(new KIO::AccessManager(this), this);//TODO KDE 4.5 Change to use new class.
    // set the consumer key and secret
    qoauth->setConsumerKey( twitterConsumerKey );
    qoauth->setConsumerSecret( twitterConsumerSecret );
    // set a timeout for requests (in msecs)
    qoauth->setRequestTimeout( 20000 );
    qoauth->setIgnoreSslErrors(true);

    QOAuth::ParamMap otherArgs;

    // send a request for an unauthorized token
    QOAuth::ParamMap reply =
        qoauth->requestToken( "https://twitter.com/oauth/request_token",
                              QOAuth::GET, QOAuth::HMAC_SHA1 );

    // if no error occurred, read the received token and token secret
    if ( qoauth->error() == QOAuth::NoError ) {
        token = reply.value( QOAuth::tokenParameterName() );
        tokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
        kDebug()<<"token: "<<token;
        QUrl url("https://twitter.com/oauth/authorize");
        url.addQueryItem("oauth_token", token);
        url.addQueryItem( "oauth_callback", "oob" );
        Choqok::openUrl(url);
        getPinCode();
    } else {
        kDebug()<<"ERROR: " <<qoauth->error()<<' '<<Choqok::qoauthErrorText(qoauth->error());
        KMessageBox::detailedError(this, i18n("Authorization Error"),
                                   Choqok::qoauthErrorText(qoauth->error()));
    }
}
bool PlurkApiOAuth::authorizeUser()
{
    kDebug();
    // set the consumer key and secret
    d->qoauth->setConsumerKey( plurkConsumerKey );
    d->qoauth->setConsumerSecret( plurkConsumerSecret );
    // set a timeout for requests (in msecs)
    d->qoauth->setRequestTimeout( 20000 );
    d->qoauth->setIgnoreSslErrors(true);

    QOAuth::ParamMap otherArgs;

    // send a request for an unauthorized token
    QOAuth::ParamMap reply =
        d->qoauth->requestToken( plurkOAuthRequestTokenURL, QOAuth::GET, QOAuth::HMAC_SHA1 );

    // if no error occurred, read the received token and token secret
    if ( d->qoauth->error() == QOAuth::NoError ) {
        d->oauthToken = reply.value( QOAuth::tokenParameterName() );
        d->oauthTokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
        kDebug() << "token: " << d->oauthToken;
        QUrl url(plurkOAuthAuthorizeURL);
        url.addQueryItem("oauth_token", d->oauthToken);
        url.addQueryItem( "oauth_callback", "oob" );
        KToolInvocation::invokeBrowser(url.toString());
        return getPinCode();
    } else {
        kDebug() << "ERROR: " << d->qoauth->error() << ' ' << oauthErrorText(d->qoauth->error());
        // TODO use a parent widget for this message box
        KMessageBox::detailedError(0, "Authorization Error",
                                   oauthErrorText(d->qoauth->error()));
    }

    return false;
}
Exemple #3
0
void TweetJob::start()
{
    kDebug() << "starting job" << m_url;
    QByteArray data;
    QOAuth::ParamMap params;

    data = "source=kdemicroblog";
    params.insert("source", "kdemicroblog");
    {
        QMapIterator<QString, QVariant> i(m_parameters);
        while (i.hasNext()) {
            i.next();
            if (!i.value().toString().isEmpty()) {
                if (i.key() == "status") {
                    const QByteArray status = i.value().toString().toUtf8().toPercentEncoding();
                    params.insert("status", status);
                    data = data.append("&status=" + status);
                } else {
                    const QByteArray key = i.key().toLatin1();
                    const QByteArray value = i.value().toString().toLatin1();
                    params.insert(key, value);
                    data = data.append("&"+key+"="+value);
                }
            }
        }
    }
    KIO::Job *job = KIO::http_post(m_url, data, KIO::HideProgressInfo);
    job->addMetaData("content-type", "Content-Type: application/x-www-form-urlencoded");

    m_source->oAuthHelper()->sign(job, m_url.pathOrUrl(), params, KOAuth::POST);
    connect(job, SIGNAL(data(KIO::Job*,QByteArray)),
            this, SLOT(recv(KIO::Job*,QByteArray)));
    connect(job, SIGNAL(result(KJob*)), this, SLOT(result(KJob*)));
}
Exemple #4
0
void Updater::checkForUpdates(int flag)
{
#ifndef MAC_APPSTORE
    if(flag == ForceNotification)
    {
        notifyUpdates = true;
    }else if(flag == NoNotification)
    {
        notifyUpdates = false;
    }
    QOAuth::Interface *qoauth = new QOAuth::Interface;
    qoauth->setConsumerKey(CONSUMER_KEY_SCREENCLOUD);
    qoauth->setConsumerSecret(CONSUMER_SECRET_SCREENCLOUD);
    QByteArray url( "http://screencloud.net/1.0/updates/check_version.xml" );
    // create a request parameters map
    QOAuth::ParamMap map;
    map.insert("version", VERSION);
    map.insert("os", OS_SHORTNAME);

    // construct the body string
    QByteArray params =
    qoauth->createParametersString( url, QOAuth::POST,
                                        token, tokenSecret,QOAuth::HMAC_SHA1, map,
                                        QOAuth::ParseForRequestContent );
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    manager->post(request, params);
#endif
}
Exemple #5
0
void TwitterSearch::requestSearchResults(const SearchInfo &searchInfo,
        const QString &sinceStatusId, uint count, uint page)
{
    Q_UNUSED(page)
    qCDebug(CHOQOK);

    TwitterAccount *account = qobject_cast< TwitterAccount * >(searchInfo.account);
    QUrl url = account->apiUrl();

    QUrlQuery urlQuery;
    QOAuth::ParamMap param;

    const QString query = searchInfo.query;
    if (searchInfo.option == TwitterSearch::FromUser) {
        url.setPath(url.path() + QLatin1String("/statuses/user_timeline.json"));

        urlQuery.addQueryItem(QLatin1String("screen_name"), query);
        param.insert("screen_name", query.toLatin1());
    } else {
        url.setPath(url.path() + QLatin1String("/search/tweets.json"));

        const QByteArray formattedQuery(QUrl::toPercentEncoding(mSearchCode[searchInfo.option] + query));
        urlQuery.addQueryItem(QLatin1String("q"), QString::fromLatin1(formattedQuery));
        param.insert("q", formattedQuery);
    }

    if (!sinceStatusId.isEmpty()) {
        urlQuery.addQueryItem(QLatin1String("since_id"), sinceStatusId);
        param.insert("since_id", sinceStatusId.toLatin1());
    }

    int cntStr;
    if (count && count <= 100) { // Twitter API specifies a max count of 100
        cntStr = count;
    } else {
        cntStr = 100;
    }
    urlQuery.addQueryItem(QLatin1String("count"), QString::number(cntStr));
    param.insert("count", QString::number(cntStr).toLatin1());

    const QUrl tmpUrl(url);
    url.setQuery(urlQuery);

    qCDebug(CHOQOK) << url;
    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    if (!job) {
        qCCritical(CHOQOK) << "Cannot create an http GET request!";
        return;
    }

    TwitterApiMicroBlog *microblog = qobject_cast<TwitterApiMicroBlog *>(account->microblog());

    job->addMetaData(QStringLiteral("customHTTPHeader"),
                     QStringLiteral("Authorization: ") +
                     QLatin1String(microblog->authorizationHeader(account, tmpUrl, QOAuth::GET, param)));

    mSearchJobs[job] = searchInfo;
    connect(job, SIGNAL(result(KJob*)), this, SLOT(searchResultsReturned(KJob*)));
    job->start();
}
Exemple #6
0
void TwitterMicroBlog::fetchUserLists(TwitterAccount *theAccount, const QString &username)
{
    qCDebug(CHOQOK);
    if (!theAccount) {
        return;
    }
    QUrl url = theAccount->apiUrl();
    url.setPath(url.path() + QStringLiteral("/lists/ownerships.%1").arg(format));
    QUrl url_for_oauth(url);//we need base URL (without params) to make OAuth signature with it!
    QUrlQuery urlQuery;
    urlQuery.addQueryItem(QLatin1String("screen_name"), username);
    url.setQuery(urlQuery);
    QOAuth::ParamMap params;
    params.insert("screen_name", username.toLatin1());

    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo) ;
    if (!job) {
        qCCritical(CHOQOK) << "TwitterMicroBlog::loadUserLists: Cannot create an http GET request!";
        return;
    }

    job->addMetaData(QStringLiteral("customHTTPHeader"),
                     QStringLiteral("Authorization: ") +
                     QLatin1String(authorizationHeader(theAccount, url_for_oauth, QOAuth::GET, params)));
    mFetchUsersListMap[ job ] = username;
    mJobsAccount[ job ] = theAccount;
    connect(job, SIGNAL(result(KJob*)), this, SLOT(slotFetchUserLists(KJob*)));
    job->start();
}
QByteArray PlurkApiOAuth::makeHeader( const QString & url, const QMap< QString, QString > & params ) const {
    QOAuth::ParamMap oaParams;
    for( QMap< QString, QString >::const_iterator it = params.begin(); it != params.end(); ++it ) {
        QByteArray key( QUrl::toPercentEncoding( it.key() ) ), value( QUrl::toPercentEncoding( it.value() ) );
        oaParams.insert( key, value );
    }
    // NOTE Always use POST and SHA1 here. This seems always work with Plurk.
    QByteArray header( d->qoauth->createParametersString( url, QOAuth::POST, d->oauthToken, d->oauthTokenSecret, QOAuth::HMAC_SHA1, oaParams, QOAuth::ParseForHeaderArguments ) );
    header.prepend( "Authorization: " );
    return header;
}
Exemple #8
0
void OAuthWizard::openUrl()
{
  QOAuth::ParamMap requestToken = qoauth->requestToken( TwitterRequestTokenURL, QOAuth::GET, QOAuth::HMAC_SHA1 );

  if ( qoauth->error() != QOAuth::NoError ) {
    if ( sender() == ui_p->okButton ) {
      delete ui_o->widget->layout();

      ui_p->okButton->deleteLater();
      ui_p->pinEdit->deleteLater();
      ui_p->pinLabel->deleteLater();
      ui_a->setupUi(ui_o->widget);
    }

    ui_a->allowLabel->setText( tr( "There was a network-related problem with completing the request. Please try again later." ) );
    ui_a->allowButton->setText( tr( "Retry" ) );
    adjustSize();
    resize( width(), height() * 1.5 );
    state = false;
    return;
  }

  token = requestToken.value( QOAuth::ParamToken );
  tokenSecret = requestToken.value( QOAuth::ParamTokenSecret );

  QString url = TwitterAuthorizeURL;

  url.append( "?" );
  url.append( "&" + QOAuth::ParamToken + "=" + token );
  url.append( "&" + ParamCallback + "=" + ParamCallbackValue );

  QDesktopServices::openUrl( QUrl( url ) );

  delete ui_o->widget->layout();

  if ( sender() == ui_p->okButton ) {
    delete ui_o->widget->layout();

    ui_p->okButton->deleteLater();
    ui_p->pinEdit->deleteLater();
    ui_p->pinLabel->deleteLater();
  } else {
    ui_a->allowLabel->deleteLater();
    ui_a->allowButton->deleteLater();
  }

  ui_p->setupUi(ui_o->widget);
  ui_p->pinEdit->setValidator( new QRegExpValidator( QRegExp( "\\d{6}" ), this ) );
  connect( ui_p->okButton, SIGNAL(clicked()), this, SLOT(authorize()) );
  connect( ui_p->pinEdit, SIGNAL(textChanged(QString)), this, SLOT(setOkButtonEnabled()) );
}
bool NewAccountPage::validatePage()
{
    if(hasCreatedAccount)
    {
        return true;
    }
    serverQueryFinished = false;
    serverQueryError = false;
    //Check if passwords match
    if(input_password->text() != input_confirmPassword->text())
    {
        label_message->setText("<font color='red'>Passwords do not match</font>");
        return false;
    }
    label_message->setText("Creating account...");
    QByteArray token, tokenSecret;
    QOAuth::Interface *qoauth = new QOAuth::Interface;
    qoauth->setConsumerKey(CONSUMER_KEY_SCREENCLOUD);
    qoauth->setConsumerSecret(CONSUMER_SECRET_SCREENCLOUD);
    QByteArray url( "https://screencloud.net/1.0/users/register.xml" );
    QString urlString = QString(url);
    // create a request parameters map
    QOAuth::ParamMap map;
    map.insert( "data[User][email]", QUrl::toPercentEncoding(input_email->text()));
    map.insert( "data[User][password]", QUrl::toPercentEncoding(input_password->text()) );
    map.insert("data[User][password_confirmation]", QUrl::toPercentEncoding(input_confirmPassword->text()));

    // construct the body string
    QByteArray body =
    qoauth->createParametersString( urlString, QOAuth::POST,
                                        token, tokenSecret,QOAuth::HMAC_SHA1, map,
                                        QOAuth::ParseForRequestContent );

    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    manager->post(request, body);
    while (!serverQueryFinished) {
       qApp->processEvents(QEventLoop::WaitForMoreEvents);
    }
    if(serverQueryError)
    {
        return false;
    }
    hasCreatedAccount = true;
    return true;
}
Exemple #10
0
RequestDataJob::RequestDataJob(const QUrl& url, QOAuth::HttpMethod method, QOAuth::ParamMap paramMap, QObject* parent) : QObject(parent)
    ,m_inlineString(moeApp->inlineString (paramMap, QOAuth::ParseForRequestContent))
    ,m_request(url)
    ,m_method(method)
{
    if (method == QOAuth::POST) {
        m_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        for (QOAuth::ParamMap::iterator it = paramMap.begin(); it != paramMap.end(); it++) {
            it.value() = QUrl::toPercentEncoding(QString::fromUtf8(it.value()));
        }
        m_request.setRawHeader("Authorization", moeApp->createParametersString(m_request.url(), method, paramMap, QOAuth::ParseForRequestContent));
    } else if (method == QOAuth::GET) {
        QUrl newUrl(url.toString().append(moeApp->createParametersString(m_request.url(), method, paramMap, QOAuth::ParseForInlineQuery)));
        m_request.setUrl(newUrl);
        // qDebug() << m_request.url();
    }

}
Exemple #11
0
void RequestTokenJob::start()
{
    QOAuth::Interface oauth(this);
    oauth.setConsumerKey(CONSUMER_KEY);
    oauth.setConsumerSecret(CONSUMER_SECRET);

    QOAuth::ParamMap map = oauth.requestToken(REQUEST_TOKEN_URL, QOAuth::POST, QOAuth::HMAC_SHA1);

    QByteArray oauthToken, oauthTokenSecret;
    bool success = false;
    if (oauth.error() == 200) {
        oauthToken = map.value (QOAuth::tokenParameterName());
        oauthTokenSecret = map.value (QOAuth::tokenSecretParameterName());
        success = true;
    }

    emit finished(success, oauthToken, oauthTokenSecret);
}
void TwitterEditAccountWidget::getPinCode()
{
    isAuthenticated = false;
    while(!isAuthenticated){
        QString verifier = KInputDialog::getText( i18n("PIN number"),
                                                  i18n("Enter PIN number received from Twitter:"));
        if(verifier.isEmpty())
            return;
        QOAuth::ParamMap otherArgs;
        otherArgs.insert( "oauth_verifier", verifier.toUtf8() );

        // send a request to exchange Request Token for an Access Token
        QOAuth::ParamMap reply =
            qoauth->accessToken( "https://twitter.com/oauth/access_token", QOAuth::POST, token,
                                tokenSecret, QOAuth::HMAC_SHA1, otherArgs );
        // if no error occurred, read the Access Token (and other arguments, if applicable)
        if ( qoauth->error() == QOAuth::NoError ) {
            username = reply.value( "screen_name" );
            token = reply.value( QOAuth::tokenParameterName() );
            tokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
            setAuthenticated(true);
            KMessageBox::information(this, i18n("Choqok is authorized successfully."),
                                     i18n("Authorized"));
        } else {
            kDebug()<<"ERROR: "<<qoauth->error()<<' '<<Choqok::qoauthErrorText(qoauth->error());
            KMessageBox::detailedError(this, i18n("Authorization Error"),
                                    Choqok::qoauthErrorText(qoauth->error()));
        }
    }
}
bool PlurkApiOAuth::getPinCode()
{
    QString verifier = KInputDialog::getText( "Security code",
                                              "Security code recieved from Plurk",
                                                    "Enter security code:");
    if(verifier.isEmpty())
        return false;
    QOAuth::ParamMap otherArgs;
    otherArgs.insert( "oauth_verifier", verifier.toUtf8() );

    // send a request to exchange Request Token for an Access Token
    QOAuth::ParamMap reply =
    d->qoauth->accessToken( QString(plurkOAuthAccessToken),
                         QOAuth::GET, d->oauthToken, d->oauthTokenSecret, QOAuth::HMAC_SHA1, otherArgs );
    // if no error occurred, read the Access Token (and other arguments, if applicable)
    if ( d->qoauth->error() == QOAuth::NoError ) {
        d->username = reply.value( "screen_name" );
        d->oauthToken = reply.value( QOAuth::tokenParameterName() );
        d->oauthTokenSecret = reply.value( QOAuth::tokenSecretParameterName() );
        // TODO use a parent widget for this message box
        KMessageBox::information(0, "Plurk is authorized successfully.",
                                 "Authorized");
        return true;
    } else {
        kDebug() << "ERROR: " << d->qoauth->error() << ' ' << oauthErrorText(d->qoauth->error());
        KMessageBox::detailedError(0, "Authorization Error",
                                oauthErrorText(d->qoauth->error()));
    }

    return false;
}
Exemple #14
0
void OAuthWizard::authorize()
{
  ui_p->pinEdit->setEnabled( false );
  QOAuth::ParamMap otherArgs;
  otherArgs.insert( ParamVerifier, ui_p->pinEdit->text().toAscii() );
  QOAuth::ParamMap accessToken = qoauth->accessToken( TwitterAccessTokenURL, QOAuth::POST, token,
                                                      tokenSecret, QOAuth::HMAC_SHA1, otherArgs );

  if ( qoauth->error() != QOAuth::NoError ) {
    ui_p->pinEdit->hide();
    ui_p->pinLabel->setText( tr( "Either the PIN you entered is incorrect, or a network-related problem occured. Please try again later." ) );
    ui_p->okButton->setText( tr( "Retry" ) );
    adjustSize();
    resize( width(), height() * 1.5 );
    disconnect( ui_p->okButton, SIGNAL(clicked()), this, SLOT(authorize()) );
    connect( ui_p->okButton, SIGNAL(clicked()), this, SLOT(openUrl()) );
    state = false;
    return;
  }

  screenName = accessToken.value( ParamScreenName );
  token = accessToken.value( QOAuth::ParamToken );
  tokenSecret = accessToken.value( QOAuth::ParamTokenSecret );
  state = true;
  accept();
}
void ScreencloudUploader::upload(QImage *screenshot)
{
    //Save to a buffer
    buffer = new QBuffer(&bufferArray, this);
    buffer->open(QIODevice::WriteOnly);
    if(format == "jpg")
    {
        if(!screenshot->save(buffer, format.toAscii(), jpegQuality))
        {
            emit uploadingError("Failed to save screenshot to " + QDir::tempPath());
        }
    }else
    {
        if(!screenshot->save(buffer, format.toAscii()))
        {
                emit uploadingError("Failed to save screenshot to " + QDir::tempPath());
        }
    }
    //Upload to screencloud
    QOAuth::Interface *qoauth = new QOAuth::Interface;
    qoauth->setConsumerKey(CONSUMER_KEY_SCREENCLOUD);
    qoauth->setConsumerSecret(CONSUMER_SECRET_SCREENCLOUD);
    QByteArray url( "http://screencloud.net/1.0/screenshots/upload.xml" );

    // create a request parameters map
    QOAuth::ParamMap map;
    map.insert( "name", QUrl::toPercentEncoding(screenshotName) );
    map.insert( "description", QUrl::toPercentEncoding("Taken on " + QDate::currentDate().toString("yyyy-MM-dd") + " at " + QTime::currentTime().toString("hh:mm") + " with the " + OPERATING_SYSTEM + " version of ScreenCloud") );

    QString mimetype = "image/" + format;
    if(format == "jpg")
    {
        mimetype = "image/jpeg";
    }
    QByteArray header =
    qoauth->createParametersString( uploadUrl, QOAuth::POST,
                                        token, tokenSecret,QOAuth::HMAC_SHA1, map,
                                        QOAuth::ParseForHeaderArguments );
    //Add post file
    QString boundaryData = QVariant(qrand()).toString()+QVariant(qrand()).toString()+QVariant(qrand()).toString();
    QByteArray boundary;
    QByteArray dataToSend; // byte array to be sent in POST

    boundary="-----------------------------" + boundaryData.toAscii();

    QByteArray body = "\r\n--" + boundary + "\r\n";

    //Name
    body += "Content-Disposition: form-data; name=\"name\"\r\n\r\n";
    body += QUrl::toPercentEncoding(screenshotName) + "\r\n";

    body += QString("--" + boundary + "\r\n").toAscii();
    body += "Content-Disposition: form-data; name=\"description\"\r\n\r\n";
    body += QUrl::toPercentEncoding("Taken on " + QDate::currentDate().toString("yyyy-MM-dd") + " at " + QTime::currentTime().toString("hh:mm") + " with the " + OPERATING_SYSTEM + " version of ScreenCloud") + "\r\n";

    body += QString("--" + boundary + "\r\n").toAscii();
    body += "Content-Disposition: form-data; name=\"file\"; filename=\" " + QUrl::toPercentEncoding(screenshotName + boundary + "." + format) + "\"\r\n";
    body += "Content-Type: " + mimetype + "\r\n\r\n";
    body += bufferArray;

    body += "\r\n--" + boundary + "--\r\n";

    url.append( qoauth->inlineParameters( map, QOAuth::ParseForInlineQuery ) );
    qDebug() << url;
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader( "Authorization", header );
    request.setRawHeader("Content-Type","multipart/form-data; boundary=" + boundary);
    request.setHeader(QNetworkRequest::ContentLengthHeader,body.size());
    manager->post(request, body);
}