summaryrefslogtreecommitdiff
path: root/src/plugins/geoservices/nokia/qplacemanagerengine_nokiav2.cpp
blob: e658ebe45145f7bc3fcad025b496b35b3cc0a6e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
** This file is part of the Nokia services plugin for the Maps and
** Navigation API.  The use of these services, whether by use of the
** plugin or by other means, is governed by the terms and conditions
** described by the file NOKIA_TERMS_AND_CONDITIONS.txt in
** this package, located in the directory containing the Nokia services
** plugin source code.
**
****************************************************************************/

#include "qplacemanagerengine_nokiav2.h"

#include "placesv2/qplacecategoriesreplyimpl.h"
#include "placesv2/qplacecontentreplyimpl.h"
#include "placesv2/qplacesearchsuggestionreplyimpl.h"
#include "placesv2/qplacesearchreplyimpl.h"
#include "placesv2/qplacerecommendationreplyimpl.h"
#include "placesv2/qplacedetailsreplyimpl.h"
#include "placesv2/qplaceidreplyimpl.h"
#include "qgeonetworkaccessmanager.h"
#include "qgeouriprovider.h"
#include "uri_constants.h"

#include <QtCore/QFile>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QStandardPaths>
#include <QtCore/QUrlQuery>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QNetworkProxyFactory>

#include <QtLocation/QPlaceContentRequest>
#include <QtLocation/QGeoBoundingCircle>

QT_BEGIN_NAMESPACE

static const char FIXED_CATEGORIES_string[] =
    "eat-drink\0"
    "going-out\0"
    "sights-museums\0"
    "transport\0"
    "accommodation\0"
    "shopping\0"
    "leisure-outdoor\0"
    "administrative-areas-buildings\0"
    "natural-geographical\0"
    "\0";

static const int FIXED_CATEGORIES_indices[] = {
       0,   10,   20,   35,   45,   59,   68,   84,
     115,   -1
};

QPlaceManagerEngineNokiaV2::QPlaceManagerEngineNokiaV2(
    QGeoNetworkAccessManager *networkManager,
    const QMap<QString, QVariant> &parameters,
    QGeoServiceProvider::Error *error,
    QString *errorString)
    : QPlaceManagerEngine(parameters)
    , m_manager(networkManager)
    , m_uriProvider(new QGeoUriProvider(this, parameters, "places.host", PLACES_HOST, PLACES_HOST_CN))
{
    Q_ASSERT(networkManager);
    m_manager->setParent(this);

    m_locales.append(QLocale());

    m_appId = parameters.value(QLatin1String("app_id")).toString();
    m_appCode = parameters.value(QLatin1String("token")).toString();

    m_theme = parameters.value("places.theme", QString()).toString();

    if (m_theme == QLatin1String("default"))
        m_theme.clear();

    m_localDataPath = parameters.value(QLatin1String("local_data_path"), QString()).toString();
    if (m_localDataPath.isEmpty()) {
        QStringList dataLocations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);

        if (!dataLocations.isEmpty() && !dataLocations.first().isEmpty()) {
            m_localDataPath = dataLocations.first()
                                + QLatin1String("/nokia/qtlocation/data");
        }
    }

    if (error)
        *error = QGeoServiceProvider::NoError;

    if (errorString)
        errorString->clear();
}

QPlaceManagerEngineNokiaV2::~QPlaceManagerEngineNokiaV2() {}

QPlaceDetailsReply *QPlaceManagerEngineNokiaV2::getPlaceDetails(const QString &placeId)
{
    QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/places/") + placeId);

    QUrlQuery queryItems;

    queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));
    //queryItems.append(qMakePair<QString, QString>(QLatin1String("size"), QString::number(5)));
    //queryItems.append(qMakePair<QString, QString>(QLatin1String("image_dimensions"), QLatin1String("w64-h64,w100")));

    requestUrl.setQuery(queryItems);

    QNetworkReply *networkReply = sendRequest(requestUrl);

    QPlaceDetailsReplyImpl *reply = new QPlaceDetailsReplyImpl(networkReply, this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    return reply;
}

