Exemple #1
0
VRequest::VRequest(const QUrl& url): QNetworkRequest(url)
{
    setRawHeader("User-Agent", "qutIM plugin VKontakte");
    setRawHeader("Accept-Charset", "utf-8");
    setRawHeader("Pragma", "no-cache");
    setRawHeader("Cache-control", "no-cache");
}
HabitRPGUserRequest::HabitRPGUserRequest(QString userID, QString apiToken, QString server) :
  QNetworkRequest(QUrl(server))
{
  //Sets the headers for the request
  setRawHeader("x-api-user",userID.toUtf8());
  setRawHeader("x-api-key",apiToken.toUtf8());
}
DownloadManager::DownloadManager(QNetworkAccessManager *manager, const YoutubeInterface *yti)
{
	this->manager = manager;
	this->yti = yti;

	setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0");
	setRawHeader("Accept-Charset", "utf-8");
	setRawHeader("Accept-Language", "en-US");
}
Exemple #4
0
Request::Request(const QUrl & url)
    :QNetworkRequest(url)
{

    setRawHeader("Content-Type","application/json;charset=UTF-8");
    mName ="No name";
}
void QNetworkAccessHttpBackend::replyHeaderChanged()
{
    // reconstruct the HTTP header
    QList<QPair<QByteArray, QByteArray> > headerMap = httpReply->header();
    QList<QPair<QByteArray, QByteArray> >::ConstIterator it = headerMap.constBegin(),
                                                        end = headerMap.constEnd();
    QByteArray header;

    for (; it != end; ++it) {
        QByteArray value = rawHeader(it->first);
        if (!value.isEmpty())
            value += ", ";
        value += it->second;
        setRawHeader(it->first, value);
    }

    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, httpReply->statusCode());
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, httpReply->reasonPhrase());

    // is it a redirection?
    switch (httpReply->statusCode()) {
    case 301:                   // Moved Permanently
    case 302:                   // Found
    case 303:                   // See Other
    case 307:                   // Temporary Redirect
        // What do we do about the caching of the HTML note?
        // The response to a 303 MUST NOT be cached, while the response to
        // all of the others is cacheable if the headers indicate it to be
        redirectionRequested(QUrl::fromEncoded(rawHeader("location")));
    }

    metaDataChanged();
}
Exemple #6
0
void Parse::deleteUser( QString objectId)
{
    if (!isReady() || sessionId.isEmpty()) return;

    setEndPoint("users/" + objectId );

    initHeaders();
    setRawHeader("X-Parse-Session-Token", sessionId.toUtf8());
    request( BaaS::DELETE);
}
Exemple #7
0
void AppReply::parseResponse()
{
    content = call_app(method, url, body);
    offset = 0;

    open(ReadOnly | Unbuffered);

    // default attribute
    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200);
    setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html; charset=UTF-8"));

    // TODO speed optimization needed
    int index;
    bool ok;
    int code;
    QByteArray line, key, value;
    QList<QByteArray> words;
    if ((index = content.indexOf("\r\n")) < 0) {
        goto finish;
    }
    line = content.left(index);
    words = line.split(' ');
    if (words.size() < 3) {
        goto finish;
    }
    code = words[1].toInt(&ok);
    if (!ok) {
        goto finish;
    }
    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, code);
    offset = index + 2;

    // iterate over lines of header
    for(; (index = content.indexOf("\r\n", offset)) > offset; offset=index+2) {
        line = content.mid(offset, index-offset);
        int pos = line.indexOf(':');
        if (pos <= 0) {
            continue;
        }
        key = line.left(pos);
        value = line.mid(pos+1).trimmed();
        setRawHeader(key, value);
    }

    if (index == offset) {
        // the CRLF seperate headers and body
        offset += 2;
    }

