refactored engine and situareservice
[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 <QNetworkReply>
27 #include "situareservice.h"
28 #include "situarecommon.h"
29 #include "../cookiehandler/cookiehandler.h"
30 #include "parser.h"
31
32 SituareService::SituareService(QObject *parent, QNetworkAccessManager *manager)
33         : QObject(parent), m_networkManager(manager)
34 {
35     qDebug() << __PRETTY_FUNCTION__;
36
37     connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));
38
39     m_imageFetcher = new ImageFetcher(new QNetworkAccessManager(this), this);
40     connect(this, SIGNAL(fetchImage(QUrl)), m_imageFetcher, SLOT(fetchImage(QUrl)));
41     connect(m_imageFetcher, SIGNAL(imageReceived(QUrl,QPixmap)), this,
42             SLOT(imageReceived(QUrl, QPixmap)));
43
44 }
45
46 SituareService::~SituareService()
47 {
48     qDebug() << __PRETTY_FUNCTION__;
49
50     delete m_networkManager;
51     if(m_user) {
52         delete m_user;
53     }
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(const FacebookCredentials &credentials)
230 {
231     qDebug() << __PRETTY_FUNCTION__;
232     m_credentials = credentials;
233     
234 }
235
236 void SituareService::parseUserData(const QByteArray &jsonReply)
237 {
238     qDebug() << __PRETTY_FUNCTION__;
239
240     m_visited = 0;
241     m_nbrOfImages = 0;
242     m_friendsList.clear();
243
244     QJson::Parser parser;
245     bool ok;
246
247     QVariantMap result = parser.parse (jsonReply, &ok).toMap();
248     if (!ok) {
249
250         qFatal("An error occurred during parsing");
251         exit (1);
252     }
253
254     QVariant userVariant = result.value("user");
255     QMap<QString, QVariant> userMap = userVariant.toMap();
256
257     QPointF coordinates(userMap["longitude"].toReal(), userMap["latitude"].toReal());
258
259     QUrl imageUrl = userMap["profile_pic"].toUrl();
260
261     m_user = new User(userMap["address"].toString(), coordinates, userMap["name"].toString(),
262                   userMap["note"].toString(), imageUrl, userMap["timestamp"].toString(),
263                   true, userMap["uid"].toString());
264
265     foreach (QVariant friendsVariant, result["friends"].toList()) {
266       QMap<QString, QVariant> friendMap = friendsVariant.toMap();
267       QVariant distance = friendMap["distance"];
268       QMap<QString, QVariant> distanceMap = distance.toMap();
269
270       QPointF coordinates(friendMap["longitude"].toReal(), friendMap["latitude"].toReal());
271
272       QUrl imageUrl = friendMap["profile_pic"].toUrl();
273
274       User *user = new User(friendMap["address"].toString(), coordinates, friendMap["name"].toString(),
275                             friendMap["note"].toString(), imageUrl, friendMap["timestamp"].toString(),
276                             false, friendMap["uid"].toString(), distanceMap["units"].toString(),
277                             distanceMap["value"].toDouble());
278
279       m_friendsList.append(user);
280     }
281     addProfileImages();
282 }
283
284 void SituareService::imageReceived(const QUrl &url, const QPixmap &image)
285 {
286     qDebug() << __PRETTY_FUNCTION__;
287     qDebug() << "Image URL: " << url << " size :" << image.size();
288
289     if(m_user->profileImageUrl() == url) {
290         m_user->setProfileImage(image);
291     }
292
293     for(int i=0;i<m_friendsList.count();i++) {
294         if(m_friendsList.at(i)->profileImageUrl() == url) {
295             m_friendsList.at(i)->setProfileImage(image);
296             m_nbrOfImages++; // indicates how many friend profile images has been downloaded
297         }
298     }
299
300     if(m_nbrOfImages == m_visited) {
301         qDebug() << "m_nbrOfImages: " << m_nbrOfImages << " m_visited: " << m_visited;
302         qDebug() << "emit userDataChanged";
303         emit userDataChanged(m_user, m_friendsList);
304     }
305 }
306
307 void SituareService::addProfileImages()
308 {
309     qDebug() << __PRETTY_FUNCTION__;
310
311     if(m_user->profileImageUrl() != QUrl("")) {
312         emit fetchImage(m_user->profileImageUrl());
313     }
314
315     for(int i=0;i<m_friendsList.count();i++) {
316         if(m_friendsList.at(i)->profileImageUrl() != QUrl("")) {
317             m_visited++; // indicates how many friends that have profile image
318             emit fetchImage(m_friendsList.at(i)->profileImageUrl());
319         }
320     }
321 }