QPlaceContentReply *QPlaceManagerEngineNokiaV2::getPlaceContent(const QString &placeId,
                                                              const QPlaceContentRequest &request)
{
    QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/places/") + placeId + QLatin1String("/media/"));

    QNetworkReply *networkReply = 0;

    QUrlQuery queryItems;

    switch (request.contentType()) {
    case QPlaceContent::ImageType:
        requestUrl.setPath(requestUrl.path() + QLatin1String("images"));

        queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

        if (request.limit() > 0) {
            queryItems.addQueryItem(QLatin1String("size"),
                                    QString::number(request.limit()));
        }
        if (request.offset() > -1) {
            queryItems.addQueryItem(QLatin1String("offset"),
                                    QString::number(request.offset()));
        }

        //queryItems.append(qMakePair<QString, QString>(QLatin1String("image_dimensions"), QLatin1String("w64-h64,w100")));

        requestUrl.setQuery(queryItems);

        networkReply = sendRequest(requestUrl);
        break;
    case QPlaceContent::ReviewType:
        requestUrl.setPath(requestUrl.path() + QLatin1String("reviews"));

        queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

        if (request.limit() > 0) {
            queryItems.addQueryItem(QLatin1String("size"),
                                    QString::number(request.limit()));
        }
        if (request.offset() > -1) {
            queryItems.addQueryItem(QLatin1String("offset"),
                                    QString::number(request.offset()));
        }

        requestUrl.setQuery(queryItems);

        networkReply = sendRequest(requestUrl);
        break;
    case QPlaceContent::EditorialType:
        requestUrl.setPath(requestUrl.path() + QLatin1String("editorials"));

        queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

        if (request.limit() > 0) {
            queryItems.addQueryItem(QLatin1String("size"),
                                    QString::number(request.limit()));
        }
        if (request.offset() > -1) {
            queryItems.addQueryItem(QLatin1String("offset"),
                                    QString::number(request.offset()));
        }

        requestUrl.setQuery(queryItems);

        networkReply = sendRequest(requestUrl);
        break;
    case QPlaceContent::NoType:
        ;
    }

    QPlaceContentReply *reply = new QPlaceContentReplyImpl(request, networkReply, this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    if (!networkReply) {
        QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                                  Q_ARG(QPlaceReply::Error, QPlaceReply::UnsupportedError),
                                  Q_ARG(QString, QString("Retrieval of given content type not supported.")));
    }

    return reply;
}

static void addAtForBoundingArea(const QGeoBoundingArea &area,
                                 QUrlQuery *queryItems)
{
    QGeoCoordinate center;
    switch (area.type()) {
    case QGeoBoundingArea::BoxType:
        center = QGeoBoundingBox(area).center();
        break;
    case QGeoBoundingArea::CircleType:
        center = QGeoBoundingCircle(area).center();
        break;
    case QGeoBoundingArea::UnknownType:
        break;
    }

    if (!center.isValid())
        return;

    queryItems->addQueryItem(QLatin1String("at"),
                             QString::number(center.latitude()) +
                             QLatin1Char(',') +
                             QString::number(center.longitude()));
}

