Welcome to mirror list, hosted at ThFree Co, Russian Federation.

booking_api.cpp « partners_api - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e877ad738a80d394d4ce7aa954c5c3504097393c (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
#include "partners_api/booking_api.hpp"

#include "platform/http_client.hpp"
#include "platform/platform.hpp"

#include "coding/url_encode.hpp"

#include "base/get_time.hpp"
#include "base/gmtime.hpp"
#include "base/logging.hpp"
#include "base/thread.hpp"

#include "std/initializer_list.hpp"
#include "std/iomanip.hpp"
#include "std/iostream.hpp"
#include "std/sstream.hpp"
#include "std/utility.hpp"

#include "3party/jansson/myjansson.hpp"

#include "private.h"

namespace
{
using namespace platform;
using namespace booking;

string const kBookingApiBaseUrl = "https://distribution-xml.booking.com/json/bookings";
string const kExtendedHotelInfoBaseUrl = "https://hotels.maps.me/getDescription";
string const kPhotoOriginalUrl = "http://aff.bstatic.com/images/hotel/max500/";
string const kPhotoSmallUrl = "http://aff.bstatic.com/images/hotel/max300/";
string const kSearchBaseUrl = "https://www.booking.com/search.html";
string g_BookingUrlForTesting = "";

bool RunSimpleHttpRequest(bool const needAuth, string const & url, string & result)
{
  HttpClient request(url);

  if (needAuth)
    request.SetUserAndPassword(BOOKING_KEY, BOOKING_SECRET);

  if (request.RunHttpRequest() && !request.WasRedirected() && request.ErrorCode() == 200)
  {
    result = request.ServerResponse();
    return true;
  }
  return false;
}

string MakeApiUrl(string const & func, initializer_list<pair<string, string>> const & params)
{
  ASSERT_NOT_EQUAL(params.size(), 0, ());

  ostringstream os;
  if (!g_BookingUrlForTesting.empty())
    os << g_BookingUrlForTesting << "." << func << "?";
  else
    os << kBookingApiBaseUrl << "." << func << "?";

  bool firstParam = true;
  for (auto const & param : params)
  {
    if (firstParam)
    {
      firstParam = false;
    }
    else
    {
      os << "&";
    }
    os << param.first << "=" << param.second;
  }

  return os.str();
}

void ClearHotelInfo(HotelInfo & info)
{
  info.m_hotelId.clear();
  info.m_description.clear();
  info.m_photos.clear();
  info.m_facilities.clear();
  info.m_reviews.clear();
  info.m_score = 0.0;
  info.m_scoreCount = 0;
}

vector<HotelFacility> ParseFacilities(json_t const * facilitiesArray)
{
  vector<HotelFacility> facilities;

  if (facilitiesArray == nullptr || !json_is_array(facilitiesArray))
    return facilities;

  size_t sz = json_array_size(facilitiesArray);

  for (size_t i = 0; i < sz; ++i)
  {
    auto itemArray = json_array_get(facilitiesArray, i);
    ASSERT(json_is_array(itemArray), ());
    ASSERT_EQUAL(json_array_size(itemArray), 2, ());

    HotelFacility facility;
    FromJSON(json_array_get(itemArray, 0), facility.m_type);
    FromJSON(json_array_get(itemArray, 1), facility.m_name);

    facilities.push_back(move(facility));
  }

  return facilities;
}

vector<HotelPhotoUrls> ParsePhotos(json_t const * photosArray)
{
  if (photosArray == nullptr || !json_is_array(photosArray))
    return {};

  vector<HotelPhotoUrls> photos;
  size_t sz = json_array_size(photosArray);
  string photoId;

  for (size_t i = 0; i < sz; ++i)
  {
    auto item = json_array_get(photosArray, i);
    FromJSON(item, photoId);

    // First three digits of id are used as part of path to photo on the server.
    if (photoId.size() < 3)
    {
      LOG(LWARNING, ("Incorrect photo id =", photoId));
      continue;
    }

    string url(photoId.substr(0, 3) + "/" + photoId + ".jpg");
    photos.push_back({kPhotoSmallUrl + url, kPhotoOriginalUrl + url});
  }

  return photos;
}

vector<HotelReview> ParseReviews(json_t const * reviewsArray)
{
  if (reviewsArray == nullptr || !json_is_array(reviewsArray))
    return {};

  vector<HotelReview> reviews;
  size_t sz = json_array_size(reviewsArray);
  string date;

  for (size_t i = 0; i < sz; ++i)
  {
    auto item = json_array_get(reviewsArray, i);
    HotelReview review;

    FromJSONObject(item, "date", date);
    istringstream ss(date);
    tm t = {};
    ss >> base::get_time(&t, "%Y-%m-%d %H:%M:%S");
    if (ss.fail())
    {
      LOG(LWARNING, ("Incorrect review date =", date));
      continue;
    }
    review.m_date = system_clock::from_time_t(mktime(&t));

    double score;
    FromJSONObject(item, "score", score);
    review.m_score = static_cast<float>(score);

    FromJSONObject(item, "author", review.m_author);
    FromJSONObject(item, "pros", review.m_pros);
    FromJSONObject(item, "cons", review.m_cons);

    reviews.push_back(move(review));
  }

  return reviews;
}

void FillHotelInfo(string const & src, HotelInfo & info)
{
  my::Json root(src.c_str());

  FromJSONObjectOptionalField(root.get(), "description", info.m_description);
  double score;
  FromJSONObjectOptionalField(root.get(), "score", score);
  info.m_score = static_cast<float>(score);

  int64_t scoreCount = 0;
  FromJSONObjectOptionalField(root.get(), "score_count", scoreCount);
  info.m_scoreCount = static_cast<uint32_t>(scoreCount);

  auto const facilitiesArray = json_object_get(root.get(), "facilities");
  info.m_facilities = ParseFacilities(facilitiesArray);

  auto const photosArray = json_object_get(root.get(), "photos");
  info.m_photos = ParsePhotos(photosArray);

  auto const reviewsArray = json_object_get(root.get(), "reviews");
  info.m_reviews = ParseReviews(reviewsArray);
}

void FillPriceAndCurrency(string const & src, string const & currency, string & minPrice,
                          string & priceCurrency)
{
  my::Json root(src.c_str());
  if (!json_is_array(root.get()))
    MYTHROW(my::Json::Exception, ("The answer must contain a json array."));
  size_t const rootSize = json_array_size(root.get());

  if (rootSize == 0)
    return;

  // Read default hotel price and currency.
  auto obj = json_array_get(root.get(), 0);
  FromJSONObject(obj, "min_price", minPrice);
  FromJSONObject(obj, "currency_code", priceCurrency);

  if (currency.empty() || priceCurrency == currency)
    return;

  // Try to get price in requested currency.
  json_t * arr = json_object_get(obj, "other_currency");
  if (arr == nullptr || !json_is_array(arr))
    return;

  size_t sz = json_array_size(arr);
  string code;
  for (size_t i = 0; i < sz; ++i)
  {
    auto el = json_array_get(arr, i);
    FromJSONObject(el, "currency_code", code);
    if (code == currency)
    {
      priceCurrency = code;
      FromJSONObject(el, "min_price", minPrice);
      break;
    }
  }
}
}  // namespace

namespace booking
{
// static
bool RawApi::GetHotelAvailability(string const & hotelId, string const & currency, string & result)
{
  char dateArrival[12]{};
  char dateDeparture[12]{};

  system_clock::time_point p = system_clock::from_time_t(time(nullptr));
  tm arrival = my::GmTime(system_clock::to_time_t(p));
  tm departure = my::GmTime(system_clock::to_time_t(p + hours(24)));
  strftime(dateArrival, sizeof(dateArrival), "%Y-%m-%d", &arrival);
  strftime(dateDeparture, sizeof(dateDeparture), "%Y-%m-%d", &departure);

  string url = MakeApiUrl("getHotelAvailability", {{"hotel_ids", hotelId},
                                                   {"currency_code", currency},
                                                   {"arrival_date", dateArrival},
                                                   {"departure_date", dateDeparture}});
  return RunSimpleHttpRequest(true, url, result);
}

// static
bool RawApi::GetExtendedInfo(string const & hotelId, string const & lang, string & result)
{
  ostringstream os;
  os << kExtendedHotelInfoBaseUrl << "?hotel_id=" << hotelId << "&lang=" << lang;
  return RunSimpleHttpRequest(false, os.str(), result);
}

string Api::GetBookHotelUrl(string const & baseUrl) const
{
  ASSERT(!baseUrl.empty(), ());
  return GetDescriptionUrl(baseUrl) + "#availability";
}

string Api::GetDescriptionUrl(string const & baseUrl) const
{
  ASSERT(!baseUrl.empty(), ());
  return baseUrl + string("?aid=") + BOOKING_AFFILIATE_ID;
}

string Api::GetHotelReviewsUrl(string const & hotelId, string const & baseUrl) const
{
  ASSERT(!baseUrl.empty(), ());
  ASSERT(!hotelId.empty(), ());
  ostringstream os;
  os << GetDescriptionUrl(baseUrl) << "&tab=4&label=hotel-" << hotelId << "_reviews";
  return os.str();
}

string Api::GetSearchUrl(string const & city, string const & name) const
{
  if (city.empty() || name.empty())
    return "";

  ostringstream paramStream;
  paramStream << city << " " << name;

  auto const urlEncodedParams = UrlEncode(paramStream.str());

  ostringstream resultStream;
  if (!urlEncodedParams.empty())
    resultStream << kSearchBaseUrl << "?aid=" << BOOKING_AFFILIATE_ID << ";" << "ss="
                 << urlEncodedParams << ";";

  return resultStream.str();
}

void Api::GetMinPrice(string const & hotelId, string const & currency,
                      GetMinPriceCallback const & fn)
{
  threads::SimpleThread([hotelId, currency, fn]()
  {
    string minPrice;
    string priceCurrency;
    string httpResult;
    if (!RawApi::GetHotelAvailability(hotelId, currency, httpResult))
    {
      fn(hotelId, minPrice, priceCurrency);
      return;
    }

    try
    {
      FillPriceAndCurrency(httpResult, currency, minPrice, priceCurrency);
    }
    catch (my::Json::Exception const & e)
    {
      LOG(LERROR, (e.Msg()));
      minPrice.clear();
      priceCurrency.clear();
    }
    fn(hotelId, minPrice, priceCurrency);
  }).detach();
}

void Api::GetHotelInfo(string const & hotelId, string const & lang, GetHotelInfoCallback const & fn)
{
  threads::SimpleThread([hotelId, lang, fn]()
  {
    HotelInfo info;
    info.m_hotelId = hotelId;

    string result;
    if (!RawApi::GetExtendedInfo(hotelId, lang, result))
    {
      fn(info);
      return;
    }

    try
    {
      FillHotelInfo(result, info);
    }
    catch (my::Json::Exception const & e)
    {
      LOG(LERROR, (e.Msg()));
      ClearHotelInfo(info);
    }

    fn(info);
  }).detach();
}

void SetBookingUrlForTesting(string const & url)
{
  g_BookingUrlForTesting = url;
}
}  // namespace booking