~timeout-scope-team/timeout-scope/timeout

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
/*
 * This file is part of Ubuntu TimeOut Scope.
 * Copyright 2014 Canonical Ltd.
 * 
 * TimeOut Scope is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation.
 *
 * TimeOut Scope is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TimeOut Scope. If not, see <http://www.gnu.org/licenses/>.
 */

#include "TimeOut-client.h"

#include <chrono>
#include <utility>

#include <QCoreApplication>
#include <QNetworkDiskCache>

#define VERBOSE

#define TIMING

#ifdef TIMING
#define INIT_TIMER auto start = std::chrono::high_resolution_clock::now();
#define START_TIMER  start = std::chrono::high_resolution_clock::now();
#define STOP_TIMER(name)  qDebug() << "RUNTIME of " << name << ": " << \
        std::chrono::duration_cast<std::chrono::milliseconds>( \
                            std::chrono::high_resolution_clock::now()-start \
                    ).count() << " ms "; 
#else
#define INIT_TIMER
#define START_TIMER
#define STOP_TIMER(name)
#endif

#define FOREACH_JSON(it, results)  for (QJsonArray::iterator it = results.begin(); it != results.end(); ++it)

const QString USER_AGENT = "TimeOut Scope (Ubuntu)";
const QString GEO_LOOKUP = "http://geoip.ubuntu.com/lookup";
const QString URL = "http://graffiti.timeout.com/v1";
const QString KEY = "ADD-YOUR-KEY-HERE";

const QString AUTH_HEADER = "Bearer %1";

using namespace Qt;

TimeOut::TimeOut() {
    useAltCity = false;
}