QPlaceSearchReply *QPlaceManagerEngineNokiaV2::search(const QPlaceSearchRequest &query)
{
    bool unsupported = false;

    unsupported |= query.visibilityScope() != QtLocation::UnspecifiedVisibility &&
                   query.visibilityScope() != QtLocation::PublicVisibility;

    unsupported |= !query.searchTerm().isEmpty() && query.offset() > 0;

    // Both a search term and search categories are not supported.
    unsupported |= !query.searchTerm().isEmpty() && !query.categories().isEmpty();

    if (unsupported) {
        QPlaceSearchReplyImpl *reply = new QPlaceSearchReplyImpl(0, this);
        QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                                  Q_ARG(QPlaceReply::Error, QPlaceReply::BadArgumentError),
                                  Q_ARG(QString, "Unsupported search request options specified."));

        return reply;
    }

    if (!query.searchTerm().isEmpty()) {
        // search term query
        QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/discover/search"));

        QUrlQuery queryItems;

        queryItems.addQueryItem(QLatin1String("q"), query.searchTerm());

        addAtForBoundingArea(query.searchArea(), &queryItems);

        queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

        if (query.limit() > 0) {
            queryItems.addQueryItem(QLatin1String("size"),
                                    QString::number(query.limit()));
        }

        requestUrl.setQuery(queryItems);

        QNetworkReply *networkReply = sendRequest(requestUrl);

        QPlaceSearchReplyImpl *reply = new QPlaceSearchReplyImpl(networkReply, this);
        connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
        connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
                this, SLOT(replyError(QPlaceReply::Error,QString)));

        return reply;
    } else {
        // category search
        // The request URL should be "/v1/discover/explore" but that returns both places and
        // clusters of places.  We don't support clusters so we use the undocumented
        // "/v1/discover/explore/places" instead which only returns places.
        QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/discover/explore/places"));

        QUrlQuery queryItems;

        QStringList ids;
        foreach (const QPlaceCategory &category, query.categories())
            ids.append(category.categoryId());

        if (ids.count() > 0) {
            queryItems.addQueryItem(QLatin1String("cat"),
                                    ids.join(QLatin1String(",")));
        }

        addAtForBoundingArea(query.searchArea(), &queryItems);

        queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

        if (query.limit() > 0) {
            queryItems.addQueryItem(QLatin1String("size"),
                                    QString::number(query.limit()));
        }
        if (query.offset() > -1) {
            queryItems.addQueryItem(QLatin1String("offset"),
                                    QString::number(query.offset()));
        }

        requestUrl.setQuery(queryItems);

        QNetworkReply *networkReply = sendRequest(requestUrl);

        QPlaceSearchReplyImpl *reply = new QPlaceSearchReplyImpl(networkReply, this);
        connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
        connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
                this, SLOT(replyError(QPlaceReply::Error,QString)));

        return reply;
    }
}

QPlaceSearchReply *QPlaceManagerEngineNokiaV2::recommendations(const QString &placeId, const QPlaceSearchRequest &query)
{
    QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/places/") + placeId + QLatin1String("/related/recommended"));

    QUrlQuery queryItems;

    queryItems.addQueryItem(QLatin1String("tf"), QLatin1String("html"));

    if (query.limit() > 0) {
        queryItems.addQueryItem(QLatin1String("size"),
                                QString::number(query.limit()));
    }
    if (query.offset() > -1) {
        queryItems.addQueryItem(QLatin1String("offset"),
                                QString::number(query.offset()));
    }

    requestUrl.setQuery(queryItems);

    QNetworkReply *networkReply = sendRequest(requestUrl);

    QPlaceRecommendationReplyImpl *reply = new QPlaceRecommendationReplyImpl(networkReply, this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    return reply;
}

QPlaceSearchSuggestionReply *QPlaceManagerEngineNokiaV2::searchSuggestions(const QPlaceSearchRequest &query)
{
    QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/suggest"));

    QUrlQuery queryItems;

    queryItems.addQueryItem(QLatin1String("q"), query.searchTerm());

    addAtForBoundingArea(query.searchArea(), &queryItems);

    requestUrl.setQuery(queryItems);

    QNetworkReply *networkReply = sendRequest(requestUrl);

    QPlaceSearchSuggestionReplyImpl *reply = new QPlaceSearchSuggestionReplyImpl(networkReply, this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    return reply;
}

QPlaceIdReply *QPlaceManagerEngineNokiaV2::savePlace(const QPlace &place)
{
    QPlaceIdReplyImpl *reply = new QPlaceIdReplyImpl(QPlaceIdReply::SavePlace, this);
    reply->setId(place.placeId());
    QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                              Q_ARG(QPlaceReply::Error, QPlaceReply::UnsupportedError),
                              Q_ARG(QString, tr("Saving places is not supported.")));
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));
    return reply;
}

