void WebContentsAdapter::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl)
{
    Q_D(WebContentsAdapter);
    QByteArray encodedData = data.toPercentEncoding();
    std::string urlString("data:");
    urlString.append(mimeType.toStdString());
    urlString.append(",");
    urlString.append(encodedData.constData(), encodedData.length());

    GURL dataUrlToLoad(urlString);
    if (dataUrlToLoad.spec().size() > content::GetMaxURLChars()) {
        d->adapterClient->loadFinished(false, baseUrl, false, net::ERR_ABORTED);
        return;
    }
    content::NavigationController::LoadURLParams params((dataUrlToLoad));
    params.load_type = content::NavigationController::LOAD_TYPE_DATA;
    params.base_url_for_data_url = toGurl(baseUrl);
    params.virtual_url_for_data_url = baseUrl.isEmpty() ? GURL(url::kAboutBlankURL) : toGurl(baseUrl);
    params.can_load_local_resources = true;
    params.transition_type = ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_API);
    params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
    d->webContents->GetController().LoadURLWithParams(params);
    d->webContents->Focus();
    d->webContents->Unselect();
}
Esempio n. 2
0
QByteArray OAuthParameters::toSignatureBase()
{
	QByteArray result;
	result += "oauth_consumer_key=";
	result += Consumer.consumerKey();
	result += '&';
	result += "oauth_nonce=";
	result += Nonce;
	result += '&';
	result +="oauth_signature_method=";
	result += SignatureMethod;
	result += '&';
	result += "oauth_timestamp=";
	result += Timestamp;
	result += '&';

	if (!Token.token().isEmpty())
	{
		result += "oauth_token=";
		result += Token.token();
		result += '&';
	}

	result += "oauth_version=";
	result += Version;

	return result.toPercentEncoding();
}
bool reportDataThread::validateUser(){
    this->setUpConnection();
    QByteArray* array = new QByteArray();
    array->append(this->userID);
    QString* encoded = new QString(array->toPercentEncoding());
    QString POST;
    POST = "POST /~dswhite21/capstone/submitResults.php HTTP/1.1\n";
    POST += "Host: users.csc.tntech.edu\n";
    POST += "Connection: keep-alive\n";
    POST += "Content-Length: " + QString::number(encoded->length() + 5) + "\n";
    POST += "Cache-Control: max-age=0\n";
    POST += "Origin: http://users.csc.tntech.edu\n";
    POST += "Content-Type: application/x-www-form-urlencoded\n";
    POST += "Accept: text/html\n";
    POST += "Accept-Encoding: None\n\n";
    POST += "user="******"ERROR: Server is not Writable";}
    }
    this->server->write(POST.toAscii().data());
    this->server->waitForBytesWritten(50000);
    if(!this->server->waitForReadyRead(50000)){
        if(DEBUG){qWarning() << "ERROR: Server not responding";}
    }
    QString result = this->server->readAll();
    if(!result.endsWith("\nvalid user")){
        return true;
    }
    return false;
}
Esempio n. 4
0
void UrlEncode::transform(const QByteArray &input, QByteArray &output) {
    if (wayValue == INBOUND){
        output = input.toPercentEncoding(exclude, include,percentSign);
    }
    else {
        output = QByteArray::fromPercentEncoding(input);
    }
}
QByteArray TwitterDataUtil::authorizationHeader(const QByteArray &oauthConsumerKey,
                                                const QByteArray &oauthConsumerSecret,
                                                const QByteArray &requestMethod,
                                                const QByteArray &requestUrl,
                                                const std::vector<std::pair<QByteArray, QByteArray>> &parameters,
                                                const QByteArray &oauthToken,
                                                const QByteArray &oauthTokenSecret,
                                                const QByteArray &oauthNonce,
                                                const QByteArray &oauthTimestamp)
{
    // Twitter requires all requests to be signed with an authorization header.
    QByteArray nonce {oauthNonce};
    if (nonce.isEmpty()) {
        nonce = QUuid::createUuid().toByteArray().toBase64();
    }
    QByteArray timestamp {oauthTimestamp};
    if (timestamp.isEmpty()) {
        timestamp = QByteArray::number(qFloor(QDateTime::currentMSecsSinceEpoch() / 1000.0));
    }

    // now build up the encoded parameters map.  We use a map to perform alphabetical sorting.
    QMap<QByteArray, QByteArray> encodedParams {};
    encodedParams.insert(QByteArray("oauth_consumer_key").toPercentEncoding(), QByteArray(oauthConsumerKey).toPercentEncoding());
    encodedParams.insert(QByteArray("oauth_nonce").toPercentEncoding(), nonce.toPercentEncoding());
    encodedParams.insert(QByteArray("oauth_signature_method").toPercentEncoding(), QByteArray(OAUTH_SIGNATURE_METHOD).toPercentEncoding());
    encodedParams.insert(QByteArray("oauth_timestamp").toPercentEncoding(), timestamp.toPercentEncoding());
    encodedParams.insert(QByteArray("oauth_version").toPercentEncoding(), QByteArray(OAUTH_VERSION).toPercentEncoding());
    if (!oauthToken.isEmpty()) {
        encodedParams.insert(QByteArray("oauth_token").toPercentEncoding(), oauthToken.toPercentEncoding());
    }
    for (const std::pair<QByteArray, QByteArray> &parameter : parameters) {
        encodedParams.insert(parameter.first, parameter.second);
    }

    QByteArray parametersByteArray {};
    QList<QByteArray> keys = encodedParams.keys();
    for (const QByteArray &key : keys) {
        parametersByteArray += key + QByteArray("=") + encodedParams.value(key) + QByteArray("&");
    }
    parametersByteArray.chop(1);

    QByteArray signatureBaseString {requestMethod.toUpper() + QByteArray("&") + requestUrl.toPercentEncoding() + QByteArray("&") + parametersByteArray.toPercentEncoding()};
    QByteArray signingKey {oauthConsumerSecret.toPercentEncoding() + QByteArray("&") + oauthTokenSecret.toPercentEncoding()};

    QByteArray oauthSignature {QMessageAuthenticationCode::hash(signatureBaseString, signingKey, QCryptographicHash::Sha1).toBase64()};
    encodedParams.insert(QByteArray("oauth_signature").toPercentEncoding(), oauthSignature.toPercentEncoding());

    // now generate the Authorization header from the encoded parameters map.
    // we need to remove the query items from the encoded parameters map first.
    QByteArray authHeader = QByteArray("OAuth ");

    for (const std::pair<QByteArray, QByteArray> &parameter : parameters) {
        encodedParams.remove(parameter.first);
    }
    keys = encodedParams.keys();
    foreach (const QByteArray &key, keys) {
        authHeader += key + "=\"" + encodedParams.value(key) + "\", ";
    } 
Esempio n. 6
0
QString MyMemory::translate(const QString &src_text, const QString &src_lang, const QString &dest_lang) {
    QByteArray html = src_text.toUtf8();

    html.replace("&", "&amp;");
    html.replace("<", "&lt;");
    html.replace(">", "&gt;");
    html.replace("\n", "<br>");

    QString query = "v=1.0&format=html";
    query += "&langpair=" + src_lang.toLatin1() + "%7C" + dest_lang.toLatin1();
    query += "&q=" + html.toPercentEncoding();

    QUrl url("http://mymemory.translated.net/api/get");

    const QString  rawdata = HTTP::POST(url, query);

    QJsonObject obj = QJsonDocument::fromJson(rawdata.toUtf8()).object();
    QString res = obj.value("responseData").toObject().value("translatedText").toString();

    return QTextDocumentFragment::fromHtml(res).toPlainText();
}
Esempio n. 7
0
	/* TODO: need to add support for arguments here */
	QString
	Medialib::encodeUrl (const QString &src, const QStringList &args)
	{
		QString ret;
#if QT_VERSION >= 0x040400
		QByteArray data = src.toUtf8 (); // this might have to be toLatin1()
		QByteArray enc = data.toPercentEncoding (excludeEnc, includeEnc);
		enc.replace (' ', '+');

		ret = QString (enc);
#else
		static const char hex[17] = "0123456789abcdef";

		for (int i = 0; i < src.size (); i ++)
		{
			char chr = src.at (i).toLatin1 ();
			if (GOODCHAR (chr)) {
				ret += chr;
			} else if (chr == ' ') {
				ret += '+';
			} else {
				ret += '%';
				ret += hex[((chr & 0xf0) >> 4)];
				ret += hex[(chr & 0x0f)];
			}
		}
#endif
		if (args.size () > 0) {
			for (int i = 0; i < args.size (); i++) {
				ret.append ( (i == 0) ? '?' : '&');
				// Perhaps I should check for '?' and '&' here.
				// But the c bindings don't so I left it out
				ret.append (args[i]);
			}
		}

		return ret;
	}
Esempio n. 8
0
QUrl Oauth::createOAuthUrl( const QUrl url, const QString oAuthConsumerKey, const QString sharedSecret, const QString verb , const QString tokenSecret )
{
    const QString current  = QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
    const QString nonce    = Nonce();

    QList<QPair<QString, QString> > inputParams = url.queryItems();
    inputParams.append(QPair<QString,QString>(QString::fromLatin1(OAUTH_CONSUMER_KEY),oAuthConsumerKey));
    inputParams.append(QPair<QString,QString>(QString::fromLatin1(OAUTH_SIGNATURE_METHOD),NETFLIX_SIGNATURE_METHOD));
    inputParams.append(QPair<QString,QString>(QString::fromLatin1(OAUTH_TIMESTAMP),current));
    inputParams.append(QPair<QString,QString>(QString::fromLatin1(OAUTH_NONCE),nonce));
    inputParams.append(QPair<QString,QString>(QString::fromLatin1(OAUTH_VERSION),NETFLIX_OAUTH_VERSION));

    qSort(inputParams.begin(),inputParams.end(),comparer);

    qDebug() << inputParams;

    QByteArray host = url.toEncoded(QUrl::RemoveQuery);

    QUrl returnUrl;
    returnUrl.setEncodedUrl(host);
    const int length = inputParams.size();
    for( int i=0; i<length ; i++)
    {
        returnUrl.addQueryItem(inputParams.at(i).first,inputParams.at(i).second);
    }

    QString oAuthParams = returnUrl.encodedQuery();
    QString requestString = QString("%1&%2&%3").arg(verb, host.toPercentEncoding(), Escape(oAuthParams));

    qDebug() << requestString;

    QByteArray signature = HmacSha1(sharedSecret,requestString, tokenSecret);
    qDebug() << signature;
    returnUrl.addEncodedQueryItem(OAUTH_SIGNATURE,signature);
    return returnUrl;
}
Esempio n. 9
0
/**
 *   Generates OAuth signature base
 *   @param url Url with encoded parameters
 *   @param method Http method
 *   @param timestamp timestamp
 *   @param nonce random string
 *   @return signature base
 */
QByteArray OAuth::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce)
{
    //OAuth spec. 9.1 https://oauth.net/core/1.0/#anchor14

    //OAuth spec. 9.1.1
    QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
    QList<QByteArray> normParameters;

    QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
    while(i.hasNext()){
            QPair<QByteArray, QByteArray> queryItem = i.next();
            QByteArray normItem = queryItem.first + '=' + queryItem.second;
            normParameters.append(normItem);
    }

    //consumer key
    normParameters.append(QByteArray("oauth_consumer_key=") + m_oauthConsumerKey);

    //token
    if(!m_oauthToken.isEmpty()){
            normParameters.append(QByteArray("oauth_token=") + m_oauthToken);
    }

    //signature method, only HMAC_SHA1
    normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
    //time stamp
    normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
    //nonce
    normParameters.append(QByteArray("oauth_nonce=") + nonce);
    //version
    normParameters.append(QByteArray("oauth_version=1.0"));

    //OAuth spec. 9.1.1.1
    qSort(normParameters);

    //OAuth spec. 9.1.1.2
    //QByteArray normString;
    //QListIterator<QByteArray> j(normParameters);
    //while(j.hasNext()){
    //	normString += j.next();
    //	normString += '&';
    //}
    //normString.chop(1);

    QByteArray normString;
    QListIterator<QByteArray> j(normParameters);
    while (j.hasNext()) {
        normString += j.next().toPercentEncoding();
        normString += "%26";
    }
    normString.chop(3);

    //OAuth spec. 9.1.2
    QString urlScheme = url.scheme();
    QString urlPath = url.path();
    QString urlHost = url.host();
    QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();

    QByteArray httpm;

    switch (method)
    {
        case OAuth::GET:
                httpm = "GET";
                break;
        case OAuth::POST:
                httpm = "POST";
                break;
        case OAuth::DELETE:
                httpm = "DELETE";
                break;
        case OAuth::PUT:
                httpm = "PUT";
                break;
    }

    //OAuth spec. 9.1.3
    return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
Esempio n. 10
0
static QByteArray urlencode(const QByteArray& data)
{
	return data.toPercentEncoding();
}
Esempio n. 11
0
QString Oauth::Escape(QString data)
{
    QByteArray x = data.toUtf8();
    return x.toPercentEncoding();
}
Esempio n. 12
0
QImage ImageProviderThumbnail::getThumbnailImage(QByteArray filename) {

    QString typeCache = (settings->thumbnailCacheFile ? "files" : "db");
    bool cacheEnabled = settings->thumbnailCache;

    if(settings->thumbnailCache && !settings->thumbnailCacheFile)
        setupDbWhenNotYetDone();

    // Create the md5 hash for the thumbnail file
    QByteArray path = "file://" + filename;
    QByteArray md5 = QCryptographicHash::hash(path,QCryptographicHash::Md5).toHex();

    // Prepare the return QImage
    QImage p;

    // We always opt for the 256px resolution for the thumbnails,
    // as then we don't have to re-create thumbnails depending on change in settings
    int ts = 256;

    // If files in XDG_CACHE_HOME/thumbnails/ shall be used, then do use them
    if(typeCache == "files" && cacheEnabled) {

        // If there exists a thumbnail of the current file already
        if(QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").exists()) {

            if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Found cached thumbnail (file cache): " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

            p.load(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png");
            uint mtime = p.text("Thumb::MTime").trimmed().toInt();

            // Use image if it's up-to-date
            if(QFileInfo(filename).lastModified().toTime_t() == mtime)
                return p;
            else if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Image was modified since thumbnail creation, not using cached thumbnail: " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

        }

    // otherwise use the database
    } else if(cacheEnabled) {

        needToReCreatedDbThumbnail = false;

        // Query database
        QSqlQuery query(db);
        query.prepare("SELECT thumbnail,filelastmod FROM Thumbnails WHERE filepath=:fpath");
        query.bindValue(":fpath",filename);
        query.exec();

        // Check for found value
        if(query.next()) {

            if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Found cached thumbnail (db cache): " << QFileInfo(filename).fileName().toStdString() << NL;

            // Check if updated
            if(query.value(query.record().indexOf("filelastmod")).toUInt() == QFileInfo(filename).lastModified().toTime_t()) {

                // If current thumbnail -> load it
                QByteArray b;
                b = query.value(query.record().indexOf("thumbnail")).toByteArray();
                p.loadFromData(b);

                // Cleaning up
                query.clear();

                // Return image
                return p;

            // The original image has been changed -> need to recreate thumbnail image
            } else {
                if(qgetenv("PHOTOQT_DEBUG") == "yes")
                    LOG << CURDATE << "ImageProviderThumbnail: Image was modified since thumbnail creation, not using cached thumbnail: " <<
                           QFileInfo(filename).fileName().toStdString() << NL;
                needToReCreatedDbThumbnail = true;
            }


        }

        // Cleaning up
        query.clear();

    }

    // If file wasn't loaded from file or database, then it doesn't exist yet (or isn't up-to-date anymore) and we have to create it

    // We create a temporary pointer, so that we can delete it properly afterwards
    QSize *tmp = new QSize(ts,ts);
    p = imageproviderfull->requestImage(filename.toPercentEncoding(),tmp,QSize(ts,ts));
    delete tmp;

    // Only if the image itself is smaller than the requested thumbnail size are both dimensions less than (strictly) than ts -> no caching
    if((p.width() < ts && p.height() < ts) || p.text("error") == "error") {
        if(qgetenv("PHOTOQT_DEBUG") == "yes")
            LOG << CURDATE << "ImageProviderThumbnail: Image is smaller than potential thumbnail, no need to cache: " <<
                   QFileInfo(filename).fileName().toStdString() << NL;
        return p;
    }

    // Create file cache thumbnail
    if(typeCache == "files" && cacheEnabled) {

        // If the file itself wasn't read from the thumbnails folder, is not a temporary file, and if the original file isn't at thumbnail size itself
        if(!filename.startsWith(QString(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails").toUtf8())
                && !filename.startsWith(QDir::tempPath().toUtf8())) {

            // Set some required (and additional) meta information
            p.setText("Thumb::URI", QString("file://%1").arg(QString(filename)));
            p.setText("Thumb::MTime", QString("%1").arg(QFileInfo(filename).lastModified().toTime_t()));
            QString mime = mimedb.mimeTypeForFile(filename, QMimeDatabase::MatchContent).name();
            // this is the default mime type if no mime type is available or file cannot be found
            if(mime != "application/octet-stream")
                p.setText("Thumb::Mimetype", mime);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
            p.setText("Thumb::Size", QString("%1").arg(p.sizeInBytes()));
#else
            QFileInfo info(filename);
            p.setText("Thumb::Size", QString("%1").arg(info.size()));
#endif

            // If the file does already exist, then the image has likely been updated -> delete old thumbnail image
            if(QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").exists())
                QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").remove();

            // And save new thumbnail image
            if(!p.save(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png"))
                LOG << CURDATE << "ImageProviderThumbnail: ERROR creating new thumbnail file: " <<
                       QFileInfo(filename).fileName().toStdString() << NL;
            else if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Successfully cached thumbnail (file cache): " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

        }

    // if not file caching -> db caching
    } else if(cacheEnabled) {

        // make sure transaction is started
        if(!dbTransactionStarted) {
            if(!db.transaction())
                LOG << CURDATE << "ImageProviderThumbnail: ERROR: Cannot start db transaction" << NL;
            dbTransactionStarted = true;
        }

        QSqlQuery query2(db);

        // convert image to bytearray
        QByteArray b;
        QBuffer buf(&b);
        buf.open(QIODevice::WriteOnly);

        // Always use png format
        p.save(&buf,"PNG");

        // If it was once created, i.e. if the file changed (i.e. if last mod date changed), then we have to update it
        if(needToReCreatedDbThumbnail)
            query2.prepare("UPDATE Thumbnails SET filepath=:path,thumbnail=:thb,filelastmod=:mod,thumbcreated=:crt WHERE filepath=:path");
        else
            query2.prepare("INSERT INTO Thumbnails(filepath,thumbnail,filelastmod,thumbcreated) VALUES(:path,:thb,:mod,:crt)");

        // bind the thumbnail properties
        query2.bindValue(":path",filename);
        query2.bindValue(":thb",b);
        query2.bindValue(":mod",QFileInfo(filename).lastModified().toTime_t());
        query2.bindValue(":crt",QDateTime::currentMSecsSinceEpoch());
        query2.exec();

        if(query2.lastError().text().trimmed().length())
            LOG << CURDATE << "ImageProviderThumbnail: ERROR [" << QString(filename).toStdString() << "]: " <<
                   query2.lastError().text().trimmed().toStdString() << NL;
        else if(qgetenv("PHOTOQT_DEBUG") == "yes")
            LOG << CURDATE << "ImageProviderThumbnail: Successfully cached thumbnail (db cache): " <<
                   QFileInfo(filename).fileName().toStdString() << NL;

        // cleaning up
        query2.clear();

    }

    // aaaaand done!
    return p;

}
Esempio n. 13
0
QString Encoding::percentEncode(const QByteArray & data)
{
    return data.toPercentEncoding();
}
Esempio n. 14
0
bool Method::execute() {

    if (!prepare())
        return false;

    if (!validate())
        return false;


    // THese are always constant with API requests
    if (getMethodName().startsWith("fql.query",Qt::CaseInsensitive))
        m_argMap.insert("method","fql.query");
    else if (getMethodName().startsWith("fql.multiquery",Qt::CaseInsensitive))
        m_argMap.insert("method","fql.multiquery");
    else
        m_argMap.insert("method", getMethodName());

    m_argMap.insert("api_key", m_userInfo->getApiKey());
    m_argMap.insert("v","1.0");
    m_argMap.insert("session_key",m_userInfo->getSessionKey());

    // This is going to have to be changed to something with greater than
    // second resolution (miliseconds or microseconds). Is there anything portable across
    // Mac/Win/Linux? Doubtful, have to build compile options for it.
    time_t tm = time(0);
    //char callId[30];
    //sprintf(callId, "%lld", tm);
    m_argMap.insert("call_id",(qlonglong)tm);


    // pull all the key/value pairs from the QMap and do the magic Facebook requires to
    // make an API call

    /********** From the Facebook API docs ****************************************
    The signature can be generated by calling generate_sig in facebook.php.
    generate_sig takes two parameters: an array of arg=val pairs and your app secret.
    The signature can also be constructed using the following algorithm
    (after all the other arguments have been determined):

    args = array of args to the request, not counting sig, formatted in non-urlencoded arg=val pairs
    sorted_array = alphabetically_sort_array_by_keys(args);
    request_str = concatenate_in_order(sorted_array);
    signature = md5(concatenate(request_str, secret))
    ***********************************************************************************/

    // In a way, this is really retarded. Facebook wants an MD5 hash of the args with no
    // serparators. You also need a set of args with '&' separated url encoded
    // key/value pairs for the actual post

    QByteArray sigByteArray;
    QByteArray postArgs;

    // QMap is automatically sorted by keys
    QMapIterator<QString, QVariant> i(m_argMap);
    while (i.hasNext()) {
         i.next();
         sigByteArray.append(i.key() + "=" + i.value().toString() );
         postArgs.append(i.key() + "=" + i.value().toString() + "&");
    }

    sigByteArray.append(m_userInfo->getSecret());

    QByteArray sig = QCryptographicHash::hash(sigByteArray,QCryptographicHash::Md5 );

    postArgs.append("sig=");
    postArgs.append(sig.toHex());

    QByteArray exclude("&=");
    QByteArray include;
    postArgs = postArgs.toPercentEncoding(exclude,include,'%');

    // qDebug() << postArgs;

    QUrl url("http://api.facebook.com/restserver.php");

    QNetworkRequest nr;
    nr.setUrl(url);
    nr.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    m_reply = m_manager->post(nr,postArgs);

    if (m_reply != 0) {
        connect(m_manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(gotReply(QNetworkReply*)));
        return true;
    }
Esempio n. 15
0
void twit_func::post(QString tweet){
    QSettings settings("tea_soak_lab", "cli_tweet");
    consumer_key = settings.value("consumer_key").toString();
    consumer_secret = settings.value("consumer_secret").toString();
    oauth_token = settings.value("oauth_token").toString();
    oauth_token_secret = settings.value("oauth_token_secret").toString();

    QString update_url = "https://api.twitter.com/1.1/statuses/update.json";

    qsrand(QDateTime::currentDateTime().toTime_t());
    QString nonce = QString::number(qrand());

    QMap<QString,QString> params;
    params["oauth_consumer_key"] = consumer_key;
    params["oauth_nonce"] = nonce;
    params["oauth_signature_method"] = "HMAC-SHA1";
    params["oauth_timestamp"] = QString::number(time(NULL));
    params["oauth_token"] = oauth_token;
    params["oauth_version"] = "1.0";
    params["status"] = QString::fromUtf8(tweet.toUtf8().toPercentEncoding());

    QString params_str;

    QMapIterator<QString,QString> i(params);
    while(i.hasNext()){
        i.next();
        params_str += QString("%1=%2&").arg(i.key()).arg(i.value());
    }
    params_str.resize(params_str.size() -1);

    QByteArray message = "POST&" + update_url.toUtf8().toPercentEncoding() + "&" + params_str.toUtf8().toPercentEncoding();

    QByteArray key = consumer_secret.toUtf8() + "&" + oauth_token_secret.toUtf8();

    unsigned char res[SHA_DIGEST_LENGTH + 1];
    unsigned int reslen;
    HMAC(EVP_sha1(), (unsigned char*)key.data(), key.length(), (unsigned char*)message.data(), message.length(), res, &reslen);
    std::string result;
    result = (char*)res;
    result.erase(reslen);

    QByteArray signature = QByteArray::fromRawData(result.c_str(), result.length()).toBase64();

    params.remove("status");
    params["oauth_signature"] = QString::fromUtf8(signature.toPercentEncoding());

    QString header_params_str = "";
    QMapIterator<QString,QString> i2(params);
    while(i2.hasNext()){
        i2.next();
        header_params_str += i2.key() + "=" + i2.value() + ",";
    }
    header_params_str.resize(header_params_str.size() -1);

QEventLoop eventLoop;

    QNetworkAccessManager *manager = new QNetworkAccessManager();

QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    //QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    QUrl url(update_url);
    QNetworkRequest r(url);

    r.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    r.setRawHeader(QObject::tr("Authorization").toUtf8(), (QObject::tr("OAuth ") + header_params_str).toUtf8());

    QNetworkReply *reply = manager->post(r, QObject::tr("status=").toUtf8() + tweet.toUtf8().toPercentEncoding());

    eventLoop.exec();

    QString reply_data = reply->readAll();
    QJsonDocument json = QJsonDocument::fromJson(reply_data.toUtf8());
    if(json.object().value("errors").toArray().at(0).toObject().value("code").toInt() != 0){
        settings.setValue("error_code",json.object().value("errors").toArray().at(0).toObject().value("code").toInt());
        settings.setValue("error_mess",json.object().value("errors").toArray().at(0).toObject().value("message").toString());
    } else {
        settings.setValue("error_code",0);
        settings.setValue("error_mess","none");
    }
}