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
|
#include "partners_api/viator_api.hpp"
#include "platform/http_client.hpp"
#include "platform/preferred_languages.hpp"
#include "coding/multilang_utf8_string.hpp"
#include "coding/url_encode.hpp"
#include "base/logging.hpp"
#include "base/thread.hpp"
#include <algorithm>
#include <set>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include "3party/jansson/myjansson.hpp"
#include "private.h"
namespace
{
using namespace platform;
using namespace viator;
std::string const kApiUrl = "https://viatorapi.viator.com";
std::string const kWebUrl = "https://www.partner.viator.com";
int8_t GetLang(std::string const & lang)
{
return StringUtf8Multilang::GetLangIndex(lang);
}
using IdsMap = std::unordered_map<int8_t, std::string>;
IdsMap const kApiKeys =
{
{GetLang("en"), VIATOR_API_KEY_EN},
{GetLang("de"), VIATOR_API_KEY_DE},
{GetLang("fr"), VIATOR_API_KEY_FR},
{GetLang("es"), VIATOR_API_KEY_ES},
{GetLang("pt"), VIATOR_API_KEY_PT},
{GetLang("it"), VIATOR_API_KEY_IT},
{GetLang("nl"), VIATOR_API_KEY_NL},
{GetLang("sv"), VIATOR_API_KEY_SV},
{GetLang("ja"), VIATOR_API_KEY_JA}
};
IdsMap const kAccountIds =
{
{GetLang("en"), VIATOR_ACCOUNT_ID_EN},
{GetLang("de"), VIATOR_ACCOUNT_ID_DE},
{GetLang("fr"), VIATOR_ACCOUNT_ID_FR},
{GetLang("es"), VIATOR_ACCOUNT_ID_ES},
{GetLang("pt"), VIATOR_ACCOUNT_ID_PT},
{GetLang("it"), VIATOR_ACCOUNT_ID_IT},
{GetLang("nl"), VIATOR_ACCOUNT_ID_NL},
{GetLang("sv"), VIATOR_ACCOUNT_ID_SV},
{GetLang("ja"), VIATOR_ACCOUNT_ID_JA}
};
std::unordered_set<std::string> const kSupportedCurrencies =
{
"USD", "GBP", "EUR", "AUD", "CAD", "NZD", "SGD", "HKD"
};
std::string GetId(IdsMap const & from)
{
int8_t const lang = GetLang(languages::GetCurrentNorm());
auto const it = from.find(lang);
if (it != from.cend())
return it->second;
LOG(LINFO, ("Viator key for language", lang, "is not found, English key will be used."));
return from.at(StringUtf8Multilang::kEnglishCode);
}
std::string GetApiKey()
{
return GetId(kApiKeys);
}
std::string GetAccountId()
{
return GetId(kAccountIds);
}
bool RunSimpleHttpRequest(std::string const & url, std::string const & bodyData,
std::string & result)
{
HttpClient request(url);
request.SetHttpMethod("POST");
request.SetBodyData(bodyData, "application/json");
if (request.RunHttpRequest() && !request.WasRedirected() && request.ErrorCode() == 200)
{
result = request.ServerResponse();
return true;
}
return false;
}
std::string MakeSearchProductsRequest(int destId, std::string const & currency, int count)
{
std::ostringstream os;
// REVIEW_AVG_RATING_D - average traveler rating (high->low).
os << R"({"topX":"1-)" << count << R"(","destId":)" << destId << R"(,"currencyCode":")"
<< currency << R"(","sortOrder":"REVIEW_AVG_RATING_D"})";
return os.str();
}
std::string MakeUrl(std::string const & apiMethod)
{
std::ostringstream os;
os << kApiUrl << apiMethod << "?apiKey=" << GetApiKey();
return os.str();
}
bool CheckJsonArray(json_t const * data)
{
if (data == nullptr)
return false;
if (!json_is_array(data))
return false;
if (json_array_size(data) <= 0)
return false;
return true;
}
bool CheckAnswer(my::Json const & root)
{
bool success;
FromJSONObjectOptionalField(root.get(), "success", success);
if (!success)
{
std::string errorMessage = "Unknown error.";
auto const errorMessageArray = json_object_get(root.get(), "errorMessageText");
if (CheckJsonArray(errorMessageArray))
FromJSON(json_array_get(errorMessageArray, 0), errorMessage);
LOG(LWARNING, ("Viator retrieved unsuccessfull status, error message:", errorMessage));
}
return success;
}
void MakeProducts(std::string const & src, std::vector<Product> & products)
{
products.clear();
my::Json root(src.c_str());
auto const data = json_object_get(root.get(), "data");
if (!CheckAnswer(root) || !CheckJsonArray(data))
return;
auto const dataSize = json_array_size(data);
for (size_t i = 0; i < dataSize; ++i)
{
Product product;
auto const item = json_array_get(data, i);
FromJSONObject(item, "shortTitle", product.m_title);
FromJSONObject(item, "rating", product.m_rating);
FromJSONObject(item, "reviewCount", product.m_reviewCount);
FromJSONObject(item, "duration", product.m_duration);
FromJSONObject(item, "price", product.m_price);
FromJSONObject(item, "priceFormatted", product.m_priceFormatted);
FromJSONObject(item, "currencyCode", product.m_currency);
FromJSONObject(item, "thumbnailHiResURL", product.m_photoUrl);
FromJSONObject(item, "webURL", product.m_pageUrl);
products.push_back(move(product));
}
}
} // namespace
namespace viator
{
// static
bool RawApi::GetTopProducts(std::string const & destId, std::string const & currency, int count,
std::string & result)
{
int dest = 0;
VERIFY(strings::to_int(destId, dest), ());
return RunSimpleHttpRequest(MakeUrl("/service/search/products"),
MakeSearchProductsRequest(dest, currency, count), result);
}
// static
std::string Api::GetCityUrl(std::string const & destId, std::string const & name)
{
std::ostringstream ost;
// The final language and city name will be calculated automatically based on account id and
// destination id.
ost << kWebUrl << "/" << languages::GetCurrentNorm() << "/" << GetAccountId() << "/"
<< UrlEncode(name) << "/d" << destId << "-ttd?activities=all";
return ost.str();
}
void Api::GetTop5Products(std::string const & destId, std::string const & currency,
GetTop5ProductsCallback const & fn) const
{
std::string curr =
kSupportedCurrencies.find(currency) == kSupportedCurrencies.cend() ? "USD" : currency;
threads::SimpleThread([destId, curr, fn]()
{
string result;
if (!RawApi::GetTopProducts(destId, curr, 5, result))
return fn(destId, {});
std::vector<Product> products;
try
{
MakeProducts(result, products);
}
catch (my::Json::Exception const & e)
{
LOG(LERROR, (e.Msg()));
products.clear();
}
SortProducts(products);
fn(destId, products);
}).detach();
}
bool operator<(Product const & lhs, Product const & rhs)
{
return lhs.m_rating < rhs.m_rating ||
(lhs.m_rating == rhs.m_rating && lhs.m_reviewCount < rhs.m_reviewCount) ||
(lhs.m_reviewCount == rhs.m_reviewCount && lhs.m_price < rhs.m_price);
}
// Sort by rating (from the best to the worst),
// then by reviews (from the largest to the smallest),
// then by price (from the biggest to the lowest)
void SortProducts(std::vector<Product> & products)
{
std::multiset<Product> productsSet;
for (auto const & p : products)
productsSet.insert(p);
std::copy(productsSet.crbegin(), productsSet.crend(), products.begin());
}
} // namespace viator
|