First version of imagefetcher. Added imagefetcher.cpp/.h
[situare] / src / situareservice / imagefetcher.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6
7    Situare is free software; you can redistribute it and/or
8    modify it under the terms of the GNU General Public License
9    version 2 as published by the Free Software Foundation.
10
11    Situare is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with Situare; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
19    USA.
20 */
21
22 #include <QDebug>
23 #include <QNetworkRequest>
24 #include <QNetworkReply>
25 #include <QImage>
26 #include "imagefetcher.h"
27
28 ImageFetcher::ImageFetcher(QNetworkAccessManager *manager, QObject *parent)
29     : QObject(parent)
30     , m_manager(manager)
31 {
32     connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(
33             downloadFinished(QNetworkReply*)));
34 }
35
36 void ImageFetcher::fetchImage(const QUrl &url)
37 {
38     qDebug() << __PRETTY_FUNCTION__;
39
40     if (url.isEmpty() || !url.isValid())
41         return;
42
43     if (m_downloadQueue.size() >= DOWNLOAD_QUEUE_SIZE)
44         m_downloadQueue.dequeue();
45
46     m_downloadQueue.enqueue(url);
47
48     if (m_currentDownloads.size() < MAX_PARALLEL_DOWNLOADS)
49         startNextDownload();
50 }
51
52 void ImageFetcher::startNextDownload()
53 {
54     qDebug() << __PRETTY_FUNCTION__;
55
56     if (m_downloadQueue.isEmpty())
57         return;
58
59     QUrl url = m_downloadQueue.dequeue();
60
61     QNetworkRequest request(url);
62     request.setRawHeader("User-Agent", "Situare");
63     QNetworkReply *reply = m_manager->get(request);
64
65     m_currentDownloads.append(reply);
66 }
67
68 void ImageFetcher::downloadFinished(QNetworkReply *reply)
69 {
70     qDebug() << __PRETTY_FUNCTION__;
71
72     if (reply->error() == QNetworkReply::NoError) {
73         QImage image;
74         QUrl url = reply->url();
75
76         if (!image.load(reply, 0))
77             image = QImage();
78
79         //emit imageReceived(url, QPixmap::fromImage(image));
80         emit imageReceived(url, image);
81     }
82     else {
83         emit error(reply->errorString());
84     }
85
86     m_currentDownloads.removeAll(reply);
87     reply->deleteLater();
88     startNextDownload();
89 }