Browse Source

Web UI code cleanup

adaptive-webui-19844
Christophe Dumez 13 years ago
parent
commit
e10a51e61e
  1. 220
      src/webui/httpconnection.cpp
  2. 16
      src/webui/httpconnection.h
  3. 106
      src/webui/httprequestparser.cpp
  4. 44
      src/webui/httprequestparser.h

220
src/webui/httpconnection.cpp

@ -54,61 +54,59 @@
using namespace libtorrent; using namespace libtorrent;
HttpConnection::HttpConnection(QTcpSocket *socket, HttpServer *parent) HttpConnection::HttpConnection(QTcpSocket *socket, HttpServer *parent)
: QObject(parent), socket(socket), httpserver(parent) : QObject(parent), m_socket(socket), m_httpserver(parent)
{ {
socket->setParent(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(read()));
connect(socket, SIGNAL(disconnected()), this, SLOT(deleteLater()));
m_needsTranslation = !Preferences().getLocale().startsWith("en"); m_needsTranslation = !Preferences().getLocale().startsWith("en");
m_socket->setParent(this);
connect(m_socket, SIGNAL(readyRead()), SLOT(read()));
connect(m_socket, SIGNAL(disconnected()), SLOT(deleteLater()));
} }
HttpConnection::~HttpConnection() HttpConnection::~HttpConnection()
{ {
delete socket; delete m_socket;
} }
void HttpConnection::processDownloadedFile(QString url, QString file_path) { void HttpConnection::processDownloadedFile(const QString &url,
qDebug("URL %s successfully downloaded !", (const char*)url.toLocal8Bit()); const QString &file_path) {
qDebug("URL %s successfully downloaded !", qPrintable(url));
emit torrentReadyToBeDownloaded(file_path, false, url, false); emit torrentReadyToBeDownloaded(file_path, false, url, false);
} }
void HttpConnection::handleDownloadFailure(QString url, QString reason) { void HttpConnection::handleDownloadFailure(const QString& url,
std::cerr << "Could not download " << (const char*)url.toLocal8Bit() << ", reason: " << (const char*)reason.toLocal8Bit() << "\n"; const QString& reason) {
std::cerr << "Could not download " << qPrintable(url) << ", reason: "
<< qPrintable(reason) << std::endl;
} }
void HttpConnection::read() void HttpConnection::read() {
{ QByteArray input = m_socket->readAll();
QByteArray input = socket->readAll();
/*qDebug(" -------");
qDebug("|REQUEST|");
qDebug(" -------"); */
//qDebug("%s", input.toAscii().constData());
if(input.size() > 100000) { if(input.size() > 100000) {
qDebug("Request too big"); qDebug("Request too big");
generator.setStatusLine(400, "Bad Request"); m_generator.setStatusLine(400, "Bad Request");
write(); write();
return; return;
} }
parser.write(input); m_parser.write(input);
if(parser.isError()) if(m_parser.isError())
{ {
generator.setStatusLine(400, "Bad Request"); m_generator.setStatusLine(400, "Bad Request");
write(); write();
} }
else else
if (parser.isParsable()) if (m_parser.isParsable())
respond(); respond();
} }
void HttpConnection::write() void HttpConnection::write()
{ {
QByteArray output = generator.toByteArray(); QByteArray output = m_generator.toByteArray();
/*qDebug(" --------"); /*qDebug(" --------");
qDebug("|RESPONSE|"); qDebug("|RESPONSE|");
qDebug(" --------"); qDebug(" --------");
qDebug()<<output;*/ qDebug()<<output;*/
socket->write(output); m_socket->write(output);
socket->disconnectFromHost(); m_socket->disconnectFromHost();
} }
void HttpConnection::translateDocument(QString& data) { void HttpConnection::translateDocument(QString& data) {
@ -151,50 +149,50 @@ void HttpConnection::translateDocument(QString& data) {
} }
void HttpConnection::respond() { void HttpConnection::respond() {
if((socket->peerAddress() != QHostAddress::LocalHost && socket->peerAddress() != QHostAddress::LocalHostIPv6) if((m_socket->peerAddress() != QHostAddress::LocalHost && m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
|| httpserver->isLocalAuthEnabled()) { || m_httpserver->isLocalAuthEnabled()) {
// Authentication // Authentication
const QString peer_ip = socket->peerAddress().toString(); const QString peer_ip = m_socket->peerAddress().toString();
const int nb_fail = httpserver->NbFailedAttemptsForIp(peer_ip); const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip);
if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) { if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
generator.setStatusLine(403, "Forbidden"); m_generator.setStatusLine(403, "Forbidden");
generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts.")); m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
write(); write();
return; return;
} }
QString auth = parser.value("Authorization"); QString auth = m_parser.value("Authorization");
if(auth.isEmpty()) { if(auth.isEmpty()) {
// Return unauthorized header // Return unauthorized header
qDebug("Auth is Empty..."); qDebug("Auth is Empty...");
generator.setStatusLine(401, "Unauthorized"); m_generator.setStatusLine(401, "Unauthorized");
generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+httpserver->generateNonce()+"\", opaque=\""+httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\""); m_generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
write(); write();
return; return;
} }
//qDebug("Auth: %s", qPrintable(auth.split(" ").first())); //qDebug("Auth: %s", qPrintable(auth.split(" ").first()));
if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0 || !httpserver->isAuthorized(auth.toLocal8Bit(), parser.method())) { if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0 || !m_httpserver->isAuthorized(auth.toLocal8Bit(), m_parser.method())) {
// Update failed attempt counter // Update failed attempt counter
httpserver->increaseNbFailedAttemptsForIp(peer_ip); m_httpserver->increaseNbFailedAttemptsForIp(peer_ip);
qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail+1); qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail+1);
// Return unauthorized header // Return unauthorized header
generator.setStatusLine(401, "Unauthorized"); m_generator.setStatusLine(401, "Unauthorized");
generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+httpserver->generateNonce()+"\", opaque=\""+httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\""); m_generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
write(); write();
return; return;
} }
// Client successfully authenticated, reset number of failed attempts // Client successfully authenticated, reset number of failed attempts
httpserver->resetNbFailedAttemptsForIp(peer_ip); m_httpserver->resetNbFailedAttemptsForIp(peer_ip);
} }
QString url = parser.url(); QString url = m_parser.url();
// Favicon // Favicon
if(url.endsWith("favicon.ico")) { if(url.endsWith("favicon.ico")) {
qDebug("Returning favicon"); qDebug("Returning favicon");
QFile favicon(":/Icons/skin/qbittorrent16.png"); QFile favicon(":/Icons/skin/qbittorrent16.png");
if(favicon.open(QIODevice::ReadOnly)) { if(favicon.open(QIODevice::ReadOnly)) {
QByteArray data = favicon.readAll(); QByteArray data = favicon.readAll();
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("png"); m_generator.setContentTypeByExt("png");
generator.setMessage(data); m_generator.setMessage(data);
write(); write();
} else { } else {
respondNotFound(); respondNotFound();
@ -250,7 +248,7 @@ void HttpConnection::respond() {
{ {
QString command = list[1]; QString command = list[1];
respondCommand(command); respondCommand(command);
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
write(); write();
return; return;
} }
@ -298,61 +296,61 @@ void HttpConnection::respond() {
} }
data = dataStr.toUtf8(); data = dataStr.toUtf8();
} }
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt(ext); m_generator.setContentTypeByExt(ext);
generator.setMessage(data); m_generator.setMessage(data);
write(); write();
} }
void HttpConnection::respondNotFound() void HttpConnection::respondNotFound()
{ {
generator.setStatusLine(404, "File not found"); m_generator.setStatusLine(404, "File not found");
write(); write();
} }
void HttpConnection::respondJson() void HttpConnection::respondJson()
{ {
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
QString string = json::toJson(manager->getEventList()); QString string = json::toJson(manager->getEventList());
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
void HttpConnection::respondGenPropertiesJson(QString hash) { void HttpConnection::respondGenPropertiesJson(QString hash) {
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
QString string = json::toJson(manager->getPropGeneralInfo(hash)); QString string = json::toJson(manager->getPropGeneralInfo(hash));
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
void HttpConnection::respondTrackersPropertiesJson(QString hash) { void HttpConnection::respondTrackersPropertiesJson(QString hash) {
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
QString string = json::toJson(manager->getPropTrackersInfo(hash)); QString string = json::toJson(manager->getPropTrackersInfo(hash));
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
void HttpConnection::respondFilesPropertiesJson(QString hash) { void HttpConnection::respondFilesPropertiesJson(QString hash) {
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
QString string = json::toJson(manager->getPropFilesInfo(hash)); QString string = json::toJson(manager->getPropFilesInfo(hash));
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
void HttpConnection::respondPreferencesJson() { void HttpConnection::respondPreferencesJson() {
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
QString string = json::toJson(manager->getGlobalPreferences()); QString string = json::toJson(manager->getGlobalPreferences());
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
@ -362,9 +360,9 @@ void HttpConnection::respondGlobalTransferInfoJson() {
info["DlInfos"] = tr("D: %1/s - T: %2", "Download speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_download_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_download)); info["DlInfos"] = tr("D: %1/s - T: %2", "Download speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_download_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_download));
info["UpInfos"] = tr("U: %1/s - T: %2", "Upload speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_upload_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_upload)); info["UpInfos"] = tr("U: %1/s - T: %2", "Upload speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_upload_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_upload));
QString string = json::toJson(info); QString string = json::toJson(info);
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); m_generator.setContentTypeByExt("js");
generator.setMessage(string); m_generator.setMessage(string);
write(); write();
} }
@ -372,7 +370,7 @@ void HttpConnection::respondCommand(QString command)
{ {
if(command == "download") if(command == "download")
{ {
QString urls = parser.post("urls"); QString urls = m_parser.post("urls");
QStringList list = urls.split('\n'); QStringList list = urls.split('\n');
foreach(QString url, list){ foreach(QString url, list){
url = url.trimmed(); url = url.trimmed();
@ -392,11 +390,11 @@ void HttpConnection::respondCommand(QString command)
return; return;
} }
if(command == "addTrackers") { if(command == "addTrackers") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
if(!hash.isEmpty()) { if(!hash.isEmpty()) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if(h.is_valid() && h.has_metadata()) {
QString urls = parser.post("urls"); QString urls = m_parser.post("urls");
QStringList list = urls.split('\n'); QStringList list = urls.split('\n');
foreach(QString url, list) { foreach(QString url, list) {
announce_entry e(url.toStdString()); announce_entry e(url.toStdString());
@ -413,7 +411,7 @@ void HttpConnection::respondCommand(QString command)
// it fails to load on Windows. // it fails to load on Windows.
QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent")); QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent"));
if (tmpfile->open()) { if (tmpfile->open()) {
tmpfile->write(parser.torrent()); tmpfile->write(m_parser.torrent());
tmpfile->close(); tmpfile->close();
emit torrentReadyToBeDownloaded(tmpfile->fileName(), false, QString(), false); emit torrentReadyToBeDownloaded(tmpfile->fileName(), false, QString(), false);
delete tmpfile; delete tmpfile;
@ -423,9 +421,9 @@ void HttpConnection::respondCommand(QString command)
return; return;
} }
// Prepare response // Prepare response
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
generator.setMessage(QString("<script type=\"text/javascript\">window.parent.hideAll();</script>")); m_generator.setMessage(QString("<script type=\"text/javascript\">window.parent.hideAll();</script>"));
write(); write();
return; return;
} }
@ -438,67 +436,67 @@ void HttpConnection::respondCommand(QString command)
return; return;
} }
if(command == "resume") { if(command == "resume") {
emit resumeTorrent(parser.post("hash")); emit resumeTorrent(m_parser.post("hash"));
return; return;
} }
if(command == "setPreferences") { if(command == "setPreferences") {
QString json_str = parser.post("json"); QString json_str = m_parser.post("json");
EventManager* manager = httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
manager->setGlobalPreferences(json::fromJson(json_str)); manager->setGlobalPreferences(json::fromJson(json_str));
m_needsTranslation = !Preferences().getLocale().startsWith("en"); m_needsTranslation = !Preferences().getLocale().startsWith("en");
} }
if(command == "setFilePrio") { if(command == "setFilePrio") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
int file_id = parser.post("id").toInt(); int file_id = m_parser.post("id").toInt();
int priority = parser.post("priority").toInt(); int priority = m_parser.post("priority").toInt();
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if(h.is_valid() && h.has_metadata()) {
h.file_priority(file_id, priority); h.file_priority(file_id, priority);
} }
} }
if(command == "getGlobalUpLimit") { if(command == "getGlobalUpLimit") {
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
generator.setMessage(QString::number(QBtSession::instance()->getSession()->settings().upload_rate_limit)); generator.setMessage(QString::number(QBtSession::instance()->getSession()->settings().upload_rate_limit));
#else #else
generator.setMessage(QString::number(QBtSession::instance()->getSession()->upload_rate_limit())); m_generator.setMessage(QString::number(QBtSession::instance()->getSession()->upload_rate_limit()));
#endif #endif
write(); write();
} }
if(command == "getGlobalDlLimit") { if(command == "getGlobalDlLimit") {
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
generator.setMessage(QString::number(QBtSession::instance()->getSession()->settings().download_rate_limit)); generator.setMessage(QString::number(QBtSession::instance()->getSession()->settings().download_rate_limit));
#else #else
generator.setMessage(QString::number(QBtSession::instance()->getSession()->download_rate_limit())); m_generator.setMessage(QString::number(QBtSession::instance()->getSession()->download_rate_limit()));
#endif #endif
write(); write();
} }
if(command == "getTorrentUpLimit") { if(command == "getTorrentUpLimit") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
generator.setMessage(QString::number(h.upload_limit())); m_generator.setMessage(QString::number(h.upload_limit()));
write(); write();
} }
} }
if(command == "getTorrentDlLimit") { if(command == "getTorrentDlLimit") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
generator.setMessage(QString::number(h.download_limit())); m_generator.setMessage(QString::number(h.download_limit()));
write(); write();
} }
} }
if(command == "setTorrentUpLimit") { if(command == "setTorrentUpLimit") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
@ -506,8 +504,8 @@ void HttpConnection::respondCommand(QString command)
} }
} }
if(command == "setTorrentDlLimit") { if(command == "setTorrentDlLimit") {
QString hash = parser.post("hash"); QString hash = m_parser.post("hash");
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
@ -515,59 +513,59 @@ void HttpConnection::respondCommand(QString command)
} }
} }
if(command == "setGlobalUpLimit") { if(command == "setGlobalUpLimit") {
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QBtSession::instance()->setUploadRateLimit(limit); QBtSession::instance()->setUploadRateLimit(limit);
Preferences().setGlobalUploadLimit(limit/1024.); Preferences().setGlobalUploadLimit(limit/1024.);
} }
if(command == "setGlobalDlLimit") { if(command == "setGlobalDlLimit") {
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QBtSession::instance()->setDownloadRateLimit(limit); QBtSession::instance()->setDownloadRateLimit(limit);
Preferences().setGlobalDownloadLimit(limit/1024.); Preferences().setGlobalDownloadLimit(limit/1024.);
} }
if(command == "pause") { if(command == "pause") {
emit pauseTorrent(parser.post("hash")); emit pauseTorrent(m_parser.post("hash"));
return; return;
} }
if(command == "delete") { if(command == "delete") {
QStringList hashes = parser.post("hashes").split("|"); QStringList hashes = m_parser.post("hashes").split("|");
foreach(const QString &hash, hashes) { foreach(const QString &hash, hashes) {
emit deleteTorrent(hash, false); emit deleteTorrent(hash, false);
} }
return; return;
} }
if(command == "deletePerm") { if(command == "deletePerm") {
QStringList hashes = parser.post("hashes").split("|"); QStringList hashes = m_parser.post("hashes").split("|");
foreach(const QString &hash, hashes) { foreach(const QString &hash, hashes) {
emit deleteTorrent(hash, true); emit deleteTorrent(hash, true);
} }
return; return;
} }
if(command == "increasePrio") { if(command == "increasePrio") {
increaseTorrentsPriority(parser.post("hashes").split("|")); increaseTorrentsPriority(m_parser.post("hashes").split("|"));
return; return;
} }
if(command == "decreasePrio") { if(command == "decreasePrio") {
decreaseTorrentsPriority(parser.post("hashes").split("|")); decreaseTorrentsPriority(m_parser.post("hashes").split("|"));
return; return;
} }
if(command == "topPrio") { if(command == "topPrio") {
foreach(const QString &hash, parser.post("hashes").split("|")) { foreach(const QString &hash, m_parser.post("hashes").split("|")) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) h.queue_position_top(); if(h.is_valid()) h.queue_position_top();
} }
return; return;
} }
if(command == "bottomPrio") { if(command == "bottomPrio") {
foreach(const QString &hash, parser.post("hashes").split("|")) { foreach(const QString &hash, m_parser.post("hashes").split("|")) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) h.queue_position_bottom(); if(h.is_valid()) h.queue_position_bottom();
} }
return; return;
} }
if(command == "recheck"){ if(command == "recheck"){
recheckTorrent(parser.post("hash")); recheckTorrent(m_parser.post("hash"));
return; return;
} }
if(command == "recheckall"){ if(command == "recheckall"){

16
src/webui/httpconnection.h

@ -48,7 +48,7 @@ class HttpConnection : public QObject
Q_DISABLE_COPY(HttpConnection) Q_DISABLE_COPY(HttpConnection)
public: public:
HttpConnection(QTcpSocket *socket, HttpServer *httpserver); HttpConnection(QTcpSocket *m_socket, HttpServer *m_httpserver);
~HttpConnection(); ~HttpConnection();
void translateDocument(QString& data); void translateDocument(QString& data);
@ -63,8 +63,8 @@ protected slots:
void respondGlobalTransferInfoJson(); void respondGlobalTransferInfoJson();
void respondCommand(QString command); void respondCommand(QString command);
void respondNotFound(); void respondNotFound();
void processDownloadedFile(QString, QString); void processDownloadedFile(const QString& url, const QString& file_path);
void handleDownloadFailure(QString, QString); void handleDownloadFailure(const QString& url, const QString& reason);
void recheckTorrent(QString hash); void recheckTorrent(QString hash);
void recheckAllTorrents(); void recheckAllTorrents();
void decreaseTorrentsPriority(const QStringList& hashes); void decreaseTorrentsPriority(const QStringList& hashes);
@ -86,12 +86,10 @@ signals:
void pauseAllTorrents(); void pauseAllTorrents();
private: private:
QTcpSocket *socket; QTcpSocket *m_socket;
HttpServer *httpserver; HttpServer *m_httpserver;
HttpRequestParser m_parser;
private: HttpResponseGenerator m_generator;
HttpRequestParser parser;
HttpResponseGenerator generator;
bool m_needsTranslation; bool m_needsTranslation;
}; };