finish:
//        qDebug() << "body:" << content.mid(offset);
    emit readyRead();
    emit finished();
}
void SpecialConfigRequest::performDnsRequest() {
	auto dnsUrl = QUrl();
	dnsUrl.setScheme(qsl("https"));
	dnsUrl.setHost(qsl("google.com"));
	dnsUrl.setPath(qsl("/resolve"));
	dnsUrl.setQuery(qsl("name=%1.stel.com&type=16").arg(cTestMode() ? qsl("tap") : qsl("ap")));
	auto dnsRequest = QNetworkRequest(QUrl(dnsUrl));
	dnsRequest.setRawHeader("Host", "dns.google.com");
	_dnsReply.reset(_manager.get(dnsRequest));
	connect(_dnsReply.get(), &QNetworkReply::finished, this, [this] { dnsFinished(); });
}
Exemple #9
0
void QNetworkAccessDebugPipeBackend::socketReadyRead()
{
    if (bareProtocol) {
        qint64 bytesToRead = socket.bytesAvailable();
        if (bytesToRead) {
            QByteArray buffer;
            buffer.resize(bytesToRead);
            qint64 bytesRead = socket.read(buffer.data(), bytesToRead);
            if (bytesRead < bytesToRead)
                buffer.truncate(bytesRead);
            writeDownstreamData(buffer);
            readyReadEmitted = true;
        }
        return;
    }

    while (canReceive() &&
            (socket.state() == QAbstractSocket::UnconnectedState || nextDownstreamBlockSize())) {
        DataPacket packet;
        if (receive(packet)) {
            if (!packet.headers.isEmpty()) {
                QList<QPair<QByteArray, QByteArray> >::ConstIterator
                it = packet.headers.constBegin(),
                end = packet.headers.constEnd();
                for ( ; it != end; ++it)
                    setRawHeader(it->first, it->second);
                metaDataChanged();
            }

            if (!packet.data.isEmpty()) {
                writeDownstreamData(packet.data);
                readyReadEmitted = true;
            }

            if (packet.headers.isEmpty() && packet.data.isEmpty()) {
                // it's an eof
                socket.close();
                readyReadEmitted = true;
            }
        } else {
            // got an error
            QString msg = QObject::tr("Read error reading from %1: %2")
                          .arg(url().toString(), socket.errorString());
            error(QNetworkReply::ProtocolFailure, msg);

            finished();
            return;
        }
    }
}
bool QNetworkAccessCacheBackend::sendCacheContents()
{
    setCachingEnabled(false);
    QAbstractNetworkCache *nc = networkCache();
    if (!nc)
        return false;

    QNetworkCacheMetaData item = nc->metaData(url());
    if (!item.isValid())
        return false;

    QNetworkCacheMetaData::AttributesMap attributes = item.attributes();
    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, attributes.value(QNetworkRequest::HttpStatusCodeAttribute));
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));

    // set the raw headers
    QNetworkCacheMetaData::RawHeaderList rawHeaders = item.rawHeaders();
    QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
                                                       end = rawHeaders.constEnd();
    for ( ; it != end; ++it) {
        if (it->first.toLower() == "cache-control" &&
            it->second.toLower().contains("must-revalidate")) {
            return false;
        }
        setRawHeader(it->first, it->second);
    }

    // handle a possible redirect
    QVariant redirectionTarget = attributes.value(QNetworkRequest::RedirectionTargetAttribute);
    if (redirectionTarget.isValid()) {
        setAttribute(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
        redirectionRequested(redirectionTarget.toUrl());
    }

    // signal we're open
    metaDataChanged();

    if (operation() == QNetworkAccessManager::GetOperation) {
        QIODevice *contents = nc->data(url());
        if (!contents)
            return false;
        contents->setParent(this);
        writeDownstreamData(contents);
    }

#if defined(QNETWORKACCESSCACHEBACKEND_DEBUG)
    qDebug() << "Successfully sent cache:" << url();
#endif
    return true;
}
Exemple #11
0
HttpInfo::HttpInfo(const QByteArray &data, PackageType type):
    m_httpVersion("HTTP/1.1"),
    m_errorCode(NoError)
{
    m_url.setScheme("http");

    QStringList list = QString::fromUtf8(data).split("\r\n");
    if(!list.isEmpty()){
        QByteArrayList tmp = list.first().toUtf8().split(' ');

        if(tmp.count() == 3){
            if(type == Request){
                setMethod(tmp[0]);
                QByteArray path = tmp[1].split('?').first();
                m_url.setPath(path);
                if(path.count() < tmp[1].count())
                    m_url.setQuery(tmp[1].mid(path.count() + 1));
                setHttpVersion(tmp[2]);
            }else{
                setHttpVersion(tmp[0]);
                setError(ErrorCode(tmp[1].toInt()));
                setErrorString(tmp[2]);
            }
        }else{
            setError(BadRequest);
            setErrorString(QString("%1 Bad Request").arg(BadRequest));
            return;
        }

        int i = 1;

        for(; i < tmp.count(); ++i){
            tmp = list[i].toUtf8().split(':');
            if(tmp.count() == 2){
                setRawHeader(tmp.first(), tmp.last().trimmed());
                if(tmp.first() == "Host")
                    m_url.setHost(tmp.last().trimmed());
            }else{
                setError(BadRequest);
                setErrorString(QString("%1 Bad Request").arg(BadRequest));
                return;
            }
        }
    }else{
        setError(BadRequest);
        setErrorString(QString("%1 Bad Request").arg(BadRequest));
        return;
    }
}
Exemple #12
0
void Parse::login( QString username, QString password )
{
    setHostURI(Cloud::getValueFor("serverURL",""));

    if (!isReady()) return;

    QUrlQuery postData;
    postData.addQueryItem("username", username);
    postData.addQueryItem("password", password);

    setEndPoint( "login?" + postData.toString() ); //TODO improve me : not use endpoint to give url encoded params

    initHeaders();
    if (registerInstallationOnLogin)
        setRawHeader("X-Parse-Installation-Id", "1");

    m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){
        disconnect(m_conn);
        if ( isLastRequestSuccessful() ) { //getHttpCode() == 201 ){
            QJsonObject obj = json.object();
            sessionId = obj.value("sessionToken").toString();
            userId = obj.value("objectId").toString();
            userName = obj.value("username").toString();
//            qWarning()<<obj;
            qWarning() << "objectId" << obj.value("objectId").toString();
            qWarning() << "sessionToken" << sessionId;
            setRawHeader("X-Parse-Session-Token", sessionId.toUtf8());
            emit loginChanged();
        }

    } );

    request( BaaS::GET);


}
Exemple #13
0
void Request::start(const QUrl &url, const QString &action, const QString &bodyText)
{
    auto requestText = QString(ENVELOPE_BEGIN).append(bodyText).append(ENVELOPE_END).toUtf8();
    auto request = QNetworkRequest(url);

    if (REQUEST_DEBUG_DUMP) {
        qDebug() << "Request::start: >>>>>>>>";
        qDebug() << "Request::start: " << requestText;
        qDebug() << "Request::start: >>>>>>>>";
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, CONTENT_TYPE);
    request.setRawHeader(SOAPACTION_HEADER, action.toUtf8());
    m_networkAccess.post(request, requestText);
}
void KNetworkReply::appendData(KIO::Job *kioJob, const QByteArray &data)
{
//     kDebug();

    if (!d->m_metaDataRead) {
        QString headers = kioJob->queryMetaData("HTTP-Headers");
        if (!headers.isEmpty()) {
            QStringList headerList = headers.split('\n');
            Q_FOREACH(const QString &header, headerList) {
                QStringList headerPair = header.split(": ");
                if (headerPair.size() == 2) {
//                     kDebug() << headerPair.at(0) << headerPair.at(1);
                    setRawHeader(headerPair.at(0).toUtf8(), headerPair.at(1).toUtf8());
                }
            }
Exemple #15
0
/*
    A simple web page that can be used to test us: http://www.procata.com/cachetest/
 */
bool QNetworkAccessHttpBackend::sendCacheContents(const QNetworkCacheMetaData &metaData)
{
    setCachingEnabled(false);
    if (!metaData.isValid())
        return false;

    QAbstractNetworkCache *nc = networkCache();
    Q_ASSERT(nc);
    QIODevice *contents = nc->data(url());
    if (!contents) {
#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
        qDebug() << "Can not send cache, the contents are 0" << url();
#endif
        return false;
    }
    contents->setParent(this);

    QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
    int status = attributes.value(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (status < 100)
        status = 200;           // fake it

    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, status);
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));
    setAttribute(QNetworkRequest::SourceIsFromCacheAttribute, true);

    QNetworkCacheMetaData::RawHeaderList rawHeaders = metaData.rawHeaders();
    QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
                                                       end = rawHeaders.constEnd();
    for ( ; it != end; ++it)
        setRawHeader(it->first, it->second);

    checkForRedirect(status);

    writeDownstreamData(contents);
#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
    qDebug() << "Successfully sent cache:" << url() << contents->size() << "bytes";
#endif
    if (httpReply)
        disconnect(httpReply, SIGNAL(finished()), this, SLOT(replyFinished()));
    return true;
}
Exemple #16
0
QNetworkReply* Parse::deleteFile(QString fileName)
{
    if (!isReady() || getMasterKey().isEmpty()) return NULL;

    setEndPoint( "files/" + fileName);

    m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){
        Q_UNUSED(json);
        disconnect(m_conn);
        if ( isLastRequestSuccessful() ) {
            emit objectDeleted( fileName );

        }
    } );

    initHeaders();
    setRawHeader("X-Parse-Master-Key", getMasterKey().toUtf8());

    return request( BaaS::DELETE );

}
void KVNetworkReply::handleResponse() {
	if(d->finished) return;

	setError(d->copied->error(), d->copied->errorString());

	copyAttribute(QNetworkRequest::HttpStatusCodeAttribute);
	copyAttribute(QNetworkRequest::HttpReasonPhraseAttribute);
	copyAttribute(QNetworkRequest::RedirectionTargetAttribute);
	copyAttribute(QNetworkRequest::ConnectionEncryptedAttribute);
	copyAttribute(QNetworkRequest::SourceIsFromCacheAttribute);
	copyAttribute(QNetworkRequest::HttpPipeliningWasUsedAttribute);

	QList<QNetworkReply::RawHeaderPair> headers = d->copied->rawHeaderPairs();
	for(int i = 0; i < headers.size(); i++)
		setRawHeader(headers[i].first, headers[i].second);

	QByteArray data = d->copied->readAll();
	d->copied->abort();

	//qDebug() << "content:" << data;

	this->postToTool(data);
	this->writeToDisk(data);

	if(d->translate)
		data = KVTranslator::instance().translateJson(data, d->copied->url().path().split("/").last());

	d->content = data;
	d->offset = 0;
	setHeader(QNetworkRequest::ContentLengthHeader, QVariant(d->content.size()));

	open(ReadOnly | Unbuffered);
	//qDebug() << "translated:" << d->content.constData();

	d->finished = true;

	emit finished();
	emit readChannelFinished();
}
void TMailMessage::addAddress(const QByteArray &field, const QByteArray &address, const QString &friendlyName)
{
    QByteArray addr = rawHeader(field);
    if (!addr.isEmpty()) {
        addr += ", ";
    }

    if (!friendlyName.isEmpty()) {
        QByteArray uname = friendlyName.toUtf8();
        if (uname.length() == friendlyName.length()) {
            addr += uname;
        } else {
            // multibyte char
            addr += THttpUtility::toMimeEncoded(friendlyName, textCodec);
        }
        addr += ' ';
    }

    addr += '<';
    addr += address.trimmed();
    addr += '>';
    setRawHeader(field, addr);
}
Exemple #19
0
QFacebookHttpReply *QFacebookHttpApi::usersQueryAfter(const QByteArray &token, const QString &cursor)
{
    auto jsonString = QString{R"({"0": ["user"], "1": "%1", "2": "50"})"}.arg(cursor);
    auto parameters =
        std::map<QByteArray, QByteArray>{{"query_id", "10154444360816729"}, {"query_params", jsonString.toUtf8()}};
    auto usersQueryRequest = QFacebookHttpRequest{"https://graph.facebook.com/graphql", token, "get",
                                                  "FetchContactsFullWithAfterQuery", parameters};
    return get(usersQueryRequest);
}

