File: filedownloader.cpp

package info (click to toggle)
pumpa 0.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid, stretch, trixie
  • size: 1,612 kB
  • ctags: 1,508
  • sloc: cpp: 8,651; ansic: 3,533; sh: 28; makefile: 8
file content (364 lines) | stat: -rw-r--r-- 10,339 bytes parent folder | download
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
  Copyright 2013-2015 Mats Sjöberg
  
  This file is part of the Pumpa programme.

  Pumpa 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.

  Pumpa 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 Pumpa.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "filedownloader.h"
#include "pumpa_defines.h"
#include "pumpasettings.h"
#include "util.h"

#ifdef QT5
#include <QStandardPaths>
#else
#include <QDesktopServices>
#endif

#include <QCryptographicHash>

//------------------------------------------------------------------------------

FileDownloadManager* FileDownloadManager::s_instance = NULL;

//------------------------------------------------------------------------------

FileDownloadManager::FileDownloadManager(QObject* parent) : QObject(parent) {
  m_nextRequestId = 0;

  m_nam = new QNetworkAccessManager(this);
  // connect(m_nam, SIGNAL(sslErrors(QNetworkReply*, QList<QSslError>)), 
  //         this, SLOT(onSslErrors(QNetworkReply*, QList<QSslError>)));

  m_oam = new KQOAuthManager(this);
  connect(m_oam, SIGNAL(authorizedRequestReady(QByteArray, int)),
          this, SLOT(onAuthorizedRequestReady(QByteArray, int)));
  connect(m_oam, SIGNAL(sslErrors(QNetworkReply*, QList<QSslError>)), 
          this, SLOT(onSslErrors(QNetworkReply*, QList<QSslError>)));
}

//------------------------------------------------------------------------------

FileDownloadManager* FileDownloadManager::getManager(QObject* parent) {
  if (s_instance == NULL && parent != 0)
    s_instance = new FileDownloadManager(parent);

  return s_instance;
}

//------------------------------------------------------------------------------

void FileDownloadManager::dumpStats() {
  // QMap<QString, FileDownloader*> m_inProgress;
  QMapIterator<QString, FileDownloader*> it(m_inProgress);
  while (it.hasNext()) {
    it.next();
    qDebug() << "[FILEDOWNLOADMANAGER] in progress" << it.key();
  }

  // QMap<QString, QString> m_urlMap;
  // QMap<int, requestData_t> m_requestMap;
  QMapIterator<int, requestData_t> itt(m_requestMap);
  while (itt.hasNext()) {
    itt.next();
    qDebug() << "[FILEDOWNLOADMANAGER] requests" << itt.key();
  }
}

//------------------------------------------------------------------------------

bool FileDownloadManager::hasFile(QString url) {
  return !fileName(url).isEmpty();
}

//------------------------------------------------------------------------------

QString FileDownloadManager::fileName(QString url) {
  QString fn = urlToPath(url);
  return QFile::exists(fn) ? fn : "";
}

//------------------------------------------------------------------------------

QPixmap FileDownloadManager::pixmap(QString url, QString brokenImage) {
  QString fn = urlToPath(url);

  QPixmap pix(fn);

  // Sometimes files are given with the wrong file ending, or Qt is
  // unable to guess the format so we try to force them into popular
  // formats.

  if (pix.isNull()) 
    pix.load(fn, "JPEG");

  if (pix.isNull())
    pix.load(fn, "PNG");

  if (pix.isNull())
    pix.load(fn, "GIF");

  if (pix.isNull() && !brokenImage.isEmpty())
    pix.load(brokenImage);

  return pix;
}

//------------------------------------------------------------------------------

QMovie* FileDownloadManager::movie(QString url) {
  QString fn = urlToPath(url);

  QMovie* mov = new QMovie(fn, QByteArray(), this);
  mov->setCacheMode(QMovie::CacheAll);  

  return mov;
}

//------------------------------------------------------------------------------

bool FileDownloadManager::supportsAnimation(QString url) {
  QString fn = urlToPath(url);

  QImageReader r(fn);
  return r.supportsAnimation();
}

//------------------------------------------------------------------------------

QString FileDownloadManager::urlToPath(QString url) {
  if (m_urlMap.contains(url))
    return m_urlMap[url];

  static QCryptographicHash hash(QCryptographicHash::Md5);
  static QStringList knownEndings;
  if (knownEndings.isEmpty())
    knownEndings << ".png" << ".jpeg" << ".jpg" << ".gif";

  if (m_cacheDir.isEmpty()) {
    m_cacheDir = 
#ifdef QT5
      QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
#else
      QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
#endif
    if (m_cacheDir.isEmpty())
      m_cacheDir = slashify(QDir::homePath())+".cache/";
    else
      m_cacheDir = slashify(m_cacheDir);
    m_cacheDir += "pumpa/";
  }
  QString path = m_cacheDir;
  QDir d;
  d.mkpath(path);

  QString ending;
  for (int i=0; i<knownEndings.count() && ending.isEmpty(); i++)
    if (url.endsWith(knownEndings[i]))
      ending = knownEndings[i];
  if (ending.isEmpty())
    ending = ".png";

  hash.reset();
  hash.addData(url.toUtf8());

  QString hashStr = hash.result().toHex();

  QString ret = path + hashStr + ending;
  m_urlMap.insert(url, ret);
  return ret;
}

//------------------------------------------------------------------------------

