Browse Source

Follow project coding style (Issue #2192).

adaptive-webui-19844
Vladimir Golovnev (Glassez) 10 years ago
parent
commit
898d454b78
  1. 3
      src/core/http/connection.cpp
  2. 101
      src/core/http/requestparser.cpp
  3. 23
      src/core/http/requestparser.h
  4. 27
      src/core/http/responsegenerator.cpp
  5. 10
      src/core/http/server.cpp
  6. 5
      src/core/qtracker.cpp
  7. 53
      src/webui/abstractwebapplication.cpp

3
src/core/http/connection.cpp

@ -59,8 +59,7 @@ void Connection::read()
Request request; Request request;
RequestParser::ErrorCode err = RequestParser::parse(m_receivedData, request); RequestParser::ErrorCode err = RequestParser::parse(m_receivedData, request);
switch (err) switch (err) {
{
case RequestParser::IncompleteRequest: case RequestParser::IncompleteRequest:
// Partial request waiting for the rest // Partial request waiting for the rest
break; break;

101
src/core/http/requestparser.cpp

@ -31,7 +31,6 @@
#include <QStringList> #include <QStringList>
#include <QUrl> #include <QUrl>
//#include <QVariant>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QUrlQuery> #include <QUrlQuery>
#endif #endif
@ -69,46 +68,40 @@ RequestParser::ErrorCode RequestParser::parseHttpRequest(const QByteArray& data,
// Parse HTTP request header // Parse HTTP request header
const int header_end = data.indexOf(EOH); const int header_end = data.indexOf(EOH);
if (header_end < 0) if (header_end < 0) {
{
qDebug() << Q_FUNC_INFO << "incomplete request"; qDebug() << Q_FUNC_INFO << "incomplete request";
return IncompleteRequest; return IncompleteRequest;
} }
if (!parseHttpHeader(data.left(header_end))) if (!parseHttpHeader(data.left(header_end))) {
{
qWarning() << Q_FUNC_INFO << "header parsing error"; qWarning() << Q_FUNC_INFO << "header parsing error";
return BadRequest; return BadRequest;
} }
// Parse HTTP request message // Parse HTTP request message
int content_length = 0; int content_length = 0;
if (m_request.headers.contains("content-length")) if (m_request.headers.contains("content-length")) {
{
content_length = m_request.headers["content-length"].toInt(); content_length = m_request.headers["content-length"].toInt();
if (content_length > static_cast<int>(m_maxContentLength)) if (content_length > static_cast<int>(m_maxContentLength)) {
{
qWarning() << Q_FUNC_INFO << "bad request: message too long"; qWarning() << Q_FUNC_INFO << "bad request: message too long";
return BadRequest; return BadRequest;
} }
QByteArray content = data.mid(header_end + EOH.length(), content_length); QByteArray content = data.mid(header_end + EOH.length(), content_length);
if (content.length() < content_length) if (content.length() < content_length) {
{
qDebug() << Q_FUNC_INFO << "incomplete request"; qDebug() << Q_FUNC_INFO << "incomplete request";
return IncompleteRequest; return IncompleteRequest;
} }
if (!parseContent(content)) if (!parseContent(content)) {
{
qWarning() << Q_FUNC_INFO << "message parsing error"; qWarning() << Q_FUNC_INFO << "message parsing error";
return BadRequest; return BadRequest;
} }
} }
// qDebug() << Q_FUNC_INFO; // qDebug() << Q_FUNC_INFO;
// qDebug() << "HTTP Request header:"; // qDebug() << "HTTP Request header:";
// qDebug() << data.left(header_end) << "\n"; // qDebug() << data.left(header_end) << "\n";
request = m_request; request = m_request;
return NoError; return NoError;
@ -118,8 +111,7 @@ bool RequestParser::parseStartingLine(const QString &line)
{ {
const QRegExp rx("^([A-Z]+)\\s+(\\S+)\\s+HTTP/\\d\\.\\d$"); const QRegExp rx("^([A-Z]+)\\s+(\\S+)\\s+HTTP/\\d\\.\\d$");
if (rx.indexIn(line.trimmed()) >= 0) if (rx.indexIn(line.trimmed()) >= 0) {
{
m_request.method = rx.cap(1); m_request.method = rx.cap(1);
QUrl url = QUrl::fromEncoded(rx.cap(2).toLatin1()); QUrl url = QUrl::fromEncoded(rx.cap(2).toLatin1());
@ -131,8 +123,7 @@ bool RequestParser::parseStartingLine(const QString &line)
#else #else
QListIterator<QPair<QString, QString> > i(QUrlQuery(url).queryItems()); QListIterator<QPair<QString, QString> > i(QUrlQuery(url).queryItems());
#endif #endif
while (i.hasNext()) while (i.hasNext()) {
{
QPair<QString, QString> pair = i.next(); QPair<QString, QString> pair = i.next();
m_request.gets[pair.first] = pair.second; m_request.gets[pair.first] = pair.second;
} }
@ -147,8 +138,7 @@ bool RequestParser::parseStartingLine(const QString &line)
bool RequestParser::parseHeaderLine(const QString &line, QPair<QString, QString>& out) bool RequestParser::parseHeaderLine(const QString &line, QPair<QString, QString>& out)
{ {
int i = line.indexOf(QLatin1Char(':')); int i = line.indexOf(QLatin1Char(':'));
if (i == -1) if (i == -1) {
{
qWarning() << Q_FUNC_INFO << "invalid http header:" << line; qWarning() << Q_FUNC_INFO << "invalid http header:" << line;
return false; return false;
} }
@ -163,18 +153,14 @@ bool RequestParser::parseHttpHeader(const QByteArray &data)
QStringList lines = str.trimmed().split(EOL); QStringList lines = str.trimmed().split(EOL);
QStringList headerLines; QStringList headerLines;
foreach (const QString& line, lines) foreach (const QString& line, lines) {
{ if (line[0].isSpace()) { // header line continuation
if (line[0].isSpace()) // header line continuation if (!headerLines.isEmpty()) { // really continuation
{
if (!headerLines.isEmpty()) // really continuation
{
headerLines.last() += QLatin1Char(' '); headerLines.last() += QLatin1Char(' ');
headerLines.last() += line.trimmed(); headerLines.last() += line.trimmed();
} }
} }
else else {
{
headerLines.append(line); headerLines.append(line);
} }
} }
@ -187,8 +173,7 @@ bool RequestParser::parseHttpHeader(const QByteArray &data)
return false; return false;
++it; ++it;
for (; it != headerLines.end(); ++it) for (; it != headerLines.end(); ++it) {
{
QPair<QString, QString> header; QPair<QString, QString> header;
if (!parseHeaderLine(*it, header)) if (!parseHeaderLine(*it, header))
return false; return false;
@ -206,12 +191,10 @@ QList<QByteArray> RequestParser::splitMultipartData(const QByteArray& data, cons
const int sepLength = sep.size(); const int sepLength = sep.size();
int start = 0, end = 0; int start = 0, end = 0;
if ((end = data.indexOf(sep, start)) >= 0) if ((end = data.indexOf(sep, start)) >= 0) {
{
start = end + sepLength; // skip first boundary start = end + sepLength; // skip first boundary
while ((end = data.indexOf(sep, start)) >= 0) while ((end = data.indexOf(sep, start)) >= 0) {
{
ret << data.mid(start, end - start); ret << data.mid(start, end - start);
start = end + sepLength; start = end + sepLength;
} }
@ -232,8 +215,7 @@ bool RequestParser::parseContent(const QByteArray& data)
qDebug() << Q_FUNC_INFO << "data.size(): " << data.size(); qDebug() << Q_FUNC_INFO << "data.size(): " << data.size();
// Parse url-encoded POST data // Parse url-encoded POST data
if (m_request.headers["content-type"].startsWith("application/x-www-form-urlencoded")) if (m_request.headers["content-type"].startsWith("application/x-www-form-urlencoded")) {
{
QUrl url; QUrl url;
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
url.setEncodedQuery(data); url.setEncodedQuery(data);
@ -242,8 +224,7 @@ bool RequestParser::parseContent(const QByteArray& data)
url.setQuery(data); url.setQuery(data);
QListIterator<QPair<QString, QString> > i(QUrlQuery(url).queryItems(QUrl::FullyDecoded)); QListIterator<QPair<QString, QString> > i(QUrlQuery(url).queryItems(QUrl::FullyDecoded));
#endif #endif
while (i.hasNext()) while (i.hasNext()) {
{
QPair<QString, QString> pair = i.next(); QPair<QString, QString> pair = i.next();
m_request.posts[pair.first.toLower()] = pair.second; m_request.posts[pair.first.toLower()] = pair.second;
} }
@ -271,26 +252,21 @@ Submit Query
--cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5-- --cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5--
**/ **/
QString content_type = m_request.headers["content-type"]; QString content_type = m_request.headers["content-type"];
if (content_type.startsWith("multipart/form-data")) if (content_type.startsWith("multipart/form-data")) {
{
const QRegExp boundaryRegexQuoted("boundary=\"([ \\w'()+,-\\./:=\\?]+)\""); const QRegExp boundaryRegexQuoted("boundary=\"([ \\w'()+,-\\./:=\\?]+)\"");
const QRegExp boundaryRegexNotQuoted("boundary=([\\w'()+,-\\./:=\\?]+)"); const QRegExp boundaryRegexNotQuoted("boundary=([\\w'()+,-\\./:=\\?]+)");
QByteArray boundary; QByteArray boundary;
if (boundaryRegexQuoted.indexIn(content_type) < 0) if (boundaryRegexQuoted.indexIn(content_type) < 0) {
{ if (boundaryRegexNotQuoted.indexIn(content_type) < 0) {
if (boundaryRegexNotQuoted.indexIn(content_type) < 0)
{
qWarning() << "Could not find boundary in multipart/form-data header!"; qWarning() << "Could not find boundary in multipart/form-data header!";
return false; return false;
} }
else else {
{
boundary = "--" + boundaryRegexNotQuoted.cap(1).toLatin1(); boundary = "--" + boundaryRegexNotQuoted.cap(1).toLatin1();
} }
} }
else else {
{
boundary = "--" + boundaryRegexQuoted.cap(1).toLatin1(); boundary = "--" + boundaryRegexQuoted.cap(1).toLatin1();
} }
@ -298,8 +274,7 @@ Submit Query
QList<QByteArray> parts = splitMultipartData(data, boundary); QList<QByteArray> parts = splitMultipartData(data, boundary);
qDebug() << parts.size() << "parts in data"; qDebug() << parts.size() << "parts in data";
foreach (const QByteArray& part, parts) foreach (const QByteArray& part, parts) {
{
if (!parseFormData(part)) if (!parseFormData(part))
return false; return false;
} }
@ -315,8 +290,7 @@ bool RequestParser::parseFormData(const QByteArray& data)
{ {
// Parse form data header // Parse form data header
const int header_end = data.indexOf(EOH); const int header_end = data.indexOf(EOH);
if (header_end < 0) if (header_end < 0) {
{
qDebug() << "Invalid form data: \n" << data; qDebug() << "Invalid form data: \n" << data;
return false; return false;
} }
@ -324,8 +298,7 @@ bool RequestParser::parseFormData(const QByteArray& data)
QString header_str = QString::fromUtf8(data.left(header_end)); QString header_str = QString::fromUtf8(data.left(header_end));
QStringList lines = header_str.trimmed().split(EOL); QStringList lines = header_str.trimmed().split(EOL);
QStringMap headers; QStringMap headers;
foreach (const QString& line, lines) foreach (const QString& line, lines) {
{
QPair<QString, QString> header; QPair<QString, QString> header;
if (!parseHeaderLine(line, header)) if (!parseHeaderLine(line, header))
return false; return false;
@ -334,16 +307,14 @@ bool RequestParser::parseFormData(const QByteArray& data)
} }
QStringMap disposition; QStringMap disposition;
if (!headers.contains("content-disposition") || if (!headers.contains("content-disposition")
!parseHeaderValue(headers["content-disposition"], disposition) || || !parseHeaderValue(headers["content-disposition"], disposition)
!disposition.contains("name")) || !disposition.contains("name")) {
{
qDebug() << "Invalid form data header: \n" << header_str; qDebug() << "Invalid form data header: \n" << header_str;
return false; return false;
} }
if (disposition.contains("filename")) if (disposition.contains("filename")) {
{
UploadedFile ufile; UploadedFile ufile;
ufile.filename = disposition["filename"]; ufile.filename = disposition["filename"];
ufile.type = disposition["content-type"]; ufile.type = disposition["content-type"];
@ -351,8 +322,7 @@ bool RequestParser::parseFormData(const QByteArray& data)
m_request.files[disposition["name"]] = ufile; m_request.files[disposition["name"]] = ufile;
} }
else else {
{
m_request.posts[disposition["name"]] = QString::fromUtf8(data.mid(header_end + EOH.length())); m_request.posts[disposition["name"]] = QString::fromUtf8(data.mid(header_end + EOH.length()));
} }
@ -364,8 +334,7 @@ bool RequestParser::parseHeaderValue(const QString& value, QStringMap& out)
QStringList items = value.split(QLatin1Char(';')); QStringList items = value.split(QLatin1Char(';'));
out[""] = items[0]; out[""] = items[0];
for (QStringList::size_type i = 1; i < items.size(); ++i) for (QStringList::size_type i = 1; i < items.size(); ++i) {
{
int pos = items[i].indexOf("="); int pos = items[i].indexOf("=");
if (pos < 0) if (pos < 0)
return false; return false;

23
src/core/http/requestparser.h

@ -40,25 +40,30 @@ namespace Http
class RequestParser class RequestParser
{ {
public: public:
enum ErrorCode { NoError = 0, IncompleteRequest, BadRequest }; enum ErrorCode
{
NoError = 0,
IncompleteRequest,
BadRequest
};
// when result != NoError parsed request is undefined // when result != NoError parsed request is undefined
// Warning! Header names are converted to lower-case. // Warning! Header names are converted to lower-case.
static ErrorCode parse(const QByteArray& data, Request& request, uint maxContentLength = 10000000 /* ~10MB */); static ErrorCode parse(const QByteArray &data, Request &request, uint maxContentLength = 10000000 /* ~10MB */);
private: private:
RequestParser(uint maxContentLength); RequestParser(uint maxContentLength);
ErrorCode parseHttpRequest(const QByteArray& data, Request& request); ErrorCode parseHttpRequest(const QByteArray &data, Request &request);
bool parseHttpHeader(const QByteArray& data); bool parseHttpHeader(const QByteArray &data);
bool parseStartingLine(const QString &line); bool parseStartingLine(const QString &line);
bool parseContent(const QByteArray& data); bool parseContent(const QByteArray &data);
bool parseFormData(const QByteArray& data); bool parseFormData(const QByteArray &data);
QList<QByteArray> splitMultipartData(const QByteArray& data, const QByteArray& boundary); QList<QByteArray> splitMultipartData(const QByteArray &data, const QByteArray &boundary);
static bool parseHeaderLine(const QString& line, QPair<QString, QString>& out); static bool parseHeaderLine(const QString &line, QPair<QString, QString> &out);
static bool parseHeaderValue(const QString& value, QStringMap& out); static bool parseHeaderValue(const QString &value, QStringMap &out);
const uint m_maxContentLength; const uint m_maxContentLength;
Request m_request; Request m_request;

27
src/core/http/responsegenerator.cpp

@ -38,22 +38,17 @@ using namespace Http;
QByteArray ResponseGenerator::generate(Response response) QByteArray ResponseGenerator::generate(Response response)
{ {
if (response.headers[HEADER_CONTENT_ENCODING] == "gzip") if (response.headers[HEADER_CONTENT_ENCODING] == "gzip") {
{
// A gzip seems to have 23 bytes overhead. // A gzip seems to have 23 bytes overhead.
// Also "Content-Encoding: gzip\r\n" is 26 bytes long // Also "Content-Encoding: gzip\r\n" is 26 bytes long
// So we only benefit from gzip if the message is bigger than 23+26 = 49 // So we only benefit from gzip if the message is bigger than 23+26 = 49
// If the message is smaller than 49 bytes we actually send MORE data if we gzip // If the message is smaller than 49 bytes we actually send MORE data if we gzip
QByteArray dest_buf; QByteArray dest_buf;
if ((response.content.size() > 49) && (gCompress(response.content, dest_buf))) if ((response.content.size() > 49) && (gCompress(response.content, dest_buf)))
{
response.content = dest_buf; response.content = dest_buf;
}
else else
{
response.headers.remove(HEADER_CONTENT_ENCODING); response.headers.remove(HEADER_CONTENT_ENCODING);
} }
}
if (response.content.length() > 0) if (response.content.length() > 0)
response.headers[HEADER_CONTENT_LENGTH] = QString::number(response.content.length()); response.headers[HEADER_CONTENT_LENGTH] = QString::number(response.content.length());
@ -66,9 +61,9 @@ QByteArray ResponseGenerator::generate(Response response)
ret = ret.arg(response.status.code).arg(response.status.text).arg(header); ret = ret.arg(response.status.code).arg(response.status.text).arg(header);
// qDebug() << Q_FUNC_INFO; // qDebug() << Q_FUNC_INFO;
// qDebug() << "HTTP Response header:"; // qDebug() << "HTTP Response header:";
// qDebug() << ret; // qDebug() << ret;
return ret.toUtf8() + response.content; return ret.toUtf8() + response.content;
} }
@ -91,19 +86,17 @@ bool gCompress(QByteArray data, QByteArray& dest_buffer)
//windowBits = 15+16 to enable gzip //windowBits = 15+16 to enable gzip
//From the zlib manual: windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits //From the zlib manual: windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits
//to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. //to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper.
ret = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, 15+16, 8, Z_DEFAULT_STRATEGY); ret = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK) if (ret != Z_OK)
return false; return false;
while (strm.avail_in != 0) while (strm.avail_in != 0) {
{
ret = deflate(&strm, Z_NO_FLUSH); ret = deflate(&strm, Z_NO_FLUSH);
if (ret != Z_OK) if (ret != Z_OK)
return false; return false;
if (strm.avail_out == 0) if (strm.avail_out == 0) {
{
dest_buffer.append(tmp_buf, BUFSIZE); dest_buffer.append(tmp_buf, BUFSIZE);
strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf); strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf);
strm.avail_out = BUFSIZE; strm.avail_out = BUFSIZE;
@ -111,10 +104,8 @@ bool gCompress(QByteArray data, QByteArray& dest_buffer)
} }
int deflate_res = Z_OK; int deflate_res = Z_OK;
while (deflate_res == Z_OK) while (deflate_res == Z_OK) {
{ if (strm.avail_out == 0) {
if (strm.avail_out == 0)
{
dest_buffer.append(tmp_buf, BUFSIZE); dest_buffer.append(tmp_buf, BUFSIZE);
strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf); strm.next_out = reinterpret_cast<unsigned char*>(tmp_buf);
strm.avail_out = BUFSIZE; strm.avail_out = BUFSIZE;

10
src/core/http/server.cpp

@ -80,11 +80,10 @@ void Server::incomingConnection(int socketDescriptor)
else else
#endif #endif
serverSocket = new QTcpSocket(this); serverSocket = new QTcpSocket(this);
if (serverSocket->setSocketDescriptor(socketDescriptor))
{ if (serverSocket->setSocketDescriptor(socketDescriptor)) {
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
if (m_https) if (m_https) {
{
static_cast<QSslSocket*>(serverSocket)->setProtocol(QSsl::AnyProtocol); static_cast<QSslSocket*>(serverSocket)->setProtocol(QSsl::AnyProtocol);
static_cast<QSslSocket*>(serverSocket)->setPrivateKey(m_key); static_cast<QSslSocket*>(serverSocket)->setPrivateKey(m_key);
static_cast<QSslSocket*>(serverSocket)->setLocalCertificate(m_certificate); static_cast<QSslSocket*>(serverSocket)->setLocalCertificate(m_certificate);
@ -93,8 +92,7 @@ void Server::incomingConnection(int socketDescriptor)
#endif #endif
new Connection(serverSocket, m_requestHandler, this); new Connection(serverSocket, m_requestHandler, this);
} }
else else {
{
serverSocket->deleteLater(); serverSocket->deleteLater();
} }
} }

5
src/core/qtracker.cpp

@ -201,7 +201,8 @@ void QTracker::respondToAnnounceRequest()
m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash()); m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash());
return; return;
} }
} else { }
else {
// Unknown torrent // Unknown torrent
if (m_torrents.size() == MAX_TORRENTS) { if (m_torrents.size() == MAX_TORRENTS) {
// Reached max size, remove a random torrent // Reached max size, remove a random torrent
@ -228,7 +229,7 @@ void QTracker::replyWithPeerList(const TrackerAnnounceRequest &annonce_req)
reply_dict["interval"] = libtorrent::entry(ANNOUNCE_INTERVAL); reply_dict["interval"] = libtorrent::entry(ANNOUNCE_INTERVAL);
QList<QPeer> peers = m_torrents.value(annonce_req.info_hash).values(); QList<QPeer> peers = m_torrents.value(annonce_req.info_hash).values();
libtorrent::entry::list_type peer_list; libtorrent::entry::list_type peer_list;
foreach (const QPeer & p, peers) { foreach (const QPeer &p, peers) {
//if (p != annonce_req.peer) //if (p != annonce_req.peer)
peer_list.push_back(p.toEntry(annonce_req.no_peer_id)); peer_list.push_back(p.toEntry(annonce_req.no_peer_id));
} }

53
src/webui/abstractwebapplication.cpp

@ -144,8 +144,7 @@ bool AbstractWebApplication::sessionInitialize()
QString sessionId; QString sessionId;
int pos = cookie.indexOf(SID_START); int pos = cookie.indexOf(SID_START);
if (pos >= 0) if (pos >= 0) {
{
pos += SID_START.length(); pos += SID_START.length();
int end = cookie.indexOf(QRegExp("[,;]"), pos); int end = cookie.indexOf(QRegExp("[,;]"), pos);
sessionId = cookie.mid(pos, end >= 0 ? end - pos : end); sessionId = cookie.mid(pos, end >= 0 ? end - pos : end);
@ -153,16 +152,13 @@ bool AbstractWebApplication::sessionInitialize()
// TODO: Additional session check // TODO: Additional session check
if (!sessionId.isNull()) if (!sessionId.isNull()) {
{ if (sessions_.contains(sessionId)) {
if (sessions_.contains(sessionId))
{
session_ = sessions_[sessionId]; session_ = sessions_[sessionId];
session_->updateTimestamp(); session_->updateTimestamp();
return true; return true;
} }
else else {
{
qDebug() << Q_FUNC_INFO << "session does not exist!"; qDebug() << Q_FUNC_INFO << "session does not exist!";
} }
} }
@ -179,15 +175,12 @@ bool AbstractWebApplication::readFile(const QString& path, QByteArray &data, QSt
ext = path.mid(index); ext = path.mid(index);
// find translated file in cache // find translated file in cache
if (translatedFiles_.contains(path)) if (translatedFiles_.contains(path)) {
{
data = translatedFiles_[path]; data = translatedFiles_[path];
} }
else else {
{
QFile file(path); QFile file(path);
if (!file.open(QIODevice::ReadOnly)) if (!file.open(QIODevice::ReadOnly)) {
{
qDebug("File %s was not found!", qPrintable(path)); qDebug("File %s was not found!", qPrintable(path));
return false; return false;
} }
@ -196,15 +189,12 @@ bool AbstractWebApplication::readFile(const QString& path, QByteArray &data, QSt
file.close(); file.close();
// Translate the file // Translate the file
if ((ext == "html") || ((ext == "js") && !path.endsWith("excanvas-compressed.js"))) if ((ext == "html") || ((ext == "js") && !path.endsWith("excanvas-compressed.js"))) {
{
QString dataStr = QString::fromUtf8(data.constData()); QString dataStr = QString::fromUtf8(data.constData());
translateDocument(dataStr); translateDocument(dataStr);
if (path.endsWith("about.html")) if (path.endsWith("about.html"))
{
dataStr.replace("${VERSION}", VERSION); dataStr.replace("${VERSION}", VERSION);
}
data = dataStr.toUtf8(); data = dataStr.toUtf8();
translatedFiles_[path] = data; // cashing translated file translatedFiles_[path] = data; // cashing translated file
@ -227,8 +217,7 @@ QString AbstractWebApplication::generateSid()
QString sid; QString sid;
qsrand(QDateTime::currentDateTime().toTime_t()); qsrand(QDateTime::currentDateTime().toTime_t());
do do {
{
const size_t size = 6; const size_t size = 6;
quint32 tmp[size]; quint32 tmp[size];
@ -260,20 +249,16 @@ void AbstractWebApplication::translateDocument(QString& data)
const QString locale = Preferences::instance()->getLocale(); const QString locale = Preferences::instance()->getLocale();
bool isTranslationNeeded = !locale.startsWith("en") || locale.startsWith("en_AU") || locale.startsWith("en_GB"); bool isTranslationNeeded = !locale.startsWith("en") || locale.startsWith("en_AU") || locale.startsWith("en_GB");
while(i < data.size() && found) while(i < data.size() && found) {
{
i = regex.indexIn(data, i); i = regex.indexIn(data, i);
if (i >= 0) if (i >= 0) {
{
//qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data()); //qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data());
QByteArray word = regex.cap(1).toUtf8(); QByteArray word = regex.cap(1).toUtf8();
QString translation = word; QString translation = word;
if (isTranslationNeeded) if (isTranslationNeeded) {
{
size_t context_index = 0; size_t context_index = 0;
while ((context_index < context_count) && (translation == word)) while ((context_index < context_count) && (translation == word)) {
{
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1); translation = qApp->translate(contexts[context_index].c_str(), word.constData(), 0, QCoreApplication::UnicodeUTF8, 1);
#else #else
@ -288,8 +273,7 @@ void AbstractWebApplication::translateDocument(QString& data)
data.replace(i, regex.matchedLength(), translation); data.replace(i, regex.matchedLength(), translation);
i += translation.length(); i += translation.length();
} }
else else {
{
found = false; // no more translatable strings found = false; // no more translatable strings
} }
} }
@ -315,8 +299,7 @@ void AbstractWebApplication::increaseFailedAttempts()
const int nb_fail = clientFailedAttempts_.value(env_.clientAddress, 0) + 1; const int nb_fail = clientFailedAttempts_.value(env_.clientAddress, 0) + 1;
clientFailedAttempts_[env_.clientAddress] = nb_fail; clientFailedAttempts_[env_.clientAddress] = nb_fail;
if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) {
{
// Max number of failed attempts reached // Max number of failed attempts reached
// Start ban period // Start ban period
UnbanTimer* ubantimer = new UnbanTimer(env_.clientAddress, this); UnbanTimer* ubantimer = new UnbanTimer(env_.clientAddress, this);
@ -347,8 +330,7 @@ void AbstractWebApplication::printFile(const QString& path)
bool AbstractWebApplication::sessionStart() bool AbstractWebApplication::sessionStart()
{ {
if (session_ == 0) if (session_ == 0) {
{
session_ = new WebSession(generateSid()); session_ = new WebSession(generateSid());
session_->updateTimestamp(); session_->updateTimestamp();
sessions_[session_->id] = session_; sessions_[session_->id] = session_;
@ -365,8 +347,7 @@ bool AbstractWebApplication::sessionStart()
bool AbstractWebApplication::sessionEnd() bool AbstractWebApplication::sessionEnd()
{ {
if ((session_ != 0) && (sessions_.contains(session_->id))) if ((session_ != 0) && (sessions_.contains(session_->id))) {
{
QNetworkCookie cookie(C_SID, session_->id.toUtf8()); QNetworkCookie cookie(C_SID, session_->id.toUtf8());
cookie.setPath(QLatin1String("/")); cookie.setPath(QLatin1String("/"));
cookie.setExpirationDate(QDateTime::currentDateTime()); cookie.setExpirationDate(QDateTime::currentDateTime());

Loading…
Cancel
Save