2 Situare - A location system for Facebook
3 Copyright (C) 2010 Ixonos Plc. Authors:
5 Kaj Wallin - kaj.wallin@ixonos.com
6 Henri Lampela - henri.lampela@ixonos.com
7 Jussi Laitinen - jussi.laitinen@ixonos.com
8 Sami Rämö - sami.ramo@ixonos.com
10 Situare is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License
12 version 2 as published by the Free Software Foundation.
14 Situare is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with Situare; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25 #include <QMessageBox>
26 #include <QNetworkReply>
29 #include "facebookservice/facebookauthentication.h"
30 #include "gps/gpsposition.h"
31 #include "map/mapengine.h"
32 #include "situareservice/situareservice.h"
33 #include "ui/mainwindow.h"
34 #include "network/networkaccessmanager.h"
40 const QString SETTINGS_GPS_ENABLED = "GPS_ENABLED"; ///< GPS setting
41 const QString SETTINGS_AUTO_CENTERING_ENABLED = "AUTO_CENTERING_ENABLED";///< Auto centering setting
42 const int DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE = 12; ///< Default zoom level when GPS available
43 const qreal USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE = 0.003;///< Min value for user move latitude
44 const qreal USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE = 0.001;///< Min value for user move longitude
45 const int MIN_UPDATE_INTERVAL_MSECS = 5*60*1000;
47 SituareEngine::SituareEngine(QMainWindow *parent)
49 m_autoCenteringEnabled(false),
50 m_automaticUpdateFirstStart(true),
51 m_automaticUpdateRequest(false),
53 m_automaticUpdateIntervalTimer(0),
54 m_lastUpdatedGPSPosition(QPointF())
56 qDebug() << __PRETTY_FUNCTION__;
57 m_ui = new MainWindow;
58 m_ui->updateItemVisibility();
60 m_networkAccessManager = NetworkAccessManager::instance();
63 m_mapEngine = new MapEngine(this);
64 m_ui->setMapViewScene(m_mapEngine->scene());
67 m_gps = new GPSPosition(this);
69 // build SituareService
70 m_situareService = new SituareService(this);
72 // build FacebookAuthenticator
73 m_facebookAuthenticator = new FacebookAuthentication(this);
76 signalsFromMapEngine();
78 signalsFromSituareService();
79 signalsFromMainWindow();
80 signalsFromFacebookAuthenticator();
82 connect(this, SIGNAL(userLocationReady(User*)),
83 m_ui, SIGNAL(userLocationReady(User*)));
85 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
86 m_ui, SIGNAL(friendsLocationsReady(QList<User*>&)));
88 connect(this, SIGNAL(userLocationReady(User*)),
89 m_mapEngine, SLOT(receiveOwnLocation(User*)));
91 connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
92 m_mapEngine, SIGNAL(friendsLocationsReady(QList<User*>&)));
94 connect(this, SIGNAL(friendImageReady(User*)),
95 m_ui, SIGNAL(friendImageReady(User*)));
97 connect(this, SIGNAL(friendImageReady(User*)),
98 m_mapEngine, SIGNAL(friendImageReady(User*)));
100 m_automaticUpdateIntervalTimer = new QTimer(this);
101 connect(m_automaticUpdateIntervalTimer, SIGNAL(timeout()),
102 this, SLOT(startAutomaticUpdate()));
104 // signals connected, now it's time to show the main window
105 // but init the MapEngine before so starting location is set
109 m_facebookAuthenticator->start();
111 m_gps->setMode(GPSPosition::Default);
112 initializeGpsAndAutocentering();
114 m_mce = new MCE(this);
115 connect(m_mce, SIGNAL(displayStateChanged(bool)), this, SLOT(displayStateChanged(bool)));
118 SituareEngine::~SituareEngine()
120 qDebug() << __PRETTY_FUNCTION__;
124 QSettings settings(DIRECTORY_NAME, FILE_NAME);
125 settings.setValue(SETTINGS_GPS_ENABLED, m_gps->isRunning());
126 settings.setValue(SETTINGS_AUTO_CENTERING_ENABLED, m_autoCenteringEnabled);
129 void SituareEngine::changeAutoCenteringSetting(bool enabled)
131 qDebug() << __PRETTY_FUNCTION__;
133 m_autoCenteringEnabled = enabled;
134 enableAutoCentering(enabled);
137 void SituareEngine::disableAutoCentering()
139 qDebug() << __PRETTY_FUNCTION__;
141 changeAutoCenteringSetting(false);
142 m_ui->buildInformationBox(tr("Auto centering disabled"));
145 void SituareEngine::displayStateChanged(bool enabled)
147 qDebug() << __PRETTY_FUNCTION__;
149 m_gps->enablePowerSave(!enabled);
151 if (m_autoCenteringEnabled)
152 enableAutoCentering(enabled);
155 void SituareEngine::enableAutoCentering(bool enabled)
157 qDebug() << __PRETTY_FUNCTION__;
159 m_ui->setAutoCenteringButtonEnabled(enabled);
160 m_mapEngine->setAutoCentering(enabled);
163 m_gps->requestLastPosition();
166 void SituareEngine::enableGPS(bool enabled)
168 qDebug() << __PRETTY_FUNCTION__;
170 m_ui->setOwnLocationCrosshairVisibility(!enabled);
172 if (m_gps->isInitialized()) {
173 m_ui->setGPSButtonEnabled(enabled);
174 m_mapEngine->setGPSEnabled(enabled);
176 if (enabled && !m_gps->isRunning()) {
178 enableAutoCentering(m_autoCenteringEnabled);
179 m_gps->requestLastPosition();
181 if(m_ui->loginState())
182 m_ui->readAutomaticLocationUpdateSettings();
184 else if (!enabled && m_gps->isRunning()) {
186 enableAutoCentering(false);
187 enableAutomaticLocationUpdate(false);
192 m_ui->buildInformationBox(tr("Unable to start GPS"));
193 m_ui->setGPSButtonEnabled(false);
194 m_mapEngine->setGPSEnabled(false);
198 void SituareEngine::enableAutomaticLocationUpdate(bool enabled, int updateIntervalMsecs)
200 qDebug() << __PRETTY_FUNCTION__;
202 //Show automatic update confirmation dialog
203 if (m_automaticUpdateFirstStart && m_gps->isRunning() && enabled) {
204 m_ui->showEnableAutomaticUpdateLocationDialog(
205 tr("Do you want to enable automatic location update with %1 min update interval?")
206 .arg(updateIntervalMsecs/1000/60));
207 m_automaticUpdateFirstStart = false;
209 if (enabled && m_gps->isRunning()) {
210 m_ui->buildInformationBox(tr("Automatic location update enabled"));
211 if (updateIntervalMsecs < MIN_UPDATE_INTERVAL_MSECS)
212 m_automaticUpdateIntervalTimer->setInterval(MIN_UPDATE_INTERVAL_MSECS);
214 m_automaticUpdateIntervalTimer->setInterval(updateIntervalMsecs);
216 connect(m_gps, SIGNAL(position(QPointF,qreal)),
217 this, SLOT(requestAutomaticUpdateIfMoved(QPointF)));
219 m_automaticUpdateIntervalTimer->start();
222 disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
223 this, SLOT(requestAutomaticUpdateIfMoved(QPointF)));
225 m_automaticUpdateIntervalTimer->stop();
230 void SituareEngine::error(const int context, const int error)
232 qDebug() << __PRETTY_FUNCTION__;
236 case SituareError::ERROR_GENERAL:
237 if(context == ErrorContext::SITUARE) {
238 m_ui->toggleProgressIndicator(false);
239 m_ui->buildInformationBox(tr("Unknown server error"), true);
242 case 1: //errors: SituareError::ERROR_MISSING_ARGUMENT and QNetworkReply::ConnectionRefusedError
243 m_ui->toggleProgressIndicator(false);
244 if(context == ErrorContext::SITUARE) {
245 m_ui->buildInformationBox(tr("Missing parameter from request"), true);
246 } else if(context == ErrorContext::NETWORK) {
247 m_ui->buildInformationBox(tr("Connection refused by the server"), true);
250 case QNetworkReply::RemoteHostClosedError:
251 if(context == ErrorContext::NETWORK) {
252 m_ui->toggleProgressIndicator(false);
253 m_ui->buildInformationBox(tr("Connection closed by the server"), true);
256 case QNetworkReply::HostNotFoundError:
257 if(context == ErrorContext::NETWORK) {
258 m_ui->toggleProgressIndicator(false);
259 m_ui->buildInformationBox(tr("Remote server not found"), true);
262 case QNetworkReply::TimeoutError:
263 if(context == ErrorContext::NETWORK) {
264 m_ui->toggleProgressIndicator(false);
265 m_ui->buildInformationBox(tr("Connection timed out"), true);
268 case QNetworkReply::UnknownNetworkError:
269 if(context == ErrorContext::NETWORK) {
270 m_ui->toggleProgressIndicator(false);
271 m_ui->buildInformationBox(tr("No network connection"), true);
274 case SituareError::SESSION_EXPIRED:
275 m_ui->buildInformationBox(tr("Session expired. Please login again"), true);
276 m_facebookAuthenticator->clearAccountInformation(true); // keep username = true
277 m_situareService->clearUserData();
278 m_ui->loggedIn(false);
281 case SituareError::LOGIN_FAILED:
282 m_ui->toggleProgressIndicator(false);
283 m_ui->buildInformationBox(tr("Invalid E-mail address or password"), true);
286 case SituareError::UPDATE_FAILED:
287 m_ui->toggleProgressIndicator(false);
288 m_ui->buildInformationBox(tr("Update failed, please try again"), true);
290 case SituareError::DATA_RETRIEVAL_FAILED:
291 m_ui->toggleProgressIndicator(false);
292 m_ui->buildInformationBox(tr("Data retrieval failed, please try again"), true);
294 case SituareError::ADDRESS_RETRIEVAL_FAILED:
295 case SituareError::ERROR_GEOLOCATION_REQUEST_FAIL:
296 case SituareError::ERROR_GEOLOCATION_LONLAT_INVALID:
297 m_ui->toggleProgressIndicator(false);
298 m_ui->buildInformationBox(tr("Address retrieval failed"), true);
300 case SituareError::IMAGE_DOWNLOAD_FAILED:
301 m_ui->buildInformationBox(tr("Image download failed"), true);
303 case SituareError::MAP_IMAGE_DOWNLOAD_FAILED:
304 m_ui->buildInformationBox(tr("Map image download failed"), true);
306 case SituareError::GPS_INITIALIZATION_FAILED:
308 m_ui->buildInformationBox(tr("GPS initialization failed"), true);
310 case SituareError::INVALID_JSON:
311 m_ui->buildInformationBox(tr("Malformatted reply from server"), true);
312 m_ui->loggedIn(false);
313 m_facebookAuthenticator->clearAccountInformation(false); // clean all
315 case SituareError::ERROR_GEOLOCATION_SERVER_UNAVAILABLE:
316 m_ui->toggleProgressIndicator(false);
317 m_ui->buildInformationBox(tr("Address server not responding"), true);
320 m_ui->toggleProgressIndicator(false);
321 if(context == ErrorContext::NETWORK)
322 qCritical() << "QNetworkReply::NetworkError: " << error;
324 qCritical() << "Unknown error: " << error;
330 void SituareEngine::fetchUsernameFromSettings()
332 qDebug() << __PRETTY_FUNCTION__;
334 m_ui->setUsername(m_facebookAuthenticator->loadUsername());
337 void SituareEngine::imageReady(User *user)
339 qDebug() << __PRETTY_FUNCTION__;
342 emit userLocationReady(user);
344 emit friendImageReady(user);
347 void SituareEngine::initializeGpsAndAutocentering()
349 qDebug() << __PRETTY_FUNCTION__;
351 QSettings settings(DIRECTORY_NAME, FILE_NAME);
352 QVariant gpsEnabled = settings.value(SETTINGS_GPS_ENABLED);
353 QVariant autoCenteringEnabled = settings.value(SETTINGS_AUTO_CENTERING_ENABLED);
355 if (m_gps->isInitialized()) {
357 if (gpsEnabled.toString().isEmpty()) { // First start. Situare.conf file does not exists
359 connect(m_gps, SIGNAL(position(QPointF,qreal)),
360 this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
362 changeAutoCenteringSetting(true);
365 m_ui->buildInformationBox(tr("GPS enabled"));
366 m_ui->buildInformationBox(tr("Auto centering enabled"));
368 } else { // Normal start
369 changeAutoCenteringSetting(autoCenteringEnabled.toBool());
370 enableGPS(gpsEnabled.toBool());
372 if (gpsEnabled.toBool())
373 m_ui->buildInformationBox(tr("GPS enabled"));
375 if (gpsEnabled.toBool() && autoCenteringEnabled.toBool())
376 m_ui->buildInformationBox(tr("Auto centering enabled"));
383 void SituareEngine::loginActionPressed()
385 qDebug() << __PRETTY_FUNCTION__;
387 if (m_networkAccessManager->isConnected()) {
388 if(m_ui->loginState()) {
390 m_situareService->clearUserData();
392 m_facebookAuthenticator->start();
396 error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
400 void SituareEngine::loginOk()
402 qDebug() << __PRETTY_FUNCTION__;
404 m_ui->loggedIn(true);
407 m_situareService->fetchLocations(); // request user locations
409 if (m_gps->isRunning())
410 m_ui->readAutomaticLocationUpdateSettings();
413 void SituareEngine::loginProcessCancelled()
415 qDebug() << __PRETTY_FUNCTION__;
417 m_ui->toggleProgressIndicator(false);
418 m_ui->updateItemVisibility();
421 void SituareEngine::logout()
423 qDebug() << __PRETTY_FUNCTION__;
425 m_ui->loggedIn(false);
427 // signal to clear locationUpdateDialog's data
428 connect(this, SIGNAL(clearUpdateLocationDialogData()),
429 m_ui, SIGNAL(clearUpdateLocationDialogData()));
430 emit clearUpdateLocationDialogData();
432 m_facebookAuthenticator->clearAccountInformation(); // clear all
433 m_automaticUpdateFirstStart = true;
436 void SituareEngine::refreshUserData()
438 qDebug() << __PRETTY_FUNCTION__;
440 if (m_networkAccessManager->isConnected()) {
441 m_ui->toggleProgressIndicator(true);
442 m_situareService->fetchLocations();
445 error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
449 void SituareEngine::requestAddress()
451 qDebug() << __PRETTY_FUNCTION__;
453 if (m_networkAccessManager->isConnected()) {
454 if (m_gps->isRunning())
455 m_situareService->reverseGeo(m_gps->lastPosition());
457 m_situareService->reverseGeo(m_mapEngine->centerGeoCoordinate());
460 error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
464 void SituareEngine::requestUpdateLocation(const QString &status, bool publish)
466 qDebug() << __PRETTY_FUNCTION__;
468 if (m_networkAccessManager->isConnected()) {
469 m_ui->toggleProgressIndicator(true);
471 if (m_gps->isRunning())
472 m_situareService->updateLocation(m_gps->lastPosition(), status, publish);
474 m_situareService->updateLocation(m_mapEngine->centerGeoCoordinate(), status, publish);
477 error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
481 void SituareEngine::requestAutomaticUpdateIfMoved(QPointF position)
483 qDebug() << __PRETTY_FUNCTION__;
485 if ((fabs(m_lastUpdatedGPSPosition.x() - position.x()) >
486 USER_MOVEMENT_MINIMUM_LONGITUDE_DIFFERENCE) ||
487 (fabs(m_lastUpdatedGPSPosition.y() - position.y()) >
488 USER_MOVEMENT_MINIMUM_LATITUDE_DIFFERENCE)) {
490 m_lastUpdatedGPSPosition = position;
494 if (m_automaticUpdateRequest && m_userMoved) {
495 requestUpdateLocation(tr("Automatic location update"));
496 m_automaticUpdateRequest = false;
501 void SituareEngine::setFirstStartZoomLevel(QPointF latLonCoordinate, qreal accuracy)
503 qDebug() << __PRETTY_FUNCTION__;
505 Q_UNUSED(latLonCoordinate);
508 if (m_autoCenteringEnabled) // autocentering is disabled when map is scrolled
509 m_mapEngine->setZoomLevel(DEFAULT_ZOOM_LEVEL_WHEN_GPS_IS_AVAILABLE);
511 disconnect(m_gps, SIGNAL(position(QPointF,qreal)),
512 this, SLOT(setFirstStartZoomLevel(QPointF,qreal)));
515 void SituareEngine::signalsFromFacebookAuthenticator()
517 qDebug() << __PRETTY_FUNCTION__;
519 connect(m_facebookAuthenticator, SIGNAL(error(int, int)),
520 this, SLOT(error(int, int)));
522 connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
523 m_situareService, SLOT(credentialsReady(FacebookCredentials)));
525 connect(m_facebookAuthenticator, SIGNAL(credentialsReady(FacebookCredentials)),
526 this, SLOT(loginOk()));
528 connect(m_facebookAuthenticator, SIGNAL(newLoginRequest()),
529 m_ui, SLOT(startLoginProcess()));
531 connect(m_facebookAuthenticator, SIGNAL(saveCookiesRequest()),
532 m_ui, SLOT(saveCookies()));
534 connect(m_facebookAuthenticator, SIGNAL(loginUsingCookies()),
535 m_ui, SLOT(loginUsingCookies()));
538 void SituareEngine::signalsFromGPS()
540 qDebug() << __PRETTY_FUNCTION__;
542 connect(m_gps, SIGNAL(position(QPointF,qreal)),
543 m_mapEngine, SLOT(gpsPositionUpdate(QPointF,qreal)));
545 connect(m_gps, SIGNAL(timeout()),
546 m_ui, SLOT(gpsTimeout()));
548 connect(m_gps, SIGNAL(error(int, int)),
549 this, SLOT(error(int, int)));
552 void SituareEngine::signalsFromMainWindow()
554 qDebug() << __PRETTY_FUNCTION__;
556 connect(m_ui, SIGNAL(error(int, int)),
557 this, SLOT(error(int, int)));
559 connect(m_ui, SIGNAL(fetchUsernameFromSettings()),
560 this, SLOT(fetchUsernameFromSettings()));
562 connect(m_ui, SIGNAL(loginActionPressed()),
563 this, SLOT(loginActionPressed()));
565 connect(m_ui, SIGNAL(saveUsername(QString)),
566 m_facebookAuthenticator, SLOT(saveUsername(QString)));
568 connect(m_ui, SIGNAL(updateCredentials(QUrl)),
569 m_facebookAuthenticator, SLOT(updateCredentials(QUrl)));
571 // signals from map view
572 connect(m_ui, SIGNAL(mapViewScrolled(QPoint)),
573 m_mapEngine, SLOT(setCenterPosition(QPoint)));
575 connect(m_ui, SIGNAL(mapViewResized(QSize)),
576 m_mapEngine, SLOT(viewResized(QSize)));
578 connect(m_ui, SIGNAL(viewZoomFinished()),
579 m_mapEngine, SLOT(viewZoomFinished()));
581 // signals from zoom buttons (zoom panel and volume buttons)
582 connect(m_ui, SIGNAL(zoomIn()),
583 m_mapEngine, SLOT(zoomIn()));
585 connect(m_ui, SIGNAL(zoomOut()),
586 m_mapEngine, SLOT(zoomOut()));
588 // signals from menu buttons
589 connect(m_ui, SIGNAL(autoCenteringTriggered(bool)),
590 this, SLOT(changeAutoCenteringSetting(bool)));
592 connect(m_ui, SIGNAL(gpsTriggered(bool)),
593 this, SLOT(enableGPS(bool)));
595 //signals from dialogs
596 connect(m_ui, SIGNAL(cancelLoginProcess()),
597 this, SLOT(loginProcessCancelled()));
599 connect(m_ui, SIGNAL(requestReverseGeo()),
600 this, SLOT(requestAddress()));
602 connect(m_ui, SIGNAL(statusUpdate(QString,bool)),
603 this, SLOT(requestUpdateLocation(QString,bool)));
605 connect(m_ui, SIGNAL(enableAutomaticLocationUpdate(bool, int)),
606 this, SLOT(enableAutomaticLocationUpdate(bool, int)));
608 // signals from user info tab
609 connect(m_ui, SIGNAL(refreshUserData()),
610 this, SLOT(refreshUserData()));
612 connect(m_ui, SIGNAL(findUser(QPointF)),
613 m_mapEngine, SLOT(centerToCoordinates(QPointF)));
615 // signals from friend list tab
616 connect(m_ui, SIGNAL(findFriend(QPointF)),
617 m_mapEngine, SLOT(centerToCoordinates(QPointF)));
620 void SituareEngine::signalsFromMapEngine()
622 qDebug() << __PRETTY_FUNCTION__;
624 connect(m_mapEngine, SIGNAL(error(int, int)),
625 this, SLOT(error(int, int)));
627 connect(m_mapEngine, SIGNAL(locationChanged(QPoint)),
628 m_ui, SIGNAL(centerToSceneCoordinates(QPoint)));
630 connect(m_mapEngine, SIGNAL(zoomLevelChanged(int)),
631 m_ui, SIGNAL(zoomLevelChanged(int)));
633 connect(m_mapEngine, SIGNAL(mapScrolledManually()),
634 this, SLOT(disableAutoCentering()));
636 connect(m_mapEngine, SIGNAL(maxZoomLevelReached()),
637 m_ui, SIGNAL(maxZoomLevelReached()));
639 connect(m_mapEngine, SIGNAL(minZoomLevelReached()),
640 m_ui, SIGNAL(minZoomLevelReached()));
642 connect(m_mapEngine, SIGNAL(locationItemClicked(QList<QString>)),
643 m_ui, SIGNAL(locationItemClicked(QList<QString>)));
645 connect(m_mapEngine, SIGNAL(newMapResolution(qreal)),
646 m_ui, SIGNAL(newMapResolution(qreal)));
649 void SituareEngine::signalsFromSituareService()
651 qDebug() << __PRETTY_FUNCTION__;
653 connect(m_situareService, SIGNAL(error(int, int)),
654 this, SLOT(error(int, int)));
656 connect(m_situareService, SIGNAL(imageReady(User*)),
657 this, SLOT(imageReady(User*)));
659 connect(m_situareService, SIGNAL(reverseGeoReady(QString)),
660 m_ui, SIGNAL(reverseGeoReady(QString)));
662 connect(m_situareService, SIGNAL(userDataChanged(User*, QList<User*>&)),
663 this, SLOT(userDataChanged(User*, QList<User*>&)));
665 connect(m_situareService, SIGNAL(updateWasSuccessful()),
666 this, SLOT(updateWasSuccessful()));
668 connect(m_situareService, SIGNAL(updateWasSuccessful()),
669 m_ui, SIGNAL(clearUpdateLocationDialogData()));
672 void SituareEngine::startAutomaticUpdate()
674 qDebug() << __PRETTY_FUNCTION__;
676 m_gps->requestUpdate();
677 m_automaticUpdateRequest = true;
680 void SituareEngine::updateWasSuccessful()
682 qDebug() << __PRETTY_FUNCTION__;
684 if (m_networkAccessManager->isConnected())
685 m_situareService->fetchLocations();
687 error(ErrorContext::NETWORK, QNetworkReply::UnknownNetworkError);
690 void SituareEngine::userDataChanged(User *user, QList<User *> &friendsList)
692 qDebug() << __PRETTY_FUNCTION__;
694 m_ui->toggleProgressIndicator(false);
697 emit userLocationReady(user);
698 emit friendsLocationsReady(friendsList);