QFacebookHttpReply *QFacebookHttpApi::usersQueryDelta(const QByteArray &token, const QString &deltaCursor)
{
    auto jsonString = QString{R"({"0": "%1", "1": ["user"], "2": "500"})"}.arg(deltaCursor);
    auto parameters =
        std::map<QByteArray, QByteArray>{{"query_id", "10154444360801729"}, {"query_params", jsonString.toUtf8()}};
    auto usersQueryRequest =
        QFacebookHttpRequest{"https://graph.facebook.com/graphql", token, "get", "FetchContactsDeltaQuery", parameters};
    return get(usersQueryRequest);
}

QFacebookHttpReply *QFacebookHttpApi::threadListQuery(const QByteArray &token)
{
    auto jsonString = QString{R"({"1": "0"})"};
    auto parameters =
        std::map<QByteArray, QByteArray>{{"query_id", "10155268192741729"}, {"query_params", jsonString.toUtf8()}};
    auto usersQueryRequest =
        QFacebookHttpRequest{"https://graph.facebook.com/graphql", token, "get", "ThreadListQuery", parameters};
    return get(usersQueryRequest);
}

QFacebookHttpReply *QFacebookHttpApi::unreadThreadListQuery(const QByteArray &token, int unreadCount)
{
    auto jsonString = QString{R"({"1": "%1", "2": "true", "12": "true", "13": "false"})"}.arg(unreadCount);
    auto parameters =
        std::map<QByteArray, QByteArray>{{"query_id", "10153919752026729"}, {"query_params", jsonString.toUtf8()}};
    auto usersQueryRequest =
        QFacebookHttpRequest{"https://graph.facebook.com/graphql", token, "get", "ThreadListQuery", parameters};
    return get(usersQueryRequest);
}

