summaryrefslogtreecommitdiff
path: root/client/DownloadClient.cpp
blob: b834622601d875676668f01ee3542404fcaedcaa (plain)
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

#include <QtCore>
#include "DownloadClient.h"


DownloadClient::DownloadClient(): isDownloading(false), current(NULL), currentId(-1)
{
	connect(this, SIGNAL(ReplyRecieved(SslClient::RequestType&, QByteArray&)),
			this, SLOT(FileDataRecieved(SslClient::RequestType&, QByteArray&)));
}

DownloadClient::DownloadClient(QString addr): SslClient(addr), isDownloading(false), current(NULL), currentId(-1)
{
	DownloadClient();
}

void DownloadClient::Download(const string &filename)
{
	pair<string, string> file(filename, 0);
	vector<pair<string, string> > fileList;
	fileList.push_back(file);
	Download(fileList);		
}

void DownloadClient::Download(const pair<string, string> &file)
{
	vector<pair<string, string> > fileList;
	fileList.push_back(file);
	Download(fileList);	
}

void DownloadClient::Download(const vector<pair<string, string> > &fileList)
{
	if (server.isEmpty())
	{
		Logger::Error("Server address isn't set! Aborting.\n");
		return;
	}
	if (isDownloading)
	{
		Logger::Error("Previous downloading process wasn't finished! Aborting.\n");
		return;
	}
	isDownloading = true;
	files = fileList;
	DoDownload();
}

void DownloadClient::DoDownload()
{	
	if (currentId < (int)files.size())
	{
		currentId++;
		pair<string, string> file = files[currentId];
		QString filename = QString::fromLocal8Bit(file.first.c_str());		
		string md5 = file.second;
		current = new QFile(filename);
		current->open(QIODevice::ReadWrite);

		Logger::Info("Downloading file %s\n", file.first.c_str());
		SendFileRequest(file.first);
	}
	else
	{
		Logger::Info("All files have been downloaded.");
		isDownloading = false;
		emit downloadFinished();
	}
}

void DownloadClient::FileDataRecieved(SslClient::RequestType &type, QByteArray &data)
{
	if (type != RegularFile)
	{
		Logger::Error("Invalid reply recieved: %x\n", type);
		return;
	}
	
	if ((current != NULL) && (current->isOpen()))
	{
		Logger::Error("File is not open or invalid state\n");
		return;
	}
	
	pair<string, string> file = files[currentId];
	string filename = file.first;
	if (data.size() == FRAGMENT_SIZE)
	{
		Logger::Debug("data:\n %s", data.constData());
		current->write(data);
		SendFileRequest(filename);
	}
	else
	{
		if (data.size() != 0)
		{
			Logger::Debug("data:\n %s", data.constData());
			current->write(data);
		}
		current->close();
		delete current;
		current = NULL;
		
		/**
		 * @todo md5 hash check
		 */
		
		DoDownload();
	}
}