summaryrefslogtreecommitdiffstats
path: root/api/logic/net/Download.cpp
blob: 7610cae3cd3eb792ec1b257612f02f96c7fc57f4 (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
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
/* Copyright 2013-2015 MultiMC Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Download.h"

#include <QFileInfo>
#include <QDateTime>
#include <QDebug>
#include "Env.h"
#include <FileSystem.h>
#include "ChecksumValidator.h"
#include "MetaCacheSink.h"
#include "ByteArraySink.h"

namespace Net {

Download::Download():NetAction()
{
	m_status = Job_NotStarted;
}

Download::Ptr Download::makeCached(QUrl url, MetaEntryPtr entry)
{
	Download * dl = new Download();
	dl->m_url = url;
	auto md5Node = new ChecksumValidator(QCryptographicHash::Md5);
	auto cachedNode = new MetaCacheSink(entry, md5Node);
	dl->m_sink.reset(cachedNode);
	dl->m_target_path = entry->getFullPath();
	return std::shared_ptr<Download>(dl);
}

Download::Ptr Download::makeByteArray(QUrl url, QByteArray *output)
{
	Download * dl = new Download();
	dl->m_url = url;
	dl->m_sink.reset(new ByteArraySink(output));
	return std::shared_ptr<Download>(dl);
}

Download::Ptr Download::makeFile(QUrl url, QString path)
{
	Download * dl = new Download();
	dl->m_url = url;
	dl->m_sink.reset(new FileSink(path));
	return std::shared_ptr<Download>(dl);
}

void Download::addValidator(Validator * v)
{
	m_sink->addValidator(v);
}

void Download::start()
{
	if(m_status == Job_Aborted)
	{
		qWarning() << "Attempt to start an aborted Download:" << m_url.toString();
		emit aborted(m_index_within_job);
		return;
	}
	QNetworkRequest request(m_url);
	m_status = m_sink->init(request);
	switch(m_status)
	{
		case Job_Finished:
			emit succeeded(m_index_within_job);
			qDebug() << "Download cache hit " << m_url.toString();
			return;
		case Job_InProgress:
			qDebug() << "Downloading " << m_url.toString();
			break;
		case Job_NotStarted:
		case Job_Failed:
			emit failed(m_index_within_job);
			return;
		case Job_Aborted:
			return;
	}

	request.setHeader(QNetworkRequest::UserAgentHeader, "MultiMC/5.0");

	auto worker = ENV.qnam();
	QNetworkReply *rep = worker->get(request);

	m_reply.reset(rep);
	connect(rep, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64)));
	connect(rep, SIGNAL(finished()), SLOT(downloadFinished()));
	connect(rep, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(downloadError(QNetworkReply::NetworkError)));
	connect(rep, SIGNAL(readyRead()), SLOT(downloadReadyRead()));
}

void Download::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
	m_total_progress = bytesTotal;
	m_progress = bytesReceived;
	emit netActionProgress(m_index_within_job, bytesReceived, bytesTotal);
}

void Download::downloadError(QNetworkReply::NetworkError error)
{
	if(error == QNetworkReply::OperationCanceledError)
	{
		qCritical() << "Aborted " << m_url.toString();
		m_status = Job_Aborted;
	}
	else
	{
		// error happened during download.
		qCritical() << "Failed " << m_url.toString() << " with reason " << error;
		m_status = Job_Failed;
	}
}

bool Download::handleRedirect()
{
	QVariant redirect = m_reply->header(QNetworkRequest::LocationHeader);
	QString redirectURL;
	if(redirect.isValid())
	{
		redirectURL = redirect.toString();
	}
	// FIXME: This is a hack for https://bugreports.qt-project.org/browse/QTBUG-41061
	else if(m_reply->hasRawHeader("Location"))
	{
		auto data = m_reply->rawHeader("Location");
		if(data.size() > 2 && data[0] == '/' && data[1] == '/')
		{
			redirectURL = m_reply->url().scheme() + ":" + data;
		}
	}
	if (!redirectURL.isEmpty())
	{
		m_url = QUrl(redirect.toString());
		qDebug() << "Following redirect to " << m_url.toString();
		start();
		return true;
	}
	return false;
}


void Download::downloadFinished()
{
	// handle HTTP redirection first
	if(handleRedirect())
	{
		qDebug() << "Download redirected:" << m_url.toString();
		return;
	}

	// if the download failed before this point ...
	if (m_status == Job_Failed)
	{
		qDebug() << "Download failed in previous step:" << m_url.toString();
		m_sink->abort();
		m_reply.reset();
		emit failed(m_index_within_job);
		return;
	}
	else if(m_status == Job_Aborted)
	{
		qDebug() << "Download aborted in previous step:" << m_url.toString();
		m_sink->abort();
		m_reply.reset();
		emit aborted(m_index_within_job);
		return;
	}

	// make sure we got all the remaining data, if any
	auto data = m_reply->readAll();
	if(data.size())
	{
		qDebug() << "Writing extra" << data.size() << "bytes to" << m_target_path;
		m_status = m_sink->write(data);
	}

	// otherwise, finalize the whole graph
	m_status = m_sink->finalize(*m_reply.get());
	if (m_status != Job_Finished)
	{
		qDebug() << "Download failed to finalize:" << m_url.toString();
		m_sink->abort();
		m_reply.reset();
		emit failed(m_index_within_job);
		return;
	}
	m_reply.reset();
	qDebug() << "Download succeeded:" << m_url.toString();
	emit succeeded(m_index_within_job);
}

void Download::downloadReadyRead()
{
	if(m_status == Job_InProgress)
	{
		auto data = m_reply->readAll();
		m_status = m_sink->write(data);
		if(m_status == Job_Failed)
		{
			qCritical() << "Failed to process response chunk for " << m_target_path;
		}
		// qDebug() << "Download" << m_url.toString() << "gained" << data.size() << "bytes";
	}
	else
	{
		qCritical() << "Cannot write to " << m_target_path << ", illegal status" << m_status;
	}
}

}

bool Net::Download::abort()
{
	if(m_reply)
	{
		m_reply->abort();
	}
	else
	{
		m_status = Job_Aborted;
	}
	return true;
}

bool Net::Download::canAbort()
{
	return true;
}