summaryrefslogtreecommitdiffstats
path: root/src/gui/clientFileReceiveDialog.cpp
blob: fc6a1a34b1b5d3a1a4b64c311e3ddcb8841582f9 (plain) (blame)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
 # Copyright (c) 2009, 2010 - OpenSLX Project, Computer Center University of
 # Freiburg
 #
 # This program is free software distributed under the GPL version 2.
 # See http://openslx.org/COPYING
 #
 # If you have any feedback please consult http://openslx.org/feedback and
 # send your suggestions, praise, or complaints to feedback@openslx.org
 #
 # General information about OpenSLX can be found at http://openslx.org/
 # -----------------------------------------------------------------------------
 # clientFileReceiveDialog.cpp
 #  - filechooser and progress dialog
 # -----------------------------------------------------------------------------
 */

#include "clientFileReceiveDialog.h"
#include <pvsinterface.h>
#include <QFileInfo>
#include <limits.h>

ClientFileReceiveDialog::ClientFileReceiveDialog(QTcpSocket *socket, QWidget *parent) :
        QDialog(parent)
{
    setupUi(this);

    _file = NULL;
    _bytesToRead = 0;
    _socket = socket;

    connect(_socket, SIGNAL(readyRead()), this, SLOT(receiveHeader()));
    connect(_socket, SIGNAL(disconnected()), this, SLOT(close()));
    connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)),
                this, SLOT(error(QAbstractSocket::SocketError)));

    qDebug("[%s] New Connection: %s", metaObject()->className(),
            qPrintable(_socket->peerAddress().toString()));

    connect(this, SIGNAL(finished(int)), this, SLOT(deleteLater()));
}

ClientFileReceiveDialog::ClientFileReceiveDialog(QString const& sender, qulonglong transferID,
        QString const& filename, qulonglong size, OrgOpenslxPvsInterface* ifaceDBus, QWidget* parent)
{
    setupUi(this);

    _transferID = transferID;
    _filename = filename;
    _ifaceDBus = ifaceDBus;
    _bytesToRead = size;
    _socket = 0;
    _file = 0;
    div = 1;
    while((size / div) > INT_MAX)
    {
        div <<= 1;
    }

    connect(ifaceDBus, SIGNAL(incomingMulticastTransferStarted(qulonglong)), SLOT(mcastTransferStarted(qulonglong)));
    connect(ifaceDBus, SIGNAL(incomingMulticastTransferProgress(qulonglong, qulonglong, qulonglong)),
            SLOT(mcastTransferProgress(qulonglong, qulonglong, qulonglong)));
    connect(ifaceDBus, SIGNAL(incomingMulticastTransferFinished(qulonglong)), SLOT(mcastTransferFinished(qulonglong)));
    connect(ifaceDBus, SIGNAL(incomingMulticastTransferFailed(qulonglong, QString)), SLOT(mcastTransferFailed(qulonglong, QString)));
    connect(cancelButton, SIGNAL(clicked()), SLOT(cancelTransfer()));

    qDebug("[%s] New multicast incoming transfer: %s from %s", metaObject()->className(),
            filename.toLocal8Bit().constData(), sender.toLocal8Bit().constData());


    filenameLabel->setText(QFileInfo(filename).baseName());
    labelNick->setText(sender);
    progressBar->setRange(0, 0);
}


ClientFileReceiveDialog::~ClientFileReceiveDialog()
{
    if(_socket)
        _socket->deleteLater();
    qDebug("[%s] Deleted!", metaObject()->className());
}

////////////////////////////////////////////////////////////////////////////////
// Private

void ClientFileReceiveDialog::receiveHeader()
{
    // parse header
    QString header = QString::fromUtf8(_socket->readLine());
    QStringList args = header.split(";");
    QString nick = args[0];
    QString filename = args[1];
    _bytesToRead = args[2].toLongLong();
    div = 1 + _bytesToRead / 1000000000; // bc. progressBar supports only int

    qDebug("[%s] Received header.", metaObject()->className());

    // ask user
    QMessageBox::StandardButton result = QMessageBox::question(0,
            tr("PVS File Transfer"),tr("User '") + nick +
            tr("' would like to send you a file: ") + filename +
            " (" + formatSize(_bytesToRead) + ").",
            QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok);

    if (result !=  QMessageBox::Ok)
    {
    	sendAck(false);
        return;
    }

    // open file
    QString saveAs = QFileDialog::getSaveFileName(this, tr("Open File"),
            QDir::homePath() + QDir::separator() + filename, "");
    if (saveAs == "")
    {
    	sendAck(false);
        return;
    }
    _file = new QFile(saveAs);
    _file->open(QIODevice::WriteOnly);

    // gui
    filenameLabel->setText(saveAs);
    progressBar->setValue(0);
    progressBar->setMaximum(_bytesToRead/div);
    labelNick->setText(nick);
    labelB->setText(formatSize(_bytesToRead));
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));

	sendAck(true);
	show();
}

