Added QPixmap for User class and implemented first version of profile image fetching...
[situare] / src / situareservice / situareservice.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 <QtGlobal>
24 #include <QStringList>
25 #include <QPixmap>
26 #include "situareservice.h"
27 #include "situarecommon.h"
28 #include "../cookiehandler/cookiehandler.h"
29 #include "parser.h"
30
31 SituareService::SituareService(QObject *parent, QNetworkAccessManager *manager)
32         : QObject(parent), m_networkManager(manager)
33 {
34     qDebug() << __PRETTY_FUNCTION__;
35
36     connect(&m_facebookAuthentication, SIGNAL(credentialsReady()), SLOT(credentialsReady()));
37
38     connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
39
40     m_imageFetcher = new ImageFetcher(new QNetworkAccessManager(this), this);
41     connect(this, SIGNAL(fetchImage(QUrl)), m_imageFetcher, SLOT(fetchImage(QUrl)));
42     connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)), this,
43             SLOT(imageReceived(QUrl, QPixmap)));
44
45     m_credentials = m_facebookAuthentication.loginCredentials();
46 }
47
48 SituareService::~SituareService()
49 {
50     qDebug() << __PRETTY_FUNCTION__;
51
52     delete m_networkManager;
53     delete m_user;
54 }
55
56 void SituareService::fetchLocations()
57 {
58     qDebug() << __PRETTY_FUNCTION__;
59
60     CookieHandler cookieHandler;
61
62     QString cookie = cookieHandler.formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
63                                               m_credentials.sessionKey(), m_credentials.sessionSecret(),
64                                               m_credentials.sig(), EN_LOCALE);
65
66     QUrl url = formUrl(SITUARE_URL, GET_LOCATIONS);
67
68     sendRequest(url, COOKIE, cookie);
69 }
70
71 void SituareService::reverseGeo(const QPointF &coordinates)
72 {
73     qDebug() << __PRETTY_FUNCTION__;
74
75     CookieHandler cookieHandler;
76
77     QString cookie = cookieHandler.formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
78                                               m_credentials.sessionKey(), m_credentials.sessionSecret(),
79                                               m_credentials.sig(), EN_LOCALE);
80
81     QString urlParameters = formUrlParameters(coordinates);
82     QUrl url = formUrl(SITUARE_URL, REVERSE_GEO, urlParameters);
83
84     sendRequest(url, COOKIE, cookie);
85 }
86
87 void SituareService::updateLocation(const QPointF &coordinates, const QString &status,
88                                     const bool &publish)
89 {
90     qDebug() << __PRETTY_FUNCTION__;
91
92     CookieHandler cookieHandler;
93
94     QString cookie = cookieHandler.formCookie(API_KEY, m_credentials.expires(), m_credentials.userID(),
95                                               m_credentials.sessionKey(), m_credentials.sessionSecret(),
96                                               m_credentials.sig(), EN_LOCALE);
97
98
99     QString publishValue;
100     if(publish) {
101         publishValue = PUBLISH_TRUE;
102     }
103     else {
104         publishValue = PUBLISH_FALSE;
105     }
106     QString urlParameters = formUrlParameters(coordinates, status, publishValue);
107     QUrl url = formUrl(SITUARE_URL, UPDATE_LOCATION, urlParameters);
108
109     sendRequest(url, COOKIE, cookie);
110 }
111
112 QUrl SituareService::formUrl(const QString &baseUrl, const QString &phpScript, QString urlParameters)
113 {
114     qDebug() << __PRETTY_FUNCTION__;
115     QString urlString;
116
117     urlString.append(baseUrl);
118     urlString.append(phpScript);
119     if(urlParameters != NULL)
120         urlString.append(urlParameters);
121
122     QUrl url = QUrl(urlString);
123
124     qDebug() << url;
125
126     return url;
127 }
128
129 QString SituareService::formUrlParameters(const QPointF &coordinates, QString status, QString publish)
130 {
131     QString parameters;
132
133     parameters.append(QUESTION_MARK);
134     parameters.append(LATITUDE);
135     parameters.append(EQUAL_MARK);
136     parameters.append(QString::number(coordinates.x()));
137     parameters.append(AMBERSAND_MARK);
138     parameters.append(LONGTITUDE);
139     parameters.append(EQUAL_MARK);
140     parameters.append(QString::number(coordinates.y()));
141
142     if(publish.compare(PUBLISH_TRUE) == 0) {
143         parameters.append(AMBERSAND_MARK);
144         parameters.append(PUBLISH);
145         parameters.append(EQUAL_MARK);
146         parameters.append(PUBLISH_TRUE);
147     }
148     else if(publish.compare(PUBLISH_FALSE) == 0) {
149         parameters.append(AMBERSAND_MARK);
150         parameters.append(PUBLISH);
151         parameters.append(EQUAL_MARK);
152         parameters.append(PUBLISH_FALSE);
153     }
154
155     if(status != NULL) {
156         parameters.append(AMBERSAND_MARK);
157         parameters.append(DATA);
158         parameters.append(EQUAL_MARK);
159         parameters.append(status);
160     }
161
162     return parameters;
163 }
164
165 void SituareService::sendRequest(const QUrl &url, const QString &cookieType, const QString &cookie)
166 {
167     qDebug() << __PRETTY_FUNCTION__ << "url: " << url;
168
169     QNetworkRequest request;
170
171     request.setUrl(url);
172     request.setRawHeader(cookieType.toAscii(), cookie.toUtf8());
173
174     QNetworkReply *reply = m_networkManager->get(request);
175
176     m_currentRequests.append(reply);
177 }
178
179 void SituareService::requestFinished(QNetworkReply *reply)
180 {
181     qDebug() << __PRETTY_FUNCTION__;
182
183     QUrl url = reply->url();
184     qDebug() << "BytesAvailable: " << reply->bytesAvailable();
185     if (reply->error()) {
186         qDebug() << reply->errorString();
187         emit error(reply->errorString());
188         // ToDo: some general http error handling etc, signal UI?
189     }
190     else {
191         qint64 max = reply->size();
192         QByteArray replyArray = reply->read(max);
193         qDebug() << "Reply from: " << url << "reply " << replyArray;
194         // ToDo: results handling includes Situare's errors
195         // works like situare's error handling i.e. both lat & lon are missing/wrong
196         // -> we get only error for wrong lon
197         if(replyArray == ERROR_LAT.toAscii()) {
198             qDebug() << "Error: " << ERROR_LAT;
199             // ToDo: signal UI?
200             emit error(replyArray);
201         }
202         else if(replyArray == ERROR_LON.toAscii()) {
203             qDebug() << "Error: " << ERROR_LON;
204             // ToDo: signal UI?
205             emit error(replyArray);
206         }
207         else if(replyArray.contains(ERROR_SESSION.toAscii())) {
208             qDebug() << "Error: " << ERROR_SESSION;
209             // ToDo: signal UI?
210             emit error(replyArray);
211         }
212         else if(replyArray.startsWith(OPENING_BRACE_MARK.toAscii())) {
213             qDebug() << "JSON string";
214             parseUserData(replyArray);
215         }
216         else if(replyArray == "") {
217             qDebug() << "No error, update was successful";
218         }
219         else {
220             // Street address ready
221             QString address(replyArray);
222             emit reverseGeoReady(address);
223         }
224     }
225     m_currentRequests.removeAll(reply);
226     reply->deleteLater();
227 }
228
229 void SituareService::credentialsReady()
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232     m_credentials = m_facebookAuthentication.loginCredentials();
233 }
234
235 void SituareService::parseUserData(const QByteArray &jsonReply)
236 {
237     qDebug() << __PRETTY_FUNCTION__;
238
239     m_visited = 0;
240     m_nbrOfImages = 0;
241     m_friendsList.clear();
242
243     QJson::Parser parser;
244     bool ok;
245
246     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
247     if (!ok) {
248
249         qFatal("An error occurred during parsing");
250         exit (1);
251     }
252
253     //QList<User *> friendsList;
254
255     QVariant userVariant = result.value("user");
256     QMap<QString, QVariant> userMap = userVariant.toMap();
257
258     QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
259
260     QUrl imageUrl = userMap["profile_pic"].toUrl();
261
262     m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
263                   userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
264                   true, userMap["uid"].toString());
265
266     foreach (QVariant friendsVariant, result["friends"].toList()) {
267       QMap<QString, QVariant> friendMap = friendsVariant.toMap();
268       QVariant distance = friendMap["distance"];
269       QMap<QString, QVariant> distanceMap = distance.toMap();
270
271       QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
272
273       QUrl imageUrl = friendMap["profile_pic"].toUrl();
274
275       User *user = new User(friendMap["address"].toString(), coordinates, friendMap["name"].toString(),
276                             friendMap["note"].toString(), imageUrl, friendMap["timestamp"].toString(),
277                             false, friendMap["uid"].toString(), distanceMap["units"].toString(),
278                             distanceMap["value"].toDouble());
279
280       m_friendsList.append(user);
281     }
282     addProfileImages();
283 }
284
285 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
286 {
287     qDebug() << __PRETTY_FUNCTION__;
288     qDebug() << "Image URL: " << url << " size :" << image.size();
289
290     if(m_user->profileImageUrl() == url) {
291         m_user->setProfileImage(image);
292     }
293
294     for(int i=0;i<m_friendsList.count();i++) {
295         if(m_friendsList.at(i)->profileImageUrl() == url) {
296             m_friendsList.at(i)->setProfileImage(image);
297             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
298         }
299     }
300
301     if(m_nbrOfImages == m_visited) {
302         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
303         qDebug() << "emit userDataChanged";
304         emit userDataChanged(m_user, m_friendsList);
305     }
306 }
307
308 void SituareService::addProfileImages()
309 {
310     qDebug() << __PRETTY_FUNCTION__;
311
312     if(m_user->profileImageUrl() != QUrl("")) {
313         emit fetchImage(m_user->profileImageUrl());
314     }
315
316     for(int i=0;i<m_friendsList.count();i++) {
317         if(m_friendsList.at(i)->profileImageUrl() != QUrl("")) {
318             m_visited++; // indicates how many friends that have profile image
319             emit fetchImage(m_friendsList.at(i)->profileImageUrl());
320         }
321     }
322 }