Exemple #1
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 #2
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();
}
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 #5
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 #6
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();
}
Exemple #7
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();
}
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;
}
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;
}
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);
}