QPlaceIdReply *QPlaceManagerEngineNokiaV2::removePlace(const QString &placeId)
{
    QPlaceIdReplyImpl *reply = new QPlaceIdReplyImpl(QPlaceIdReply::RemovePlace, this);
    reply->setId(placeId);
    QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                              Q_ARG(QPlaceReply::Error, QPlaceReply::UnsupportedError),
                              Q_ARG(QString, tr("Removing places is not supported.")));
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));
    return reply;
}

QPlaceIdReply *QPlaceManagerEngineNokiaV2::saveCategory(const QPlaceCategory &category, const QString &parentId)
{
    Q_UNUSED(parentId)

    QPlaceIdReplyImpl *reply = new QPlaceIdReplyImpl(QPlaceIdReply::SaveCategory, this);
    reply->setId(category.categoryId());
    QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                              Q_ARG(QPlaceReply::Error, QPlaceReply::UnsupportedError),
                              Q_ARG(QString, tr("Saving categories is not supported.")));
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));
    return reply;
}

QPlaceIdReply *QPlaceManagerEngineNokiaV2::removeCategory(const QString &categoryId)
{
    QPlaceIdReplyImpl *reply = new QPlaceIdReplyImpl(QPlaceIdReply::RemoveCategory, this);
    reply->setId(categoryId);
    QMetaObject::invokeMethod(reply, "setError", Qt::QueuedConnection,
                              Q_ARG(QPlaceReply::Error, QPlaceReply::UnsupportedError),
                              Q_ARG(QString, tr("Removing categories is not supported.")));
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));
    return reply;
}

QPlaceReply *QPlaceManagerEngineNokiaV2::initializeCategories()
{
    if (m_categoryReply)
        return m_categoryReply.data();

    for (int i = 0; FIXED_CATEGORIES_indices[i] != -1; ++i) {
        const QString id = QString::fromLatin1(FIXED_CATEGORIES_string +
                                               FIXED_CATEGORIES_indices[i]);

        QUrl requestUrl(m_uriProvider->getCurrentHost() + QLatin1String("/v1/categories/places/") + id);
        QNetworkReply *networkReply = sendRequest(requestUrl);
        connect(networkReply, SIGNAL(finished()), this, SLOT(categoryReplyFinished()));
        connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)),
                this, SLOT(categoryReplyError()));

        m_categoryRequests.insert(id, networkReply);
    }

    QPlaceCategoriesReplyImpl *reply = new QPlaceCategoriesReplyImpl(this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    m_categoryReply = reply;
    return reply;
}

QString QPlaceManagerEngineNokiaV2::parentCategoryId(const QString &categoryId) const
{
    return m_categoryTree.value(categoryId).parentId;
}

QStringList QPlaceManagerEngineNokiaV2::childCategoryIds(const QString &categoryId) const
{
    return m_categoryTree.value(categoryId).childIds;
}

QPlaceCategory QPlaceManagerEngineNokiaV2::category(const QString &categoryId) const
{
    return m_categoryTree.value(categoryId).category;
}

QList<QPlaceCategory> QPlaceManagerEngineNokiaV2::childCategories(const QString &parentId) const
{
    QList<QPlaceCategory> results;
    foreach (const QString &childId, m_categoryTree.value(parentId).childIds)
        results.append(m_categoryTree.value(childId).category);
    return results;
}

QList<QLocale> QPlaceManagerEngineNokiaV2::locales() const
{
    return m_locales;
}

void QPlaceManagerEngineNokiaV2::setLocales(const QList<QLocale> &locales)
{
    m_locales = locales;
}

