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

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

#include "indexer/feature.hpp"

#include "geometry/mercator.hpp"

#include "base/logging.hpp"
#include "base/macros.hpp"

#include "std/algorithm.hpp"
#include "std/random.hpp"
#include "std/sstream.hpp"

#include "private.h"

using editor::XMLFeature;

namespace
{
m2::RectD GetBoundingRect(vector<m2::PointD> const & geometry)
{
  m2::RectD rect;
  for (auto const & p : geometry)
  {
    auto const latLon = MercatorBounds::ToLatLon(p);
    rect.Add({latLon.lon, latLon.lat});
  }
  return rect;
}

bool OsmFeatureHasTags(pugi::xml_node const & osmFt)
{
  return osmFt.child("tag");
}

string const static kVowels = "aeiouy";

vector<string> const static kMainTags = {"amenity",   "shop",    "tourism", "historic", "craft",
                                         "emergency", "barrier", "highway", "office",   "leisure",
                                         "waterway",  "natural", "place",   "entrance", "building"};

string GetTypeForFeature(XMLFeature const & node)
{
  for (string const & key : kMainTags)
  {
    if (node.HasTag(key))
    {
      string const value = node.GetTagValue(key);
      if (value == "yes")
        return key;
      else if (key == "shop" || key == "office" || key == "building" || key == "entrance")
        return value + " " + key;  // "convenience shop"
      else if (!value.empty() && value.back() == 's')
        // Remove 's' from the tail: "toilets" -> "toilet".
        return value.substr(0, value.size() - 1);
      else
        return value;
    }
  }

  // Did not find any known tags.
  return node.HasAnyTags() ? "unknown object" : "empty object";
}

vector<m2::PointD> NaiveSample(vector<m2::PointD> const & source, size_t count)
{
  count = min(count, source.size());
  vector<m2::PointD> result;
  result.reserve(count);
  vector<size_t> indexes;
  indexes.reserve(count);

  minstd_rand engine;
  uniform_int_distribution<size_t> distrib(0, source.size());

  while (count--)
  {
    size_t index;
    do
    {
      index = distrib(engine);
    } while (find(begin(indexes), end(indexes), index) != end(indexes));
    result.push_back(source[index]);
    indexes.push_back(index);
  }

  return result;
}
}  // namespace

namespace pugi
{
string DebugPrint(xml_document const & doc)
{
  ostringstream stream;
  doc.print(stream, "  ");
  return stream.str();
}
}  // namespace pugi

namespace osm
{
ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret,
                                   ServerApi06::TKeyValueTags const & comments) noexcept
  : m_changesetComments(comments), m_api(OsmOAuth::ServerAuth(keySecret))
{
}

ChangesetWrapper::~ChangesetWrapper()
{
  if (m_changesetId)
  {
    try
    {
      m_changesetComments["comment"] = GetDescription();
      m_api.UpdateChangeSet(m_changesetId, m_changesetComments);
      m_api.CloseChangeSet(m_changesetId);
    }
    catch (std::exception const & ex)
    {
      LOG(LWARNING, (ex.what()));
    }
  }
}

void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc,
                                      double radiusInMeters)
{
  auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon, radiusInMeters);
  if (response.first != OsmOAuth::HTTP::OK)
    MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesAtLatLon", ll));

  if (pugi::status_ok != doc.load(response.second.c_str()).status)
    MYTHROW(
        OsmXmlParseException,
        ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second));
}

void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & min, ms::LatLon const & max,
                                      pugi::xml_document & doc)
{
  auto const response = m_api.GetXmlFeaturesInRect(min.lat, min.lon, max.lat, max.lon);
  if (response.first != OsmOAuth::HTTP::OK)
    MYTHROW(HttpErrorException, ("HTTP error", response, "with GetXmlFeaturesInRect", min, max));

  if (pugi::status_ok != doc.load(response.second.c_str()).status)
    MYTHROW(OsmXmlParseException,
            ("Can't parse OSM server response for GetXmlFeaturesInRect request", response.second));
}

XMLFeature ChangesetWrapper::GetMatchingNodeFeatureFromOSM(m2::PointD const & center)
{
  // Match with OSM node.
  ms::LatLon const ll = MercatorBounds::ToLatLon(center);
  pugi::xml_document doc;
  // Throws!
  LoadXmlFromOSM(ll, doc);

  pugi::xml_node const bestNode = GetBestOsmNode(doc, ll);
  if (bestNode.empty())
  {
    MYTHROW(OsmObjectWasDeletedException,
            ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc));
  }

  if (!OsmFeatureHasTags(bestNode))
  {
    stringstream sstr;
    bestNode.print(sstr);
    LOG(LDEBUG, ("Node has no tags", sstr.str()));
    MYTHROW(EmptyFeatureException, ("Node has no tags"));
  }

  return XMLFeature(bestNode);
}