106
src/webui/httprequestparser.cpp

@ -33,11 +33,9 @@
#include <QUrl> #include <QUrl>
#include <QDebug> #include <QDebug>
HttpRequestParser::HttpRequestParser() HttpRequestParser::HttpRequestParser(): m_headerDone(false),
m_messageDone(false), m_error(false)
{ {
headerDone = false;
messageDone = false;
error = false;
} }
HttpRequestParser::~HttpRequestParser() HttpRequestParser::~HttpRequestParser()
@ -46,103 +44,89 @@ HttpRequestParser::~HttpRequestParser()
bool HttpRequestParser::isParsable() const bool HttpRequestParser::isParsable() const
{ {
return !error && headerDone && isValid() && (messageDone || !hasContentLength() || contentLength() == 0); return !m_error && m_headerDone && isValid()
&& (m_messageDone || !hasContentLength() || contentLength() == 0);
} }
bool HttpRequestParser::isError() const bool HttpRequestParser::isError() const
{ {
return error; return m_error;
} }
QString HttpRequestParser::url() const QString HttpRequestParser::url() const
{ {
return path; return m_path;
} }
QByteArray HttpRequestParser::message() const QByteArray HttpRequestParser::message() const
{ {
if(isParsable()) if(isParsable())
return data; return m_data;
return QByteArray(); return QByteArray();
} }
QString HttpRequestParser::get(const QString key) const QString HttpRequestParser::get(const QString& key) const
{ {
return getMap.value(key); return m_getMap.value(key);
} }
QString HttpRequestParser::post(const QString key) const QString HttpRequestParser::post(const QString& key) const
{ {
return postMap.value(key); return m_postMap.value(key);
} }
QByteArray HttpRequestParser::torrent() const QByteArray HttpRequestParser::torrent() const
{ {
return torrent_content; return m_torrentContent;
} }
void HttpRequestParser::write(QByteArray str) void HttpRequestParser::write(QByteArray ba)
{ {
while (!headerDone && str.size()>0) while (!m_headerDone && !ba.isEmpty()) {
{ const int index = ba.indexOf('\n') + 1;
int index = str.indexOf('\n') + 1; if(index == 0) {
if(index == 0) m_data += ba;
{ ba.clear();
data += str; } else {
str.clear(); m_data += ba.left(index);
} ba.remove(0, index);
else if(m_data.right(4) == "\r\n\r\n") {
{ QHttpRequestHeader::operator=(QHttpRequestHeader(m_data));
data += str.left(index); m_headerDone = true;
str.remove(0, index); m_data.clear();
if(data.right(4) == "\r\n\r\n")
{
QHttpRequestHeader::operator=(QHttpRequestHeader(data));
headerDone = true;
data.clear();
QUrl url = QUrl::fromEncoded(QHttpRequestHeader::path().toAscii()); QUrl url = QUrl::fromEncoded(QHttpRequestHeader::path().toAscii());
path = url.path(); m_path = url.path();
//() << path;
QListIterator<QPair<QString, QString> > i(url.queryItems()); QListIterator<QPair<QString, QString> > i(url.queryItems());
while (i.hasNext()) while (i.hasNext()) {
{
QPair<QString, QString> pair = i.next(); QPair<QString, QString> pair = i.next();
getMap[pair.first] = pair.second; m_getMap[pair.first] = pair.second;
//qDebug() << pair.first << "=" << get(pair.first);
} }
} }
} }
} }
if(!messageDone && str.size()>0) if(!m_messageDone && !ba.isEmpty()) {
{ if(hasContentLength()) {
if(hasContentLength()) m_data += ba;
{ if(m_data.size() >= (int) contentLength()) {
data += str; m_data.resize(contentLength());
if(data.size() >= (int) contentLength()) m_messageDone = true;
{
data.resize(contentLength());
messageDone = true;
//parse POST data //parse POST data
if(contentType() == "application/x-www-form-urlencoded") if(contentType() == "application/x-www-form-urlencoded") {
{
QUrl url; QUrl url;
url.setEncodedQuery(data); url.setEncodedQuery(m_data);
QListIterator<QPair<QString, QString> > i(url.queryItems()); QListIterator<QPair<QString, QString> > i(url.queryItems());
while (i.hasNext()) while (i.hasNext()) {
{
QPair<QString, QString> pair = i.next(); QPair<QString, QString> pair = i.next();
postMap[pair.first] = pair.second; m_postMap[pair.first] = pair.second;
//qDebug() << pair.first << "=" << post(pair.first);
} }
} }
if(contentType() == "multipart/form-data") if(contentType() == "multipart/form-data") {
{ m_torrentContent = m_data.right(m_data.size()-m_data.indexOf("\r\n\r\n")-QByteArray("\r\n\r\n").size());
//qDebug() << data.right(data.size()-data.indexOf("\r\n\r\n")-QByteArray("\r\n\r\n").size());
torrent_content = data.right(data.size()-data.indexOf("\r\n\r\n")-QByteArray("\r\n\r\n").size());
} }
} }
} } else {
else m_error = true;
error = true; }
} }
} }

44
src/webui/httprequestparser.h

@ -34,29 +34,29 @@
#include<QHttpRequestHeader> #include<QHttpRequestHeader>
class HttpRequestParser : public QHttpRequestHeader class HttpRequestParser : public QHttpRequestHeader {
{
private:
bool headerDone;
bool messageDone;
bool error;
QByteArray data;
QString path;
QMap<QString, QString> postMap;
QMap<QString, QString> getMap;
QByteArray torrent_content;
public: public:
HttpRequestParser(); HttpRequestParser();
~HttpRequestParser(); ~HttpRequestParser();
bool isParsable() const; bool isParsable() const;
bool isError() const; bool isError() const;
QString url() const; QString url() const;
QByteArray message() const; QByteArray message() const;
QString get(const QString key) const; QString get(const QString& key) const;
QString post(const QString key) const; QString post(const QString& key) const;
QByteArray torrent() const; QByteArray torrent() const;
void write(QByteArray str); void write(QByteArray ba);
private:
bool m_headerDone;
bool m_messageDone;
bool m_error;
QByteArray m_data;
QString m_path;
QMap<QString, QString> m_postMap;
QMap<QString, QString> m_getMap;
QByteArray m_torrentContent;
}; };
#endif #endif

Loading…
Cancel
Save