~mateo-salta/nitroshare/nitroshare

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
/* NitroShare - A simple network file sharing tool.
   Copyright (C) 2012 Nathan Osman

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QVariantList>
#include <qjson/qobjecthelper.h>

#include <file/CFileSender.h>
#include <util/settings.h>

CFileSender::CFileSender(QObject * parent, QStringList filenames)
    : CBasicSocket(parent), m_state(WaitingForConnection),
      m_total_uncompressed(0), m_current_uncompressed(0)
{
    connect(this, SIGNAL(connected()),      SLOT(OnConnected()));
    connect(this, SIGNAL(Data(QByteArray)), SLOT(OnData(QByteArray)));

    /* Immediately begin preparing the headers for the transfer. */
    PrepareHeaders(filenames);
}

CFileSender::~CFileSender()
{
    qDeleteAll(m_headers);
}

void CFileSender::Start(CMachine machine)
{
    qDebug() << "Attempting connection to" << machine.address.toString() << "...";

    /* Once we know the information for connecting to the remote
       machine, we immediately attempt a connection. */
    connectToHost(machine.address, machine.port);
}

void CFileSender::OnConnected()
{
    qDebug() << "Connection with remote server established.";

    /* Once we have established connection with the remote machine,
       we immediately begin sending headers for all of the files. */
    QVariantList header_list;
    foreach(CFileHeader * header, m_headers)
        header_list.append(QJson::QObjectHelper::qobject2qvariant(header));

    /* Prepare the JSON object we will send over the wire containing
       the header and some other basic information about the transfer. */
    QVariantMap map;
    map["hostname"] = Settings::Get("General/MachineName");
    map["files"]    = header_list;

    SendData(EncodeJSON(map));

    /* Our current state is now waiting for the response from the remote machine. */
    qDebug() << "File headers sent, awaiting server response.";
    m_state = WaitingForHeaderResponse;
}

void CFileSender::OnData(QByteArray data)
{
    qDebug() << "Data received from remote server" << data;

    /* The client sends us two messages during the process.
       - the first is immediately after we send the headers
       - the second occurs after each file transfer
       Both of these responses are in JSON format. */

    QVariantMap response = DecodeJSON(data);
    if(!response.contains("status") || response["status"] != "continue")
    {
        emit Message("The remote machine aborted the transfer.", QSystemTrayIcon::Critical);

        disconnectFromHost();
        return;
    }

    /* Regardless of our current state, we can assume our task here is to begin
       transferring the next file in the list (if there is one). */
    m_state = TransferringFiles;

    if(m_headers.size())
    {
        CFileHeader * header = m_headers.takeFirst();
        SendFile(header);
        delete header;
    }
    /* Otherwise we're done! Emit the signal and disconnect from the server. */
    else
    {
        emit Progress(ProgressComplete);
        disconnectFromHost();
    }
}

void CFileSender::PrepareHeaders(QStringList filenames)
{
    /* Loop through all of the files that we are sending, finding out
       some basic information about each and marking whether the contents
       are compressed or should contain a CRC checksum. */
    bool compress = Settings::Get("General/CompressFiles").toBool();
    bool checksum = Settings::Get("General/CalculateChecksum").toBool();

    foreach(QString filename, filenames)
    {
        QFileInfo info(filename);

        CFileHeader * header = new CFileHeader(filename);
        header->SetFilename(info.fileName());
        header->SetUncompressedSize(info.size());
        header->SetCompressed(compress);
        header->SetChecksum(checksum);

        m_headers.append(header);

        /* Add the uncompressed size to our running total. */
        m_total_uncompressed += info.size();
    }
}

void CFileSender::SendFile(CFileHeader * header)
{
    qDebug() << "Preparing to transfer" << header->GetFilename() << "...";

    /* Now we actually begin the transmission of the file. */
    QByteArray contents;
    qint64 uncompressed_size;

    if(header->GetContents(contents, uncompressed_size))
    {
        /* Calculate the checksum if requested. */
        if(header->GetChecksum())
        {
            QByteArray crc = QByteArray::number(qChecksum(contents.data(), contents.size()));
            contents.prepend(crc + TerminatingCharacter);

            qDebug() << "Calculated CRC:" << crc;
        }

        /* Send the actual data. */
        SendData(contents);

        /* Emit a signal indicating progress. */
        m_current_uncompressed += uncompressed_size;
        emit Progress((double)m_current_uncompressed / (double)m_total_uncompressed * 100.0);
    }
    else
        disconnectFromHost();
}