QString QPlaceManagerEngineNokiaV2::iconPath(const QString &remotePath) const
{
    if (remotePath.isEmpty())
        return QString();

    QString remoteIcon = remotePath
            + (!m_theme.isEmpty() ? QLatin1Char('.') + m_theme : QString());

    if (!remotePath.contains(QLatin1String("/icons/categories/"))
            || m_localDataPath.isEmpty()) {
        return remoteIcon;
    }

    QString localIcon = remotePath.mid(remotePath.lastIndexOf(QLatin1Char('/')) + 1);
    localIcon.prepend(m_localDataPath + QLatin1String("/icons/categories/"));

    if (!m_theme.isEmpty())
        localIcon.append(QLatin1Char('.') + m_theme);

    if (QFile::exists(localIcon))
        return QString::fromLatin1("file://") + localIcon;
    else
        return remoteIcon;
}

void QPlaceManagerEngineNokiaV2::replyFinished()
{
    QPlaceReply *reply = qobject_cast<QPlaceReply *>(sender());
    if (reply)
        emit finished(reply);
}

void QPlaceManagerEngineNokiaV2::replyError(QPlaceReply::Error error_, const QString &errorString)
{
    QPlaceReply *reply = qobject_cast<QPlaceReply *>(sender());
    if (reply)
        emit error(reply, error_, errorString);
}

void QPlaceManagerEngineNokiaV2::categoryReplyFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument document = QJsonDocument::fromJson(reply->readAll());
        if (!document.isObject()) {
            if (m_categoryReply) {
                QMetaObject::invokeMethod(m_categoryReply.data(), "setError", Qt::QueuedConnection,
                                          Q_ARG(QPlaceReply::Error, QPlaceReply::ParseError),
                                          Q_ARG(QString, tr("Error parsing response.")));
            }
            return;
        }

        QJsonObject category = document.object();

        PlaceCategoryNode node;
        node.category.setCategoryId(category.value(QLatin1String("categoryId")).toString());
        node.category.setName(category.value(QLatin1String("name")).toString());

        QString iconPath = QPlaceManagerEngineNokiaV2::iconPath(
                        category.value(QLatin1String("icon")).toString());
        QVariantMap parameters;
        parameters.insert(QPlaceIcon::SingleUrl,
                          QUrl(iconPath));
        QPlaceIcon icon;
        icon.setParameters(parameters);
        node.category.setIcon(icon);

        m_categoryTree.insert(node.category.categoryId(), node);

        m_categoryTree[QString()].childIds.append(node.category.categoryId());
    }

    m_categoryRequests.remove(m_categoryRequests.key(reply));
    reply->deleteLater();

    if (m_categoryRequests.isEmpty() && m_categoryReply)
        m_categoryReply.data()->emitFinished();
}

void QPlaceManagerEngineNokiaV2::categoryReplyError()
{
    if (m_categoryReply) {
        QMetaObject::invokeMethod(m_categoryReply.data(), "setError", Qt::QueuedConnection,
                                  Q_ARG(QPlaceReply::Error, QPlaceReply::CommunicationError),
                                  Q_ARG(QString, tr("Network error.")));
    }
}

QNetworkReply *QPlaceManagerEngineNokiaV2::sendRequest(const QUrl &url)
{
    QUrlQuery queryItems(url);
    queryItems.addQueryItem(QLatin1String("app_id"), m_appId);
    queryItems.addQueryItem(QLatin1String("app_code"), m_appCode);

    QUrl requestUrl = url;
    requestUrl.setQuery(queryItems);

    QNetworkRequest request;
    request.setUrl(requestUrl);

    request.setRawHeader("Accept", "application/json");
    request.setRawHeader("Accept-Language", createLanguageString());

    return m_manager->get(request);
}

QByteArray QPlaceManagerEngineNokiaV2::createLanguageString() const
{
    QByteArray language;

    QList<QLocale> locales = m_locales;
    if (locales.isEmpty())
        locales << QLocale();

    foreach (const QLocale &loc, locales) {
        language.append(loc.name().replace(2, 1, QLatin1Char('-')).toLatin1());
        language.append(", ");
    }
    language.chop(2);

    return language;
}

QT_END_NAMESPACE