forked from mapsme/omim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.cpp
1656 lines (1381 loc) · 51.2 KB
/
storage.cpp
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "storage/http_map_files_downloader.hpp"
#include "storage/storage.hpp"
#include "defines.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"
#include "platform/preferred_languages.hpp"
#include "platform/servers_list.hpp"
#include "platform/settings.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/internal/file_data.hpp"
#include "coding/reader.hpp"
#include "coding/url_encode.hpp"
#include "base/logging.hpp"
#include "base/scope_guard.hpp"
#include "base/stl_helpers.hpp"
#include "base/string_utils.hpp"
#include "std/algorithm.hpp"
#include "std/bind.hpp"
#include "std/chrono.hpp"
#include "std/sstream.hpp"
#include "std/target_os.hpp"
#include "3party/Alohalytics/src/alohalytics.h"
using namespace downloader;
using namespace platform;
namespace storage
{
namespace
{
uint64_t GetLocalSize(shared_ptr<LocalCountryFile> file, MapOptions opt)
{
if (!file)
return 0;
uint64_t size = 0;
for (MapOptions bit : {MapOptions::Map, MapOptions::CarRouting})
{
if (HasOptions(opt, bit))
size += file->GetSize(bit);
}
return size;
}
uint64_t GetRemoteSize(CountryFile const & file, MapOptions opt, int64_t version)
{
if (version::IsSingleMwm(version))
return opt == MapOptions::Nothing ? 0 : file.GetRemoteSize(MapOptions::Map);
uint64_t size = 0;
for (MapOptions bit : {MapOptions::Map, MapOptions::CarRouting})
{
if (HasOptions(opt, bit))
size += file.GetRemoteSize(bit);
}
return size;
}
void DeleteCountryIndexes(LocalCountryFile const & localFile)
{
platform::CountryIndexes::DeleteFromDisk(localFile);
}
void DeleteFromDiskWithIndexes(LocalCountryFile const & localFile, MapOptions options)
{
DeleteCountryIndexes(localFile);
localFile.DeleteFromDisk(options);
}
TCountryTreeNode const & LeafNodeFromCountryId(TCountryTree const & root,
TCountryId const & countryId)
{
TCountryTreeNode const * node = root.FindFirstLeaf(countryId);
CHECK(node, ("Node with id =", countryId, "not found in country tree as a leaf."));
return *node;
}
} // namespace
void GetQueuedCountries(Storage::TQueue const & queue, TCountriesSet & resultCountries)
{
for (auto const & country : queue)
resultCountries.insert(country.GetCountryId());
}
MapFilesDownloader::TProgress Storage::GetOverallProgress(TCountriesVec const & countries) const
{
MapFilesDownloader::TProgress overallProgress = {0, 0};
for (auto const & country : countries)
{
NodeAttrs attr;
GetNodeAttrs(country, attr);
ASSERT_EQUAL(attr.m_mwmCounter, 1, ());
if (attr.m_downloadingProgress.second != -1)
{
overallProgress.first += attr.m_downloadingProgress.first;
overallProgress.second += attr.m_downloadingProgress.second;
}
}
return overallProgress;
}
Storage::Storage(string const & pathToCountriesFile /* = COUNTRIES_FILE */, string const & dataDir /* = string() */)
: m_downloader(new HttpMapFilesDownloader()), m_currentSlotId(0), m_dataDir(dataDir)
, m_downloadMapOnTheMap(nullptr)
{
SetLocale(languages::GetCurrentTwine());
LoadCountriesFile(pathToCountriesFile, m_dataDir);
}
Storage::Storage(string const & referenceCountriesTxtJsonForTesting,
unique_ptr<MapFilesDownloader> mapDownloaderForTesting)
: m_downloader(move(mapDownloaderForTesting)), m_currentSlotId(0)
, m_downloadMapOnTheMap(nullptr)
{
m_currentVersion =
LoadCountries(referenceCountriesTxtJsonForTesting, m_countries, m_affiliations);
CHECK_LESS_OR_EQUAL(0, m_currentVersion, ("Can't load test countries file"));
}
void Storage::Init(TUpdateCallback const & didDownload, TDeleteCallback const & willDelete)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
m_didDownload = didDownload;
m_willDelete = willDelete;
}
void Storage::DeleteAllLocalMaps(TCountriesVec * existedCountries /* = nullptr */)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
for (auto const & localFiles : m_localFiles)
{
for (auto const & localFile : localFiles.second)
{
LOG_SHORT(LINFO, ("Remove:", localFiles.first, DebugPrint(*localFile)));
if (existedCountries)
existedCountries->push_back(localFiles.first);
localFile->SyncWithDisk();
DeleteFromDiskWithIndexes(*localFile, MapOptions::MapWithCarRouting);
}
}
}
bool Storage::HaveDownloadedCountries() const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
return !m_localFiles.empty();
}
Storage * Storage::GetPrefetchStorage()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
ASSERT(m_prefetchStorage.get() != nullptr, ());
return m_prefetchStorage.get();
}
void Storage::PrefetchMigrateData()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
m_prefetchStorage.reset(new Storage(COUNTRIES_FILE, "migrate"));
m_prefetchStorage->EnableKeepDownloadingQueue(false);
m_prefetchStorage->Init(
[](TCountryId const &, TLocalFilePtr const){},
[](TCountryId const &, TLocalFilePtr const){return false;});
if (!m_downloadingUrlsForTesting.empty())
m_prefetchStorage->SetDownloadingUrlsForTesting(m_downloadingUrlsForTesting);
}
void Storage::Migrate(TCountriesVec const & existedCountries)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
platform::migrate::SetMigrationFlag();
Clear();
m_countries.Clear();
TMappingOldMwm mapping;
LoadCountriesFile(COUNTRIES_FILE, m_dataDir, &mapping);
vector<TCountryId> prefetchedMaps;
m_prefetchStorage->GetLocalRealMaps(prefetchedMaps);
// Move prefetched maps into current storage.
for (auto const & countryId : prefetchedMaps)
{
string prefetchedFilename = m_prefetchStorage->GetLatestLocalFile(countryId)->GetPath(MapOptions::Map);
CountryFile const countryFile = GetCountryFile(countryId);
auto localFile = PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, countryFile);
string localFilename = localFile->GetPath(MapOptions::Map);
LOG_SHORT(LINFO, ("Move", prefetchedFilename, "to", localFilename));
my::RenameFileX(prefetchedFilename, localFilename);
}
// Remove empty migrate folder
Platform::RmDir(m_prefetchStorage->m_dataDir);
// Cover old big maps with small ones and prepare them to add into download queue
stringstream ss;
for (auto const & country : existedCountries)
{
ASSERT(!mapping[country].empty(), ());
for (auto const & smallCountry : mapping[country])
ss << (ss.str().empty() ? "" : ";") << smallCountry;
}
settings::Set("DownloadQueue", ss.str());
}
void Storage::Clear()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
m_downloader->Reset();
m_queue.clear();
m_justDownloaded.clear();
m_failedCountries.clear();
m_localFiles.clear();
m_localFilesForFakeCountries.clear();
SaveDownloadQueue();
}
void Storage::RegisterAllLocalMaps()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
m_localFiles.clear();
m_localFilesForFakeCountries.clear();
vector<LocalCountryFile> localFiles;
FindAllLocalMapsAndCleanup(GetCurrentDataVersion(), m_dataDir, localFiles);
auto compareByCountryAndVersion = [](LocalCountryFile const & lhs, LocalCountryFile const & rhs)
{
if (lhs.GetCountryFile() != rhs.GetCountryFile())
return lhs.GetCountryFile() < rhs.GetCountryFile();
return lhs.GetVersion() > rhs.GetVersion();
};
auto equalByCountry = [](LocalCountryFile const & lhs, LocalCountryFile const & rhs)
{
return lhs.GetCountryFile() == rhs.GetCountryFile();
};
sort(localFiles.begin(), localFiles.end(), compareByCountryAndVersion);
auto i = localFiles.begin();
while (i != localFiles.end())
{
auto j = i + 1;
while (j != localFiles.end() && equalByCountry(*i, *j))
{
LocalCountryFile & localFile = *j;
LOG(LINFO, ("Removing obsolete", localFile));
localFile.SyncWithDisk();
DeleteFromDiskWithIndexes(localFile, MapOptions::MapWithCarRouting);
++j;
}
LocalCountryFile const & localFile = *i;
string const & name = localFile.GetCountryName();
TCountryId countryId = FindCountryIdByFile(name);
if (IsCoutryIdCountryTreeLeaf(countryId))
RegisterCountryFiles(countryId, localFile.GetDirectory(), localFile.GetVersion());
else
RegisterFakeCountryFiles(localFile);
LOG(LINFO, ("Found file:", name, "in directory:", localFile.GetDirectory()));
i = j;
}
RestoreDownloadQueue();
}
void Storage::GetLocalMaps(vector<TLocalFilePtr> & maps) const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
for (auto const & p : m_localFiles)
maps.push_back(GetLatestLocalFile(p.first));
for (auto const & p : m_localFilesForFakeCountries)
maps.push_back(p.second);
maps.erase(unique(maps.begin(), maps.end()), maps.end());
}
size_t Storage::GetDownloadedFilesCount() const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
return m_localFiles.size();
}
Country const & Storage::CountryLeafByCountryId(TCountryId const & countryId) const
{
return LeafNodeFromCountryId(m_countries, countryId).Value();
}
Country const & Storage::CountryByCountryId(TCountryId const & countryId) const
{
TCountryTreeNode const * node = m_countries.FindFirst(countryId);
CHECK(node, ("Node with id =", countryId, "not found in country tree."));
return node->Value();
}
bool Storage::IsCoutryIdCountryTreeLeaf(TCountryId const & countryId) const
{
if (!IsCountryIdValid(countryId))
return false;
TCountryTreeNode const * const node = m_countries.FindFirst(countryId);
return node != nullptr && node->ChildrenCount() == 0 /* countryId is a leaf. */;
}
bool Storage::IsCoutryIdCountryTreeInnerNode(TCountryId const & countryId) const
{
if (!IsCountryIdValid(countryId))
return false;
TCountryTreeNode const * const node = m_countries.FindFirst(countryId);
return node != nullptr && node->ChildrenCount() != 0 /* countryId is an inner node. */;
}
TLocalAndRemoteSize Storage::CountrySizeInBytes(TCountryId const & countryId, MapOptions opt) const
{
QueuedCountry const * queuedCountry = FindCountryInQueue(countryId);
TLocalFilePtr localFile = GetLatestLocalFile(countryId);
CountryFile const & countryFile = GetCountryFile(countryId);
if (queuedCountry == nullptr)
{
return TLocalAndRemoteSize(GetLocalSize(localFile, opt),
GetRemoteSize(countryFile, opt, GetCurrentDataVersion()));
}
TLocalAndRemoteSize sizes(0, GetRemoteSize(countryFile, opt, GetCurrentDataVersion()));
if (!m_downloader->IsIdle() && IsCountryFirstInQueue(countryId))
{
sizes.first = m_downloader->GetDownloadingProgress().first +
GetRemoteSize(countryFile, queuedCountry->GetDownloadedFiles(),
GetCurrentDataVersion());
}
return sizes;
}
CountryFile const & Storage::GetCountryFile(TCountryId const & countryId) const
{
return CountryLeafByCountryId(countryId).GetFile();
}
Storage::TLocalFilePtr Storage::GetLatestLocalFile(CountryFile const & countryFile) const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
TCountryId const countryId = FindCountryIdByFile(countryFile.GetName());
if (IsCoutryIdCountryTreeLeaf(countryId))
{
TLocalFilePtr localFile = GetLatestLocalFile(countryId);
if (localFile)
return localFile;
}
auto const it = m_localFilesForFakeCountries.find(countryFile);
if (it != m_localFilesForFakeCountries.end())
return it->second;
return TLocalFilePtr();
}
Storage::TLocalFilePtr Storage::GetLatestLocalFile(TCountryId const & countryId) const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
auto const it = m_localFiles.find(countryId);
if (it == m_localFiles.end() || it->second.empty())
return TLocalFilePtr();
list<TLocalFilePtr> const & files = it->second;
TLocalFilePtr latest = files.front();
for (TLocalFilePtr const & file : files)
{
if (file->GetVersion() > latest->GetVersion())
latest = file;
}
return latest;
}
Status Storage::CountryStatus(TCountryId const & countryId) const
{
// Check if this country has failed while downloading.
if (m_failedCountries.count(countryId) > 0)
return Status::EDownloadFailed;
// Check if we already downloading this country or have it in the queue
if (IsCountryInQueue(countryId))
{
if (IsCountryFirstInQueue(countryId))
return Status::EDownloading;
else
return Status::EInQueue;
}
return Status::EUnknown;
}
Status Storage::CountryStatusEx(TCountryId const & countryId) const
{
return CountryStatusFull(countryId, CountryStatus(countryId));
}
void Storage::CountryStatusEx(TCountryId const & countryId, Status & status, MapOptions & options) const
{
status = CountryStatusEx(countryId);
if (status == Status::EOnDisk || status == Status::EOnDiskOutOfDate)
{
options = MapOptions::Map;
TLocalFilePtr localFile = GetLatestLocalFile(countryId);
ASSERT(localFile, ("Invariant violation: local file out of sync with disk."));
if (localFile->OnDisk(MapOptions::CarRouting))
options = SetOptions(options, MapOptions::CarRouting);
}
}
void Storage::SaveDownloadQueue()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
if (!m_keepDownloadingQueue)
return;
stringstream ss;
for (auto const & item : m_queue)
ss << (ss.str().empty() ? "" : ";") << item.GetCountryId();
settings::Set("DownloadQueue", ss.str());
}
void Storage::RestoreDownloadQueue()
{
if (!m_keepDownloadingQueue)
return;
string queue;
if (!settings::Get("DownloadQueue", queue))
return;
strings::SimpleTokenizer iter(queue, ";");
while (iter)
{
DownloadNode(*iter);
++iter;
}
}
void Storage::DownloadCountry(TCountryId const & countryId, MapOptions opt)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
if (opt == MapOptions::Nothing)
return;
if (QueuedCountry * queuedCountry = FindCountryInQueue(countryId))
{
queuedCountry->AddOptions(opt);
return;
}
m_failedCountries.erase(countryId);
m_queue.push_back(QueuedCountry(countryId, opt));
if (m_queue.size() == 1)
DownloadNextCountryFromQueue();
else
NotifyStatusChangedForHierarchy(countryId);
SaveDownloadQueue();
}
void Storage::DeleteCountry(TCountryId const & countryId, MapOptions opt)
{
ASSERT(m_willDelete != nullptr, ("Storage::Init wasn't called"));
TLocalFilePtr localFile = GetLatestLocalFile(countryId);
opt = NormalizeDeleteFileSet(opt);
bool const deferredDelete = m_willDelete(countryId, localFile);
DeleteCountryFiles(countryId, opt, deferredDelete);
DeleteCountryFilesFromDownloader(countryId, opt);
NotifyStatusChangedForHierarchy(countryId);
}
void Storage::DeleteCustomCountryVersion(LocalCountryFile const & localFile)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
CountryFile const countryFile = localFile.GetCountryFile();
DeleteFromDiskWithIndexes(localFile, MapOptions::MapWithCarRouting);
{
auto it = m_localFilesForFakeCountries.find(countryFile);
if (it != m_localFilesForFakeCountries.end())
{
m_localFilesForFakeCountries.erase(it);
return;
}
}
TCountryId const countryId = FindCountryIdByFile(countryFile.GetName());
if (!(IsCoutryIdCountryTreeLeaf(countryId)))
{
LOG(LERROR, ("Removed files for an unknown country:", localFile));
return;
}
}
void Storage::NotifyStatusChanged(TCountryId const & countryId)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
for (CountryObservers const & observer : m_observers)
observer.m_changeCountryFn(countryId);
}
void Storage::NotifyStatusChangedForHierarchy(TCountryId const & countryId)
{
// Notification status changing for a leaf in country tree.
NotifyStatusChanged(countryId);
// Notification status changing for ancestors in country tree.
ForEachAncestorExceptForTheRoot(countryId,
[&](TCountryId const & parentId, TCountryTreeNode const &)
{
NotifyStatusChanged(parentId);
});
}
void Storage::DownloadNextCountryFromQueue()
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
bool const stopDownload = !m_downloadingPolicy->IsDownloadingAllowed();
if (m_queue.empty())
{
m_downloadingPolicy->ScheduleRetry(m_failedCountries, [this](TCountriesSet const & needReload)
{
for (auto const & country : needReload)
{
NodeStatuses status;
GetNodeStatuses(country, status);
if (status.m_error == NodeErrorCode::NoInetConnection)
RetryDownloadNode(country);
}
});
return;
}
QueuedCountry & queuedCountry = m_queue.front();
TCountryId const & countryId = queuedCountry.GetCountryId();
// It's not even possible to prepare directory for files before
// downloading. Mark this country as failed and switch to next
// country.
if (stopDownload || !PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, GetCountryFile(countryId)))
{
OnMapDownloadFinished(countryId, false /* success */, queuedCountry.GetInitOptions());
NotifyStatusChangedForHierarchy(countryId);
CorrectJustDownloadedAndQueue(m_queue.begin());
DownloadNextCountryFromQueue();
return;
}
DownloadNextFile(queuedCountry);
// New status for the country, "Downloading"
NotifyStatusChangedForHierarchy(queuedCountry.GetCountryId());
}
void Storage::DownloadNextFile(QueuedCountry const & country)
{
TCountryId const & countryId = country.GetCountryId();
CountryFile const & countryFile = GetCountryFile(countryId);
string const filePath = GetFileDownloadPath(countryId, country.GetCurrentFile());
uint64_t size;
// It may happen that the file already was downloaded, so there're
// no need to request servers list and download file. Let's
// switch to next file.
if (GetPlatform().GetFileSizeByFullPath(filePath, size))
{
OnMapFileDownloadFinished(true /* success */, MapFilesDownloader::TProgress(size, size));
return;
}
// send Country name for statistics
m_downloader->GetServersList(GetCurrentDataVersion(), countryFile.GetName(),
bind(&Storage::OnServerListDownloaded, this, _1));
}
void Storage::DeleteFromDownloader(TCountryId const & countryId)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
DeleteCountryFilesFromDownloader(countryId, MapOptions::MapWithCarRouting);
NotifyStatusChangedForHierarchy(countryId);
}
bool Storage::IsDownloadInProgress() const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
return !m_queue.empty();
}
TCountryId Storage::GetCurrentDownloadingCountryId() const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
return IsDownloadInProgress() ? m_queue.front().GetCountryId() : storage::TCountryId();
}
void Storage::LoadCountriesFile(string const & pathToCountriesFile, string const & dataDir,
TMappingOldMwm * mapping /* = nullptr */)
{
m_dataDir = dataDir;
if (!m_dataDir.empty())
{
Platform & platform = GetPlatform();
platform.MkDir(my::JoinFoldersToPath(platform.WritableDir(), m_dataDir));
}
if (m_countries.IsEmpty())
{
string json;
ReaderPtr<Reader>(GetPlatform().GetReader(pathToCountriesFile)).ReadAsString(json);
m_currentVersion = LoadCountries(json, m_countries, m_affiliations, mapping);
LOG_SHORT(LINFO, ("Loaded countries list for version:", m_currentVersion));
if (m_currentVersion < 0)
LOG(LERROR, ("Can't load countries file", pathToCountriesFile));
}
}
int Storage::Subscribe(TChangeCountryFunction const & change, TProgressFunction const & progress)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
CountryObservers obs;
obs.m_changeCountryFn = change;
obs.m_progressFn = progress;
obs.m_slotId = ++m_currentSlotId;
m_observers.push_back(obs);
return obs.m_slotId;
}
void Storage::Unsubscribe(int slotId)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
for (auto i = m_observers.begin(); i != m_observers.end(); ++i)
{
if (i->m_slotId == slotId)
{
m_observers.erase(i);
return;
}
}
}
void Storage::OnMapFileDownloadFinished(bool success,
MapFilesDownloader::TProgress const & progress)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
if (m_queue.empty())
return;
QueuedCountry & queuedCountry = m_queue.front();
TCountryId const countryId = queuedCountry.GetCountryId();
if (success && queuedCountry.SwitchToNextFile())
{
DownloadNextFile(queuedCountry);
return;
}
OnMapDownloadFinished(countryId, success, queuedCountry.GetInitOptions());
CorrectJustDownloadedAndQueue(m_queue.begin());
SaveDownloadQueue();
m_downloader->Reset();
NotifyStatusChangedForHierarchy(countryId);
DownloadNextCountryFromQueue();
}
void Storage::ReportProgress(TCountryId const & countryId, MapFilesDownloader::TProgress const & p)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
for (CountryObservers const & o : m_observers)
o.m_progressFn(countryId, p);
}
void Storage::ReportProgressForHierarchy(TCountryId const & countryId,
MapFilesDownloader::TProgress const & leafProgress)
{
// Reporting progress for a leaf in country tree.
ReportProgress(countryId, leafProgress);
// Reporting progress for the parents of the leaf with |countryId|.
TCountriesSet setQueue;
GetQueuedCountries(m_queue, setQueue);
auto calcProgress = [&](TCountryId const & parentId, TCountryTreeNode const & parentNode)
{
TCountriesVec descendants;
parentNode.ForEachDescendant([&descendants](TCountryTreeNode const & container)
{
descendants.push_back(container.Value().Name());
});
MapFilesDownloader::TProgress localAndRemoteBytes =
CalculateProgress(countryId, descendants, leafProgress, setQueue);
ReportProgress(parentId, localAndRemoteBytes);
};
ForEachAncestorExceptForTheRoot(countryId, calcProgress);
}
void Storage::OnServerListDownloaded(vector<string> const & urls)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
// Queue can be empty because countries were deleted from queue.
if (m_queue.empty())
return;
QueuedCountry const & queuedCountry = m_queue.front();
TCountryId const & countryId = queuedCountry.GetCountryId();
MapOptions const file = queuedCountry.GetCurrentFile();
vector<string> const & downloadingUrls =
m_downloadingUrlsForTesting.empty() ? urls : m_downloadingUrlsForTesting;
vector<string> fileUrls;
fileUrls.reserve(downloadingUrls.size());
for (string const & url : downloadingUrls)
fileUrls.push_back(GetFileDownloadUrl(url, countryId, file));
string const filePath = GetFileDownloadPath(countryId, file);
m_downloader->DownloadMapFile(fileUrls, filePath, GetDownloadSize(queuedCountry),
bind(&Storage::OnMapFileDownloadFinished, this, _1, _2),
bind(&Storage::OnMapFileDownloadProgress, this, _1));
}
void Storage::OnMapFileDownloadProgress(MapFilesDownloader::TProgress const & progress)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
// Queue can be empty because countries were deleted from queue.
if (m_queue.empty())
return;
if (m_observers.empty())
return;
ReportProgressForHierarchy(m_queue.front().GetCountryId(), progress);
}
bool Storage::RegisterDownloadedFiles(TCountryId const & countryId, MapOptions files)
{
CountryFile const countryFile = GetCountryFile(countryId);
TLocalFilePtr localFile = GetLocalFile(countryId, GetCurrentDataVersion());
if (!localFile)
localFile = PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, countryFile);
if (!localFile)
{
LOG(LERROR, ("Local file data structure can't be prepared for downloaded file(", countryFile,
files, ")."));
return false;
}
bool ok = true;
vector<MapOptions> mapOpt = {MapOptions::Map};
if (!version::IsSingleMwm(GetCurrentDataVersion()))
mapOpt.emplace_back(MapOptions::CarRouting);
for (MapOptions file : mapOpt)
{
if (!HasOptions(files, file))
continue;
string const path = GetFileDownloadPath(countryId, file);
if (!my::RenameFileX(path, localFile->GetPath(file)))
{
ok = false;
break;
}
}
localFile->SyncWithDisk();
if (!ok)
{
localFile->DeleteFromDisk(files);
return false;
}
RegisterCountryFiles(localFile);
return true;
}
void Storage::OnMapDownloadFinished(TCountryId const & countryId, bool success, MapOptions files)
{
ASSERT(m_didDownload != nullptr, ("Storage::Init wasn't called"));
ASSERT_NOT_EQUAL(MapOptions::Nothing, files,
("This method should not be called for empty files set."));
{
alohalytics::LogEvent("$OnMapDownloadFinished",
alohalytics::TStringMap({{"name", countryId},
{"status", success ? "ok" : "failed"},
{"version", strings::to_string(GetCurrentDataVersion())},
{"option", DebugPrint(files)}}));
}
success = success && RegisterDownloadedFiles(countryId, files);
if (!success)
{
m_failedCountries.insert(countryId);
return;
}
TLocalFilePtr localFile = GetLocalFile(countryId, GetCurrentDataVersion());
ASSERT(localFile, ());
DeleteCountryIndexes(*localFile);
m_didDownload(countryId, localFile);
}
string Storage::GetFileDownloadUrl(string const & baseUrl, TCountryId const & countryId,
MapOptions file) const
{
CountryFile const & countryFile = GetCountryFile(countryId);
string const fileName = GetFileName(countryFile.GetName(), file, GetCurrentDataVersion());
return GetFileDownloadUrl(baseUrl, fileName);
}
string Storage::GetFileDownloadUrl(string const & baseUrl, string const & fName) const
{
return baseUrl + OMIM_OS_NAME "/" + strings::to_string(GetCurrentDataVersion()) + "/" +
UrlEncode(fName);
}
TCountryId Storage::FindCountryIdByFile(string const & name) const
{
// @TODO(bykoianko) Probably it's worth to check here if name represent a node in the tree.
return TCountryId(name);
}
TCountriesVec Storage::FindAllIndexesByFile(TCountryId const & name) const
{
// @TODO(bykoianko) This method should be rewritten. At list now name and the param of Find
// have different types: string and TCountryId.
TCountriesVec result;
if (m_countries.FindFirst(name))
result.push_back(name);
return result;
}
void Storage::GetOutdatedCountries(vector<Country const *> & countries) const
{
for (auto const & p : m_localFiles)
{
TCountryId const & countryId = p.first;
string const name = GetCountryFile(countryId).GetName();
TLocalFilePtr file = GetLatestLocalFile(countryId);
if (file && file->GetVersion() != GetCurrentDataVersion() &&
name != WORLD_COASTS_FILE_NAME && name != WORLD_COASTS_OBSOLETE_FILE_NAME && name != WORLD_FILE_NAME)
{
countries.push_back(&CountryLeafByCountryId(countryId));
}
}
}
Status Storage::CountryStatusWithoutFailed(TCountryId const & countryId) const
{
// First, check if we already downloading this country or have in in the queue.
if (!IsCountryInQueue(countryId))
return CountryStatusFull(countryId, Status::EUnknown);
return IsCountryFirstInQueue(countryId) ? Status::EDownloading : Status::EInQueue;
}
Status Storage::CountryStatusFull(TCountryId const & countryId, Status const status) const
{
if (status != Status::EUnknown)
return status;
TLocalFilePtr localFile = GetLatestLocalFile(countryId);
if (!localFile || !localFile->OnDisk(MapOptions::Map))
return Status::ENotDownloaded;
CountryFile const & countryFile = GetCountryFile(countryId);
if (GetRemoteSize(countryFile, MapOptions::Map, GetCurrentDataVersion()) == 0)
return Status::EUnknown;
if (localFile->GetVersion() != GetCurrentDataVersion())
return Status::EOnDiskOutOfDate;
return Status::EOnDisk;
}
// @TODO(bykoianko) This method does nothing and should be removed.
MapOptions Storage::NormalizeDeleteFileSet(MapOptions options) const
{
// Car routing files are useless without map files.
if (HasOptions(options, MapOptions::Map))
options = SetOptions(options, MapOptions::CarRouting);
return options;
}
QueuedCountry * Storage::FindCountryInQueue(TCountryId const & countryId)
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
auto it = find(m_queue.begin(), m_queue.end(), countryId);
return it == m_queue.end() ? nullptr : &*it;
}
QueuedCountry const * Storage::FindCountryInQueue(TCountryId const & countryId) const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
auto it = find(m_queue.begin(), m_queue.end(), countryId);
return it == m_queue.end() ? nullptr : &*it;
}
bool Storage::IsCountryInQueue(TCountryId const & countryId) const
{
return FindCountryInQueue(countryId) != nullptr;
}
bool Storage::IsCountryFirstInQueue(TCountryId const & countryId) const
{
ASSERT_THREAD_CHECKER(m_threadChecker, ());
return !m_queue.empty() && m_queue.front().GetCountryId() == countryId;
}
void Storage::SetLocale(string const & locale)
{
m_countryNameGetter.SetLocale(locale);
}
string Storage::GetLocale() const
{
return m_countryNameGetter.GetLocale();
}
void Storage::SetDownloaderForTesting(unique_ptr<MapFilesDownloader> && downloader)
{
m_downloader = move(downloader);
}
void Storage::SetCurrentDataVersionForTesting(int64_t currentVersion)
{
m_currentVersion = currentVersion;
}
void Storage::SetDownloadingUrlsForTesting(vector<string> const & downloadingUrls)
{
m_downloadingUrlsForTesting = downloadingUrls;
}
void Storage::SetLocaleForTesting(string const & jsonBuffer, string const & locale)
{
m_countryNameGetter.SetLocaleForTesting(jsonBuffer, locale);
}
Storage::TLocalFilePtr Storage::GetLocalFile(TCountryId const & countryId, int64_t version) const
{
auto const it = m_localFiles.find(countryId);
if (it == m_localFiles.end() || it->second.empty())
return TLocalFilePtr();
for (auto const & file : it->second)
{
if (file->GetVersion() == version)
return file;
}
return TLocalFilePtr();
}
void Storage::RegisterCountryFiles(TLocalFilePtr localFile)
{