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