XMLFeature ChangesetWrapper::GetMatchingAreaFeatureFromOSM(vector<m2::PointD> const & geometry)
{
  auto const kSamplePointsCount = 3;
  bool hasRelation = false;
  // Try several points in case of poor osm response.
  for (auto const & pt : NaiveSample(geometry, kSamplePointsCount))
  {
    ms::LatLon const ll = MercatorBounds::ToLatLon(pt);
    pugi::xml_document doc;
    // Throws!
    LoadXmlFromOSM(ll, doc);

    if (doc.select_node("osm/relation"))
    {
      auto const rect = GetBoundingRect(geometry);
      LoadXmlFromOSM(ms::LatLon(rect.minY(), rect.minX()), ms::LatLon(rect.maxY(), rect.maxX()), doc);
      hasRelation = true;
    }

    pugi::xml_node const bestWayOrRelation = GetBestOsmWayOrRelation(doc, geometry);
    if (!bestWayOrRelation)
    {
      if (hasRelation)
        break;
      continue;
    }

    if (strcmp(bestWayOrRelation.name(), "relation") == 0)
    {
      stringstream sstr;
      bestWayOrRelation.print(sstr);
      LOG(LDEBUG, ("Relation is the best match", sstr.str()));
      MYTHROW(RelationFeatureAreNotSupportedException, ("Got relation as the best matching"));
    }

    if (!OsmFeatureHasTags(bestWayOrRelation))
    {
      stringstream sstr;
      bestWayOrRelation.print(sstr);
      LOG(LDEBUG, ("Way or relation has no tags", sstr.str()));
      MYTHROW(EmptyFeatureException, ("Way or relation has no tags"));
    }

    // TODO: rename to wayOrRelation when relations are handled.
    XMLFeature const way(bestWayOrRelation);
    ASSERT(way.IsArea(), ("Best way must be an area."));

    // AlexZ: TODO: Check that this way is really match our feature.
    // If we had some way to check it, why not to use it in selecting our feature?

    return way;
  }
  MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature"));
}

void ChangesetWrapper::Create(XMLFeature node)
{
  if (m_changesetId == kInvalidChangesetId)
    m_changesetId = m_api.CreateChangeSet(m_changesetComments);

  // Changeset id should be updated for every OSM server commit.
  node.SetAttribute("changeset", strings::to_string(m_changesetId));
  // TODO(AlexZ): Think about storing/logging returned OSM ids.
  UNUSED_VALUE(m_api.CreateElement(node));
  m_created_types[GetTypeForFeature(node)]++;
}

void ChangesetWrapper::Modify(XMLFeature node)
{
  if (m_changesetId == kInvalidChangesetId)
    m_changesetId = m_api.CreateChangeSet(m_changesetComments);

  // Changeset id should be updated for every OSM server commit.
  node.SetAttribute("changeset", strings::to_string(m_changesetId));
  m_api.ModifyElement(node);
  m_modified_types[GetTypeForFeature(node)]++;
}

void ChangesetWrapper::Delete(XMLFeature node)
{
  if (m_changesetId == kInvalidChangesetId)
    m_changesetId = m_api.CreateChangeSet(m_changesetComments);

  // Changeset id should be updated for every OSM server commit.
  node.SetAttribute("changeset", strings::to_string(m_changesetId));
  m_api.DeleteElement(node);
  m_deleted_types[GetTypeForFeature(node)]++;
}

string ChangesetWrapper::TypeCountToString(TTypeCount const & typeCount)
{
  if (typeCount.empty())
    return string();

  // Convert map to vector and sort pairs by count, descending.
  vector<pair<string, size_t>> items;
  for (auto const & tc : typeCount)
    items.push_back(tc);

  sort(items.begin(), items.end(),
       [](pair<string, size_t> const & a, pair<string, size_t> const & b)
       {
         return a.second > b.second;
       });

  ostringstream ss;
  size_t const limit = min(size_t(3), items.size());
  for (size_t i = 0; i < limit; ++i)
  {
    if (i > 0)
    {
      // Separator: "A and B" for two, "A, B, and C" for three or more.
      if (limit > 2)
        ss << ", ";
      else
        ss << " ";
      if (i == limit - 1)
        ss << "and ";
    }

    auto & currentPair = items[i];
    // If we have more objects left, make the last one a list of these.
    if (i == limit - 1 && limit < items.size())
    {
      int count = 0;
      for (auto j = i; j < items.size(); ++j)
        count += items[j].second;
      currentPair = {"other object", count};
    }

    // Format a count: "a shop" for single shop, "4 shops" for multiple.
    if (currentPair.second == 1)
    {
      if (kVowels.find(currentPair.first.front()) != string::npos)
        ss << "an";
      else
        ss << "a";
    }
    else
    {
      ss << currentPair.second;
    }
    ss << ' ' << currentPair.first;
    if (currentPair.second > 1)
    {
      if (currentPair.first.size() >= 2)
      {
        string const lastTwo = currentPair.first.substr(currentPair.first.size() - 2);
        // "bench" -> "benches", "marsh" -> "marshes", etc.
        if (lastTwo.back() == 'x' || lastTwo == "sh" || lastTwo == "ch" || lastTwo == "ss")
        {
          ss << 'e';
        }
        // "library" -> "libraries"
        else if (lastTwo.back() == 'y' && kVowels.find(lastTwo.front()) == string::npos)
        {
          long const pos = ss.tellp();
          ss.seekp(pos - 1);
          ss << "ie";
        }
      }
      ss << 's';
    }
  }
  return ss.str();
}

string ChangesetWrapper::GetDescription() const
{
  string result;
  if (!m_created_types.empty())
    result = "Created " + TypeCountToString(m_created_types);
  if (!m_modified_types.empty())
  {
    if (!result.empty())
      result += "; ";
    result += "Updated " + TypeCountToString(m_modified_types);
  }
  if (!m_deleted_types.empty())
  {
    if (!result.empty())
      result += "; ";
    result += "Deleted " + TypeCountToString(m_deleted_types);
  }
  return result;
}

}  // namespace osm