This repository has been archived by the owner on Mar 3, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
Connection.cpp
78 lines (67 loc) · 2.35 KB
/
Connection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "Connection.h"
#include "WebPage.h"
#include "WebPageManager.h"
#include "CommandParser.h"
#include "CommandFactory.h"
#include "PageLoadingCommand.h"
#include "TimeoutCommand.h"
#include "SocketCommand.h"
#include "ErrorMessage.h"
#include <QTcpSocket>
Connection::Connection(QTcpSocket *socket, WebPageManager *manager, QObject *parent) :
QObject(parent) {
m_socket = socket;
m_manager = manager;
m_commandFactory = new CommandFactory(m_manager, this);
m_commandParser = new CommandParser(socket, m_commandFactory, this);
m_pageSuccess = true;
m_pendingCommand = NULL;
connect(m_socket, SIGNAL(readyRead()), m_commandParser, SLOT(checkNext()));
connect(m_commandParser, SIGNAL(commandReady(Command *)), this, SLOT(commandReady(Command *)));
connect(m_manager, SIGNAL(pageFinished(bool)), this, SLOT(pendingLoadFinished(bool)));
}
void Connection::commandReady(Command *command) {
m_manager->log() << "Received" << command->toString();
startCommand(command);
}
void Connection::startCommand(Command *command) {
if (m_pendingCommand) {
m_pendingCommand->deleteLater();
}
if (m_pageSuccess) {
m_pendingCommand = new TimeoutCommand(new PageLoadingCommand(command, m_manager, this), m_manager, this);
connect(m_pendingCommand, SIGNAL(finished(Response *)), this, SLOT(finishCommand(Response *)));
m_pendingCommand->start();
} else {
writePageLoadFailure();
}
}
void Connection::pendingLoadFinished(bool success) {
m_pageSuccess = m_pageSuccess && success;
}
void Connection::writePageLoadFailure() {
m_pageSuccess = true;
QString message = currentPage()->failureString();
Response response(false, new ErrorMessage(message));
writeResponse(&response);
}
void Connection::finishCommand(Response *response) {
m_pageSuccess = true;
writeResponse(response);
sender()->deleteLater();
m_pendingCommand = NULL;
}
void Connection::writeResponse(Response *response) {
if (response->isSuccess())
m_socket->write("ok\n");
else
m_socket->write("failure\n");
m_manager->log() << "Wrote response" << response->isSuccess() << response->message();
QByteArray messageUtf8 = response->message();
QString messageLength = QString::number(messageUtf8.size()) + "\n";
m_socket->write(messageLength.toLatin1());
m_socket->write(messageUtf8);
}
WebPage *Connection::currentPage() {
return m_manager->currentPage();
}