Line data Source code
1 : #include "ImageGrabber.h"
2 :
3 : #include <QDebug>
4 : #include <QString>
5 : #include <QStringList>
6 : #include <QNetworkReply>
7 : #include "ErrorHandling.h"
8 :
9 27 : ImageGrabber::ImageGrabber(QObject *parent) :
10 : FangObject(parent),
11 27 : manager(),
12 27 : urlsToCheck(),
13 54 : results()
14 : {
15 : // Signals!
16 27 : connect(&manager, &FangNetworkAccessManager::finished, this, &ImageGrabber::onRequestFinished);
17 27 : }
18 :
19 0 : void ImageGrabber::fetchUrl(const QUrl &url)
20 : {
21 0 : QList<QUrl> urls;
22 0 : urls.append(url);
23 0 : fetchUrls(urls);
24 0 : }
25 :
26 3 : void ImageGrabber::fetchUrls(const QList<QUrl> &urls)
27 : {
28 : // Reset everything.
29 3 : results.clear();
30 3 : urlsToCheck.clear();
31 :
32 : // Do it!
33 6 : for (QUrl url : urls) {
34 3 : checkUrl(url);
35 3 : }
36 3 : }
37 :
38 3 : void ImageGrabber::checkUrl(const QUrl &url)
39 : {
40 3 : if (urlsToCheck.contains(url)) {
41 0 : return; // Already workin' on this one.
42 : }
43 :
44 3 : urlsToCheck.append(url);
45 :
46 3 : QNetworkRequest request(url);
47 3 : manager.get(request);
48 3 : }
49 :
50 3 : void ImageGrabber::onRequestFinished(QNetworkReply * reply)
51 : {
52 3 : QUrl requestedUrl = reply->request().url();
53 3 : FANG_CHECK(urlsToCheck.contains(requestedUrl), "ImageGrabber: Unexpected URL received");
54 :
55 : //
56 : // TODO: Handle HTTP redirects correctly.
57 : //
58 :
59 : // Let's see what we got 'ere.
60 3 : if (reply->error() != QNetworkReply::NoError) {
61 : // Error.
62 : // Insert an empty image.
63 0 : results.insert(requestedUrl, QImage());
64 : } else {
65 : // Great success!
66 : // Got something, maybe it's an image. Who knows! More importantly, who cares?
67 3 : results.insert(requestedUrl, QImage::fromData(reply->readAll()));
68 : }
69 :
70 : // Are we there yet?
71 3 : checkCompletion();
72 3 : }
73 :
74 :
75 3 : void ImageGrabber::checkCompletion()
76 : {
77 : // Only continue if we're done.
78 3 : if (results.size() != urlsToCheck.size()) {
79 0 : return;
80 : }
81 :
82 : // And we're done here!
83 3 : emit finished();
84 : }
85 :
|