]> git.sur5r.net Git - minitube/blob - src/downloaditem.cpp
Imported Upstream version 1.4.1
[minitube] / src / downloaditem.cpp
1 #include "downloaditem.h"
2 #include "networkaccess.h"
3 #include "video.h"
4
5 #include <QDesktopServices>
6
7 namespace The {
8     NetworkAccess* http();
9 }
10
11 DownloadItem::DownloadItem(Video *video, QUrl url, QString filename, QObject *parent)
12     : QObject(parent)
13     , m_bytesReceived(0)
14     , m_startedSaving(false)
15     , m_finishedDownloading(false)
16     , m_url(url)
17     , m_file(filename)
18     , m_reply(0)
19     , video(video)
20     , m_status(Idle)
21 {
22     speedCheckTimer = new QTimer(this);
23     speedCheckTimer->setInterval(2000);
24     speedCheckTimer->setSingleShot(true);
25     connect(speedCheckTimer, SIGNAL(timeout()), SLOT(speedCheck()));
26 }
27
28 DownloadItem::~DownloadItem() {
29     if (m_reply) delete m_reply;
30     if (video) delete video;
31 }
32
33 void DownloadItem::start() {
34     m_reply = The::http()->simpleGet(m_url);
35     init();
36 }
37
38 void DownloadItem::init() {
39     if (!m_reply)
40         return;
41
42     if (m_file.exists())
43         m_file.remove();
44
45     m_status = Starting;
46
47     m_startedSaving = false;
48     m_finishedDownloading = false;
49
50     // attach to the m_reply
51     m_url = m_reply->url();
52     connect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
53     connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
54             this, SLOT(error(QNetworkReply::NetworkError)));
55     connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
56             this, SLOT(downloadProgress(qint64, qint64)));
57     connect(m_reply, SIGNAL(metaDataChanged()),
58             this, SLOT(metaDataChanged()));
59     connect(m_reply, SIGNAL(finished()),
60             this, SLOT(requestFinished()));
61
62     // start timer for the download estimation
63     m_downloadTime.start();
64     speedCheckTimer->start();
65
66     if (m_reply->error() != QNetworkReply::NoError) {
67         error(m_reply->error());
68         requestFinished();
69     }
70 }
71
72
73 void DownloadItem::stop() {
74     if (m_reply)
75         m_reply->abort();
76     m_status = Idle;
77     emit statusChanged();
78 }
79
80 void DownloadItem::open() {
81     QFileInfo info(m_file);
82     QUrl url = QUrl::fromLocalFile(info.absoluteFilePath());
83     QDesktopServices::openUrl(url);
84 }
85
86 void DownloadItem::openFolder() {
87     QFileInfo info(m_file);
88     QUrl url = QUrl::fromLocalFile(info.absolutePath());
89     QDesktopServices::openUrl(url);
90 }
91
92 void DownloadItem::tryAgain() {
93     if (m_reply)
94         m_reply->abort();
95
96     if (m_file.exists())
97         m_file.remove();
98
99     m_reply = The::http()->simpleGet(m_url);
100     init();
101     emit statusChanged();
102 }
103
104 void DownloadItem::downloadReadyRead() {
105
106     if (!m_file.isOpen()) {
107         if (!m_file.open(QIODevice::ReadWrite)) {
108             qDebug() << QString("Error opening output file: %1").arg(m_file.errorString());
109             stop();
110             emit statusChanged();
111             return;
112         }
113         emit statusChanged();
114     }
115
116     if (-1 == m_file.write(m_reply->readAll())) {
117         /*
118         downloadInfoLabel->setText(tr("Error saving: %1")
119                                    .arg(m_output.errorString()));
120         stopButton->click();
121         */
122     } else {
123         m_startedSaving = true;
124         if (m_status != Downloading) {
125             // m_status = Downloading;
126             // emit statusChanged();
127         } else if (m_finishedDownloading)
128             requestFinished();
129     }
130 }
131
132 void DownloadItem::error(QNetworkReply::NetworkError) {
133
134 #ifdef DOWNLOADMANAGER_DEBUG
135     qDebug() << "DownloadItem::" << __FUNCTION__ << m_reply->errorString() << m_url;
136 #endif
137
138     qDebug() << m_reply->errorString();
139
140     m_errorMessage = m_reply->errorString();
141     m_reply = 0;
142     m_status = Failed;
143
144     emit finished();
145 }
146
147 QString DownloadItem::errorMessage() const {
148     return m_errorMessage;
149 }
150
151 void DownloadItem::metaDataChanged() {
152     QVariant locationHeader = m_reply->header(QNetworkRequest::LocationHeader);
153     if (locationHeader.isValid()) {
154         m_url = locationHeader.toUrl();
155         // qDebug() << "Redirecting to" << m_url;
156         m_reply->deleteLater();
157         m_reply = The::http()->simpleGet(m_url);
158         init();
159         return;
160     }
161
162 #ifdef DOWNLOADMANAGER_DEBUG
163     qDebug() << "DownloadItem::" << __FUNCTION__ << "not handled.";
164 #endif
165 }
166
167 int DownloadItem::initialBufferSize() {
168     // qDebug() << video->getDefinitionCode();
169     switch (video->getDefinitionCode()) {
170     case 18:
171         return 1024*192;
172     case 22:
173         return 1024*512;
174     case 37:
175         return 1024*768;
176     }
177     return 1024*128;
178 }
179
180 void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
181
182     if (m_lastProgressTime.elapsed() < 150) return;
183     m_lastProgressTime.start();
184
185     m_bytesReceived = bytesReceived;
186
187     if (m_status != Downloading) {
188
189         int neededBytes = (int) (bytesTotal * .01);
190         // qDebug() << bytesReceived << bytesTotal << neededBytes << m_downloadTime.elapsed();
191         int bufferSize = initialBufferSize();
192         if (bytesReceived > bufferSize
193             && bytesReceived > neededBytes
194             && m_downloadTime.elapsed() > 1000 ) {
195             emit bufferProgress(100);
196             m_status = Downloading;
197             emit statusChanged();
198         } else {
199             int bufferPercent = bytesReceived * 100 / qMax(bufferSize, neededBytes);
200             emit bufferProgress(bufferPercent);
201         }
202
203     } else {
204
205         if (bytesTotal > 0) {
206             int percent = bytesReceived * 100 / bytesTotal;
207             if (percent != this->percent) {
208                 this->percent = percent;
209                 emit progress(percent);
210             }
211         }
212
213     }
214 }
215
216 void DownloadItem::speedCheck() {
217     if (!m_reply) return;
218     if (m_bytesReceived < initialBufferSize() / 3) {
219         m_reply->disconnect();
220         m_reply->abort();
221         m_reply->deleteLater();
222         m_reply = 0;
223
224         // too slow! retry
225         qDebug() << "Retrying...";
226         connect(video, SIGNAL(gotStreamUrl(QUrl)), SLOT(gotStreamUrl(QUrl)));
227         video->loadStreamUrl();
228     }
229 }
230
231 void DownloadItem::gotStreamUrl(QUrl streamUrl) {
232
233     Video *video = static_cast<Video *>(sender());
234     if (!video) {
235         qDebug() << "Cannot get sender";
236         return;
237     }
238     video->disconnect(this);
239
240     m_reply = The::http()->simpleGet(video->getStreamUrl());
241     init();
242 }
243
244 qint64 DownloadItem::bytesTotal() const {
245     if (!m_reply) return 0;
246     return m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
247 }
248
249 qint64 DownloadItem::bytesReceived() const {
250     return m_bytesReceived;
251 }
252
253 double DownloadItem::remainingTime() const {
254     if (m_finishedDownloading)
255         return -1.0;
256
257     double timeRemaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed();
258
259     // When downloading the eta should never be 0
260     if (timeRemaining == 0)
261         timeRemaining = 1;
262
263     return timeRemaining;
264 }
265
266 double DownloadItem::currentSpeed() const {
267     if (m_finishedDownloading)
268         return -1.0;
269
270     return m_bytesReceived * 1000.0 / m_downloadTime.elapsed();
271 }
272
273 void DownloadItem::requestFinished() {
274     m_reply = 0;
275     m_finishedDownloading = true;
276     if (!m_startedSaving) {
277         qDebug() << "Request finished but never started saving";
278         return;
279     }
280     m_file.close();
281     m_status = Finished;
282     emit statusChanged();
283     emit finished();
284 }
285
286 QString DownloadItem::formattedFilesize(qint64 size) {
287     /*
288     if (size < 1024) return tr("%1 bytes").arg(size);
289     else if (size < 1024*1024) return tr("%1 KB").arg(size/1024);
290     else if (size < 1024*1024*1024) return tr("%1 MB").arg(size/1024/1024);
291     else return tr("%1 GB").arg(size/1024/1024/1024);
292     */
293     QString unit;
294     if (size < 1024) {
295         unit = tr("bytes");
296     } else if (size < 1024*1024) {
297         size /= 1024;
298         unit = tr("KB");
299     } else {
300         size /= 1024*1024;
301         unit = tr("MB");
302     }
303     return QString(QLatin1String("%1 %2")).arg(size).arg(unit);
304 }
305
306 QString DownloadItem::formattedSpeed(double speed) {
307     /*
308     static const int K = 1024;
309     if (speed < K) return tr("%1 bytes/s").arg(speed);
310     else if (speed < K*K) return tr("%1 KB/s").arg(speed/K);
311     else if (speed < K*K*K) return tr("%1 MB/s").arg(speed/K/K);
312     else return tr("%1 GB/s").arg(speed/K/K/K);
313     */
314     int speedInt = (int) speed;
315     QString unit;
316     if (speedInt < 1024) {
317         unit = tr("bytes/sec");
318     } else if (speedInt < 1024*1024) {
319         speedInt /= 1024;
320         unit = tr("KB/sec");
321     } else {
322         speedInt /= 1024*1024;
323         unit = tr("MB/sec");
324     }
325     return QString(QLatin1String("%1 %2")).arg(speedInt).arg(unit);
326 }
327
328 QString DownloadItem::formattedTime(double timeRemaining) {
329     QString timeRemainingString = tr("seconds");
330     if (timeRemaining > 60) {
331         timeRemaining = timeRemaining / 60;
332         timeRemainingString = tr("minutes");
333     }
334     timeRemaining = floor(timeRemaining);
335     return tr("%4 %5 remaining")
336             .arg(timeRemaining)
337             .arg(timeRemainingString);
338 }