Beispiel #1
0
QString Posterous::getAuthToken(const QUrl &localUrl)
{
    QUrl url(QLatin1String("http://posterous.com/api/2/auth/token"));
    QString login = PosterousSettings::login();
    QString pass = Choqok::PasswordManager::self()->readPassword(QStringLiteral("posterous_%1").arg(PosterousSettings::login()));
    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    job->addMetaData(QLatin1String("customHTTPHeader"),
                     QLatin1String("Authorization: Basic ") + QLatin1String(QStringLiteral("%1:%2").arg(login).arg(pass).toUtf8().toBase64()));
    job->exec();
    if (!job->error()) {
        const QByteArray data = job->data();
        const QJsonDocument json = QJsonDocument::fromJson(data);
        if (!json.isNull()) {
            QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("api_token"))) {
                QString tkn = map.value(QLatin1String("api_token")).toString();
                return tkn;
            } else {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
                qWarning() << "Parse error:" << data;
            }
        }
    } else {
        qCritical() << "Job error:" << job->errorString();
    }

    return QString();
}
Beispiel #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();
}
Beispiel #3
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();
}
Beispiel #4
0
void Resource::authenticate(const QString &name, const QString &password)
{
    QUrl url = baseUrl;
    url = url.adjusted(QUrl::StripTrailingSlash);
    url.setPath(url.path() + '/' + "/authorizations");
    QByteArray data = "{ \"scopes\": [\"repo\"], \"note\": \"KDevelop Github Provider\" }";
    KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo);
    job->addMetaData("customHTTPHeader", "Authorization: Basic " + QString (name + ':' + password).toUtf8().toBase64());
    connect(job, &KIO::StoredTransferJob::result, this, &Resource::slotAuthenticate);
    job->start();
}
void TwitterApiWhoisWidget::loadUserInfo(TwitterApiAccount* theAccount, const QString& username)
{
    kDebug();
    QString urlStr;
    QString user = username;
    if(user.contains('@')) {
        QStringList lst = user.split('@');
        if(lst.count() == 2){//USER@HOST
            QString host = lst[1];
            urlStr = QString("http://%1/api").arg(host);
            user = lst[0];
        }
    } else if( d->currentPost.source == "ostatus" && !d->currentPost.author.homePageUrl.isEmpty() ) {
        urlStr = d->currentPost.author.homePageUrl;
        if(urlStr.endsWith(user)) {
            int len = urlStr.length();
            int userLen = user.length();
            urlStr.remove(len - userLen, userLen);
            kDebug()<<urlStr;
        }
        urlStr.append("api");
    } else {
        urlStr = theAccount->apiUrl().url();
    }
    KUrl url( urlStr );

    url.addPath( QString( "/users/show/%1.json" ).arg(user));

//     kDebug() << url;

    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    if( d->currentPost.source != "ostatus" )
        job->addMetaData("customHTTPHeader", "Authorization: " + d->mBlog->authorizationHeader(theAccount,
                                                                                           url, QOAuth::GET));

    d->job = job;
    connect( job, SIGNAL(result(KJob*)), SLOT(userInfoReceived(KJob*)));
    job->start();
}
Beispiel #6
0
void Posterous::upload(const QUrl &localUrl, const QByteArray &medium, const QByteArray &mediumType)
{
    PosterousSettings::self()->load();
    KIO::StoredTransferJob *job = 0;
    if (PosterousSettings::basic()) {
        QString login = PosterousSettings::login();
        QString pass = Choqok::PasswordManager::self()->readPassword(QStringLiteral("posterous_%1").arg(PosterousSettings::login()));
        QString token = getAuthToken(localUrl);
        if (!token.isEmpty()) {
            QUrl url(QLatin1String("http://posterous.com/api/2/users/me/sites/primary/posts"));
            QMap<QString, QByteArray> formdata;
            formdata[QLatin1String("post[title]")] = QByteArray();
            formdata[QLatin1String("post[body]")] = QByteArray();
            formdata[QLatin1String("autopost")] = "0";
            formdata[QLatin1String("source")] = "Choqok";
            formdata[QLatin1String("api_token")] = token.toUtf8();

            QMap<QString, QByteArray> mediafile;
            mediafile[QLatin1String("name")] = "media";
            mediafile[QLatin1String("filename")] = localUrl.fileName().toUtf8();
            mediafile[QLatin1String("mediumType")] = mediumType;
            mediafile[QLatin1String("medium")] = medium;
            QList< QMap<QString, QByteArray> > listMediafiles;
            listMediafiles.append(mediafile);

            QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);
            job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo);
            job->addMetaData(QLatin1String("customHTTPHeader"),
                             QLatin1String("Authorization: Basic ") +
                             QLatin1String(QStringLiteral("%1:%2").arg(login).arg(pass).toUtf8().toBase64()));
        }
    } else if (PosterousSettings::oauth()) {
        QString alias = PosterousSettings::alias();
        if (alias.isEmpty()) {
            qCritical() << "No account to use";
            Q_EMIT uploadingFailed(localUrl, i18n("There is no Twitter account configured to use."));
            return;
        }
        TwitterApiAccount *acc = qobject_cast<TwitterApiAccount *> (Choqok::AccountManager::self()->findAccount(alias));
        if (!acc) {
            return;
        }

        QUrl url(QLatin1String("http://posterous.com/api2/upload.json"));

        QMap<QString, QByteArray> formdata;
        formdata[QLatin1String("source")] = "Choqok";
        formdata[QLatin1String("sourceLink")] = "http://choqok.gnufolks.org/";

        QMap<QString, QByteArray> mediafile;
        mediafile[QLatin1String("name")] = "media";
        mediafile[QLatin1String("filename")] = localUrl.fileName().toUtf8();
        mediafile[QLatin1String("mediumType")] = mediumType;
        mediafile[QLatin1String("medium")] = medium;
        QList< QMap<QString, QByteArray> > listMediafiles;
        listMediafiles.append(mediafile);

        QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);

        KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ;
        QOAuth::ParamMap params;
        QString requrl = QLatin1String("https://api.twitter.com/1/account/verify_credentials.json");
        QByteArray credentials = acc->oauthInterface()->createParametersString(requrl,
                                 QOAuth::GET, acc->oauthToken(),
                                 acc->oauthTokenSecret(),
                                 QOAuth::HMAC_SHA1,
                                 params, QOAuth::ParseForHeaderArguments);

        QString cHeader = QLatin1String("X-Verify-Credentials-Authorization: ") +  QLatin1String(credentials) + QLatin1String("\r\n");
        cHeader.append(QLatin1String("X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.json"));
        job->addMetaData(QLatin1String("customHTTPHeader"), cHeader);
    }
    if (!job) {
        qCritical() << "Cannot create a http POST request!";
        return;
    }
    job->addMetaData(QStringLiteral("content-type"),
                     QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x"));
    mUrlMap[job] = localUrl;
    connect(job, SIGNAL(result(KJob*)),
            SLOT(slotUpload(KJob*)));
    job->start();
}
Beispiel #7
0
void TwitterMicroBlog::createPostWithAttachment(Choqok::Account *theAccount, Choqok::Post *post,
        const QString &mediumToAttach)
{
    if (mediumToAttach.isEmpty()) {
        TwitterApiMicroBlog::createPost(theAccount, post);
    } else {
        const QUrl picUrl = QUrl::fromUserInput(mediumToAttach);
        KIO::StoredTransferJob *picJob = KIO::storedGet(picUrl, KIO::Reload, KIO::HideProgressInfo);
        picJob->exec();
        if (picJob->error()) {
            qCCritical(CHOQOK) << "Job error:" << picJob->errorString();
            KMessageBox::detailedError(Choqok::UI::Global::mainWindow(),
                                       i18n("Uploading medium failed: cannot read the medium file."),
                                       picJob->errorString());
            return;
        }
        const QByteArray picData = picJob->data();
        if (picData.count() == 0) {
            qCCritical(CHOQOK) << "Cannot read the media file, please check if it exists.";
            KMessageBox::error(Choqok::UI::Global::mainWindow(),
                               i18n("Uploading medium failed: cannot read the medium file."));
            return;
        }

        TwitterAccount *account = qobject_cast<TwitterAccount *>(theAccount);
        QUrl url = account->uploadUrl();
        url.setPath(url.path() + QStringLiteral("/statuses/update_with_media.%1").arg(format));
        const QMimeDatabase db;
        QByteArray fileContentType = db.mimeTypeForUrl(picUrl).name().toUtf8();

        QMap<QString, QByteArray> formdata;
        formdata[QLatin1String("status")] = post->content.toUtf8();
        if (!post->replyToPostId.isEmpty()) {
            formdata[QLatin1String("in_reply_to_status_id")] = post->replyToPostId.toLatin1();
        }
        formdata[QLatin1String("source")] = QCoreApplication::applicationName().toLatin1();

        QMap<QString, QByteArray> mediafile;
        mediafile[QLatin1String("name")] = "media[]";
        mediafile[QLatin1String("filename")] = picUrl.fileName().toUtf8();
        mediafile[QLatin1String("mediumType")] = fileContentType;
        mediafile[QLatin1String("medium")] = picData;
        QList< QMap<QString, QByteArray> > listMediafiles;
        listMediafiles.append(mediafile);

        QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);

        KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ;
        if (!job) {
            qCCritical(CHOQOK) << "Cannot create a http POST request!";
            return;
        }
        job->addMetaData(QStringLiteral("content-type"),
                         QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x"));
        job->addMetaData(QStringLiteral("customHTTPHeader"),
                         QStringLiteral("Authorization: ") +
                         QLatin1String(authorizationHeader(account, url, QOAuth::POST)));
        mCreatePostMap[ job ] = post;
        mJobsAccount[job] = theAccount;
        connect(job, SIGNAL(result(KJob*)),
                SLOT(slotCreatePost(KJob*)));
        job->start();
    }
}