QFacebookHttpReply *
QFacebookHttpApi::unreadMessagesListQuery(const QByteArray &token, QFacebookUid uid, int unreadCount)
{
    auto jsonString =
        QString{R"({"0": ["%1"], "10": "true", "11": "true", "12": "%2", "13": "false"})"}.arg(uid).arg(unreadCount);
    auto parameters =
        std::map<QByteArray, QByteArray>{{"query_id", "10153919752036729"}, {"query_params", jsonString.toUtf8()}};
    auto usersQueryRequest =
        QFacebookHttpRequest{"https://graph.facebook.com/graphql", token, "get", "ThreadQuery", parameters};
    return get(usersQueryRequest);
}

QFacebookHttpReply *QFacebookHttpApi::get(const QFacebookHttpRequest &request)
{
    auto authUrl = QStringLiteral();
    auto params = request.parameters();
    params.insert(std::make_pair("api_key", "256002347743983"));
    params.insert(std::make_pair("device_id", m_deviceId));
    params.insert(std::make_pair("fb_api_req_friendly_name", request.friendlyName()));
    params.insert(std::make_pair("format", "json"));
    params.insert(std::make_pair("method", request.method()));
    params.insert(std::make_pair("local", "pl_PL"));

    std::vector<QByteArray> keys;
    std::transform(
        std::begin(params), std::end(params), std::back_inserter(keys),
        [](const std::pair<QByteArray, QByteArray> &x) { return x.first; });
    std::sort(std::begin(keys), std::end(keys));

    QCryptographicHash md5sum{QCryptographicHash::Md5};
    std::for_each(std::begin(keys), std::end(keys), [&params, &md5sum](const QByteArray &x) {
        md5sum.addData(x);
        md5sum.addData(QByteArray{"="});
        md5sum.addData(params[x]);
    });
    md5sum.addData(QByteArray{"374e60f8b9bb6b8cbb30f78030438895"});

    params.insert(std::make_pair("sig", md5sum.result().toHex()));

    auto urlQuery = QUrlQuery{};
    for (auto const &i : params)
        urlQuery.addQueryItem(QString::fromUtf8(i.first), QString::fromUtf8(i.second));

    auto url = QUrl{request.url()};
    url.setQuery(urlQuery);

    auto httpRequest = QNetworkRequest{url};
    httpRequest.setHeader(QNetworkRequest::UserAgentHeader, "Facebook plugin / Kadu / [FBAN/Orca-Android;FBAV/38.0.0.22.155;FBBV/14477681]");
    auto token = request.token();
    if (token)
        httpRequest.setRawHeader("Authorization", QByteArray{"OAuth "} + *token);

    return new QFacebookHttpReply{m_nam.get(httpRequest)};
}
/*!
  Sets the value of the header field content-length to \a len.
*/
void TInternetMessageHeader::setContentLength(int len)
{
    setRawHeader("Content-Length", QByteArray::number(len));
}
/*!
  Sets the value of the header field date to \a date.
*/
void TInternetMessageHeader::setDate(const QByteArray &date)
{
    setRawHeader("Date", date);
}
Exemple #22
0
AMANetworkReplyPostProxy::AMANetworkReplyPostProxy(QObject *parent,
                                           const QNetworkRequest &req,
                                           const QNetworkAccessManager::Operation op,
                                           QIODevice *data,
                                           AMAQtBridge *bridge) :
    m_bridge(bridge), QNetworkReply(parent)
{
    QString sData = data->readAll().replace("+", "%20").replace("%2B", "+");
    qDebug() << "Posting something." << req.url().toString() + "?" + sData;
    QUrlQuery uqData(sData);
    QList<QPair<QString, QString>>  params = uqData.queryItems();
    QString oper = uqData.queryItemValue("oper");

    /// [Request stuff]
    setRequest(req);
    setOperation(op);
    setUrl(req.url());
    QNetworkReply::open(QIODevice::ReadOnly | QIODevice::Unbuffered);
    /// End [Request stuff]

    /// [Response-data stuff]
    m_lOffset = 0;
    m_content.clear();
    /// End [Response-data stuff]


    QVariantMap response;
    int httpStatus = 501;
    QString operRes =  "not implemented";


    if (oper.compare("edit") == 0) {
        QVariantMap edit;

        qDebug() << "Editing" << uqData.queryItemValue(bridge->m_id_field);
        int len = params.size();
        for (int i = 0; i < len; i++) {
            edit[params.at(i).first] = params.at(i).second;
        }
        bool ret = bridge->changeRecord(edit);

        if (ret) {
            operRes = "success";
            httpStatus = 200;
        } else {
            operRes = "error";
            // Set status 500 Server Error
            httpStatus = 500;
        }
    } else if (oper.compare("del") == 0) {
        bool ok;
        int rId = uqData.queryItemValue("id").toInt(&ok);
        if (ok) {
            if (bridge->deleteRecord(rId)) {
                operRes = "success";
                httpStatus = 200;
            } else {
                operRes = "error";
                // Deleting failed (DB or whatever)
                httpStatus = 500;
            }
        } else {
            operRes = "error";
            // Client sent something that is not sane
            httpStatus = 400;
        }
    }

    response[oper] = operRes;
    setAttribute( QNetworkRequest::HttpStatusCodeAttribute, QVariant( httpStatus ) );

    // Allow "cross site resource usage" if running in Qt client.
    setRawHeader( "Access-Control-Allow-Origin", "qrc://" );

    m_content.append(QJsonDocument(QJsonObject::fromVariantMap(response)).toJson(QJsonDocument::Compact));

    // Set reply size
    setHeader( QNetworkRequest::ContentLengthHeader, QVariant( m_content.size() ) );

    // Please do not cache (but the browser does anyway)
    setRawHeader( "Cache-Control", "must-revalidate" );
    setHeader( QNetworkRequest::LastModifiedHeader, QDateTime::currentDateTimeUtc() );


    // That way the browser does not offer the resource for download or does other strange things
    setHeader( QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8" );


    // Call notify functions
    QMetaObject::invokeMethod( this, "metaDataChanged", Qt::QueuedConnection );
    QMetaObject::invokeMethod( this, "readyRead", Qt::QueuedConnection );
    QMetaObject::invokeMethod( this, "downloadProgress", Qt::QueuedConnection,
                                                       Q_ARG( qint64, m_content.size() ), Q_ARG( qint64, m_content.size() ) );
    QMetaObject::invokeMethod( this, "finished", Qt::QueuedConnection );
    setFinished(true);
}
Exemple #23
0
AMANetworkReplyProxy::AMANetworkReplyProxy(QObject *parent,
                                           const QNetworkRequest &req,
                                           const QNetworkAccessManager::Operation op,
                                           AMAQtBridge *bridge) :
    m_bridge(bridge), m_imgs(0), QNetworkReply(parent)
{
    /// [Request stuff]
    setRequest(req);
    setOperation(op);
    setUrl(req.url());
    QNetworkReply::open(QIODevice::ReadOnly | QIODevice::Unbuffered);
    /// End [Request stuff]

    /// [Response-data stuff]
    m_lOffset = 0;
    m_content.clear();
    /// End [Response-data stuff]

    QString sReq = req.url().toString();
    QString fileExtension;

    if (sReq.startsWith("qrc:/data/")) {
        if (op == QNetworkAccessManager::PostOperation) {
            /// Upload
            this->open(QIODevice::ReadOnly | QIODevice::Text);
            qDebug() << op << QString( this->readAll() ) << this->isOpen() << this->isReadable() << this->size();
            this->close();
        } else {
            /// Serving JSON data
            QStringList dataRequested = req2DataRequested(req);
            fileExtension = dataRequested.last().toUpper();

            QStringList dataRequestOpts;
            dataRequestOpts << "COMPOUNDDATA" << "RENDERFIELDS" << "RENDERGROUPINFO" << "QUERYFIELDS" << "QUERYGROUPINFO" << "HRFCORR" << "AMAVIEWS" << "LEGEND";

            QJsonArray a;
            QJsonObject o;
            switch(dataRequestOpts.indexOf(dataRequested.first().toUpper())) {
            case 0: {
                QVariantList d = bridge->getData();
                a = QJsonArray::fromVariantList(d);
                break;
            }
            case 1: {
                QVariantList d = bridge->getRenderFields();
                a = QJsonArray::fromVariantList(d);
                break;
            }
            case 2: {
                QVariantMap d = bridge->getRendergroupinfo();
                o = QJsonObject::fromVariantMap(d);
                break;
            }
            case 3: {
                QVariantList d = bridge->getQueryfields();
                a = QJsonArray::fromVariantList(d);
                break;
            }
            case 4: {
                QVariantMap d = bridge->getQuerygroupinfo();
                o = QJsonObject::fromVariantMap(d);
                break;
            }
            case 5: {
                QVariantList d = bridge->getHrfCorr();
                a = QJsonArray::fromVariantList(d);
                break;
            }
            case 6: {
                QVariantList d = bridge->getAmaviews();
                a = QJsonArray::fromVariantList(d);
                break;
            }
            case 7: {
                QString txt = bridge->getMetaSetting("legend");
                QVariantMap d;
                d.insert("legend", txt);
                o = QJsonObject::fromVariantMap(d);
                break;
            }
            default:
                qWarning() << "Cannot handle request " << dataRequested.first().toUpper() << ". Unknown resource.";
            }

            QJsonDocument doc;
            if (a.size()) {
                doc = QJsonDocument(a);
            } else {
                doc = QJsonDocument(o);
            }
            // Create the JSONP-response
            // We're using JSONP because this works cross-site in
            // all browsers, even on localhost or file which is
            // (the latter is restricted by Opera, for example, even
            // when doing the AJAX from a HTML page saved on the local
            // file system)
            m_content
                    .append( "window['" )
                    .append( dataRequested.first().toUtf8().replace("'", "\\'") )
                    .append( "']" )
                    .append( "(" )
                    .append( doc.toJson(QJsonDocument::Compact) )
                    .append( ");" );
        }
    } else if (sReq.startsWith("qrc:/images/GHS/")) {
        // Since filtered later and the request may arrive from different threads,
        // better use our own model
        // This is not the bottlenack; the slow client side JavaScript execution, however is.
        m_imgs = new QSqlRelationalTableModel(this);
        m_imgs->setTable("ghs");

        // CAVE: Ugly and possibly exploitable (SQL-injection)
        QStringList filename = req2FilenameParts(req);
        fileExtension = filename.last().toUpper();
        m_imgs->setFilter("ghs_code='" + filename.first() + "'");
        m_imgs->select();

        // Set response-body content. Since some browsers have the habit
        // asking multiple times for the same stuff, only parts (HTTP-range-request),
        // to boost performance, we read them once and store these little
        // formula files in memory.
        QByteArray qba = m_imgs->record(0).value("ghs_" + fileExtension.toLower()).toByteArray();
        if (qba.length() == 0) {
            qWarning() << " GHS: No " << fileExtension << " for " << filename.first();
        }
        m_content.append(qba);
    } else if (sReq.startsWith("qrc:/formulae/")) {
        // Since filtered later and the request may arrive from different threads,
        // better use our own model
        // This is not the bottlenack; the slow client side JavaScript execution, however is.
        m_imgs = new QSqlRelationalTableModel(this);
        m_imgs->setTable("FORMULAE");
        m_imgs->setRelation(m_imgs->fieldIndex("compound_id"), QSqlRelation("COMPOUNDS", bridge->m_id_field, "c_structure_name"));

        // CAVE: Ugly and possibly exploitable (SQL-injection)
        QStringList filename = req2FilenameParts(req);
        fileExtension = filename.last().toUpper();
        m_imgs->setFilter("c_structure_name='" + filename.first() + "'");
        m_imgs->select();

        // Set response-body content. Since some browsers have the habit
        // asking multiple times for the same stuff, only parts (HTTP-range-request),
        // to boost performance, we read them once and store these little
        // formula files in memory.
        QByteArray qba = m_imgs->record(0).value(fileExtension).toByteArray();
        if (qba.length() == 0) {
            qWarning() << " FROMULA: No " << fileExtension << " for " << filename.first() << req.url().path();
        }
        m_content.append(qba);
    } else if (sReq.startsWith("qrc:/images/photos/")) {
        QStringList photoName = req2FilenameParts(req);
        QDir photoDir(*(m_bridge->m_app_dir) + "/" + "photos");
        if (photoDir.exists()) {
            QString photoPath = photoDir.absoluteFilePath(photoName.first() + '.' + photoName.last());
            QFile photo(photoPath);
            photo.open(QIODevice::ReadOnly);
            m_content.append(photo.readAll());
            photo.close();
        }
    }

    QString mime;

    // C++ cannot switch-by-string, even if constant. Using a helper construct.
    QStringList fileExtensions;
    fileExtensions << "PNG" << "JPG" << "JPEG" << "SVG" << "JS";
    switch(fileExtensions.indexOf(fileExtension)) {
    case 0:
        mime = "image/png";
        break;
    case 1:
    case 2:
        mime = "image/jpeg";
        break;
    case 3:
        mime = "image/svg+xml";
        break;
    case 4:
        mime = "text/javascript;charset=utf-8";
        break;
    default:
        mime = "application/octet-stream";
    }

    // Set 200 OK - status
    setAttribute( QNetworkRequest::HttpStatusCodeAttribute, QVariant( 200 ) );

    // Set reply size
    setHeader( QNetworkRequest::ContentLengthHeader, QVariant( m_content.size() ) );

    // Please do not cache (but the browser does anyway)
    setRawHeader("Cache-Control", "must-revalidate");
    setHeader(QNetworkRequest::LastModifiedHeader, QDateTime::currentDateTimeUtc());


    // That way the browser does not offer the resource for download or does other strange things
    if ( mime.length() )
            setHeader( QNetworkRequest::ContentTypeHeader, QVariant( mime.toUtf8() ) );

    // Allow "cross site resource usage". Nothing confidental here.
    // Prevents for example that canvas gets polluted, ...
    setRawHeader( "Access-Control-Allow-Origin", "*" );

    // Call notify functions
    QMetaObject::invokeMethod( this, "metaDataChanged", Qt::QueuedConnection );
    QMetaObject::invokeMethod( this, "readyRead", Qt::QueuedConnection );
    QMetaObject::invokeMethod( this, "downloadProgress", Qt::QueuedConnection,
                                                       Q_ARG( qint64, m_content.size() ), Q_ARG( qint64, m_content.size() ) );
    QMetaObject::invokeMethod( this, "finished", Qt::QueuedConnection );
    setFinished(true);

    // Created on the heap but not required anymore
    if (m_imgs) {
        m_imgs->clear();
        m_imgs->deleteLater();
    }
}
/*!
  Sets the value of the header field date to \a localTime
  as the local time on the computer.
*/
void TInternetMessageHeader::setDate(const QDateTime &localTime)
{
    setRawHeader("Date", THttpUtility::toHttpDateTimeString(localTime));
}
void TMailMessage::setSubject(const QString &subject)
{
    setRawHeader("Subject", THttpUtility::toMimeEncoded(subject, textCodec));
}
Exemple #26
0
void Parse::initHeaders( )
{
    setRawHeader("X-Parse-Application-Id",applicationId.toUtf8());
    setRawHeader("Accept","application/json");
    setHeader(QNetworkRequest::ContentTypeHeader, "application/Json");
}
Exemple #27
0
void QNetworkAccessHttpBackend::replyHeaderChanged()
{
    // reconstruct the HTTP header
    QList<QPair<QByteArray, QByteArray> > headerMap = httpReply->header();
    QList<QPair<QByteArray, QByteArray> >::ConstIterator it = headerMap.constBegin(),
                                                        end = headerMap.constEnd();
    QByteArray header;

    for (; it != end; ++it) {
        QByteArray value = rawHeader(it->first);
        if (!value.isEmpty()) {
            if (it->first.toLower() == "set-cookie")
                value += "\n";
            else
                value += ", ";
        }
        value += it->second;
        setRawHeader(it->first, value);
    }

    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, httpReply->statusCode());
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, httpReply->reasonPhrase());

    // is it a redirection?
    const int statusCode = httpReply->statusCode();
    checkForRedirect(statusCode);

    if (statusCode >= 500 && statusCode < 600) {
        QAbstractNetworkCache *nc = networkCache();
        if (nc) {
            QNetworkCacheMetaData metaData = nc->metaData(url());
            QNetworkHeadersPrivate cacheHeaders;
            cacheHeaders.setAllRawHeaders(metaData.rawHeaders());
            QNetworkHeadersPrivate::RawHeadersList::ConstIterator it;
            it = cacheHeaders.findRawHeader("Cache-Control");
            bool mustReValidate = false;
            if (it != cacheHeaders.rawHeaders.constEnd()) {
                QHash<QByteArray, QByteArray> cacheControl = parseHttpOptionHeader(it->second);
                if (cacheControl.contains("must-revalidate"))
                    mustReValidate = true;
            }
            if (!mustReValidate && sendCacheContents(metaData))
                return;
        }
    }

    if (statusCode == 304) {
#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
        qDebug() << "Received a 304 from" << url();
#endif
        QAbstractNetworkCache *nc = networkCache();
        if (nc) {
            QNetworkCacheMetaData oldMetaData = nc->metaData(url());
            QNetworkCacheMetaData metaData = fetchCacheMetaData(oldMetaData);
            if (oldMetaData != metaData)
                nc->updateMetaData(metaData);
            if (sendCacheContents(metaData))
                return;
        }
    }


    if (statusCode != 304 && statusCode != 303) {
        if (!isCachingEnabled())
            setCachingEnabled(true);
    }
    metaDataChanged();
}
Exemple #28
0
 foreach (QByteArray key, rawHeaderList())
 {
     setRawHeader(key,QByteArray());
 }
Exemple #29
0
void HttpInfo::setBody(const QByteArray &body, int bodyLength)
{
    m_body = body;
    setRawHeader("Content-Length", QByteArray::number(bodyLength == -1 ? m_body.length() : bodyLength));
}
/*!
  Sets the value of the header field date to \a utc as Coordinated
  Universal Time.
*/
void TInternetMessageHeader::setDateUTC(const QDateTime &utc)
{
    setRawHeader("Date", THttpUtility::toHttpDateTimeUTCString(utc));
}