void print(QMap<QString, QString> map) {
    QMap<QString, QString>::iterator it;
    for (it = map.begin(); it != map.end(); ++it)
        qDebug() << it.key() << ": " << it.value();
}
QMap<QString,QString> TimeOut::getCityLogos() {
    QMap<QString,QString> myMap;
    myMap["Accra"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/accra.png";
    myMap["Amsterdam"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/amsterdam.png";
    myMap["Barcelona"]="http://www.timeout.cat/bundles/timeoutfrontend/images/logos/bcn.png";
    myMap["Berlin"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/berlin.png";
    myMap["Boston"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/boston.png";
    myMap["Chicago"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/chicago.png";
    myMap["Kuala Lumpur"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/kualalumpur.png";
    myMap["Las Vegas"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/lasvegas.png";
    myMap["London"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/london.png";
    myMap["Los Angeles"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/la.png";
    myMap["Madrid"]="http://www.timeout.es/bundles/timeoutfrontend/images/logos/madrid.png";
    myMap["Miami"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/miami.png";
    myMap["México, DF"]="http://www.timeoutmexico.mx/bundles/timeoutfrontend/images/logos/mex.png";
    myMap["New York"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/ny.png";
    myMap["Paris"]="http://www.timeout.fr/bundles/timeoutfrontend/images/logos/paris.png";
    myMap["Washington, DC"]="http://www.timeout.com/bundles/timeoutfrontend/images/logos/washingtondc.png";
    myMap["unknown"]="http://www.timeout.com/wp-content/uploads/2014/06/TO-web-logo-global.png";
    return myMap;
}

void TimeOut::setCacheDirectory(std::string const &cacheDirectory) {
    scopeCache = QString::fromStdString(cacheDirectory);
}

bool inBox(locBox box, coordinates point){
    double big,small;
    if(box.bottom > box.top){
        big=box.bottom;
        small=box.top;
     } else {
        big=box.top;
        small=box.bottom;
    }
    if (!(point.lat<big && point.lat > small))
        return false;

    if(box.left > box.right){
        big=box.left;
        small=box.right;
     } else {
        big=box.right;
        small=box.left;
    }
    if (!(point.lon<big && point.lon > small))
        return false;

    return true;

}

bool TimeOut::setupCity() {
    coordinates city = getCurrentCity();
    std::vector<CityType> cities = fetchSupportedCities();
    for (unsigned int i = 0 ; i < cities.size(); i++){
        if (inBox(cities[i].box,city)) {
            this->city = cities[i].name;
            this->url = QUrl(cities[i].url);
            qDebug() << "City set to: " << this->city;
            useCurrentCity();
            return true;
        }
    }
    qDebug() << "Unsupported location " << city.lat <<" : " <<city.lon;
    this->city = "";
    this->url = "";
    return false;
}

QString TimeOut::getCityFromUrl(QString url) {

    auto iCity = url.right(url.size() - url.indexOf("mobile") - 7);
    iCity = iCity.left(iCity.indexOf("/"));
    qDebug() << "city from url is " <<iCity << " for " << url;
    auto cities = getSupportedCities();
    for (unsigned int i = 0 ; i < cities.size(); i++){
        if(cities[i].url.contains(iCity))
            return cities[i].url;
    }
    return "";
}

QByteArray TimeOut::makeRequest(QNetworkRequest &request) const {
    int argc = 1;
    char *argv = const_cast<char*>("timeout-scope");
    QCoreApplication *app = new QCoreApplication(argc, &argv);
    QNetworkAccessManager manager;
    QByteArray reply;
    QNetworkDiskCache *cache = new QNetworkDiskCache();
    cache->setCacheDirectory(scopeCache);

    QString authorizationHeader = AUTH_HEADER.arg(KEY);
    request.setRawHeader("Authorization", authorizationHeader.toStdString().c_str());
    request.setRawHeader("User-Agent", USER_AGENT.toStdString().c_str());
    request.setRawHeader("Content-Type", "application/json");
    request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);

    QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), app, SLOT(quit()));
    QObject::connect(&manager, &QNetworkAccessManager::finished,
            [&reply](QNetworkReply *msg) {
                reply = msg->readAll();
                msg->deleteLater();
            });

    manager.setCache(cache);
    manager.get(request);
    app->exec();

    delete cache;
    return reply;
}

QJsonValuePair TimeOut::get(QUrl url, int = 1) const {
    INIT_TIMER
    START_TIMER
    QNetworkRequest request(url); // Add paging when we support it.
    QByteArray data = makeRequest(request);
    STOP_TIMER(QString("GET ").append(url.path()));

    QJsonParseError e;
    QJsonDocument document = QJsonDocument::fromJson(data, &e);
    if (e.error != QJsonParseError::NoError) {
        qCritical() << "failed to parse response " << e.errorString() << "\n" << QString(data);
        throw QString("Failed to parse response: %1").arg(e.errorString());
    }

    if(!document.isObject()) {
        throw QString("json is not an object");
    }
    QJsonObject object = document.object();
    if (object.contains("meta")) {
        QJsonValue meta = object.value("meta");
        QJsonValue body = object.value("body");

        return RESPONSE(meta, body);
    } else {
        // XXX workaround for inconsistent "curateds" API endpoint format
        qCritical() << "No 'meta' tag present!";
        QJsonValue meta, body;
        if (document.isArray()) {
            body = document.array();
        }
        return RESPONSE(meta, body);
    }
}

coordinates TimeOut::getCurrentCity() {
    //Insert coordinates here for test
    //mycoordinates.lat= 41.4583; mycoordinates.lon= 2.0625; //Barcelona
    //mycoordinates.lat= 41.1583; mycoordinates.lon= -3.6625; //Madrid
    //mycoordinates.lat= 0; mycoordinates.lon= 0; //nowhere


    qDebug()<< "lat is " << mycoordinates.lat << " , long is " <<mycoordinates.lon;

    return mycoordinates;
}

std::vector<CityType> TimeOut::fetchSupportedCities() {
    QUrl url(URL + "/mobile");
    auto response = get(url);
    supportedCities.clear();

    qDebug() <<"my locale is" << locale_;
    QJsonValue body = response.second;
    QJsonArray results = body.toArray();
    QJsonArray::iterator it;
    for (it = results.begin(); it != results.end(); ++it) {
        CityType iCity;
        QJsonObject o = (*it).toObject();

        //get coordinates for the city
        QJsonObject boundingBox = o.value("bounding_box").toObject();
        iCity.box.top=boundingBox.value("top").toDouble();
        iCity.box.bottom=boundingBox.value("bottom").toDouble();
        iCity.box.right=boundingBox.value("right").toDouble();
        iCity.box.left=boundingBox.value("left").toDouble();
        QJsonObject defaultLocale = o.value("default_locale").toObject();
        iCity.name = defaultLocale.value("name").toString();
        //blacklist accra as seems broken
        if (iCity.name == "Accra")
            continue;
        iCity.url = defaultLocale.value("url").toString();
        QJsonArray locales = o.value("locales").toArray();

        bool locale_found=false;
        bool en_found=false;
        QString en_url="";

        //check if my locale is supported
        FOREACH_JSON(alocal,locales) {
            QJsonObject o = (*alocal).toObject();
            auto loc_lang = o.value("id").toString();
            qDebug()<<"city supports:" <<loc_lang << "checking against" <<locale_;
            if (loc_lang.contains(locale_)) {
                iCity.url = o.value("url").toString();
                locale_found =true;
            }
            if (loc_lang.contains("en")) {
                en_url = o.value("url").toString();
                en_found =true;
            }
        }
        //if my locale is not found, then try english, if not default
        if (!locale_found && en_found) iCity.url = en_url;

#ifdef VERBOSE
        qDebug() << iCity.name << " url :" << iCity.url << "\nbox :\nbottom " << iCity.box.bottom
                 <<"left "<< iCity.box.left
                 << "top "<< iCity.box.top
                 << "right " <<iCity.box.right;
#endif
        supportedCities.push_back(iCity);
    }
    return supportedCities;
}

void TimeOut::getCityEndpoints() {
    site.clear();
    auto response = get(useAltCity?this->alternateUrl:this->url, 1);

    QJsonValue body = response.second;
    QJsonArray results = body.toArray();
    QJsonArray::iterator it;
    for (it = results.begin(); it != results.end(); ++it) {
        QJsonObject endpoint = (*it).toObject();
        QString id = endpoint.value("id").toString();
        QString url = endpoint.value("url").toString();
#ifdef VERBOSE
        qDebug() << id;
#endif
        site[id] = QUrl(url);
    }
}

QJsonValuePair TimeOut::getEndpoint(QString endpoint, int page) const {
    /*
       "booking-providers" 
       "canned-queries" 
       "curateds" 
       "editor-lists" 
       "editor-picks" 
       "facet-groups" 
       "page-types" 
       "pages" 
       "search" 
       "windows"
    */
    return this->get(this->site[endpoint], page);
}

QJsonArray TimeOut::getCannedQueries(int page = 1) const {
    QJsonValuePair response = getEndpoint(QString("canned-queries"), page);
    return BODY(response);
}

QJsonArray TimeOut::getCurated(int page = 1) const {
    auto response = getEndpoint(QString("curateds"), page);
    return BODY(response);
}

QJsonArray TimeOut::getEditorLists(int page = 1) const {
    auto response = getEndpoint(QString("editor-lists"), page);
    return BODY(response);
}

QJsonArray TimeOut::getEditorPicks(int page = 1) const {
    auto response = getEndpoint(QString("editor-picks"), page);
    return BODY(response);
}

QJsonArray TimeOut::getFacetGroups(int page = 1) const {
    auto response = getEndpoint(QString("facet-groups"), page);
    return BODY(response);
}

QJsonArray TimeOut::search(QString query, int page = 1) const {
    QString lat= QString::number(mycoordinates.lat);
    QString lng= QString::number(mycoordinates.lon);;
    QString radius("2");

    QString location = QString("&latitude=%1&longitude=%2&radius=%3")
            .arg(lat).arg(lng).arg(radius);
    QString s = this->site["search"].toString() + QString("&q=%1").arg(query) + location;
    auto response = this->get(QUrl(s), page);
    return BODY(response);
}
/*
   // This is left here for standalone test runs.
int main(int argc, char **argv) {
    TimeOut timeout;
    timeout.setupCity();

    QJsonArray curated = timeout.getCurated();
    if (curated.empty()) {
        qWarning() << "no curated results!";
    }
#ifdef VERBOSE
    QJsonArray::iterator it;
    for (it = curated.begin(); it != curated.end(); ++it) {
        QJsonObject item = (*it).toObject();
        QString name = item.value("name").toString();
        QString url = item.value("url").toString();
        qDebug() << name << ": " << url;
    }
#endif
    return 0;
}
*/