void ClientFileReceiveDialog::sendAck(bool b)
{
	disconnect(_socket, SIGNAL(readyRead()), this, SLOT(receiveHeader()));

	if (b)
	{
		QString ack = QString("ok\n");
		_socket->write(ack.toUtf8());
		qDebug("[%s] Sending ack...", metaObject()->className());
		connect(_socket, SIGNAL(readyRead()), this, SLOT(receiveFile()));
	}
	else
	{
		QString ack = QString("no\n");
		_socket->write(ack.toUtf8());
		qDebug("[%s] Sending nack!!!", metaObject()->className());
		close();
	}
}

void ClientFileReceiveDialog::receiveFile()
{
	qint64 bytesRead = _file->write(_socket->readAll());
	_bytesToRead -= bytesRead;
	progressBar->setValue(progressBar->value() + bytesRead/div);
	labelA->setText(formatSize(progressBar->value()*div));
}

void ClientFileReceiveDialog::close()
{
    if (_file && _file->isOpen())
    {
    	_file->flush();
    	_file->close();
    	qDebug("[%s] File closed.", metaObject()->className());
    }

    if (_socket && _socket->isOpen())
    {
        disconnect(_socket, SIGNAL(readyRead()), this, SLOT(receiveHeader()));
        disconnect(_socket, SIGNAL(readyRead()), this, SLOT(receiveFile()));
        disconnect(_socket, SIGNAL(disconnected()), this, SLOT(close()));
        disconnect(_socket, SIGNAL(error(QAbstractSocket::SocketError)),
                            this, SLOT(error(QAbstractSocket::SocketError)));
        _socket->disconnectFromHost();
    	qDebug("[%s] Connection closed.", metaObject()->className());
    }

    disconnect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));

    if (_bytesToRead == 0)
    {
    	accept();
    	QMessageBox::information(0, tr("PVS - File Transfer"),
    	        tr("File Transfer complete."));
    }
    else
    {
    	reject();
    	QMessageBox::warning(0, tr("PVS - File Transfer"),
    	        tr("File Transfer canceled!"));
    }
}

void ClientFileReceiveDialog::error(QAbstractSocket::SocketError error)
{
    if (error == QAbstractSocket::RemoteHostClosedError)
        qDebug("[%s] Socket closed by remote host.", metaObject()->className());
    else
        qDebug("[%s] Socket error: %i", metaObject()->className(), error);

    close();
}

void ClientFileReceiveDialog::mcastTransferStarted(qulonglong transferID)
{
    if(transferID != _transferID)
        return;
}

void ClientFileReceiveDialog::mcastTransferProgress(qulonglong transferID, qulonglong bytes, qulonglong of)
{
    if(transferID != _transferID)
        return;

    progressBar->setRange(0, of);
    progressBar->setValue(bytes);

    labelA->setText(formatSize(bytes));
    labelB->setText(formatSize(of));
}

void ClientFileReceiveDialog::mcastTransferFinished(qulonglong transferID)
{
    if(transferID != _transferID)
        return;

    QString filename = QFileDialog::getSaveFileName(this, tr("Where should I save %1?").arg(_filename), _filename);
    QFile* file = new QFile(_filename);
    if(filename.isNull() || filename.isEmpty())
    {
    	file->remove();
    }
    else
    {
		if(!file->rename(filename))
		{
			QMessageBox::warning(this, tr("Could not rename file"), tr("Failed to rename %1 to %2").arg(_filename).arg(filename));
		}
    }
    accept();
    deleteLater();
}

void ClientFileReceiveDialog::mcastTransferFailed(qulonglong transferID, QString reason)
{
    if(transferID != _transferID)
        return;

    QMessageBox::warning(this, tr("File transfer failed"), tr("File transfer failed for the following reason:\n%1").arg(reason));
    reject();
    deleteLater();
}

void ClientFileReceiveDialog::cancelTransfer()
{
    _ifaceDBus->cancelIncomingMulticastTransfer(_transferID);
}

QString ClientFileReceiveDialog::formatSize(qint64 size)
{
    if (size >= 1000000000) // GB
        return QString("%1GB").arg((qreal)size / 1000000000, 0, 'f',1);
    else if (size >= 1000000) // MB
        return QString("%1MB").arg((qreal)size / 1000000, 0, 'f',1);
    else if (size >= 1000) // KB
        return QString("%1KB").arg((qreal)size / 1000, 0, 'f',1);
    else // B
        return QString("%1B").arg((qreal)size, 0, 'f',1);
}