FileDownloader* FileDownloadManager::download(QString url) {
  if (m_inProgress.contains(url))
    return m_inProgress[url];

#ifdef DEBUG_NET
  qDebug() << "[DOWNLOAD]" << url;
#endif

  FileDownloader* fd = new FileDownloader(url, this);
  m_inProgress.insert(url, fd);
  connect(fd, SIGNAL(fileReady()), this, SLOT(onFileReady()));
  connect(fd, SIGNAL(networkError(QString)), this, SLOT(onFileReady(QString)));

  return fd;
}

//------------------------------------------------------------------------------

void FileDownloadManager::executeAuthorizedRequest(KQOAuthRequest* oar,
						   FileDownloader* fd) {
  int id = m_nextRequestId++;

  if (m_nextRequestId > 32000) { // bound to be smaller than any MAX_INT
    m_nextRequestId = 0;
    while (m_requestMap.contains(m_nextRequestId))
      m_nextRequestId++;
  }

  m_requestMap.insert(id, qMakePair(oar, fd));
  m_oam->executeAuthorizedRequest(oar, id);
}


//------------------------------------------------------------------------------

void FileDownloadManager::onSslErrors(QNetworkReply* nr, QList<QSslError>) {
  (void) nr; // suppress unused warning
#ifdef DEBUG_NET
  qDebug() << "FileDownloadManager SSL ERROR" << nr->url();
#endif
}

//------------------------------------------------------------------------------

void FileDownloadManager::onAuthorizedRequestReady(QByteArray response,
						   int id) {
  QPair<KQOAuthRequest*, FileDownloader*> rp = m_requestMap.take(id);
  KQOAuthRequest* oar = rp.first;
  FileDownloader* fd = rp.second;

  fd->requestReady(response, oar);
}

//------------------------------------------------------------------------------

void FileDownloadManager::onFileReady(QString) {
  FileDownloader *fd = qobject_cast<FileDownloader*>(sender());

  if (!fd)
    return;

  m_inProgress.remove(fd->url());
  fd->deleteLater();
}

//------------------------------------------------------------------------------

FileDownloader::FileDownloader(QString url, FileDownloadManager* fdm) :
  QObject(fdm),
  m_url(url),
  m_oar(NULL),
  m_redirs(0),
  m_fdm(fdm)
{
  PumpaSettings* ps = PumpaSettings::getSettings();

  if (ps && m_url.startsWith(ps->siteUrl())) {
    m_oar = new KQOAuthRequest(this);
    m_oar->initRequest(KQOAuthRequest::AuthorizedRequest, QUrl(m_url));

    m_oar->setConsumerKey(ps->clientId());
    m_oar->setConsumerSecretKey(ps->clientSecret());
    m_oar->setToken(ps->token());
    m_oar->setTokenSecret(ps->tokenSecret());

    m_oar->setHttpMethod(KQOAuthRequest::GET); 
    m_oar->setTimeout(60000); // one minute time-out

    m_fdm->executeAuthorizedRequest(m_oar, this);
  } else {
    QNetworkReply* nr = m_fdm->m_nam->get(QNetworkRequest(QUrl(m_url)));
    connect(nr, SIGNAL(finished()), this, SLOT(replyFinished()));
  }
}

//------------------------------------------------------------------------------

void FileDownloader::replyFinished() {
  QNetworkReply *nr = qobject_cast<QNetworkReply *>(sender());
  QString url = nr->url().toString();

  int status = nr->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

  if (nr->error()) {
    emit networkError(tr("Network error: ")+nr->errorString());
    nr->deleteLater();
    return;
  }

  if (status >= 301 && status <= 399) {
    if (m_redirs > 5) {
      emit networkError(tr("Network error: too many redirections!"));
      nr->deleteLater();
      return;
    }
    
    QUrl newUrl = nr->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    m_redirs++;

    QNetworkReply* nr2 = m_fdm->m_nam->get(QNetworkRequest(nr->url().resolved(newUrl)));
    connect(nr2, SIGNAL(finished()), this, SLOT(replyFinished()));
    nr->deleteLater();
    return;
  }

  requestReady(nr->readAll(), NULL);
  nr->deleteLater();
}

//------------------------------------------------------------------------------

void FileDownloader::requestReady(QByteArray response, KQOAuthRequest* oar) {
  if (oar != NULL && m_fdm->m_oam->lastError()) {
    emit networkError(QString(tr("Unable to download %1 (Error #%2)."))
                      .arg(m_url)
                      .arg(m_fdm->m_oam->lastError()));
    return;
  }

  QString fn = m_fdm->urlToPath(m_url);

  QFile* fp = new QFile(fn);
  if (!fp->open(QIODevice::WriteOnly)) {
    emit networkError(QString(tr("Could not open file %1 for writing: ")).
                      arg(fn) + fp->errorString());
    delete fp;
    return;
  }
  fp->write(response);
  fp->close();
  delete fp;
  
  QPixmap pix = m_fdm->pixmap(m_url);

  resizeImage(pix, fn);

  emit fileReady();
}

//------------------------------------------------------------------------------

void FileDownloader::resizeImage(QPixmap pix, QString fn) {
  if (pix.isNull())
    return;

  int w = pix.width();
  int h = pix.height();
  
  if (w <= IMAGE_MAX_WIDTH && h <= IMAGE_MAX_HEIGHT)
    return;

  QPixmap newPix;
  if (w > h) 
    newPix = pix.scaledToWidth(IMAGE_MAX_WIDTH);
  else
    newPix = pix.scaledToHeight(IMAGE_MAX_HEIGHT);
  newPix.save(fn);
}